一、导入依赖
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency>
二、整合ssm框架
在sqlSessionFactoryBean内加入配置即可
<!-- 把交给IOC管理 SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <props> <prop key="helpDialect">oracle</prop> <prop key="reasonable">true</prop> </props> </property> </bean> </array> </property> </bean>
三、coding部分
在controller层传入参数(page:当前页码,pageSize:每页显示的条数)
controller层
@Controller @RequestMapping("/orders") public class OrdersController { @Autowired private IOrdersService ordersService; @RequestMapping("/findAll.do") public ModelAndView findAll(@RequestParam(name = "page", required = true, defaultValue = "1") Integer page, @RequestParam(name = "pageSize", required = true, defaultValue = "4") Integer pageSize) throws Exception { List<Orders> ordersList = ordersService.findAll(page,pageSize); PageInfo pageInfo = new PageInfo(ordersList); ModelAndView mv = new ModelAndView(); mv.setViewName("orders-list"); mv.addObject("pageInfo", pageInfo); return mv; } }
service层
PageHelper.startPage(page,pageSize);一定要在查询方法前中间不能插入其他代码 ,否则拦截器无法将分页语句注入。
@Service public class IOrdersServiceImpl implements IOrdersService { @Autowired private IOrdersDao ordersDao; @Override public List<Orders> findAll(Integer page,Integer pageSize) throws Exception { PageHelper.startPage(page,pageSize); List<Orders> list = ordersDao.findAll(); return list; } }
四、前端页面显示
<div class="box-footer"> <div class="pull-left"> <div class="form-group form-inline"> 总共${pageInfo.pages}页,共${pageInfo.total} 条数据。 每页 <select class="form-control" id="changePageSize" onchange="changePageSize()"> <option>1</option> <option>2</option> <option>3</option> <option>4</option> <option>5</option> </select> 条 </div> </div> <div class="box-tools pull-right"> <ul class="pagination"> <li> <a href="${pageContext.request.contextPath}/orders/findAll.do?page=1&pageSize=${pageInfo.pageSize}" aria-label="Previous">首页</a> </li> <li><a href="${pageContext.request.contextPath}/orders/findAll.do?page=${pageInfo.pageNum-1}&pageSize=${pageInfo.pageSize}">上一页</a></li> <c:forEach begin="1" end="${pageInfo.pages}" var="pageNum"> <li><a href="${pageContext.request.contextPath}/orders/findAll.do?page=${pageNum}&pageSize=${pageInfo.pageSize}">${pageNum}</a></li> </c:forEach> <li><a href="${pageContext.request.contextPath}/orders/findAll.do?page=${pageInfo.pageNum+1}&pageSize=${pageInfo.pageSize}">下一页</a></li> <li> <a href="${pageContext.request.contextPath}/orders/findAll.do?page=${pageInfo.pages}&pageSize=${pageInfo.pageSize}" aria-label="Next">尾页</a> </li> </ul> </div> </div>
注:
PageInfo类相当于一个分页Bean
该类中的相关属性:
list:表示分页后每页显示的数据
pages:表示总页数
pageSize:表示当前页显示的条数
total:表示总条数
pageNum:表示当前页(当前页页码)