spring博客实现分页查询

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;
		}
	}
	
	//开始的索引,select * from message limit ?,?   开始索引,页面大小
	public Integer getStart() {
		return (this.currentPage-1)*this.pageSize;
	}

	//get/set
}

2、在查询请求中返回PageBean

	@Autowired
	private MessageService messageService;
	
	@RequestMapping("/findAllMessage") //查找当前页的所有留言
	public ModelAndView findAllMessage(Integer currentPage,Model model) {
		
		//查找当前页所有留言(分页查询)
		PageBean messagePageBean = messageService.getMessagePageBean(currentPage);
		//放入model中
		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 pageBean = new PageBean(currentPage, totalCount, 5);
		//拿到当前页list
		List<Message> list = messageRepository.getMessagePageList(pageBean.getStart(),pageBean.getPageSize());
		//赋值给pageBean
		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>

你可能感兴趣的:(#,个人博客项目,spring,java,spring,boot,后端)