上次我们分享了自定义JSP标签foreach和select(http://t.csdn.cn/lfuiV),今天分享的内容是通用分页。
目录
Junit是一个Java语言的单元测试框架,能够针对单个方法进行测试
在我们要测试方法时,创建一个Junit进行测试
在当前类中Ctrl+N就能弹出次窗口,搜索Junit就能出来

- package com.oyang.dao;
-
- import java.util.List;
-
- import org.junit.After;
- import org.junit.Before;
- import org.junit.Test;
-
- import com.oyang.entity.Book;
- import com.oyang.util.PageBean;
-
- /**
- * Junit 能够针对单个方法进行测试
- * 相对于main方法而言,测试耦合新降低了
- * @author yang
- *
- * @date 2022年6月21日下午10:03: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 testList1() throws Exception {
- System.out.println("测试代码1");
- }
- }
右键,点击debug

测试结果:

我们在运行结果能看见,跟main方法的执行差不多,但是它们相比的话Junit还是有优势的。
优点:可以针对单个方法进行测试,相较于main方法而言,测试耦合性降低了
PageBean :
- package com.oyang.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 + "]";
- }
-
- }
EncodingFiter :
- package com.oyang.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();
- }
- }
-
- }
DBAccess :
- package com.oyang.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("数据库连接(关闭)成功");
- }
- }
CallBack<T>:谁调用,谁处理
- package com.oyang.util;
-
- import java.sql.ResultSet;
- import java.util.List;
-
- /**
- * 回调函数接口类的作用?
- * 谁调用谁处理
- *
- * @author yang
- *
- * @date 2022年6月21日下午8:13:46
- */
- public interface CallBack<T> {
-
- List<T> foreach(ResultSet rs);
-
- }
- package com.oyang.dao;
-
- import java.sql.Connection;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
-
- import com.oyang.entity.Book;
- import com.oyang.util.BaseDao;
- import com.oyang.util.DBAccess;
- import com.oyang.util.PageBean;
- import com.oyang.util.StringUtils;
-
- public class BookDao extends BaseDao<Book>{
- //以前
- public List<Book> list(Book book,PageBean PageBean) throws Exception {
- List<Book> list=new ArrayList<Book>();
- /**
- * 1.拿到数据库连接
- * 2.拿到域定义对象 PreparedStatement
- * 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;
- }
- java.sql.PreparedStatement ps = con.prepareStatement(sql);//重复代码2
- ResultSet rs=ps.executeQuery();//重复代码3
- while(rs.next()) {
- list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
- }
- return list;
- }
- }
- package com.oyang.dao;
-
- import java.sql.Connection;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.util.ArrayList;
- import java.util.List;
-
- import com.oyang.entity.Book;
- import com.oyang.util.BaseDao;
- import com.oyang.util.DBAccess;
- import com.oyang.util.PageBean;
- import com.oyang.util.StringUtils;
-
- public class BookDao extends BaseDao<Book>{
- //版本一
- 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<Book>();
- try {
- while(rs.next()) {
- list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
- }
- } catch (SQLException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return list;
- });
- }
- }

- package com.oyang.util;
-
- import java.sql.Connection;
- import java.sql.ResultSet;
- import java.util.ArrayList;
- import java.util.List;
-
- import com.oyang.entity.Book;
-
- /**
- * T代表的实体类,可以说是Book/User/Goods...
- * @author yang
- *
- * @date 2022年6月21日下午7:11:08
- */
- public class BaseDao<T> {//不知道查什么,就用泛型替代
- 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 y from (SELECT * FROM `t_mvc_book` where bname like '%圣墟%') a;
- //目的就是为了得到总记录数->得到总页数
- //SELECT * FROM `t_mvc_book` where bname like '%圣墟%' limit 10,10;
- /**
- * 1.拿到数据库连接
- * 2.拿到域定义对象 PreparedStatement
- * 3.执行SQL语句
- */
- Connection con = null;//重复代码1
- java.sql.PreparedStatement ps = null;//重复代码2
- ResultSet rs=null;//重复代码3
- if(PageBean!=null&&PageBean.isPagination()) {//分页时
- String countSQL=getCountSQL(sql);
- con=DBAccess.getConnection();//重复代码1
- ps=con.prepareStatement(countSQL);//重复代码2
- rs= ps.executeQuery();//重复代码3
- if(rs.next()) {
- //当前实体类就包含了总记录数
- PageBean .setTotal(rs.getString("y"));
- }
- String pageSQL=getpageSQL(sql,PageBean);
- con=DBAccess.getConnection();//重复代码1
- ps=con.prepareStatement(pageSQL);//重复代码2
- rs= ps.executeQuery();//重复代码3
- }else {// 不分页
- con=DBAccess.getConnection();//重复代码1
- ps=con.prepareStatement(sql);//重复代码2
- rs= ps.executeQuery();//重复代码3
- }
- //查询不同的表,必然要处理不同的结果集,谁调用谁处理
- //接口是调用方来实现
- return CallBack.foreach(rs);
- }
-
- /**
- * 拼装第N页的数据的SQL
- * @param sql
- * @return
- */
- private String getpageSQL(String sql, PageBean pageBean) {
- // TODO Auto-generated method stub
- return sql+" limit "+pageBean.getStartIndex() + ","+pageBean.getRows();
- }
-
-
- /**
- * 拼装符合条件总记录数的sql
- * @param sql
- * @param pageBean
- * @return
- */
- private String getCountSQL(String sql) {
- // TODO Auto-generated method stub
- return "select count(1) as y from ("+sql+") t ";
- }
-
- }

打印结果:

OK,今日的学习就到此结束啦,如果对个位看官有帮助的话可以留下免费的赞哦(收藏或关注也行),如果文章中有什么问题或不足以及需要改正的地方可以私信博主,博主会做出改正的。个位看官,小陽在此跟大家说拜拜啦!