Java表格页跳转

Java表格页跳转

表格页跳转需要用到四个参数:数据的总条数,数据的总页数,页大小,当前页。

在jsp中用<c:if>标签判断当前页是否大于1,大于1添加首页和上一页的a标签,再判断当前页是否小于总页数,小于尾页添加下一页和尾页的a标签。a标签的链接定位至servlet,把当前页和页大小两个参数传过去。

<c:if test="${pagination > 1}">
	<a href="${pageContext.request.contextPath}/servlet/MainServlet?type=findAll&pagination=1&pageSize=${pageSize}">首页</a>
	<a href="${pageContext.request.contextPath}/servlet/MainServlet?type=findAll&pagination=${pagination-1}&pageSize=${pageSize}">上一页</a>
</c:if>
<c:if test="${pagination < page}">
	<a href="${pageContext.request.contextPath}/servlet/MainServlet?type=findAll&pagination=${pagination+1}&pageSize=${pageSize}">下一页</a>
	<a href="${pageContext.request.contextPath}/servlet/MainServlet?type=findAll&pagination=${page}&pageSize=${pageSize}">尾页</a>
</c:if>

超链接的请求方式是get请求,首先会调用doGet,通常使用的都是doPost方法,只要在servlet中让这两个方法互相调用就行了。

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	doPost(request, response);
}

直接就会去调用doPost,因为他们的参数都一样。首先要设置对客户端请求进行重新编码,根据name取参来调用表格页跳转的方法,这样方便调用其他方法。

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	request.setCharacterEncoding("utf-8");
	String type=request.getParameter("type");
	if ("findAll".equals(type)) {
    		findAll(request,response);
	}
}

在表格页跳转方法中,首先需要获取当前页和页大小,根据当前页和页大小查出当前页的数据,然后把所需要的数据放在jsp的内置对象的request里,最后转发至jsp。

private void findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	AccountService accountService = new AccountServiceImpl();//实例化
	int pagination=Integer.parseInt(request.getParameter("pagination"));
	int pageSize=Integer.parseInt(request.getParameter("pageSize"));
	request.setAttribute("account", accountService.SelectPage(pagination, pageSize));//当前页的数据
	int count = accountService.Selectaccount().size();
	request.setAttribute("count", count);//总条数
	request.setAttribute("page",(count+pageSize-1)/pageSize);//总页数
	request.setAttribute("pagination", pagination);//当前页
	request.setAttribute("pageSize", pageSize);//页大小
	request.getRequestDispatcher("/jsp/Account.jsp").forward(request, response);
}

SelectPage(pagination, pageSize)和Selectaccount()是AccountServiceImpl里封装好的查询当前页的数据和查询所有数据的方法,其区别在于sql语句不同,SelectPage(pagination, pageSize)中的sql语句如下:

select * from account limit "+(pagination-1)*pageSize+","+pageSize;

猜你喜欢

转载自blog.csdn.net/weixin_44547599/article/details/90902337