查询频道列表接口
接口设计文档
请求:
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);
}
}
实现结果
我们登录到账号上,就可以看到频道列表了