springmvc调用pageHelper实现分页功能
时间: 2023-07-12 11:36:46 浏览: 76
首先,需要在项目中引入PageHelper的依赖,例如在Maven项目中可以添加以下依赖:
```xml
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
```
然后,在Controller中注入PageHelper的PageHelperInterceptor拦截器,并使用@InitBinder注解将其绑定到WebDataBinder中:
```java
@Controller
public class MyController {
@Autowired
private PageHelperInterceptor pageHelperInterceptor;
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.addInterceptors(pageHelperInterceptor);
}
@GetMapping("/list")
public ModelAndView list(@RequestParam(required = false, defaultValue = "1") Integer pageNum) {
ModelAndView mav = new ModelAndView("list");
// 在查询前调用PageHelper.startPage方法,pageNum表示第几页,pageSize表示每页显示的条数
PageHelper.startPage(pageNum, 10);
List<MyEntity> list = myService.getList();
// 将查询结果封装到PageInfo对象中,便于在页面上显示分页信息
PageInfo<MyEntity> pageInfo = new PageInfo<>(list);
mav.addObject("list", list);
mav.addObject("pageInfo", pageInfo);
return mav;
}
}
```
最后,在页面中使用PageInfo对象的相关属性即可实现分页功能,例如:
```html
<ul>
<#list pageInfo.list as item>
<li>${item.name}</li>
</#list>
</ul>
<div>
<a href="?pageNum=${pageInfo.prePage}">上一页</a>
<span>${pageInfo.pageNum}/${pageInfo.pages}</span>
<a href="?pageNum=${pageInfo.nextPage}">下一页</a>
</div>
```
阅读全文