1导入jar
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>4.1.6</version> </dependency>2配置spring.xml文件:
plugins属性为新加的属性。
<!--配置SqlSessionFactory--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource"> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageHelper"> <property name="properties"> <value> dialect=mysql offsetAsPageNum=true rowBoundsWithCount=true pageSizeZero=true reasonable=true </value> </property> </bean> </array> </property> </bean>3把数据库中找出的数据封装:
@Service("bookService") public class BookServiceImpl implements BookService{ @Autowired private BookMapper bookMapper; public PageInfo<Book> getAll() { List<Book> bookList=bookMapper.findAll(); return new PageInfo<Book>(bookList); } }分页操作:
@Controller public class BookController { @Autowired @Qualifier("bookService") private BookService bookService; @RequestMapping(value = "/main") public String main(Model model,Integer pageNum,Integer size){ PageHelper.startPage(pageNum==null?1:pageNum,size==null?5:size);//重点这一句 PageInfo<Book> book_list=bookService.getAll(); System.out.println(book_list.getLastPage()+","+book_list.getPages()); model.addAttribute("book_list",book_list); return "main"; } }前端显示页面:
<table border="1"> <tr> <th>编号</th> <th>封面</th> <th>书名</th> <th>作者</th> <th>价格</th> </tr> <c:forEach items="${requestScope.book_list.list}" var="book"> <tr> <td>${book.id}</td> <td> ${book.image}</td> <td>${book.name}</td> <td>${book.author}</td> <td>${book.price}</td> </tr> </c:forEach> <tr> <td>当前页:${book_list.pageNum}</td> <td>当前页的数量:${book_list.size}</td> <td>总记录:${book_list.total}</td> <td>总页数:${book_list.pages}</td> </tr> <tr> <td><a href="main?pageNum=${book_list.firstPage}">首页</a></td> <td><a href="main?pageNum=${book_list.prePage}">前一页</a> </td> <td><a href="main?pageNum=${book_list.nextPage}">下一页</a></td> <td><a href="main?pageNum=${book_list.pages}">最后一页</a></td> </tr> </table>