Web在线聊天室(7) --- 查询频道列表

查询频道列表接口

接口设计文档

请求:
GET /channel
响应:
HTTP/1.1 200 OK
[
	ok:true
	reason:xxx
	data{
		channelId: 1,
		channelName: xxx
	}
]

编写前端ajax回调函数

	   getChannels() {
          $.ajax({
            type: "get",
            url: "channel",
            success: function(body, status) {
              if(body.ok) {
                app.channels = body.data;
              }else {
                alert(body.reason)
              }
            }
          })
        }

编写servlet实现doget方法

@WebServlet("/channel")

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("applicaation/json");
        Response response = new Response();
        try {
            //查询所有频道列表返回
            List<Channel> list = ChannelDao.query();
            response.setOk(true);
            response.setData(list);
            //ok:true,data[{},{}]
        }catch (Exception e) {
            e.printStackTrace();
            //目前,前端的实现,在后端报错,要返回空的list
            //改造前端为解析ok,reason
            //参考LoginServlet改造
            response.setReason(e.getMessage());
            //ok:false,reason:""
        }
        resp.getWriter().println(Util.serialize(response));
    }

编写操作数据库方法

    /**
     * 查询频道列表
     */
    public static List<Channel> query() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        //定义返回数据
        List<Channel> list = new ArrayList<>();
        try {
            //1. 获取数据库连接Connection
            connection = Util.getConnection();
            //2. 通过Connection+sql 创建操作命令对象Statement
            String sql = "select channelId,channelName from channel";
            statement = connection.prepareStatement(sql);
            //3. 执行sql:执行前替换占位符
            resultSet = statement.executeQuery();
            //如果是查询操作,处理结果集
            while (resultSet.next()) {//移动到下一行,有数据返回true
                Channel channel = new Channel();
                //设置属性
                channel.setChannelId(resultSet.getInt("channelId"));
                channel.setChannelName(resultSet.getString("channelName"));
                list.add(channel);
            }
            return list;
        }catch (Exception e) {
            throw new AppException("查询频道列表出错", e);
        }finally {
            //释放资源
            Util.close(connection,statement,resultSet);
        }
    }

实现结果

我们登录到账号上,就可以看到频道列表了
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值