通用分页1
Posted huxiaocong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通用分页1相关的知识,希望对你有一定的参考价值。
首先连接数据库
设置连接数据库的properties文件(mysql).
#mysql5
#加载驱动字符串
driver=com.mysql.jdbc.Driver
#连接字符串,将?前的sys为你的数据库名
url=jdbc:mysql://127.0.0.1:3306/sys?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
#用户名
user=root
#密码
pwd=123
创建一个连接关闭数据库的工具类(别忘了导入jar包)
package com.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("数据库连接(关闭)成功");
运行这个类如果输出如下,代表连接成功:
创建与要查询的表相对应的实体类:
package com.entity; public class Book private int bid; private String bname; private float price; public Book() super(); // TODO Auto-generated constructor stub public Book(int bid, String bname, float price) super(); this.bid = bid; this.bname = bname; this.price = 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;
编写过滤器处理中文乱码
package com.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.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.java
分页三要素
page 页码 视图层传递过来
rows 页大小 视图层传递过来
total 总记录数 后台查出来
package com.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 + "]";
编写通用的dao层进行查询分页
package com.dao; 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.entity.Book; import com.util.DBAccess; import com.util.PageBean; import com.util.StringUtils; /** * T代表你要对那个实体类对应表进行分页查询 * @author 旧城 * * @param <T> */ public class BaseDao<T> public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException Connection con=DBAccess.getConnection(); PreparedStatement ps=null; ResultSet rs=null; List<T> list=new ArrayList<>(); T t; if(pageBean!=null&&pageBean.isPagination()) //需要分页 //算出符合条件的总记录数 String countSql=getCountSql(sql); ps=con.prepareStatement(countSql); rs=ps.executeQuery(); if(rs.next()) pageBean.setTotal(rs.getLong(1)+""); //查询出符合条件的结果集 String pageSql=getPageSql(sql, pageBean); ps=con.prepareStatement(pageSql); rs=ps.executeQuery(); else ps=con.prepareStatement(sql); rs=ps.executeQuery(); while(rs.next()) /** * 1.实例化一个对象 * 2.取book的所有属性值 * 2.1获取所有属性对象 * 2.2给所有属性对象赋值 * 3.赋完值的book对象装进list容器中 * */ // list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price"))); t=(T)clz.newInstance(); Field[] field=clz.getDeclaredFields(); for (Field f : field) f.setAccessible(true); f.set(t, rs.getObject(f.getName())); list.add(t); DBAccess.close(con, ps, rs); return list; private String getPageSql(String sql,PageBean pageBean) return sql+" limit "+pageBean.getStartIndex()+","+pageBean.getRows(); /** * 获取符合条件的总记录数的sql语句 * @param sql * @return */ private String getCountSql(String sql) return "select count(1) from ("+sql+") t";
利用反射编写BookDao并继承BaseDao进行分页查询测试
编写main方法测试分页:
package com.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.entity.Book; import com.util.DBAccess; import com.util.PageBean; import com.util.StringUtils; public class BookDao extends BaseDao<Book> public List<Book> list(Book book,PageBean PageBean) throws SQLException, InstantiationException, IllegalAccessException String sql="select * from t_mvc_book where true "; String bname=book.getBname(); if(StringUtils.isNotBlank(bname)) sql+=" and bname like ‘%"+bname+"%‘"; return executeQuery(sql, Book.class, PageBean); public static void main(String[] args) throws InstantiationException, IllegalAccessException BookDao bookDao=new BookDao(); Book book=new Book(); //查询圣墟的书籍 book.setBname("圣墟"); PageBean pageBean=new PageBean(); //设置可以分页 pageBean.setPagination(false); //查询第一页 pageBean.setPage(2); try List<Book> list=bookDao.list(book, pageBean); for (Book b : list) System.out.println(b); catch (SQLException e) // TODO Auto-generated catch block e.printStackTrace();
运行结果如下,因为默认每行10条所以出现的是10条数据:
Fri Jun 21 15:21:44 CST 2019 WARN: Establishing SSL connection without server‘s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn‘t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false‘. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. Book [bid=27, bname=圣墟第27章, price=27.0] Book [bid=28, bname=圣墟第28章, price=28.0] Book [bid=29, bname=圣墟第29章, price=29.0] Book [bid=30, bname=圣墟第30章, price=30.0] Book [bid=31, bname=圣墟第31章, price=31.0] Book [bid=32, bname=圣墟第32章, price=32.0] Book [bid=33, bname=圣墟第33章, price=33.0] Book [bid=34, bname=圣墟第34章, price=34.0] Book [bid=35, bname=圣墟第35章, price=35.0] Book [bid=36, bname=圣墟第36章, price=36.0]
以上是关于通用分页1的主要内容,如果未能解决你的问题,请参考以下文章