• J2EE基础-通用分页


    前言

    上次我们分享了自定义JSP标签foreach和select(http://t.csdn.cn/lfuiV),今天分享的内容是通用分页。


    目录

    一、Junit的运用

    A、创建

    B、使用

    二、通用分页

    分页工具类

    中文乱码处理类

    数据库工具类

    回调函数接口类

    Dao方法

    以前写的BookDao 

    测试结果:

    使用通用分页的BookDao

    分页

    MySQL分页语句

    BaseDao:

    测试


    一、Junit的运用

    Junit是一个Java语言的单元测试框架,能够针对单个方法进行测试

    A、创建

    在我们要测试方法时,创建一个Junit进行测试

    在当前类中Ctrl+N就能弹出次窗口,搜索Junit就能出来

    B、使用

    1. package com.oyang.dao;
    2. import java.util.List;
    3. import org.junit.After;
    4. import org.junit.Before;
    5. import org.junit.Test;
    6. import com.oyang.entity.Book;
    7. import com.oyang.util.PageBean;
    8. /**
    9. * Junit 能够针对单个方法进行测试
    10. * 相对于main方法而言,测试耦合新降低了
    11. * @author yang
    12. *
    13. * @date 2022年6月21日下午10:03:58
    14. */
    15. public class BookDaoTest {
    16. @Before
    17. public void setUp() throws Exception {
    18. System.out.println("对测试方法执行前调用");
    19. }
    20. @After
    21. public void tearDown() throws Exception {
    22. System.out.println("对测试方法执行之后调用");
    23. }
    24. @Test
    25. public void testList1() throws Exception {
    26. System.out.println("测试代码1");
    27. }
    28. }

    右键,点击debug

     测试结果:

     我们在运行结果能看见,跟main方法的执行差不多,但是它们相比的话Junit还是有优势的。

    优点:可以针对单个方法进行测试,相较于main方法而言,测试耦合性降低了

    二、通用分页

    分页工具类

    PageBean :

    1. package com.oyang.util;
    2. /**
    3. * 分页工具类
    4. *
    5. */
    6. public class PageBean {
    7. private int page = 1;// 页码
    8. private int rows = 10;// 页大小
    9. private int total = 0;// 总记录数
    10. private boolean pagination = true;// 是否分页
    11. public PageBean() {
    12. super();
    13. }
    14. public int getPage() {
    15. return page;
    16. }
    17. public void setPage(int page) {
    18. this.page = page;
    19. }
    20. public int getRows() {
    21. return rows;
    22. }
    23. public void setRows(int rows) {
    24. this.rows = rows;
    25. }
    26. public int getTotal() {
    27. return total;
    28. }
    29. public void setTotal(int total) {
    30. this.total = total;
    31. }
    32. public void setTotal(String total) {
    33. this.total = Integer.parseInt(total);
    34. }
    35. public boolean isPagination() {
    36. return pagination;
    37. }
    38. public void setPagination(boolean pagination) {
    39. this.pagination = pagination;
    40. }
    41. /**
    42. * 获得起始记录的下标
    43. *
    44. * @return
    45. */
    46. public int getStartIndex() {
    47. return (this.page - 1) * this.rows;
    48. }
    49. @Override
    50. public String toString() {
    51. return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
    52. }
    53. }

    中文乱码处理类

    EncodingFiter :

    1. package com.oyang.util;
    2. import java.io.IOException;
    3. import java.util.Iterator;
    4. import java.util.Map;
    5. import java.util.Set;
    6. import javax.servlet.Filter;
    7. import javax.servlet.FilterChain;
    8. import javax.servlet.FilterConfig;
    9. import javax.servlet.ServletException;
    10. import javax.servlet.ServletRequest;
    11. import javax.servlet.ServletResponse;
    12. import javax.servlet.http.HttpServletRequest;
    13. import javax.servlet.http.HttpServletResponse;
    14. /**
    15. * 中文乱码处理
    16. *
    17. */
    18. public class EncodingFiter implements Filter {
    19. private String encoding = "UTF-8";// 默认字符集
    20. public EncodingFiter() {
    21. super();
    22. }
    23. public void destroy() {
    24. }
    25. public void doFilter(ServletRequest request, ServletResponse response,
    26. FilterChain chain) throws IOException, ServletException {
    27. HttpServletRequest req = (HttpServletRequest) request;
    28. HttpServletResponse res = (HttpServletResponse) response;
    29. // 中文处理必须放到 chain.doFilter(request, response)方法前面
    30. res.setContentType("text/html;charset=" + this.encoding);
    31. if (req.getMethod().equalsIgnoreCase("post")) {
    32. req.setCharacterEncoding(this.encoding);
    33. } else {
    34. Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
    35. Set set = map.keySet();// 取出所有参数名
    36. Iterator it = set.iterator();
    37. while (it.hasNext()) {
    38. String name = (String) it.next();
    39. String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
    40. for (int i = 0; i < values.length; i++) {
    41. values[i] = new String(values[i].getBytes("ISO-8859-1"),
    42. this.encoding);
    43. }
    44. }
    45. }
    46. chain.doFilter(request, response);
    47. }
    48. public void init(FilterConfig filterConfig) throws ServletException {
    49. String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
    50. if (null != s && !s.trim().equals("")) {
    51. this.encoding = s.trim();
    52. }
    53. }
    54. }

    数据库工具类

    DBAccess :

    1. package com.oyang.util;
    2. import java.io.InputStream;
    3. import java.sql.Connection;
    4. import java.sql.DriverManager;
    5. import java.sql.ResultSet;
    6. import java.sql.SQLException;
    7. import java.sql.Statement;
    8. import java.util.Properties;
    9. /**
    10. * 提供了一组获得或关闭数据库对象的方法
    11. *
    12. */
    13. public class DBAccess {
    14. private static String driver;
    15. private static String url;
    16. private static String user;
    17. private static String password;
    18. static {// 静态块执行一次,加载 驱动一次
    19. try {
    20. InputStream is = DBAccess.class
    21. .getResourceAsStream("config.properties");
    22. Properties properties = new Properties();
    23. properties.load(is);
    24. driver = properties.getProperty("driver");
    25. url = properties.getProperty("url");
    26. user = properties.getProperty("user");
    27. password = properties.getProperty("pwd");
    28. Class.forName(driver);
    29. } catch (Exception e) {
    30. e.printStackTrace();
    31. throw new RuntimeException(e);
    32. }
    33. }
    34. /**
    35. * 获得数据连接对象
    36. *
    37. * @return
    38. */
    39. public static Connection getConnection() {
    40. try {
    41. Connection conn = DriverManager.getConnection(url, user, password);
    42. return conn;
    43. } catch (SQLException e) {
    44. e.printStackTrace();
    45. throw new RuntimeException(e);
    46. }
    47. }
    48. public static void close(ResultSet rs) {
    49. if (null != rs) {
    50. try {
    51. rs.close();
    52. } catch (SQLException e) {
    53. e.printStackTrace();
    54. throw new RuntimeException(e);
    55. }
    56. }
    57. }
    58. public static void close(Statement stmt) {
    59. if (null != stmt) {
    60. try {
    61. stmt.close();
    62. } catch (SQLException e) {
    63. e.printStackTrace();
    64. throw new RuntimeException(e);
    65. }
    66. }
    67. }
    68. public static void close(Connection conn) {
    69. if (null != conn) {
    70. try {
    71. conn.close();
    72. } catch (SQLException e) {
    73. e.printStackTrace();
    74. throw new RuntimeException(e);
    75. }
    76. }
    77. }
    78. public static void close(Connection conn, Statement stmt, ResultSet rs) {
    79. close(rs);
    80. close(stmt);
    81. close(conn);
    82. }
    83. public static boolean isOracle() {
    84. return "oracle.jdbc.driver.OracleDriver".equals(driver);
    85. }
    86. public static boolean isSQLServer() {
    87. return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
    88. }
    89. public static boolean isMysql() {
    90. return "com.mysql.cj.jdbc.Driver".equals(driver);
    91. }
    92. public static void main(String[] args) {
    93. Connection conn = DBAccess.getConnection();
    94. System.out.println(conn);
    95. DBAccess.close(conn);
    96. System.out.println("isOracle:" + isOracle());
    97. System.out.println("isSQLServer:" + isSQLServer());
    98. System.out.println("isMysql:" + isMysql());
    99. System.out.println("数据库连接(关闭)成功");
    100. }
    101. }

    回调函数接口类

    CallBack<T>:谁调用,谁处理

    1. package com.oyang.util;
    2. import java.sql.ResultSet;
    3. import java.util.List;
    4. /**
    5. * 回调函数接口类的作用?
    6. * 谁调用谁处理
    7. *
    8. * @author yang
    9. *
    10. * @date 2022年6月21日下午8:13:46
    11. */
    12. public interface CallBack<T> {
    13. List<T> foreach(ResultSet rs);
    14. }

    Dao方法

    以前写的BookDao 

    1. package com.oyang.dao;
    2. import java.sql.Connection;
    3. import java.sql.ResultSet;
    4. import java.sql.SQLException;
    5. import java.util.ArrayList;
    6. import java.util.List;
    7. import com.oyang.entity.Book;
    8. import com.oyang.util.BaseDao;
    9. import com.oyang.util.DBAccess;
    10. import com.oyang.util.PageBean;
    11. import com.oyang.util.StringUtils;
    12. public class BookDao extends BaseDao<Book>{
    13. //以前
    14. public List<Book> list(Book book,PageBean PageBean) throws Exception {
    15. List<Book> list=new ArrayList<Book>();
    16. /**
    17. * 1.拿到数据库连接
    18. * 2.拿到域定义对象 PreparedStatement
    19. * 3.执行SQL语句
    20. */
    21. Connection con = DBAccess.getConnection();//重复代码1
    22. String sql="select *from t_mvc_book where 1=1 ";
    23. String bname = book.getBname();
    24. if(StringUtils.isNotBlank(bname)) {
    25. sql+=" and bname like '%"+bname+"%' ";
    26. }
    27. int bid = book.getBid();
    28. if(bid!=0) {
    29. sql+=" and bid ="+bid;
    30. }
    31. java.sql.PreparedStatement ps = con.prepareStatement(sql);//重复代码2
    32. ResultSet rs=ps.executeQuery();//重复代码3
    33. while(rs.next()) {
    34. list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
    35. }
    36. return list;
    37. }
    38. }

    测试结果:

    使用通用分页的BookDao

    1. package com.oyang.dao;
    2. import java.sql.Connection;
    3. import java.sql.ResultSet;
    4. import java.sql.SQLException;
    5. import java.util.ArrayList;
    6. import java.util.List;
    7. import com.oyang.entity.Book;
    8. import com.oyang.util.BaseDao;
    9. import com.oyang.util.DBAccess;
    10. import com.oyang.util.PageBean;
    11. import com.oyang.util.StringUtils;
    12. public class BookDao extends BaseDao<Book>{
    13. //版本一
    14. public List<Book> list2(Book book,PageBean PageBean) throws Exception {
    15. String sql="select *from t_mvc_book where 1=1 ";
    16. String bname = book.getBname();
    17. if(StringUtils.isNotBlank(bname)) {
    18. sql+=" and bname like '%"+bname+"%' ";
    19. }
    20. int bid = book.getBid();
    21. if(bid!=0) {
    22. sql+=" and bid ="+bid;
    23. }
    24. return super.executeQuery(sql, PageBean, rs->{
    25. List<Book> list=new ArrayList<Book>();
    26. try {
    27. while(rs.next()) {
    28. list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
    29. }
    30. } catch (SQLException e) {
    31. // TODO Auto-generated catch block
    32. e.printStackTrace();
    33. }
    34. return list;
    35. });
    36. }
    37. }

    分页

    MySQL分页语句

    BaseDao:

    1. package com.oyang.util;
    2. import java.sql.Connection;
    3. import java.sql.ResultSet;
    4. import java.util.ArrayList;
    5. import java.util.List;
    6. import com.oyang.entity.Book;
    7. /**
    8. * T代表的实体类,可以说是Book/User/Goods...
    9. * @author yang
    10. *
    11. * @date 2022年6月21日下午7:11:08
    12. */
    13. public class BaseDao<T> {//不知道查什么,就用泛型替代
    14. public List<T> executeQuery(String sql,PageBean PageBean,CallBack<T> CallBack) throws Exception {
    15. //SELECT * FROM `t_mvc_book` where bname like '%圣墟%'
    16. //从上面得到select count(1) as y from (SELECT * FROM `t_mvc_book` where bname like '%圣墟%') a;
    17. //目的就是为了得到总记录数->得到总页数
    18. //SELECT * FROM `t_mvc_book` where bname like '%圣墟%' limit 10,10;
    19. /**
    20. * 1.拿到数据库连接
    21. * 2.拿到域定义对象 PreparedStatement
    22. * 3.执行SQL语句
    23. */
    24. Connection con = null;//重复代码1
    25. java.sql.PreparedStatement ps = null;//重复代码2
    26. ResultSet rs=null;//重复代码3
    27. if(PageBean!=null&&PageBean.isPagination()) {//分页时
    28. String countSQL=getCountSQL(sql);
    29. con=DBAccess.getConnection();//重复代码1
    30. ps=con.prepareStatement(countSQL);//重复代码2
    31. rs= ps.executeQuery();//重复代码3
    32. if(rs.next()) {
    33. //当前实体类就包含了总记录数
    34. PageBean .setTotal(rs.getString("y"));
    35. }
    36. String pageSQL=getpageSQL(sql,PageBean);
    37. con=DBAccess.getConnection();//重复代码1
    38. ps=con.prepareStatement(pageSQL);//重复代码2
    39. rs= ps.executeQuery();//重复代码3
    40. }else {// 不分页
    41. con=DBAccess.getConnection();//重复代码1
    42. ps=con.prepareStatement(sql);//重复代码2
    43. rs= ps.executeQuery();//重复代码3
    44. }
    45. //查询不同的表,必然要处理不同的结果集,谁调用谁处理
    46. //接口是调用方来实现
    47. return CallBack.foreach(rs);
    48. }
    49. /**
    50. * 拼装第N页的数据的SQL
    51. * @param sql
    52. * @return
    53. */
    54. private String getpageSQL(String sql, PageBean pageBean) {
    55. // TODO Auto-generated method stub
    56. return sql+" limit "+pageBean.getStartIndex() + ","+pageBean.getRows();
    57. }
    58. /**
    59. * 拼装符合条件总记录数的sql
    60. * @param sql
    61. * @param pageBean
    62. * @return
    63. */
    64. private String getCountSQL(String sql) {
    65. // TODO Auto-generated method stub
    66. return "select count(1) as y from ("+sql+") t ";
    67. }
    68. }

    测试

    打印结果:

     


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

  • 相关阅读:
    pcl--第五节 点云表面法线估算
    【C++】内联函数&auto&范围for循环&nullptr
    我的学校网页期末作业(纯html+css实现)
    动态住宅代理VS静态住宅代理,怎么选择?
    ORACLE设置快照回滚点
    Windows任务计划程序Task Scheduler笔记
    Oracle中ALTER TABLE的五种用法(一)
    3.蓝牙模块HC-08
    C# Sqlite数据库的搭建及使用技巧
    TensorFlow2从磁盘读取图片数据集的示例(tf.data.Dataset.list_files)
  • 原文地址:https://blog.csdn.net/weixin_65211978/article/details/125407191