自定义标签,实现分页。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://csdn.hbsi/pageTag" prefix="q"%></html>
package com.csdn.hbsi.Servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class TestPaperServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private List<String> datas;//用于用户存储数据的集合
public static final int PAGER_PAGESIZE=10;//定义每页要显示的数据条数
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
int recordCount=this.datas.size();//获取总记录数
int pageNo=1; //获取当前页号
String pageNoStr=request.getParameter("pageNo");
if(pageNoStr!=null&&!pageNoStr.equals("")){
pageNo=Integer.parseInt(pageNoStr);
}
//获取分页数据
int start=(pageNo-1)*PAGER_PAGESIZE; //定义开始位置
int end=start+PAGER_PAGESIZE; //定义结束位置
if(end>this.datas.size()){
end=this.datas.size();
}
List<String>result=this.datas.subList(start, end);//subList方法返回列表中指定的start(包括)和end(不包括)之间的数据视图
//把用户分页的数据和分页标签的需要的属性放到request中
request.setAttribute("datas",result);
request.setAttribute("pageNo",pageNo);
request.setAttribute("pageSize",PAGER_PAGESIZE );
request.setAttribute("recordCount", recordCount);
//请求转发到JSP页面
request.getRequestDispatcher("/Paper.jsp").forward(request, response);
}
public void init() throws ServletException {//在初始化servlet的时候进行的数据
//准备用户分页的数据
datas=new ArrayList<String>();
for(int i=1;i<=123;i++){
datas.add("字符串"+i);
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>w</short-name>
<uri>http://csdn.hbsi/pageTag</uri>
<tag>
<name>Paper</name>
<tag-class>com.hbsi.csdn.tags.PaperTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>pageNo</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>pageSize</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>recordCount</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>url</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>