springmvc+jpa实现分页的两种方式
1.工具类
public final class QueryTool {public static PageRequest buildPageRequest(int pageNumber, int pageSize, String sortType){Sort sort = null;if("auto".equals(sortType)) {sort = new Sort(Direction.DESC, "ctime");} else {sort = new Sort(Direction.DESC, "ctime");}return new PageRequest(pageNumber, pageSize, sort);}public static <T> Specification<T> buildSpecification(Map<String, Object> searchParams, Class<T> domainClass){Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);Specification<T> spec = DynamicSpecifications.bySearchFilter(filters.values(), domainClass);return spec;} }
2.Service类(只给出CommentService)
@Service public class CommentService {@Autowiredprivate CommentDao commentDao;@Transactionalpublic void addComment(Comment comment) {if(comment == null) return;commentDao.save(comment);}@Transactionalpublic Page<Comment> findAllComments(String problemId, PageRequest pageable){Page<Comment> page = commentDao.findAllCommentsByProblemId(problemId, pageable);return page;} }
3.repository类(problem 和 comment 属于 一对多 的关系)
@Repository public interface CommentDao extends JpaSpecificationExecutor<Comment>,PagingAndSortingRepository<Comment, String> {@Query("select c from Comment c where c.problem.problemid = ?1")public Page<Comment> findAllCommentsByProblemId(String problemId, Pageable pageable); }
4.Controller类
第一种方式
@Controller public class ProblemController {@Autowiredprivate ProblemService problemService;@Autowiredprivate CommentService commentService;@RequestMapping(value="getCurProblemComments")@ResponseBodypublic String getCurProblemComments(String problemName, @RequestParam(value = "pn", defaultValue = "1") int pageNumber,@RequestParam(value = "ps", defaultValue = "4") int pageSize,@RequestParam(value = "sortType", defaultValue = "auto") String sortType){JSONObject jsono = new JSONObject();try {Problem problem = problemService.getProblemByName(problemName);if(problem == null){problem = problemService.addProblem(problemName);}PageRequest pageRequest = QueryTool.buildPageRequest(pageNumber, pageSize, sortType);//根据题目的id获取所有的评论Page<Comment> page = commentService.findAllComments(problem.getProblemid(), pageRequest);//对 Comment 这个类中的一些字段进行过滤SimplePropertyPreFilter spp = new SimplePropertyPreFilter();spp.getExcludes().addAll(Comment.getExcludeString());jsono.put("success", true);jsono.put("message", JSON.toJSONString(page, spp));} catch(Exception e){e.printStackTrace();jsono.put("success", false);jsono.put("message", "inner error.");}return jsono.toString();} }
第二种方式,(懒了,有些内容是放在servic中的。)
通过JpaSpecificationExecutor<T> 的Page<T> findAll(Specification<T> spec, Pageable pageable); 方法(按照指定的规格条件)实现分页查询。
public String getCurProblemComments(@RequestParam(value = "pn", defaultValue = "1") int pageNumber,@RequestParam(value = "ps", defaultValue = "2") int pageSize,@RequestParam(value = "sortType", defaultValue = "auto") String sortType, ServletRequest request) {Map<String, Object> searchParams = new HashMap<String, Object>();searchParams = Servlets.getParametersStartingWith(request, "search_");System.out.println(EncodeUtils.toUTF8((String)searchParams.get("LIKE_name")));PageRequest pageRequest = QueryTool.buildPageRequest(pageNumber, pageSize, sortType);searchParams.put(Operator.EQ + "_dr", "0");//逻辑删除中,字段dr=0表示这条数据没有删除Specification<Comment> spec = QueryTool.buildSpecification(searchParams, Comment.class);Page<Comment> page = commentDao.findAll(spec, pageRequest);return JSON.toJSONString(page); }
其中,Specification中的一些比较操作org.springside.modules.persistence.SearchFilter.Operator这个类中找到,如下:
public static enum Operator {EQ, LIKE, GT, LT, GTE, LTE; }
前台传递过来的参数名称中可以包含 Operator 中的一些操作, 比如参数名称是: search_LIKE_name (search表示要查询时比较, LIKE是比较的操作, name是表的字段名)。
5.java简单实现分页
分页面板类(MyPagePanel.java)
public class MyPagePanel extends JPanel{private final int PAGE_BTN_NUM = 6;//按钮的数目的最大值, 一定为偶数private JButton[] pageBtns = new JButton[PAGE_BTN_NUM];private JButton preBtn = new JButton("<<");//前一页private JButton nextBtn = new JButton(">>");//后一页private JButton jumpBtn = new JButton("跳转");private JTextField jumpText = new JTextField(5);//输入页号private JLabel totPageLabel = new JLabel("共0页");//提示一共多少页public static final int PAGE_SIZE = 2;private CommunicationPanel parentPanel;private ChatPanel chatPanel;//刷新某页public void refreshPage(){if(curPage == -1){JOptionPane.showMessageDialog(null, "请选择题目,然后再刷新!", "温馨提示",JOptionPane.WARNING_MESSAGE);} else {requestPage(curPage);}}//请求某页public void requestPage(int pageNumber){//当前页按钮设为 trueif(curBtnPos >= 0)pageBtns[curBtnPos].setEnabled(true);JSONObject jsono = new JSONObject();jsono.put("problemName", JavaRequest.problemName);jsono.put("pageSize", String.valueOf(PAGE_SIZE));jsono.put("pageNumber", String.valueOf(pageNumber));String data = JavaRequest.sendPost("getCurProblemComments", jsono);//获取当前题目的 评论记录JSONObject result = JSONObject.fromObject(data);if((Boolean) result.get("success")){//分页显示JSONObject message = JSONObject.fromObject(result.get("message"));Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();classMap.put("content", MyMessage.class);MyPage myPage = (MyPage) JSONObject.toBean(message, MyPage.class, classMap);this.updatePage(myPage);} else {JOptionPane.showMessageDialog(null, result.getString("message"), "温馨提示",JOptionPane.WARNING_MESSAGE);if(result.get("returnLogin") != null && (Boolean)result.get("returnLogin")){//如果用户登录超时返回用户登陆界面 parentPanel.switchPanel(CommunicationPanel.LOGIN_PANEL);}}}//跳转都页面private void jumpPage(int pageNumber) throws Exception{if(pageNumber < 0 || pageNumber >= totalPages)throw new Exception("不存在该页号!");requestPage(pageNumber);}public MyPagePanel(CommunicationPanel parentPanelx, ChatPanel chatPanelx){this.parentPanel = parentPanelx;this.chatPanel = chatPanelx;preBtn.setEnabled(false);this.add(preBtn);preBtn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {requestPage(curPage-1);}});for(int i=0; i<pageBtns.length; ++i) {pageBtns[i] = new JButton();this.add(pageBtns[i]);pageBtns[i].setVisible(false);pageBtns[i].addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {//JButton text 表示的是页号String text = ((JButton)e.getSource()).getText();int pageNumber = Integer.valueOf(text);requestPage(pageNumber);}});}nextBtn.setEnabled(false);this.add(nextBtn);nextBtn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {requestPage(curPage+1);}});jumpBtn.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {try{if(jumpText.getText().isEmpty()) throw new Exception("页数不能为空!");int pageNumber = Integer.valueOf(jumpText.getText());jumpPage(pageNumber);} catch (Exception ex){ex.printStackTrace();JOptionPane.showMessageDialog(null, "请确定页号是否正确!", "温馨提示",JOptionPane.WARNING_MESSAGE);}}});this.add(totPageLabel);this.add(jumpText);this.add(jumpBtn);}private int curPage = -1, totalPages, curBtnPos = -1;public void updatePage(MyPage myPage){//清除当页面的信息chatPanel.getJpChat().setText("");//处理接受到的 评论消息for(MyMessage message : myPage.getContent()){chatPanel.addRecMsg(message.getCcontent(), StyleConstants.ALIGN_LEFT);}curPage = myPage.getNumber();totalPages = myPage.getTotalPages();totPageLabel.setText("共" + totalPages + "页");if(curPage == 0) preBtn.setEnabled(false);else preBtn.setEnabled(true);if(curPage == totalPages-1 || totalPages == 0) nextBtn.setEnabled(false);else nextBtn.setEnabled(true);List<Integer> pageNum = new LinkedList<Integer>();if(totalPages > 0) {int step = PAGE_BTN_NUM/2-1;for(int i=step; i>=1; --i) {if(curPage-i>=0)pageNum.add(curPage-i);}pageNum.add(curPage);for(int i=1; i<=step+1 && curPage+i<totalPages; ++i)pageNum.add(curPage+i);if(pageNum.size() < PAGE_BTN_NUM){while(pageNum.size() < PAGE_BTN_NUM && pageNum.get(0)-1 >= 0)pageNum.add(0, pageNum.get(0)-1);while(pageNum.size() < PAGE_BTN_NUM && pageNum.get(pageNum.size()-1)+1 < totalPages)pageNum.add(pageNum.get(pageNum.size()-1)+1);}}int bi = 0;for(int pi=0; pi < pageNum.size(); ++pi, ++bi){pageBtns[bi].setText(String.valueOf(pageNum.get(pi)));if(pageNum.get(pi) == curPage){curBtnPos = bi;//记录这个按钮的页号值 和 当前页号值相等 }}//重新显示按钮for(int i=0; i<bi; ++i)pageBtns[i].setVisible(true);//后面这些按钮都是没有 用上的for(int i=bi; i < pageBtns.length; ++i){pageBtns[i].setVisible(false);}if(totalPages > 0)pageBtns[curBtnPos].setEnabled(false);} }
View Code
MyMessage.class
public class MyMessage{private String ccontent;private String commentid;public String getCcontent() {return ccontent;}public void setCcontent(String ccontent) {this.ccontent = ccontent;}public String getCommentid() {return commentid;}public void setCommentid(String commentid) {this.commentid = commentid;} }
View Code
MyPage.class
public class MyPage{private List<MyMessage> content;private boolean first;private boolean last;private int number;private int numberOfElements;private int size;private String totalElements;private String sort;public String getSort() {return sort;}public void setSort(String sort) {this.sort = sort;}public List<MyMessage> getContent() {return content;}public void setContent(List<MyMessage> content) {this.content = content;}public boolean isFirst() {return first;}public void setFirst(boolean first) {this.first = first;}public boolean isLast() {return last;}public void setLast(boolean last) {this.last = last;}public int getNumber() {return number;}public void setNumber(int number) {this.number = number;}public int getNumberOfElements() {return numberOfElements;}public void setNumberOfElements(int numberOfElements) {this.numberOfElements = numberOfElements;}public int getSize() {return size;}public void setSize(int size) {this.size = size;}public String getTotalElements() {return totalElements;}public void setTotalElements(String totalElements) {this.totalElements = totalElements;}public int getTotalPages() {return totalPages;}public void setTotalPages(int totalPages) {this.totalPages = totalPages;}private int totalPages; }
View Code
实现思路:
1. 首先看一下后台的json数据的格式(其中message的值是spring Data JPA分页查询结果的json)
{"success":true,"message":{"content":[{"ccontent":"hjz 2016-38-11 15:38:21*****宋体|12|0-0-0| *****0$$$$$70#####","commentid":"8ae45d92549da2a801549ec092ce001f"},{"ccontent":"hjz 2016-38-11 15:38:10*****宋体|12|0-0-0|哇哇 *****2$$$$$55#####","commentid":"8ae45d92549da2a801549ec068c7001e"}],"first":true,"last":false,"number":0,"numberOfElements":2,"size":2,"sort":{},"totalElements":8,"totalPages":4}}
2. 将“message”对应的值转换成MyPage对象,因为MyPage中有一个List<MyMessage>,如果属性中含有复杂的类型,当其中属性有类似List , Map ,ArrayList、自定义的类型,如List<MyMessage> content, 普通的转换会报错:java.lang.ClassCastException: net.sf.ezmorph.bean.MorphDynaBean cannot be cast to XXX,在JSONObject.toBean的时候如果转换的类中有集合,可以先定义Map<String, Class> classMap = new HashMap<String, Class>();在classMap中put你要转换的类中的集合名 。本例中需要将“content”对应的值转换成 MyMessage对象。
//data为后台的json串 JSONObject result = JSONObject.fromObject(data); if((Boolean) result.get("success")){//分页显示JSONObject message = JSONObject.fromObject(result.get("message"));Map<String, Class<?>> classMap = new HashMap<String, Class<?>>();classMap.put("content", MyMessage.class);MyPage myPage = (MyPage) JSONObject.toBean(message, MyPage.class, classMap);this.updatePage(myPage); }
3.然后通过分页的信息,简单的实现分页按钮,详情看MyPagePanel.java
转载于:https://www.cnblogs.com/hujunzheng/p/5477523.html
springmvc+jpa实现分页的两种方式相关推荐
- vue实现分页的两种方式
vue实现分页的两种方式 (1)方法一:使用slice方法 一次调用后端接口返回所有数据tableData,然后使用tableData.slice((currentPage-1)*pageSize,c ...
- Java 分页,两种方式的分页,即取即用的代码,不客气
两种方式,一种是currentPage + pageSize, 一种是limit + offset (limit + offset 这个逻辑太恶心,边缘测试很麻烦) 第一种(currentPage + ...
- java web oracle 分页_Oracle分页的两种方式
第一种: select b.* from (select rownum as rid, a.* from om_cm_book_hotword a) b where b.rid <= 10 an ...
- bootstraptable控制分页_bootstrap table分页(前后端两种方式实现)
bootstrap table分页的两种方式: 前端分页:一次性从数据库查询所有的数据,在前端进行分页(数据量小的时候或者逻辑处理不复杂的话可以使用前端分页) 服务器分页:每次只查询当前页面加载所需要 ...
- springmvc和servlet在上传和下载文件(保持文件夹和存储数据库Blob两种方式)
参与该项目的文件上传和下载.一旦struts2下完成,今天springmvc再来一遍.发现springmvc特别好包,基本上不具备的几行代码即可完成,下面的代码贴: FileUpAndDown.jsp ...
- springMVC两种方式实现多文件上传及效率比较
springMVC实现多文件上传的方式有两种,一种是我们经常使用的以字节流的方式进行文件上传,另外一种是使用springMVC包装好的解析器进行上传.这两种方式对于实现多文件上传效率上却有着很大的差距 ...
- SpringMVC 控制器默认支持GET和POST两种方式
在SpringMVC的controller中,@RequestMapping只写路径,不包含RequetMethod.GET和RequetMethod.POST,HttpServletRequest的 ...
- 基于Netty手工实现springMVC框架-----两种方式加载控制器
1.手写springMVC框架 本篇我们通过两种方式来加载控制器,一种是配置文件的方式:另外一种是通过注解的形式. 1.配置文件方式 1.自定义Controller配置文件XML 我定义的格式如下: ...
- Eclipse安装SVN插件的两种方式
登录 | 注册 收藏成功 确定 收藏失败,请重新收藏 确定 查看所有私信查看所有通知 暂没有新通知 想要绕过微信小程序开发中的坑吗?不妨来听这个,今晚8点,1小时帮你搞定! 23小时以前 CSDN日报 ...
最新文章
- CF-241 E.Flights(差分约束)
- 量子计算机怎么编程,量子计算机编程(一)——QPU编程
- 做自适应网站专业乐云seo_什么叫网站优化-网站建设-SEO优化
- arm汇编指令集_1. 从0开始学ARM安装Keil MDK uVision集成开发环境
- ubuntu中Ruby开发集成环境
- Leetcode--用两个栈实现一个队列
- 蓝桥杯质数c语言,2017年第八届蓝桥杯C/C++程序设计本科B组省赛 等差素数列(结果填空)(素数筛)...
- 【论文翻译】Deep Learning
- 华三虚拟机服务器型号,03-虚拟机配置
- Oracle-12c新功能基于时间点recover table
- Python socket和前端html
- VA78L05V6DYE 24V转5V电源 限流电阻参数设计
- 项目实战|史上最简单的springboot 整合elk教程,实现日志收集(带视频哦)
- 有关于服务器6010端口
- 搜狗微信下线了怎么获取公众号文章?手把手教你最新获取方式
- 网卡出现“Windows 仍在设置此设备的类配置。 (代码 56)“
- vue滑动图片验证的方式
- 安卓获取打气筒服务的三种方式
- 北京大学信科2017机试真题之水淹七军
- 微信小程序蓝牙连接硬件设备并进行通讯,小程序蓝牙因距离异常断开自动重连,js实现crc校验位
热门文章
- 计算机论文哪儿找,查找关于计算机毕业论文.docx
- Vue3 --- 在Main.js引入封装的axiosAPI 方法
- 【Java】数据结构——队列(图文)
- linux virtualhost不能正常运行,造成网站无法正常运行的4个原因!
- C语言 指针 p++ / p-- - C语言零基础入门教程
- BugkuCTF-Crypto题奇怪的密码
- 初识C++之函数重载
- 计算机专业英语第07章,计算机专业英语 -第7章1.ppt
- centos写mysql光标移到上一行_mysql:一条SQL更新语句(update)是如何执行的
- androidstudio调用系统相机为什么resultcode一直返回0_函数递归调用?看这文就够了...