1、首先创建dto下的分页类PageBean
package com. zzz. blog. dto ; import java. util. List ; public class PageBean { private Integer pageSize; private Integer currentPage; private Integer totalCount; private Integer totalPage; private List list; public PageBean ( Integer currentPage, Integer totalCount, Integer pageSize) { this . pageSize = pageSize; this . currentPage = currentPage; this . totalCount = totalCount; if ( this . currentPage == null ) { this . currentPage = 1 ; } if ( this . pageSize == null ) { this . pageSize = 5 ; } this . totalPage = ( int ) Math . ceil ( 1.0 * this . totalCount / this . pageSize) ; if ( this . currentPage > this . totalPage) { this . currentPage = this . totalPage; } if ( this . currentPage < 1 ) { this . currentPage = 1 ; } } public Integer getStart ( ) { return ( this . currentPage- 1 ) * this . pageSize; }
}
2、在查询请求中返回PageBean
@Autowired private MessageService messageService; @RequestMapping ( "/findAllMessage" ) public ModelAndView findAllMessage ( Integer currentPage, Model model) { PageBean messagePageBean = messageService. getMessagePageBean ( currentPage) ; model. addAttribute ( "messagePageBean" , messagePageBean) ; return new ModelAndView ( "/gustbook" , "messageModel" , model) ; }
3、实现getMessagePageBean方法和完成jpa的crud接口
package com. zzz. blog. service ; import . . . @Component
public class MessageServiceImpl implements MessageService { @Autowired private MessageRepository messageRepository; . . . @Override public PageBean getMessagePageBean ( Integer currentPage) { Integer totalCount = messageRepository. findAllMessageNum ( ) ; PageBean pageBean = new PageBean ( currentPage, totalCount, 5 ) ; List < Message > list = messageRepository. getMessagePageList ( pageBean. getStart ( ) , pageBean. getPageSize ( ) ) ; pageBean. setList ( list) ; return pageBean; } }
package com. zzz. blog. repository ; import . . . import com. zzz. blog. domain. Message ; public interface MessageRepository extends CrudRepository < Message , Long > { @Query ( value= "select count(*) from message" , nativeQuery = true ) Integer findAllMessageNum ( ) ; @Query ( value= "select * from message limit ?1,?2" , nativeQuery = true ) List < Message > getMessagePageList ( Integer start, Integer pageSize) ; }
4、前端接收参数
< li th: each= " message:${messagePageBean.list}" >
...
< img th: src= " ${message.visitor.image}" >
...
</ li>