一、导入相关依赖
<!--mybatis分页插件相关依赖-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>3.7.5</version>
</dependency>
<dependency>
<groupId>com.github.jsqlparser</groupId>
<artifactId>jsqlparser</artifactId>
<version>1.1</version>
</dependency>
二、Mybatis配置文件配置插件
applicationContext.xml
<!--配置 mybatis 的分页插件;-->
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageHelper">
<property name="properties">
<value> dialect=mysql </value>
</property>
</bean>
</array>
</property>
三、定义一个通用的分页PageBean
PageBean.java
public class PageBean<T> {
private long total; //所有记录行数
private List<T> rows;//当前页的数据
private int pageSize = 2;//每页2条
private int pageTotals = 0;//一共多少页
private int pageIndex = 1; //第几页,默认第一页
public PageBean() {
}
public PageBean(long total, List<T> rows, int pageSize, int pageTotals, int pageIndex){
this.total = total;
this.rows = rows;
this.pageSize = pageSize;
this.pageTotals = pageTotals;
this.pageIndex = pageIndex;
}
}
四、Service层
@Service
public class TUserServiceImpl implements ITUsersService {
@Autowired
private TUsersMapper tUsersMapper;
@Override
public PageBean<TUsers> getAllUsersAndRoles(int index) {
//开始分页,默认每页两条数据
PageHelper.startPage(index,2);
List<TUsers> rows = tUsersMapper.getAllUsersAndRoles();
Page<TUsers> plist = (Page<TUsers>) rows;
PageBean<TUsers> pb = new PageBean<>(
plist.getTotal(),
plist.getResult(),
plist.getPageSize(),
plist.getPages(),
plist.getPageNum()
);
return pb;
}
}
五、controller层
@Controller
@RequestMapping("/users")
public class TUsersController {
@Autowired
private ITUsersService itUsersService;
@RequestMapping("/list")
public String getAllUsersAndRoles(Model model,@RequestParam(required = true,defaultValue = "1") int index) {
model.addAttribute("pb", itUsersService.getAllUsersAndRoles(index));
return "/users/list";
}
}
六、页面显示
<tr>
<td colspan="5">
<ul class="pagination">
<c:forEach begin="1" end="${pb.pageTotals}" var="p" step="1">
<li>
<a href="/users/list.action?index=${p}">${p}</a>
</li>
</c:forEach>
</ul>
</td>
</tr>
分页展示