目标
将数据库中的 Admin 数据在页面上以分页形式显示。
思路
代码
1、引入PageHelper
确认是否加入依赖
<!-- MyBatis 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
</dependency>
在SqlSessionFactoryBena中配置Mybatis插件
<!-- 配置插件 -->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<props>
<!-- 配置数据库方言,告诉PageHelper当前使用的数据库 -->
<prop key="dialect">mysql</prop>
<!-- 配置页码的合理化修正,在1到总页数之间修正页面:
比如用户想要第五十页,但是我们总共只有二十页,那么返回我们的最后一页给用户 -->
<prop key="reasonable">true</prop>
</props>
</property>
</bean>
</array>
</property>
2、在AdminMapper.xml中编写SQL语句
<select id="selectAdminByKeyword" resultMap="BaseResultMap">
select
id, login_acct, user_pswd, user_name, email, create_time
from t_admin
where
login_acct like concat("%",#{keyword},"%") or
user_name like concat("%",#{keyword},"%") or
email like concat("%",#{keyword},"%")
</select>
3、在AdminMapper这个接口中添加对应的方法
/**
* 根据关键词进行模糊查询
* @param keyword
* @return
*/
List<Admin> selectAdminByKeyword(String keyword);
4、在AdminService接口中添加分页的方法
/**
* 进行分页查询的方法
* @param keyword 模糊查询的关键字
* @param pageNum 当前页数
* @param pageSize 每页显示多少条数据
* @return
*/
PageInfo<Admin> getPageInfo(String keyword,Integer pageNum,Integer pageSize);
5、在AdminServiceImpl中添加具体实现
@Override
public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {
// 这里体现了PageHelper的“非侵入式”涉及,原本要做的查询不必有任何修改
// 1、调用pageHelper的静态方法开启分页的功能
PageHelper.startPage(pageNum,pageSize);
// 2、执行查询
List<Admin> list = adminMapper.selectAdminByKeyword(keyword);
// 3、封装到PageInfo对象中,因为Page是继承了ArrayList的,所以这个参数传递属于一个向上转型
return new PageInfo<>(list);
}
6、在AdminHandler添加对应的handler方法
@RequestMapping("/admin/get/page.html")
public String getPageInfo(
// 使用RequestParam注解的defaultValue去指定默认值,在请求中没有携带对应参数时使用默认值
// keyword默认值使用空字符串,和Sql语句配合实现两种情况的适配
@RequestParam(value = "keyword",defaultValue = "") String keyword,
@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize,
ModelMap modelMap
){
// 调用Service方法获取PageInfo对象
PageInfo<Admin> pageInfo = adminService.getPageInfo(keyword, pageNum, pageSize);
// 将PageInfo对象存入模型
modelMap.addAttribute(CrowdConstant.ATTR_NAME_PAGE_INFO,pageInfo);
return "admin-page";
}