1、需要的资源
DBAccess类:提供了一组获得或关闭数据库对象的方法
config.properties:连接数据库
EncodingFiter类:中文乱码处理
StringUtils类:判断是否存在
Book类:它是一个实体类
PageTag类 :自定义标签的助手类
BookDao类 :所用到的dao方法
PageBean类 :分页的工具类【核心类】
2、分页的实现
分页工具类【核心代码】PageBean类
package com.zyp.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 String url;
private Map<String, String[]> paramMap = new HashMap<>();
public void setRequest(HttpServletRequest req) {
this.setPage(req.getParameter("page"));
this.setRows(req.getParameter("rows"));
this.setPagination(req.getParameter("pagination"));
// getRequestURL获取到浏览器请求的全路径
this.setUrl(req.getRequestURL().toString());
// getParameterMap可以获取到一次url请求所携带的所有参数
this.setParamMap(req.getParameterMap());
}
public void setPagination(String pagination) {
if (StringUtils.isNotBlank(pagination)) {
this.setPagination(!"false".equals(pagination));//是否分页
}
}
public void setRows(String rows) {
if (StringUtils.isNotBlank(rows))
this.setRows(Integer.valueOf(rows));//每页多少天数据
}
public void setPage(String page) {
if (StringUtils.isNotBlank(page)) {
this.setPage(Integer.valueOf(page));//多少页
}
}
public PageBean() {
super();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getParamMap() {
return paramMap;
}
public void setParamMap(Map<String, String[]> paramMap) {
this.paramMap = paramMap;
}
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;
}
}
PageTag类
package com.zyp.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.zyp.util.PageBean;
public class PageTag extends BodyTagSupport{
private static final long serialVersionUID = -3609493782238830873L;
private PageBean pageBean;
@Override
public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
try {
out.write(toHTML());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.doStartTag();
}
public String toHTML() {
StringBuffer sb = new StringBuffer();
//下一次请求提交到后台的表单html代码拼接
sb.append("<form id='pageBeanForm' action='"+pageBean.getUrl()+"' method='post'>");
Map<String, String[]> paramMap = pageBean.getParamMap();
if(paramMap !=null && paramMap.size()>0) {
Set<Entry<String, String[]>> entrySet = paramMap.entrySet();
for(Entry<String, String[]> entry:paramMap.entrySet()) {
if(!"page".equals(entry.getKey())) {
sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+entry.getValue()+"'>");
}
}
}
sb.append("<input type='hidden' name='page'>");
sb.append("</form>");
//分页条html代码拼接
sb.append("<div style='text-align: right; font-size: 12px;'>");
sb.append("每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页 <a href='javascript:gotoPage("+pageBean.getPreviousPage()+")'>首页</a> <a");
sb.append(" href='javascript:gotoPage(1)'>上一页</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)>maxPage){");
sb.append(" alert('请输入1~N的数字');");
sb.append(" return;");
sb.append(" }");
sb.append(" gotoPage(page);");
sb.append("}");
sb.append("</script>");
return sb.toString();
}
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
}
BookServlet类
package com.zyp.web;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zyp.dao.BookDao;
import com.zyp.entity.Book;
import com.zyp.util.PageBean;
public class BookServlet extends HttpServlet{
// 调用数据层访问数据库
private BookDao bookDao = new BookDao();
private static final long serialVersionUID = -7654671804738498584L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 拿到前台的dname
String bname = req.getParameter("bname");
// 将前台传过来的值封装到实体类中
Book book = new Book();
//把bname放进去
book.setBname(bname);//有可能查询维度不止这个bname,有可能还会有别的。这里的话以bname为例
PageBean pagebean = new PageBean();
try {
// list 查出符合条件的某一页的记录数 默认是第一页
List<Book> list = bookDao.list(book, pagebean);
// 转发的同时转到req的作用域中
req.setAttribute("bookList", list);
req.setAttribute("pagebean", pagebean);//pagebean传过去了,最大页数,当前页数,是否分页,第几页都传过去了。
req.getRequestDispatcher("bookList.jsp").forward(req, resp);//转发
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
z.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>zking 1.1 core library</description>
<display-name>zking core</display-name>
<tlib-version>1.1</tlib-version>
<short-name>c</short-name>
<uri>/zking</uri>
<tag>
<!-- 标签库中的标签名 -->
<name>page</name>
<!-- 标签对应的助手类的全路径名 -->
<tag-class>com.zking.tags.PageTag</tag-class>
<!-- JSP -->
<body-content>JSP</body-content>
<attribute>
<!-- 属性名 -->
<name>pageBean</name>
<!-- 属性值是否必填 -->
<required>true</required>
<!-- 是否支持表达式 -->
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
web.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>T224_Z</display-name>
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.zking.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.zking.web.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>bookServlet</servlet-name>
<url-pattern>/bookServlet</url-pattern>
</servlet-mapping>
</web-app>
这里利用了上面所提到的EncodingFiter类处理中文乱码。
bookList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="/zking" prefix="z" %>
<!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="hidden" name="rows" value="20"> -->
<input type="hidden" name="pagination" value="false">
书名:<input type="text" name="bname"> <input type="submit"
value="确定">
</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>
</table>
<z:page pageBean="${pagebean }"></z:page>
</body>
</html>
输出结果如下:
如想了解更多,联系博主。