通用分页(二)
完善的 分页通用代码一 https://blog.csdn.net/wx1762813417/article/details/96644761
让数据分页在网页中显示
视图层 需要用到的新方法
req.getRequestURL() //获取请求全路径
Map<String, String[]> parameterMap = req.getParameterMap();//获得请求中的所有参数
具体思路:
1、补全servlet
2、页面展示
3、分页重要参数(page、rows、是否分页、上一次请求、上一次的表单参数)
4、自定义分页标签
代码演示:
代码对应的位置
1 . com.hyf.util 工具类
首先链接数据:
- 读取同级目录下的配置文件 config.properties 获得 链接数据库地址 ,url ,用户名,和密码
#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.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/tb_student?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
user=root
pwd=123
链接数据库需要改动的地方:
链接 数据库工具类:DBAccess.java
package com.hyf.util;
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 DBAccess {
private static String driver;
private static String url;
private static String user;
private static String password;
static {// 静态块执行一次,加载 驱动一次
try {
InputStream is = DBAccess.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 getConnection() {
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 close(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.jdbc.Driver".equals(driver);
}
public static void main(String[] args) {
Connection conn = DBAccess.getConnection();
DBAccess.close(conn);
System.out.println("isOracle:" + isOracle());
System.out.println("isSQLServer:" + isSQLServer());
System.out.println("isMysql:" + isMysql());
System.out.println("数据库连接(关闭)成功");
}
}
解决中文乱码 EncodingFiter.java
package com.hyf.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();
}
}
}
判断字符串等于null或去空格后等于 StringUtils.java
package com.hyf.util;
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
}
分页工具类 PageBean
package com.hyf.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 []> paMap=new HashMap<>();
/**
* pageBean 初始化方法
*/
public void setRequest(HttpServletRequest req) {
this.setPage(req.getParameter("page"));
this.setRows(req.getParameter("rows"));
this.setPagination(req.getParameter("pagination"));
this.setUrl(req.getRequestURL().toString());
this.setPaMap(req.getParameterMap());
}
public void setPagination(String pagination) {
if("false".equals(pagination)) {
this.setPagination(false);
}
}
/**
* 改变 rows属性 页大小
* @param rows
*/
public void setRows(String rows) {
if(StringUtils.isNotBlank(rows)) {
this.setRows(Integer.valueOf(rows));
}
}
/**
* 改变 page属性 页码的大小
* @param page
*/
public void setPage(String page) {
if(StringUtils.isNotBlank(page)) {
this.setPage(Integer.valueOf(page));
}
}
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;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String[]> getPaMap() {
return paMap;
}
public void setPaMap(Map<String, String[]> paMap) {
this.paMap = paMap;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
/**
* 获取上一页的方法
* @return
*/
public int getPreviousPage() {
return this.page>1 ? this.page-1 : this.page;
}
/**
* 获取下一页的方法
* @return
*/
public int getNextPage() {
return this.page<this.getMaxPage() ? this.page+1 : this.getMaxPage();
}
/**
* 获取最大页码
* @return
*/
public int getMaxPage() {
return this.total % this.rows == 0 ? this.total/this.rows : this.total/this.rows+1 ;
}
}
处理所有的表的通用的增删改查的基类 BaseDao
package com.hyf.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.hyf.entity.Book;
/**
* 用来处理所有的表的通用的增删改查的基类
*
* @author 17628
*
*/
public class BaseDao<T> {
/**
* @param sql
* 可能查不同的表,那么意味着sql语句是变化的,那么它是从子类处理好在传递到父类的
* @param clz
* 需要返回不同的对象集合 Book.class/Order.class
* @param pagebean
* 可能要分页
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List<T> executeQuery(String sql, Class clz, PageBean pagebean) throws Exception {
List<T> list = new ArrayList<>();
Connection con = DBAccess.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
if(pagebean !=null && pagebean.isPagination()) {
// 分页代码
/*
* 1、分页是与pagebean中total,意味真需要查询数据库得到total赋值给pagebean
* 2、查询出符合条件的某一页的数据
*/
String countSql=getCountSql(sql);
ps=con.prepareStatement(countSql);
rs=ps.executeQuery();
if(rs.next()) {
pagebean.setTotal(rs.getInt(1));
}
// 进行拼接
String pageSql=getPageSql(sql,pagebean);
ps = con.prepareStatement(pageSql);
rs =ps.executeQuery();
}else {
ps = con.prepareStatement(sql);
rs =ps.executeQuery();
}
T t = null; // 泛型传过来的对象 进行实例化
while(rs.next()) {
t=(T) clz.newInstance();
Field [] fields = clz.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
f.set(t, rs.getObject(f.getName()));
}
list.add(t);
}
return list;
}
private String getPageSql(String sql,PageBean pagebean) {
return sql + "limit "+pagebean.getStartIndex()+","+pagebean.getRows() ;
}
private String getCountSql(String sql) { // 获得总记录 查询的数据有多少数据
return "select count(1) from ("+sql+") t";
}
}
2.com.hyf.entity 实体类
package com.hyf.entity;
public class Book {
private int bid;
private String bname;
private float price;
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();
}
}
3.com.hyf.dao 方法
BookDao 他与要继承父类 BaseDao 定义一个sql语句来调用父类的方法进行分页
package com.hyf.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.hyf.entity.Book;
import com.hyf.util.BaseDao;
import com.hyf.util.DBAccess;
import com.hyf.util.PageBean;
import com.hyf.util.StringUtils;
public class BookDao extends BaseDao<Book> {
public List<Book> list(Book book,PageBean pageBean) throws Exception{
// sql 语句
String sql="select * from t_mvc_book where true ";
String bname=book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql +=" and bname like '%"+bname+"%'";
}
return super.executeQuery(sql, Book.class, pageBean);
}
}
4 com.hyf.tag 助手类
这个助手类的作用就是把它进行封装,通过传入 PageBean 来控制分页。封装使代码更简洁,并且
提高代码多次使用
package com.hyf.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.hyf.util.PageBean;
public class PageTag extends BodyTagSupport {
private static final long serialVersionUID = 383258790166308355L;
private PageBean pageBean;
public int doStartTag() throws JspException {
JspWriter out = pageContext.getOut();
try {
out.print(toHTML());
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
private String toHTML() {
StringBuilder sb = new StringBuilder();
System.out.println("pageBean.getUrl()"+pageBean.getUrl());
// 拼接下一次分页请求搜提交的分页表单
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) {
for(String value :entry.getValue() ) {
if(!"page".equals(entry.getKey())) {
sb.append("<input type='hidden' name='"+entry.getKey()+"' value='"+value+"'>");
System.out.println("entry.getKey()"+entry.getKey());
System.out.println("value"+value);
}
}
}
}
sb.append("</form>");
// 拼接分页条
sb.append("<div style='text-align: right; font-size: 12px;'>");
sb.append(" 每页"+pageBean.getRows()+"条,共"+pageBean.getTotal()+"条,第"+pageBean.getPage()+"页,共"+pageBean.getMaxPage()+"页 ");
sb.append(" <a href='javascript:gotoPage(1)'>首页</a> ");
sb.append(" <a href='javascript:gotoPage("+pageBean.getPreviousPage()+")'>上一页</a> ");
sb.append(" <a href='javascript:gotoPage("+pageBean.getNextPage()+")'>下一页</a> ");
sb.append(" <a href='javascript:gotoPage("+pageBean.getMaxPage()+")'>尾页</a> ");
sb.append(" <input type='text' id='skipPage' style='text-align: center; font-size: 12px; width: 50px;'> ");
sb.append(" <a href='javascript:skipPage()'>Go</a>");
sb.append(" </div>");
// 拼接分页的javascript 代码
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();
}
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
}
配置 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>hyf 1.1 core library</description>
<display-name>hyf core</display-name>
<tlib-version>1.1</tlib-version>
<short-name>c</short-name>
<uri>/hyf</uri>
<tag>
<name>page</name>
<tag-class>com.hyf.tag.PageTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>pageBean</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
5 com.hyf.sevlete
package com.hyf.servlet;
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.hyf.dao.BookDao;
import com.hyf.entity.Book;
import com.hyf.util.PageBean;
public class BookServlet extends HttpServlet {
private static final long serialVersionUID = -8665397287433149998L;
private BookDao bookDao = new BookDao();
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String bname=req.getParameter("bname"); // 页面传来查询书籍的值
Book b = new Book();
PageBean pagebean = new PageBean();
pagebean.setPagination(true); // 设置要不要分页 默认为true
b.setBname(bname);
pagebean.setRequest(req);
try {
List<Book> l = new BookDao().list(b, pagebean);
req.setAttribute("bookList", l);
req.setAttribute("pagebean", pagebean);
req.getRequestDispatcher("/bookList.jsp").forward(req, resp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
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="/hyf" prefix="h"%>
<!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">
<!--用户设置查询 一页20条记录 -->
<!-- <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>
</body>
<h:page pageBean="${pagebean}"></h:page>
</html>
直接运行:
用户控制
不分页:
把这行代码注释去掉
输出:
控制页码行数:
把这行代码注释去掉
输出: