- 通过https://start.spring.io/ 一键生成springboot项目,自动整合并配置thymeleaf、aop、dectools。十分方便。
- 通过https://mvnrepository.com/ maven仓库,导入mybatis、等组件。
- 设计数据库,通过mabatis完成基本增删改查。
..........
@Mapper不自动注入。经过很长时间的自我怀疑和重新导依赖,发现是Idea误报。-_-|| 并不影响使用。强迫症患者建议在加上@Repository。
- 开发分页工具。
由于上一个项目分页做的很糟糕,这次有了前车之鉴,首先把分页模块做好。分页思路如下:
- 前台发送查询数据请求时,要带上当前页面和每页数据量这两个参数。(二者默认值分别为1,10);
- 用Page类封装一些属性和方法。如需要传给controller的数据,如查询起始行号和结束行号,以及通过当前页显示当前页附近的页码。还需要传给前台的参数,如总页数、上一页、下一页、附近页的页数及跳转路径。
- 前台接收到Model对象中的数据以及page封装的页数信息进行页面展现。
前台主要代码如下:
页码按钮上的链接完全通过后台传入,可以实现代码的复用。
后台代码如下
通过传来的page对象获取页码行号信息,并依据这些之查询数据,将其封装为map并通过model对象传给前台。在方法调用前,SpringMVC会自动为我们实例化model和page对象,并将page注入到model,因此Thymeleaf可以直接取到page对象中的值。
Page类如下:需要在set方法中对边界值进行判断
1 /** 2 * 封装分页相关的信息. 3 */ 4 public class Page { 5 6 // 当前页码 7 private int current = 1; 8 // 显示上限 9 private int limit = 10; 10 // 数据总数(用于计算总页数) 11 private int rows; 12 // 查询路径(用于复用分页链接) 13 private String path; 14 15 public int getCurrent() { 16 return current; 17 } 18 19 public void setCurrent(int current) { 20 if (current >= 1) { 21 this.current = current; 22 } 23 } 24 25 public int getLimit() { 26 return limit; 27 } 28 29 public void setLimit(int limit) { 30 if (limit >= 1 && limit <= 100) { 31 this.limit = limit; 32 } 33 } 34 35 public int getRows() { 36 return rows; 37 } 38 39 public void setRows(int rows) { 40 if (rows >= 0) { 41 this.rows = rows; 42 } 43 } 44 45 public String getPath() { 46 return path; 47 } 48 49 public void setPath(String path) { 50 this.path = path; 51 } 52 53 /** 54 * 获取当前页的起始行 55 * 56 * @return 57 */ 58 public int getOffset() { 59 // current * limit - limit 60 return (current - 1) * limit; 61 } 62 63 /** 64 * 获取总页数 65 * 66 * @return 67 */ 68 public int getTotal() { 69 // rows / limit [+1] 70 if (rows % limit == 0) { 71 return rows / limit; 72 } else { 73 return rows / limit + 1; 74 } 75 } 76 77 /** 78 * 获取起始页码 79 * 80 * @return 81 */ 82 public int getFrom() { 83 int from = current - 2; 84 return from < 1 ? 1 : from; 85 } 86 87 /** 88 * 获取结束页码 89 * 90 * @return 91 */ 92 public int getTo() { 93 int to = current + 2; 94 int total = getTotal(); 95 return to > total ? total : to; 96 } 97 98 }