通用分页(2)将上一次查询请求再发一次,只不过改变了页码。
具体思路:
1、补全servlet
2、页面展示
3、分页重要参数(page、rows、是否分页、上一次请求、上一次的表单参数)
4、自定义分页标签
1.实体类
package com.huangwen.entity;
public class Book {
private int bid;
private String bname;
private float price;
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
}
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Book(int bid, String bname, float price) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
}
public Book() {
super();
}
}
分页工具类
package com.huangwen.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;// 是否分页
private Map paMap=new HashMap<>();
private String url;
public void setRequest(HttpServletRequest req) {
Map parameterMap = req.getParameterMap();
StringBuffer url = req.getRequestURL();
//保存上一次请求所携带的参数
this.setPaMap(req.getParameterMap());
this.setUrl(req.getRequestURI().toString());
//在jsp页面来控制是否分页
this.setPagination(!"false".equals(req.getParameter("pagination")));
//在jsp页面来控制一页展示多少条数据
this.setRows(req.getParameter("rows"));
this.setPage(req.getParameter("page"));
}
public void setPage(String page) {
// TODO Auto-generated method stub
this.page=StringUtils.isNotBlank(page) ? Integer.valueOf(page) : this.page;
}
public void setRows(String rows) {
// TODO Auto-generated method stub
this.rows=StringUtils.isNotBlank(rows) ? Integer.valueOf(rows) : this.rows;
}
public Map getPaMap() {
return paMap;
}
public void setPaMap(Map paMap) {
this.paMap = paMap;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
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 + "]";
}
/**
* 获取最大页码数
* @return
*/
public int getMaxPage() {
return this.total%this.rows==0 ? this.total/this.rows : this.total/this.rows+1;
}
/**
* 下一页
* @return
*/
public int getNextPage() {
return this.page1?this.page-1:this.page;
}
}
中文乱码处理
package com.huangwen.util;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 中文乱码处理
*
*/
public class EncodingFiter implements Filter {
private String encoding = "UTF-8";// 默认字符集
public EncodingFiter() {
super();
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// 中文处理必须放到 chain.doFilter(request, response)方法前面
res.setContentType("text/html;charset=" + this.encoding);
if (req.getMethod().equalsIgnoreCase("post")) {
req.setCharacterEncoding(this.encoding);
} else {
Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
Set set = map.keySet();// 取出所有参数名
Iterator it = set.iterator();
while (it.hasNext()) {
String name = (String) it.next();
String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
for (int i = 0; i < values.length; i++) {
values[i] = new String(values[i].getBytes("ISO-8859-1"),
this.encoding);
}
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig filterConfig) throws ServletException {
String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
if (null != s && !s.trim().equals("")) {
this.encoding = s.trim();
}
}
}
dao类
package com.huangwen.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.huangwen.entity.Book;
import com.huangwen.util.BaseDao;
import com.huangwen.util.DBAccess;
import com.huangwen.util.PageBean;
import com.huangwen.util.StringUtils;
/**
* book 封装这个jsp传递过来的查询参数
* pagebean 决定dao层的list调用时是否分页
* @author NJ321
*
*/
public class BookDao extends BaseDao{
public List list(Book book,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
String sql="select * from t_mvc_book where true";
String bname=book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql+=" and bname like '%"+bname+"%'";
}
return super.list(sql, Book.class, pageBean);
}
}
BaseDao类
package com.huangwen.util;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.huangwen.entity.Book;
/**
* T代表对哪个实体类对应表进行分页查询
* @author NJ321
*
* @param
*/
public class BaseDao {
/**
*
* @param sql 查询不同的实体类,那么对应的sql语句不同,所以需要传递
* @param clz 生产出不同的实体类对应的的实例,然后装进list容器中返回
* @param pageBean 决定是否分页
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List list(String sql,Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
Connection con=DBAccess.getConnection();
PreparedStatement pst=null;
ResultSet rs=null;
if(pageBean!=null && pageBean.isPagination()) {
//需要分页
//算符合条件的总记录数
String countsql=getcountsql(sql);
pst=con.prepareStatement(countsql);
rs=pst.executeQuery();
if(rs.next()) {
pageBean.setTotal(rs.getLong(1)+"");
}
//查询出符合条件的结果集
String pagesql=getpagesql(sql,pageBean);
pst=con.prepareStatement(pagesql);
rs=pst.executeQuery();
}else {
pst=con.prepareStatement(sql);
rs=pst.executeQuery();
}
List list=new ArrayList<>();
while(rs.next()) {
/**
* 1.实例化一个book对象(空对象)
* 2.取book的所有属性,然后给其赋值
* 2.1.获取所有属性对象
* 2.2.给属性对象赋值
* 3.赋值之后的book对象装进list容器中
*/
//list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
T t = (T) clz.newInstance();
Field[] fields = clz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
field.set(t, rs.getObject(field.getName()));
}
list.add(t);
}
DBAccess.close(con, pst, rs);
return list;
}
/**
* 利用原生sql拼装出符合条件的结果集的查询sql
* @param sql
* @param pageBean
* @return
*/
private String getpagesql(String sql, PageBean pageBean) {
// TODO Auto-generated method stub
return sql+" limit "+pageBean.getStartIndex()+","+pageBean.getRows();
}
/**
* 获取符合条件的总记录数的sql语句
* @param sql
* @return
*/
private String getcountsql(String sql) {
// TODO Auto-generated method stub
return "select count(1) from ("+sql+") t";
}
}
Booklist.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="/huangwen" prefix="n" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Insert title here
小说目录
编号
名称
价格
${b.bid }
${b.bname }
${b.price }
tid
huangwen 1.1 core library
huangwen core
1.1
n
/huangwen
page
com.huangwen.util.PageTag
JSP
pageBean
true
true
web.XML
pagebean
encodingFiter
com.huangwen.util.EncodingFiter
encodingFiter
/*
bookServlet
com.huangwen.web.BookServlet
bookServlet
/bookServlet
PageTag 类
package com.huangwen.util;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import sun.nio.cs.ext.DoubleByte.Encoder_DBCSONLY;
import com.huangwen.util.PageBean;
public class PageTag extends BodyTagSupport {
private static final long serialVersionUID = -553969530960334073L;
private PageBean pageBean;
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
@Override
public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
try {
out.print(toHTML());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.doStartTag();
}
private String toHTML() {
StringBuilder sb=new StringBuilder();
// 拼接下一次发送请求所要提交的隐藏的from表单
sb.append("");
// 拼接分页条
sb.append("");
// 拼接分页所需要的js代码
sb.append("");
return sb.toString();
}
}
BookServlet 类
package com.huangwen.web;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.huangwen.entity.Book;
import com.huangwen.dao.BookDao;
import com.huangwen.util.PageBean;
public class BookServlet extends HttpServlet {
private static final long serialVersionUID = -5039284256017836881L;
private BookDao bookDao=new BookDao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// TODO Auto-generated method stub
// 过滤器转码
String bname=req.getParameter("bname");
Book book=new Book();
book.setBname(bname);
// 这两个方法应保存在PageBean中
// 可拿到从jsp界面传过来的所有参数
// Map parameterMap = req.getParameterMap();
// StringBuffer url = req.getRequestURL();
PageBean pageBean=new PageBean();
try {
pageBean.setRequest(req);
List list = this.bookDao.list(book, pageBean);
req.setAttribute("bookList", list);
req.setAttribute("pageBean", pageBean);
req.getRequestDispatcher("bookList.jsp").forward(req, resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}