ajax向后端传入点击加载更多按钮的次数,进而控制后端从数据库取出数据的位置,以及每次取出的数量
int count=6;//每次从数据库取出的数量 int clickNum=Integer.parseInt(request.getParameter("clickNum"));//获取点击加载更多次数;// 1 2 3 4 int start = clickNum*count;//每次点加的查询位置(初始页面会显示6条数据,所以从6开始) // 6 12 18 24 //根据获取前端传过来的page进行分页查询 Listmessages =messageService.getMessages(start,count);//查询
主要有:jsp,dao,service,controller页面
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//初始显示6条数据
if ("/show/message.do".equals(request.getServletPath())){
List messages =messageService.getMessages(0,6);//分页查询全部留言
if (messages!=null){
request.setAttribute("messages",messages);
request.getRequestDispatcher("/WEB-INF/views/message.jsp").forward(request,response);
}
// 前台加载更多
} else if("/show/more.do".equals(request.getServletPath())){
int count=6;//每次从数据库取出的数量
int clickNum=Integer.parseInt(request.getParameter("clickNum"));//获取点击加载更多次数;// 1 2 3 4
int start = clickNum*count;//每次点加的查询位置(初始页面会显示6条数据) // 6 12 18 24
List messages =messageService.getMessages(start,count);//查询
//把message变成json数据,使用了(https://mvnrepository.com/artifact/net.sf.json-lib/json-lib)
JSONArray json = JSONArray.fromObject(messages);
String str = json.toString();
response.getWriter().write(str);
}
/**
* 查询部分文章
* @param start (开始位置)从点击数*6个
* @param count 每页数量
* @return
*/
public List getMessages(int start, int count) {
// 得到messages
return messageDao.getMessageList(start,count);
}
public List getMessageList(int start , int count) {
Connection conn=null;
PreparedStatement stmt = null;
ResultSet rs = null;
List messages = new ArrayList();
try {
conn=ConnectUtil.getConnection();
String sql="select * from message order by create_time desc limit ?,?";
stmt = conn.prepareStatement(sql);
stmt.setInt(1, start );//开始位置
stmt.setInt(2, count);//结束位置
rs = stmt.executeQuery();
while (rs.next()) {
messages.add(new Message(
rs.getInt("id"),
rs.getInt("user_id"),
rs.getString("username"),
rs.getString("title"),
rs.getString("content"),
rs.getTimestamp("create_time")));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
ConnectUtil.release(rs, stmt, conn);
}
return messages;
}
初始页面:select * from message order by create_time desc limit 0,6
第一次点击加载更多:select * from message order by create_time desc limit 6,6
第二次点击加载更多:select * from message order by create_time desc limit 12,6
第三次点击加载更多:select * from message order by create_time desc limit 18,6
JSONArray json = JSONArray.fromObject(messages);(List
这个对象需要额外的jnet.sf.json包,这里使用maven引入依赖
net.sf.json-lib
json-lib
2.4
jdk15
commons-beanutils
commons-beanutils
1.7.0
commons-collections
commons-collections
3.1
commons-lang
commons-lang
2.5
net.sf.ezmorph
ezmorph
1.0.3
文档地址:http://json-lib.sourceforge.net/apidocs/net/sf/json/JSONArray.html