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、前端接收参数

<!-- 取list里的对象,命名为message,并且遍历list -->
<li th:each="message:${messagePageBean.list}">
...
<img th:src="${message.visitor.image}">
...
</li>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值