哈喽~大家好,我又又又来啦~~~今天给大家分享的是我们的通用分页,话不多说!跟着我一起来了解一下吧~
首先我们先来看一下我们的分页工具
目录
一、PageBean
package com.zlp2.util;
/**
* 分页工具类
*
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
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 + "]";
}
}
二、通用分页
如何连接数据库:
package com.zlp.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.cj.jdbc.Driver".equals(driver);
}
public static void main(String[] args) {
Connection conn = DBAccess.getConnection();
System.out.println(conn);
DBAccess.close(conn);
System.out.println("isOracle:" + isOracle());
System.out.println("isSQLServer:" + isSQLServer());
System.out.println("isMysql:" + isMysql());
System.out.println("数据库连接(关闭)成功");
}
}
需要记得修改用户名密码和库名
#oracle9i
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:orcl
#user=scott
#pwd=123
#sql2005
#driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#url=jdbc:sqlserver://localhost:1433;DatabaseName=test1
#user=sa
#pwd=123
#sql2000
#driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
#url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=unit6DB
#user=sa
#pwd=888888
#mysql
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/t280?useUnicode=true&characterEncoding=UTF-8&useSSL=false
user=root
pwd=123456
中文乱码处理:
package com.zlp.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();
}
}
}
判断字符是否为空:
package com.zlp.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);
}
}
实体类:
package com.zlp.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() {
// TODO Auto-generated constructor stub
}
}
basedao:
package com.zlp.util;
import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.zlp.entity.Book;
public class BaseDao<T> {
/*public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack) throws Exception{
//**
* 1.拿到数据库连接
* 2.拿到域定义对象(preparestatement)
* 3.执行SQL语句
*//*
Connection con = DBAccess.getConnection();//连接对象 //重复代码1
java.sql.PreparedStatement pst = con.prepareStatement(sql );//执行对象 //重复代码2
ResultSet rs = pst.executeQuery();//重复代码3
while(rs.next()){
//实例化并且赋值加入集合中去
list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
}
return list;
//查询不同的表,必然要处理不同的结果集
// 接口是调用放来实现
return callBack.foreach(rs);
}*/
public List<T> executeQuery(String sql,PageBean pageBean,CallBack<T> callBack) throws Exception{
// select * from t_mvc_book where bname like '%圣墟%';
// 从上面得到 select count(1) as n from (select * from t_mvc_book where bname like '%圣墟%') t;
// 目的是为了得到总记录数->得到总页数
// select * from t_mvc_book where bname like '%圣墟%' limit 10,10;
/*
1.拿到数据库连接
2.拿到域定义对象(preparestatement)
3.执行SQL语句*/
Connection con = null;//连接对象 //重复代码1
java.sql.PreparedStatement pst = null;//执行对象 //重复代码2
ResultSet rs = null;//重复代码3
if(pageBean !=null && pageBean.isPagination()) {//分页
String countSQL = getCountSQL(sql);
con = DBAccess.getConnection();//连接对象 //重复代码1
pst = con.prepareStatement(countSQL);//执行对象 //重复代码2
rs = pst.executeQuery();//重复代码3
if(rs.next()) {
// pageBean包含了当前实体类的总记录数
pageBean.setTotal(rs.getString("n"));
}
String pageSQL = getPageSQL(sql,pageBean);
con = DBAccess.getConnection();//连接对象 //重复代码1
pst = con.prepareStatement(pageSQL);//执行对象 //重复代码2
rs = pst.executeQuery();//重复代码3
}
else {//不分页
con = DBAccess.getConnection();//连接对象 //重复代码1
pst = con.prepareStatement(sql);//执行对象 //重复代码2
rs = pst.executeQuery();//重复代码3
}
return callBack.foreach(rs);
}
/**
* 拼装第n页的数据
*
* @param sql
* @param pageBean
* @return
*/
private String getPageSQL(String sql, PageBean pageBean) {
return sql+" limit "+pageBean.getStartIndex()+","+pageBean.getRows();
}
/**
* 拼装符合条件总记录数的SQL
* @param sql
* @return
*/
private String getCountSQL(String sql) {
// select * from t_mvc_book where bname like '%圣墟%';
// 从上面得到 select count(1) as n from (select * from t_mvc_book where bname like '%圣墟%') t;
return "select count(1) as n from ("+sql+") t";
}
}
bookDao:
package com.zlp.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import com.zlp.entity.Book;
import com.zlp.util.BaseDao;
import com.zlp.util.CallBack;
import com.zlp.util.DBAccess;
import com.zlp.util.PageBean;
import com.zlp.util.StringUtils;
public class BookDao extends BaseDao<Book>{
// S阶段
public List<Book> list(Book book,PageBean pageBean) throws Exception{
List<Book> list=new ArrayList<Book>();
/**
* 1.拿到数据库连接
* 2.拿到preparestatement
* 3.执行sql语句
*/
Connection con = DBAccess.getConnection();//重复代码1
String sql="select * from t_mvc_book where 1=1 ";
String bname = book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql+=" and bname like '%"+bname+"%'";
}
int bid=book.getBid();
if(bid!=0) {
sql+=" and bid =" +bid;
}
PreparedStatement pst = con.prepareStatement(sql);//重复代码2
ResultSet rs = pst.executeQuery();//重复代码3
while(rs.next()) {
list.add(new Book(rs.getInt("bid"),rs.getString("bname"),rs.getFloat("price")));
}
return list;
}
// Y极端第1个版本
public List<Book> list2(Book book,PageBean pageBean) throws Exception{
String sql="select * from t_mvc_book where 1=1 ";
String bname = book.getBname();
if(StringUtils.isNotBlank(bname)) {
sql+=" and bname like '%"+bname+"%'";
}
int bid=book.getBid();
if(bid!=0) {
sql+=" and bid =" +bid;
}
return super.executeQuery(sql, pageBean, rs-> {
List<Book> list=new ArrayList<>();
try {
while(rs.next()) {
list.add(new Book(rs.getInt("bid"),rs.getString("bname"),rs.getFloat("price")));
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
});
}
// 增删改
public static void main(String[] args) throws Exception {
// List<Book> list = new BookDao().list(new Book(), null);
// for (Book book : list) {
// System.out.println(book);
// }
}
}
CallBack接口:
package com.zlp.util;
import java.sql.ResultSet;
import java.util.List;
/**
* 回调函数接口类的作用?
* 谁调用谁处理
* @author zjjt
*/
public interface CallBack<T> {
List<T> foreach(ResultSet rs);
}
今天的分享就到这啦~我们下期再见!!!!