一、分页
在allUser.jsp中添加如下代码
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0c6bd8836b50947fc7ade1b3816cb868.png)
在去web.xml中添加上
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/2100d08c4326f2afaf3ce4b2a9b70994.png)
在servlet包中新建一个FindByPageServlet:
package com.zhongruan.servlet;
import com.zhongruan.pojo.PageInfo;
import com.zhongruan.service.IUserService;
import com.zhongruan.service.impl.UserServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class FindByPageServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int currentPage=1;
int size=5;
IUserService userService=new UserServiceImpl();
PageInfo pageInfo=userService.findByPage(currentPage,size);
HttpSession session=req.getSession();
session.setAttribute("pageInfo",pageInfo);
req.getRequestDispatcher("allUser.jsp").forward(req,resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String current=req.getParameter("currentPage");
String size1=req.getParameter("size");
int currentPage=Integer.parseInt(current);
int size=Integer.parseInt(size1);
IUserService userService=new UserServiceImpl();
PageInfo pageInfo=userService.findByPage(currentPage,size);
HttpSession session=req.getSession();
session.setAttribute("pageInfo",pageInfo);
req.getRequestDispatcher("allUser.jsp").forward(req,resp);
}
}
在IUserDao中添加“ ListfindByPage(int start,int size);”。
在UserDaoImpl中添加以下代码:
public List<User> findByPage(int start, int size) {
ResultSet resultSet = null;
PreparedStatement statement = null;
Connection connection = null;
List<User>users = new ArrayList<>();
try {
connection = DBUtil.getConnection();
String sql = "select * from account limit ?,?";
statement = connection.prepareStatement(sql);
statement.setInt(1,start);
statement.setInt(2,size);
resultSet = statement.executeQuery();
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt(1));
user.setUsername(resultSet.getString(2));
user.setPassword(resultSet.getString(3));
users.add(user);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBUtil.closeALL(resultSet, statement, connection);
}
return users;
}
在IUserService中添加“ PageInfo findByPage(int currentPage,int size);”。
在UserServicelmpl中添加以下代码:
@Override
public PageInfo findByPage(int currentPage, int size) {
PageInfo pageInfo=new PageInfo();
pageInfo.setCurrentPage(currentPage);
pageInfo.setSize(size);
int start=(currentPage-1)*size;
List<User>users=userDao.findByPage(start,size);
pageInfo.setList(users);
int count=userDao.seletCount();
pageInfo.setTotalCount(count);
Double c=Double.valueOf(count);
Double ceil=Math.ceil(c/size);
pageInfo.setTotalPage(ceil.intValue());
return pageInfo;
}