完成前端通用分页
1.通用分页核心思路
将上一次查询请求再发一次,只不过页码变了
2.分页三要素
page 页码 视图层传递过来
rows 页大小 视图层传递过来
total 总记录数 后台查出来
3.书写BookDao方法继承BaseDao方法
package com.ningjie.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.ningjie.entity.Book;
import com.ningjie.util.BaseDao;
import com.ningjie.util.DBAccess;
import com.ningjie.util.PageBean;
import com.ningjie.util.StringUtils;
/**
* book 封装这个jsp传递过来的查询参数
* pagebean 决定dao层的list调用时是否分页
* @author NJ321
*
*/
public class BookDao extends BaseDao<Book>{
public List<Book> 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);
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
BookDao bookDao=new BookDao();
Book book=new Book();
book.setBname("圣墟");
PageBean pageBean=new PageBean();
pageBean.setPage(2);
try {
List<Book> list=bookDao.list(book, pageBean);
for (Book b : list) {
System.out.println(b);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
package com.ningjie.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.ningjie.entity.Book;
/**
* T代表对哪个实体类对应表进行分页查询
* @author NJ321
*
* @param <T>
*/
public class BaseDao<T> {
/**
*
* @param sql 查询不同的实体类,那么对应的sql语句不同,所以需要传递
* @param clz 生产出不同的实体类对应的的实例,然后装进list容器中返回
* @param pageBean 决定是否分页
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List<T> 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<T> 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";
}
}
4.写一个实体类Book
package com.ningjie.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();
}
}
5.写一个进行查询的servlet
如何将上一次查询请求再发一次
获得请求中的所有参数
Map<String, String[]> parameterMap = req.getParameterMap();
请求的地址
String url = req.getServletPath();
package com.ningjie.web;
import java.io.IOException;
import java.sql.SQLException;
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.ningjie.dao.BookDao;
import com.ningjie.entity.Book;
import com.ningjie.util.PageBean;
public class BookServlet extends HttpServlet{
private BookDao bookDao=new BookDao();
private static final long serialVersionUID = 6165908906828917342L;
@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);
//能够获取jsp页面传过来的所有参数和所有值
//Map<String, String[]> parameterMap = req.getParameterMap();
//获取路径
//StringBuffer url = req.getRequestURL();
PageBean pageBean=new PageBean();
try {
pageBean.setRequest(req);
List<Book> list=this.bookDao.list(book, pageBean);
req.setAttribute("bookList", list);
req.setAttribute("pageBean", pageBean);
req.getRequestDispatcher("/bookList.jsp").forward(req, resp);;
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
6.进行xml配置(过滤器配置)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>pagebean</display-name>
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.ningjie.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>bookServlet</servlet-name>
<servlet-class>com.ningjie.web.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>bookServlet</servlet-name>
<url-pattern>/bookServlet</url-pattern>
</servlet-mapping>
</web-app>
7.写一个帮助类pageBean
package com.ningjie.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<String, String[]> paMap=new HashMap<>();
private String url;
public void setRequest(HttpServletRequest req) {
Map<String, String[]> 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<String, String[]> getPaMap() {
return paMap;
}
public void setPaMap(Map<String, String[]> 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.page<this.getMaxPage()?this.page+1:this.page;
}
/**
* 上一页
* @return
*/
public int getPreviousPage() {
return this.page>1?this.page-1:this.page;
}
}
8.写一个视图层PageTag
package com.ningjie.tag;
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 com.ningjie.util.PageBean;
public class PageTag extends BodyTagSupport{
/**
*
*/
private static final long serialVersionUID = -4097540471746887353L;
private PageBean pageBean;
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
@Override
public int doStartTag() throws JspException {
// TODO Auto-generated method stub
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();
//拼接下一次请求所要提交隐藏的form表单
sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>");
sb.append("<input type='hidden' name='page'>");
Map<String, String[]> paMap = pageBean.getPaMap();
if(paMap!=null && paMap.size()>0) {
Set<Entry<String, String[]>> entrySet = paMap.entrySet();
for (Entry<String, String[]> entry : entrySet) {
//上一次请求可能携带页码name=page的参数,但是改参数在前面已经单独赋值
if(!"page".equals(entry.getKey())) {
for (String val:entry.getValue()) {
sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+val+"'> ");
}
}
}
}
sb.append("</form>");
//拼接分页条
sb.append("<div style='text-align: right; font-size: 12px;'>");
sb.append("每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页 <a href='javascript:gotoPage(?)'>首页</a> <a");
sb.append(" href='javascript:gotoPage("+pageBean.getPreviousPage()+")'>上一页</a> <a");
sb.append(" href='javascript:gotoPage("+pageBean.getNextPage()+")'>下一页</a> <a");
sb.append(" href='javascript:gotoPage("+pageBean.getMaxPage()+")'>尾页</a> <input type='text'");
sb.append(" id='skipPage'");
sb.append(" style='text-align: center; font-size: 12px; width: 50px;'> <a");
sb.append(" href='javascript:skipPage()'>Go</a>");
sb.append("</div>");
//拼接分页所需要的js代码
sb.append("<script type='text/javascript'>");
sb.append(" function gotoPage(page) {");
sb.append(" document.getElementById('pageBeanForm').page.value = page;");
sb.append(" document.getElementById('pageBeanForm').submit();");
sb.append("}");
sb.append(" function skipPage() {");
sb.append(" var page = document.getElementById('skipPage').value;");
sb.append(" if(!page || isNaN(page) || parseInt(page)<1 || parseInt(page)>"+pageBean.getMaxPage()+"){");
sb.append(" alert('请输入1~N的数字');");
sb.append(" return;");
sb.append("}");
sb.append("gotoPage(page);");
sb.append("}");
sb.append("</script>");
return sb.toString();
}
}
9.对视图层进行tld文件自定义标签配置
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>ningjie 1.1 core library</description>
<display-name>ningjie core</display-name>
<tlib-version>1.1</tlib-version>
<short-name>n</short-name>
<uri>/ningjie</uri>
<tag>
<!-- 标签库中的标签(类似c:set和c:out的定义) -->
<name>page</name>
<!-- 是标签运行具体代码,也就是助手类,下面填写的是助手类的全路径 -->
<tag-class>com.ningjie.tag.PageTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<!-- 该标签的属性 -->
<name>pageBean</name>
<!-- 该属性是否必填 -->
<required>true</required>
<!-- 是否支持表达式 -->
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
10.写一个jsp页面进行测试
<!-- 控制jsp页面是否 -->
<input type="hidden" name="pagination" value="true">
<!-- 控制jsp页面每页显示几条 -->
<input type="hidden" name="rows" value="10">
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="/ningjie" prefix="n" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h2>小说目录</h2>
<br>
<form action="${pageContext.request.contextPath}/bookServlet"
method="post">
书名:<input type="text" name="bname"> <input type="submit" value="确定">
<!-- 控制jsp页面是否 -->
<input type="hidden" name="pagination" value="true">
<!-- 控制jsp页面每页显示几条 -->
<input type="hidden" name="rows" value="10">
</form>
<table border="1" width="100%">
<tr>
<td>编号</td>
<td>名称</td>
<td>价格</td>
</tr>
<c:forEach items="${bookList }" var="b">
<tr>
<td>${b.bid }</td>
<td>${b.bname }</td>
<td>${b.price }</td>
</tr>
</c:forEach>
<n:page pageBean="${pageBean}"></n:page>
</table>
</body>
</html>
每页10条数据分页运行结果(分页条在上面请忽略)