通用分页的实例

 一思维导图

 二、后端

帮助类

DBHelper—数据库帮助类

package com.util.ty;
 
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
 
/**
 * 提供了一组获得或关闭数据库对象的方法
 * 
 */
public class DBHelper {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;
 
	static {// 静态块执行一次,加载 驱动一次
		try {
			InputStream is = DBHelper.class.getResourceAsStream("config.properties");
			Properties properties = new Properties();
			properties.load(is);
 
			driver = properties.getProperty("driver");
			url = properties.getProperty("url");
			user = properties.getProperty("user");
			password = properties.getProperty("pwd");
 
			Class.forName(driver);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
 
	/**
	 * 获得数据连接对象
	 * 
	 * @return
	 */
	public static Connection getCon() {
		try {
			Connection conn = DriverManager.getConnection(url, user, password);
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}
 
	public static void close(ResultSet rs) {
		if (null != rs) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}
 
	public static void close(Statement stmt) {
		if (null != stmt) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}
 
	public static void close(Connection conn) {
		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}
 
	public static void myClose(Connection conn, Statement stmt, ResultSet rs) {
		close(rs);
		close(stmt);
		close(conn);
	}
 
	public static boolean isOracle() {
		return "oracle.jdbc.driver.OracleDriver".equals(driver);
	}
 
	public static boolean isSQLServer() {
		return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
	}
	
	public static boolean isMysql() {
		return "com.mysql.cj.jdbc.Driver".equals(driver);
	}
 
	public static void main(String[] args) {
		Connection conn = DBHelper.getCon();
		System.out.println(conn);
		DBHelper.close(conn);
		System.out.println("isOracle:" + isOracle());
		System.out.println("isSQLServer:" + isSQLServer());
		System.out.println("isMysql:" + isMysql());
		System.out.println("数据库连接(关闭)成功");
	}
}

对应的tld文件

#oracle9i
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:ora9
#user=test
#pwd=test
 
 
#sql2005
#driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#url=jdbc:sqlserver://localhost:1423;DatabaseName=test
#user=sa
#pwd=sa
 
 
#sql2000
#driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
#url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=unit6DB
#user=sa
#pwd=888888
 
 
#mysql5
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/study?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&useSSL=true
user=root
pwd=root123

EncodingFiter—编码过滤类

package com.util.ty;
 
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.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * 中文乱码处理
 * 
 */
@WebFilter("*.do")
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();
		}
	}
 
}

PageBean—分页工具类

package com.util.ty;
 
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import org.omg.CORBA.INTERNAL;
 
/**
 * 分页工具类
 *
 */
public class PageBean {
 
	private int page = 1;// 页码
 
	private int rows = 10;// 页大小
 
	private int total = 0;// 总记录数
 
	private boolean pagination = true;// 是否分页
	
	private String URL;//上一次请求的URL
	
	private Map<String, String[]> m=new HashMap<String, String[]>();//存放上一次请求携带的参数
	
 
	public String getURL() {
		return URL;
	}
 
	public void setURL(String uRL) {
		URL = uRL;
	}
 
	public Map<String, String[]> getM() {
		return m;
	}
 
	public void setM(Map<String, String[]> m) {
		this.m = m;
	}
 
	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 boolean isPagination() {
		return pagination;
	}
	
	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}
	
	public void setPage(String page) {
		if(page!=null)this.page = Integer.parseInt(page);
	}
	
	public void setRows(String rows) {
		if(rows!=null)
		this.rows = Integer.parseInt(rows);
	}
 
	public void setTotal(String total) {
		if(total!=null)
		this.total = Integer.parseInt(total);
	}
	
	public void setPagination(String pagination) {
		if(pagination != null)
		this.pagination = Boolean.getBoolean(pagination);
	}
	
	/**
	 * pageBean的初始化
	 * @param req
	 */
	public void init(HttpServletRequest req) {
		//初始化jsp界面传递过来的当前页
		this.setPage(req.getParameter("page"));
		//初始化jsp界面传递过来的页大小
		this.setRows(req.getParameter("rows"));
		//初始化jsp界面传递过来的是否分页参数
		this.setPagination(req.getParameter("pagination"));
		//初始化上一次请求路径
		this.setURL(req.getRequestURL().toString());
		//初始化上一次请求参数
		this.setM(req.getParameterMap());
	}
 
	/**
	 * 获得起始记录的下标
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}
	
	/**
	 * 返回最大页数
	 * @return
	 */
	public int getMaxPage() {
		return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows+1;
	}
	
	/**
	 * 获得上一页页码    最小页码为1
	 * @return
	 */
	public int backPage() {
		return this.page - 1 == 0 ? 1 : this.page-1;
	}
	
	/**
	 * 获得下一页页码    最大页码为 this.page
	 * @return
	 */
	public int nextPage() {
		return this.page + 1 > this.getMaxPage() ? this.getMaxPage() : this.page+1;
	}
 
	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination
				+ ", URL=" + URL + ", m=" + m + "]";
	}
}

三·前端分页

效果图

 

package com.ty.entity;
 
import java.util.HashMap;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import com.lxy.util.StringUtils;
 
/**
 * 分页工具类
 *
 */
public class PageBean {
	private int page=1;//页码
	private int rows=10;//页大小
	private int total=0;//总记录数
	private boolean pagination=true;//是否分页
	
	private String url;//保存上一次请求的url
	private Map<String, String[]> paramMap=new HashMap<String, String[]>();//保存上一次请求的参数
	/**
	 * 初始化pagebean的,保存上一次请求的重要参数
	 */
	public void setRequest(HttpServletRequest req) {
//		 1.1、需要保存上一次请求的URL
		this.setUrl(req.getRequestURI().toString());
//		 1.2、需要保存上一次请求的参数 bname 、price
		this.setParamMap(req.getParameterMap());
//		 1.3、需要保存上一次请求的分页设置 pagination
		this.setPagination(req.getParameter("pagination"));
//		 1.4、需要保存上一次请求的展示条目数
		this.setRows(req.getParameter("rows"));
//		 1.5、初始化请求的页码 page
		this.setPage(req.getParameter("page"));
		
		
	}
	
	
	public void setPage(String page) {
		if(StringUtils.isNotBlank(page)) {
			this.setPage(Integer.valueOf(page));
		}
	}
	public void setRows(String rows) {
		if(StringUtils.isNotBlank(rows)) {
			this.setRows(Integer.valueOf(rows));
		}
	}
	public void setPagination(String pagination) {
		//只要在前台jsp填写了pagination=false,才代表不分页
		if(StringUtils.isNotBlank(pagination)) {
			this.setPagination(!"false".equals(pagination));
		}
	}
 
 
	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;
	}
	
	/**
	 * 获得起始记录的下标
	 */
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}
 
	/**
	 * 最大页
	 */
	public int maxPage() {
		return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
	}
 
	/**
	 * 下一页
	 */
	public int nextPage() {
		return this.page < maxPage() ? this.page + 1 : this.page;
	}
	/**
	 * 上一页
	 */
	public int previousPage() {
		return this.page > 1 ? this.page-1 : this.page;
	}
 
	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
	}
	public PageBean(int page, int rows, int total, boolean pagination) {
		super();
		this.page = page;
		this.rows = rows;
		this.total = total;
		this.pagination = pagination;
	}
	
	public PageBean() {
		// TODO Auto-generated constructor stub
	}
}

主要界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- 引入自定义标签 -->
<%@ taglib prefix="z" uri="http://zking.sum" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link
	href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
	rel="stylesheet">
<script
	src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<title>书籍列表</title>
<style type="text/css">
.page-item input {
	padding: 0;
	width: 40px;
	height: 100%;
	text-align: center;
	margin: 0 6px;
}
 
.page-item input, .page-item b {
	line-height: 38px;
	float: left;
	font-weight: 400;
}
 
.page-item.go-input {
	margin: 0 10px;
}
</style>
</head>
<body>
	<form class="form-inline"
		action="${pageContext.request.contextPath }/book" method="post">
		<div class="form-group mb-2">
			<input type="text" class="form-control-plaintext" name="bname"
				placeholder="请输入书籍名称">
		</div>
		<button type="submit" class="btn btn-primary mb-2">查询</button>
	</form>
 
	<table class="table table-striped bg-success">
		<thead>
			<tr>
				<th scope="col">书籍id</th>
				<th scope="col">书籍名</th>
				<th scope="col">价格</th>
			</tr>
		</thead>
		<tbody>
		<c:forEach items="${book }" var="b">
			<tr>
				<td>${b. bid}</td>
				<td>${b.bname}</td>
				<td>${b.bprice}</td>
			</tr>
			</c:forEach>
 
		</tbody>
	</table>
<!-- 分页条	 -->
<z:page p="${pagebean}"></z:page>
	
</body>
</html>

pageTag设置

package com.ty.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.lxy.entity.PageBean;
import com.sun.org.apache.xml.internal.serializer.ToHTMLStream;
 
public class PageTag extends BodyTagSupport{
	private PageBean pageBean=new PageBean();//包含所有分页相关的东西
	//get/set方法
	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() {
		StringBuffer sb=new StringBuffer();
		// 隐藏的form表单--这个就是上一次请求下次重发的奥义所在
		//上一次请求的url
		sb.append("<form action='"+pageBean.getUrl()+"' id='pageBeanForm' method='post'>");
		sb.append(" <input type='hidden' name='page'>");
		//上一次请求的参数
		Map<String, String[]> paramMap = pageBean.getParamMap();
		if(paramMap!=null&&paramMap.size()>0) {
			Set<Entry<String, String[]>> entrySet = paramMap.entrySet();
			for (Entry<String, String[]> entry : entrySet) {
				//参数名
				String key=entry.getKey();
				//参数值
				String[] value = entry.getValue();
				for (String values : value) {
					//上一次请求的参数,再一次组装成了新的form表单
					//注意:page参数每次都会提交,我们需要避免
					if(!"page".equals(key)) {
						sb.append(" <input type='hidden' name='"+key+"' value='"+values+"'>");
					}
				}
			}
		}
		sb.append("</form>");
		//分页条
		sb.append("<ul class='pagination justify-content-center'>");
		sb.append(" <li class='page-item "+(pageBean.getPage()==1?"disabled":"")+"'><a class='page-link'");
		sb.append(" href='javascript:gotoPage(1)'>首页</a></li>");
		sb.append(" <li class='page-item "+(pageBean.getPage()==1?"disabled":"")+"'><a class='page-link'");
		sb.append(" href='javascript:gotoPage("+pageBean.previousPage()+")'>&lt;</a></li>");//上一页
		//sb.append(" <li class='page-item'><a class='page-link' href='#'>1</a></li>");
		//sb.append(" <li class='page-item'><a class='page-link' href='#'>2</a></li>");
		sb.append(" <li class='page-item active'><a class='page-link' href='#'>"+pageBean.getPage()+"</a></li>");//第几页
		sb.append(" <li class='page-item "+(pageBean.getPage()==pageBean.maxPage()?"disabled":"")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.nextPage()+")'>&gt;</a></li>");//下一页
		sb.append(" <li class='page-item "+(pageBean.getPage()==pageBean.maxPage()?"disabled":"")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.maxPage()+")'>尾页</a></li>");//最大页
		sb.append(" <li class='page-item go-input'><b>到第</b><input class='page-link'");
		sb.append(" type='text' id='skipPage' name='' /><b>页</b></li>");
		sb.append(" <li class='page-item go'><a class='page-link'");
		sb.append(" href='javascript:skipPage()'>确定</a></li>");
		sb.append(" <li class='page-item'><b>共"+pageBean.getTotal()+"</b></li>");
		sb.append("</ul>");
		//分页执行的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.maxPage()+") {");//最大页码
		sb.append(" alert('请输入1~"+pageBean.getTotal()+"的数字');");
		sb.append(" return;");
		sb.append(" }");
		sb.append(" gotoPage(page);");
		sb.append(" }");
		sb.append("</script>");
		return sb.toString();
	}
 
}
 

标签库描述的文件

标签库描述文件
<tag>
  <name>Page</name>
  <tag-class>com.lxy.tag.PageTag</tag-class>
  <body-content>JSP</body-content>
 
  <attribute>
     <!--  自定义标签的成员变量名称-->
            <name>pageBean</name>
             <!--  该成员变量是否必传 -->
            <required>true</required>
              <!--  是否支持EL表达式 -->
            <rtexprvalue>true</rtexprvalue>
        </attribute>
  </tag>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值