SpringMVC 通用分页
前言:
可能诸位不大理解通用分页的意思,其实,通用分页其实就是:
将上一次查询请求再发一次,只不过页码变了而已。
通 用 分 页 详 细 思 路 :
1、准备工作
① 导入现有的工具类:
-
数据库连接
-
字符集处理
-
字符串帮助类
-
通用分页实体类
② 添加junit包,作为调测使用
2、dao层的方法实现
-
编写查询的方法
-
测试写好的方法没有问题
3、修改sql语句
- 修改sql语句变成带条件的查询(select * from 表名 where 1=1)
4、编写servlet代码
- 在servlet实现好查询,并将结果保存到集合
5、完成web.xml的配置
-
处理字符串编码集
-
处理查询的servlet
6、在jsp界面添加带条件查询
- ${pageContext.request.contextPath}
7、改造dao
-
将dao向上改造成通用的baseDao
-
生成查询总记录行数的sql语句
-
生成分页查询的sql语句
-
在basedao中定义内部接口返回
8、改变Object类型
-
将Object类型改成泛型
-
在junit中做测试
9、增强pagebean
-
添加url、paramMap属性
-
添加初始化pagebean的方法、最大页、上一页、下一页方法
10、自定义page分页标签
① 定义标签助手类pageTag
-
将按钮条写入pageTag
-
将隐藏的form表单写入pageTag
-
将对应的js代码写入pageTag
② 创建标签库描述文件tld
- 添加自定义标签的配置
③ jsp引用标签库
④ 测试通用分页是否完善
1、PageBean
分页三要素 :
page | 页码 ------ 视图层传递过来 |
---|---|
rows | 页大小 ------ 视图层传递过来 |
total | 总记录数 ------- 后台查出来 |
pagination | 是否分页 |
2、后台
-
entity
-
dao
第一次查满足条件的总记录数
第二次查指定页码并满足条件的记录
二次查询的条件要一致 -
控制层
Servlet
3、视图层
PageTag
4、 junit
java单元测试/白盒测试
setUp
tearDown
测试用例
符合条件的总记录数:
select count(1) from (select * from 表名 ) t;
从第二页开始(一页十条)符合条件的记录数:
select * from 表名 limit 10,10
请诸位先了解下基本的实体类以及当中的重要属性。
代码是根据简单的学生表、教师表、班级表而设计的,大家酌情参考。
重要代码如下:
PageBean分页工具类:
private int page = 1;// 页码
private int rows = 6;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
/**
* 获得起始记录的下标
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
dao方法的代码如下:
/**
* 步骤:
* 1、加载驱动
* 2、创建连接
* 3、获得预定义处理对象
* 4、执行sql语句
* 5、处理结果集
* 6、关闭连接
* @author 86182
*/
/**
* @param student 是从jsp传递过来的参数,封装成对象做为参数查询并执行sql
* @param pageBean 决定是否分页
* @return list 集合
* @throws SQLException
*/
通用分页查询:
/**
* @param student 是从jsp传递过来的参数,封装成对象做为参数查询并执行sql
* @param pageBean 决定是否分页
* @return list 集合
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List<Student> list(Student student,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
String sql = "select * from tb_stu where 1=1 ";
if(StringUtils.isNotBlank(student.getSname())) {
sql += " and sname like '%"+student.getSname()+"%' ";
}
return super.executeQuery(sql, Student.class, pageBean);
}
测试:
StudentDao sd = new StudentDao();
try {
Student stu = new Student();
PageBean pageBean = new PageBean();
pageBean.setPagination(false);//不分页
stu.setSname("安");
List<Student> list = sd.list(stu, pageBean);
for (Student s : list) {
System.out.println(s);
}
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
BaseDao:
/**
* T = Student.class
* @author 86182
* @param <T>
*/
public class BaseDao<T> {
/**
* @param sql 决定查询哪张表的数据
* @param clz 查询出来的数据封装到哪个实体类中
* @param pageBean 决定是否分页
* @return list 集合
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
List<T> list = new ArrayList<>();
//扩大作用域
java.sql.Connection con = null;
java.sql.PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DBAccess.getConnection();//获得连接
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、创建一个Student对象
* 2、从 ResultSet 结果集中获取值给对象赋值
* 2.1 获取到Student的属性对象
* 2.2 给属性对象赋值
* 3、将已经有值的对象加入集合中
*/
//1、创建一个Student对象
T t = (T) clz.newInstance();
//2、从 ResultSet 结果集中获取值给对象赋值
Field[] fs = clz.getDeclaredFields();
for (Field f : fs) {
f.setAccessible(true);
f.set(t, rs.getObject(f.getName()));
}
//3、将已经有值的对象加入集合中
list.add(t);
}
} finally {
DBAccess.close(con);//关闭连接
}
return (List<T>) list;
}
/**
* 将原生sql拼接出符合条件的某一页的数据查询sql
* @param sql 原生sql
* @param pageBean
* @return
*/
private String getPageSql(String sql, PageBean pageBean) {
return sql + "limit "+pageBean.getStartIndex()+","+pageBean.getRows();
}
/**
* 用原生sql拼接出符合条件的总行数
* @param sql 原生sql
* @return
*/
private String getCountSql(String sql) {
return "select count(1) from ("+sql+") t";
}
}
通过以上代码的对比,我们可以清楚的看到,使用了通用分页的代码,在我们使用时只需要直接调用即可。
注意:
有些类可能和诸位的不一样,
如下:
DBAccess类 处理数据库:
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);
}
}
StringUtils类 私有化构造方法:
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;
}
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
}
EncodingFiter类 处理中文乱码:
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();
}
}
}