pom.xml
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>4.2.1</version>
</dependency>
mybatis-config.xml
<plugins>
<plugin interceptor="com.github.pagehelper.PageHelper">
<!-- 设置数据库类型 Oracle,Mysql,MariaDB,SQLite,Hsqldb,PostgreSQL六种数据库 -->
<property name="dialect" value="mysql" />
<!--当设置为true的时候,如果pagesize设置为0 就不执行分页,返回全部结果 -->
<property name="pageSizeZero" value="true" />
<!--合理化查询 比如如果pageNum<1会查询第一页;如果pageNum>pages会查询最后一页(设置为false返回空) -->
<property name="reasonable" value="false" />
<!-- 支持通过Mapper接口参数来传递分页参数 -->
<property name="supportMethodsArguments" value="false" />
<!-- 总是返回PageInfo类型,check检查返回类型是否为PageInfo,none返回Page -->
<property name="returnPageInfo" value="none" />
</plugin>
</plugins>
Service
@Service("userService")
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public PageInfo<User> getUserPage(int pageNum, int pageSize) {
//设置当前页数与每页大小
PageHelper.startPage(pageNum, pageSize);
//从数据库获得要实现分页的数据
List<User> list = userMapper.getUserPage();
//插入分页数据
PageInfo<User> pageInfo = new PageInfo<>(list);
return pageInfo;
}
}
Controller
@Controller
@RequestMapping("/api")
public class UserController {
private static final int PAGESIZE = 3;
@Autowired
private UserService userService;
@RequestMapping(value="/list/{currPage}")
public String pageUser(@PathVariable("currPage") Integer currPage,Map<String,Object> map){
PageInfo<User> pageUser = userService.getUserPage(currPage, PAGESIZE);
//返回指定页数的数据
map.put("users", pageUser.getList());
//返回当前页
map.put("currPage", currPage);
//返回总页数
map.put("totalPage", pageUser.getPages());
return "aa/list";
}
}
Jsp
<table>
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.gender}</td>
</tr>
</c:forEach>
<tr align="center">
<td>
<a href="1">首页</a>
<c:if test="${currPage!=1}">
<a href="${currPage-1}">上一页</a>
</c:if>
<c:if test="${currPage != totalPage }">
<a href="${currPage+1}">下一页</a>
</c:if>
<a href="${totalPage}">尾页</a>
</td>
</tr>
</table>
记得引用jstl标签