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>

文章来源地址https://uudwc.com/A/9djvz

原文地址:https://blog.csdn.net/heiye_007/article/details/133302681

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请联系站长进行投诉反馈,一经查实,立即删除!

h
上一篇 2023年09月26日 14:51
【项目实战】Linux系统下jar包自启动
下一篇 2023年09月26日 14:52