1.通用的Page模板。T可以为自己声明的bean类。
import java.util.List;
public class Page<T> {
//数据列表 数据库获取
private List<T> data;
//总记录 数据库获取
private int totalRecord;
//总页数 计算
private int totalPage;
//当前页数 前台传递
private int currentPage;
//每页记录数 前台设置
private int pageSize;
//分页的数据的路径
private String path;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public Page() {
super();
// TODO Auto-generated constructor stub
}
//页面记录开始索引 计算
public int getBegin() {
return (currentPage - 1) * pageSize;
}
public List<T> getData() {
return data;
}
public void setData(List<T> data) {
this.data = data;
}
public int getTotalRecord() {
return totalRecord;
}
public void setTotalRecord(int totalRecord) {
this.totalRecord = totalRecord;
}
public int getTotalPage() {
totalPage = totalRecord % pageSize == 0 ?(totalRecord/pageSize):(totalRecord/pageSize+1);
return totalPage;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public Page(int totalRecord, int currentPage, int pageSize) {
super();
this.totalRecord = totalRecord;
this.currentPage = currentPage;
this.pageSize = pageSize;
}
}
2.Service层的操作。
(1)从数据库获取总的记录数目。
int totalRecord = stuDao.getTotalRecord();
Page<Student> pageStu = new Page<Student>(totalRecord, currentPage, Constant.pageSize);
此处我的
Constant.pageSize
是一个常量,5.
(3)根据page对象,得到该Page对象中的data数据,data是list数据,并设置。
list = stuDao.getLimitStudent(pageStu);
pageStu.setData(list);
(1)从前台获取当前页,调用service方法。
int currentPage = Integer.parseInt(request.getParameter("currentPage"));
Page<Student>pageStu = stuService.getLimitStudent(currentPage);
(2)获取项目的请求路径,并赋给page对象。
pageStu.setPath(WEBUtil.getPath(request));
WEBUtil工具类见下。
(3)将page对象设置到域对象,并且转发到新的界面。
request.setAttribute("pageStu", pageStu);
request.getRequestDispatcher("WEB-INF/main.jsp").forward(request, response);
后台的操作基本完成。
前台的操作可以套用模板,github等网站有很多大牛写的比较好看的页面导航,可以拿来使用。此处不再赘述。
WEBUtil.java
import javax.servlet.http.HttpServletRequest;
public class WEBUtil {
public static String getPath(HttpServletRequest request){
String requestURI = request.getRequestURI();
String queryString = request.getQueryString();
String URL = requestURI + "?" + queryString;
if(URL.contains("&¤tPage")){
URL = URL.substring(0, URL.indexOf("&¤tPage"));
}
return URL;
}
}
下面的代码为前端分页代码:
http://blog.csdn.net/gpf951101/article/details/77185244