今天给大家分享一个简单的小框架,通用的分页:
目录
一、前期准备
我们以MySql为数据库,拥有一些前期所需要的实体类……
DBAccess:
package com.zq.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("数据库连接(关闭)成功");
}
}
过滤器:
package com.zq.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.zq.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.zq.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);
}
}
配置文件:
#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/pro?useUnicode=true&characterEncoding=UTF-8&useSSL=false
user=root
pwd=123456
实体类Book:
package com.zq.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() {
// TODO Auto-generated constructor stub
}
public Book(int bid, String bname, float price) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
}
}
查询的Dao方法:
package com.zq.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.zq.entity.Book;
import com.zq.util.BaseDao;
import com.zq.util.CallBack;
import com.zq.util.DBAccess;
import com.zq.util.PageBean;
import com.zq.util.StringUtils;
public class BookDao extends BaseDao<Book> {
public List<Book> list(Book book,PageBean pageBean) throws Exception{
List<Book> list = new ArrayList<Book>();
//拿到数据库连接
Connection con = DBAccess.getConnection();
//拿到执行对象
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;
}
//执行sql语句
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()) {
list.add(new Book(rs.getInt(1), rs.getString(2),rs.getFloat(3)));
}
return list;
}
//增删改 junit
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);
}
}
}
做好这些部分我们的基础就完成了,接下来就是编码工作进行编写通用分页了!
基础结果:
二、测试工具类Junit
第二个内容我来和大家分享一个测试工具类,作用是可以在一个测试类中写多个方法进行可供选择的测试:
①首先我们第一步要在运行测试的类同包的情况下建立,如我这里在BookDao里面建立一个Junit4,选择包右键或者在BookDao按住Ctrl+n
②选择Junit Text Case,点击Next,最上面选择New JUnit 4 text,下面的setUp() tearDown()看自己需求选,点击ok就可以建立一个测试类
③到这里点击就创建好一个测试类了:
package com.zq.dao;
import static org.junit.Assert.*;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.zq.entity.Book;
import com.zq.util.PageBean;
/**
* junit能够正对单个方法进行测试
* 相较于main方法而言,测试耦合性降低了
* @author 张强
*
* 2022年6月22日上午9:50:58
*/
public class BookDaoTest {
@Before
public void setUp() throws Exception {
System.out.println("被测试方法测试前调用");
}
@After
public void tearDown() throws Exception {
System.out.println("被测试方法测试后调用");
}
@Test
public void testList() {
List<Book> list;
try {
list = new BookDao().list(new Book(), null);
for (Book book : list) {
System.out.println(book);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
④将我们要测试的代码放入 testList()的方法中,便可以测试了,测试方法:双击方法名——》右键——》Run as
优点:可以针对单个方法进行测试,相较于main方法而言,测试耦合性降低了
三、Dao方法分析与实例
大家可以发现我们在做完基础的代码后我们的重复代码还是有点多的,那么现在优化重复代码
我们建立一个泛类,来优化代码BeseDao.java:
package com.zq.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.zq.entity.Book;
/**
* T代表的是实体类 是随意的哪种实体类
* @author 张强
*
* 2022年6月22日上午9:55:03
*/
public class BaseDao<T> {
public List<T> executeQuery(String sql,PageBean pageBean ,CallBack<T> callBack) throws Exception{
//拿到数据库连接
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
//拼接sql 从上面得到总记录数——》得到总页数
//判断是否需要分页
if(pageBean!= null &&pageBean.isPagination()) {
String countSql = getCountSql(sql);
con = DBAccess.getConnection();
ps = con.prepareStatement(countSql);
rs = ps.executeQuery();
if(rs.next()) {
//当前实体类就包含了总记录数
pageBean.setTotal(rs.getString("n"));
}
String pageSQL = getpageSql(sql,pageBean);
con = DBAccess.getConnection();
ps = con.prepareStatement(pageSQL);
rs = ps.executeQuery();
}else {
//不分页
con = DBAccess.getConnection();
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
}
/**
* 我们查询不同的表,结果集也是不一样的,我们应该怎么做呢?
* 我们将结果集传给CallBack接口,在接口中返回一个集合
* 在接口中处理rs
*/
return callBack.foreach(rs);
}
/**
* 拼装第N页数据的Sql
* @param sql
* @param pageBean
* @return
*/
private String getpageSql(String sql, PageBean pageBean) {
return sql+ " limit " + pageBean.getStartIndex() +" , " +pageBean.getRows();
}
/**
* 拼接sql语句
* @param sql 原始sql语句
* @return 最后拼接的SQL语句获得总数据数
*/
private String getCountSql(String sql) {
return "select count(1) as n from ("+sql+") t";
}
}
这里需要实现一个接口,以便于处理各种调用事物 CallBack.java
package com.zq.util;
import java.sql.ResultSet;
import java.util.List;
/**
* 回调函数接口类的作用
* 谁调用谁处理
* @author 张强
*
* 2022年6月22日上午9:56:46
*/
public interface CallBack<T> {
List<T> foreach(ResultSet rs);
}
到这里我么就可以改变Dao方法,将分页的内容加进来:
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 (Exception e) {
e.printStackTrace();
}
return list;
});
}
接下来就OK了,测试一下,直接分页第二页的数据:
@Test
public void testList3() {
List<Book> list;
try {
Book b = new Book();
PageBean pageBean =new PageBean();
pageBean.setPage(2);
list = new BookDao().list2(b, pageBean);
for (Book book : list) {
System.out.println(book);
}
} catch (Exception e) {
e.printStackTrace();
}
}
结果为: