目录
一、改造pageBean
所需条件:
①需要新增变量保存上一次查询条件;
②需要新增变量保存上一次请求地址;比如:http://localhost:8080/t280_page/book/search
③需要添加方法:获取最大页的页码;
④需要添加方法:获取下一页的页码;
⑤需要添加方法:获取上一页的页码;
⑥需要增加方法:初始化pagebean。
PageBean类:
package com.chenchen.util;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
/**
* 分页工具类
*
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
// 需要新增变量保存上一次请求地址;比如:http://localhost:8080/t280_page/book/search
private String url;
// 需要新增变量保存上一次查询条件
private Map<String,String[]> parameterMap = new HashMap<>();
// 需要添加方法:获取最大页的页码
public int maxPage() {
return this.total % this.rows == 0 ?
this.total / this.rows
: this.total / this.rows+1;
}
// 需要添加方法:获取上一页的页码;
public int previousPage() {
return this.page > 1 ? this.page-1 : this.page;
}
// 需要添加方法:获取下一页的页码
public int nextPage() {
return this.page < this.maxPage()?
this.page+1:this.page;
}
// 需要增加方法:初始化pagebean
public void setRequest(HttpServletRequest req) {
this.setPage(req.getParameter("page"));
this.setRows(req.getParameter("rows"));
this.setPagination(req.getParameter("pagination"));
this.setUrl(req.getRequestURI().toString());
this.setParameterMap(req.getParameterMap());
}
private void setPagination(String pagination) {
if(StringUtils.isNotBlank(pagination)) {
this.setPagination(!"false".equals(pagination));
}
}
private void setRows(String rows) {
if(StringUtils.isNotBlank(rows)) {
this.setRows(Integer.valueOf(rows));
}
}
public void setPage(String page) {
if(StringUtils.isNotBlank(page)) {
// set自动生成的方法
this.setPage(Integer.valueOf(page));
}
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getParameterMap() {
return parameterMap;
}
public void setParameterMap(Map<String, String[]> parameterMap) {
this.parameterMap = parameterMap;
}
public PageBean() {
super();
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
this.total = Integer.parseInt(total);
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
+ ", url=" + url + ", parameterMap=" + parameterMap + "]";
}
}
然后新建一个 BookServlet :
package com.chenchen.web;
import java.io.IOException;
import java.util.Map;
impo