SpringMVC+Spring Data JPA +Bootstrap 分页实现和模糊查询分页

avatar 2017年12月02日19:12:08 8 8590 views
博主分享免费Java教学视频,B站账号:Java刘哥 ,长期提供技术问题解决、项目定制:本站商品点此
本文将介绍使用 SpringMVC + Spring Data JPA 实现分页功能。

Spring Data JSP 里面一个一个 Pageable 的类可以帮我们实现分页,非常好用。

先看效果图


用户列表分页





用户查询(根据用户名,昵称,email,个人主页,手机号)模糊查询 分页







如果是首页不显示上一页,如果是尾页不显示下一页。


分页的API


使用 Spirng Data JPA 的 Page 替代之前的 List。

下面是返回给前台的数据
  1. // 20171202185123
  2. // http://localhost:8090/admin/user/list
  3. {
  4.   "content": [
  5.     {
  6.       "id"1,
  7.       "username""liubei",
  8.       "password"null,
  9.       "nickname""刘玄德",
  10.       "email""liubei@shu.com",
  11.       "avatar""/uploads/2017/12/刘备.png",
  12.       "website""http://liubei.com",
  13.       "phone""15711111111",
  14.       "createTime"1512193914000,
  15.       "status"1
  16.     },
  17.     {
  18.       "id"2,
  19.       "username""lv007",
  20.       "password""007",
  21.       "nickname""吕玲绮",
  22.       "email""007@san.com",
  23.       "avatar""/uploads/2017/12/吕玲绮.png",
  24.       "website""http://007.com",
  25.       "phone""15711111112",
  26.       "createTime"1512194060000,
  27.       "status"1
  28.     },
  29.     {
  30.       "id"3,
  31.       "username""mayunlu",
  32.       "password""123",
  33.       "nickname""马云禄",
  34.       "email""mayunlu@san.com",
  35.       "avatar""/uploads/2017/12/马云禄.png",
  36.       "website""http://mayunlu.com",
  37.       "phone""13533333333",
  38.       "createTime"1512194114000,
  39.       "status"1
  40.     }
  41.   ],
  42.   "last"false,
  43.   "totalElements"29,
  44.   "totalPages"10,
  45.   "size"3,
  46.   "number"0,
  47.   "sort"null,
  48.   "first"true,
  49.   "numberOfElements"3
  50. }

可以看到能获得总共记录数totalElements,总页数totalPages,每页显示的记录数size,当前页码number(从0开始计),排序规则sort,是否为首页first,是否为尾页last,当前页的记录数。content 里的是记录内容


后台代码


1、dao 层

UserDao.java
  1. package com.liuyanzhao.blog.dao;
  2. import com.liuyanzhao.blog.entity.User;
  3. import org.springframework.data.domain.Page;
  4. import org.springframework.data.domain.Pageable;
  5. import org.springframework.data.jpa.repository.JpaRepository;
  6. import org.springframework.data.jpa.repository.Query;
  7. /**
  8.  * @author 言曌
  9.  * @date 2017/11/28 下午3:31
  10.  */
  11. public interface UserDao extends JpaRepository<User, Integer> {
  12.     //根据用户名昵称等信息模糊查询
  13.     @Query("select u from User u where u.username like %?1% or u.nickname like %?1% or u.email like %?1% or u.website like %?1% or u.phone like %?1% or u.id = ?1")
  14.     Page<User> findSearch(String query, Pageable pageable);
  15. }



2、Service 层

UserServie.java
  1. package com.liuyanzhao.blog.service;
  2. import com.liuyanzhao.blog.dto.UserDTO;
  3. import org.springframework.data.domain.Page;
  4. import org.springframework.data.domain.Pageable;
  5. /**
  6.  * @author 言曌
  7.  * @date 2017/11/28 下午3:32
  8.  */
  9. public interface UserService {
  10.     //全部查询
  11.     Page<UserDTO> findAll(Pageable pageable);
  12.     //根据用多种信息查询模糊用户
  13.     Page<UserDTO> findSearch(String username,Pageable pageable);
  14. }



UserServiceImpl.java
  1. package com.liuyanzhao.blog.service.Impl;
  2. import com.liuyanzhao.blog.converter.User2UserDTOConverter;
  3. import com.liuyanzhao.blog.dao.UserDao;
  4. import com.liuyanzhao.blog.dto.UserDTO;
  5. import com.liuyanzhao.blog.entity.User;
  6. import com.liuyanzhao.blog.service.UserService;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.data.domain.Page;
  9. import org.springframework.data.domain.PageImpl;
  10. import org.springframework.data.domain.Pageable;
  11. import org.springframework.stereotype.Service;
  12. import javax.transaction.Transactional;
  13. import java.util.List;
  14. /**
  15.  * @author 言曌
  16.  * @date 2017/11/28 下午3:32
  17.  */
  18. @Service("userService")
  19. public class UserServiceImpl implements UserService {
  20.     @Autowired
  21.     private UserDao userDao;
  22.     //分页获得列表
  23.     @Override
  24.     public Page<UserDTO> findAll(Pageable pageable) {
  25.         Page<User> userPage = userDao.findAll(pageable);
  26.         List<UserDTO> userDTOList = User2UserDTOConverter.convert(userPage.getContent());
  27.         Page<UserDTO> userDTOPage = new PageImpl<UserDTO>(userDTOList,pageable,userPage.getTotalElements());
  28.         return userDTOPage;
  29.     }
  30.     @Override
  31.     public Page<UserDTO> findSearch(String query,Pageable pageable) {
  32.         Page<User> userPage = userDao.findSearch(query,pageable);
  33.         List<UserDTO> userDTOList  = User2UserDTOConverter.convert(userPage.getContent());
  34.         Page<UserDTO> userDTOPage = new PageImpl<UserDTO>(userDTOList,pageable,userPage.getTotalElements());
  35.         return userDTOPage;
  36.     }
  37. }



3、controller 层

UserController.java
  1. package com.liuyanzhao.blog.controller;
  2. import com.liuyanzhao.blog.dto.UserDTO;
  3. import com.liuyanzhao.blog.service.UserService;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.data.domain.Page;
  6. import org.springframework.data.domain.PageRequest;
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.web.bind.annotation.*;
  9. import org.springframework.web.servlet.ModelAndView;
  10. import javax.servlet.http.HttpServletRequest;
  11. /**
  12.  * @author 言曌
  13.  * @date 2017/11/28 下午3:33
  14.  */
  15. @Controller
  16. @RequestMapping(value = "/admin/user")
  17. public class UserController {
  18.     @Autowired
  19.     private UserService userService;
  20.     @RequestMapping(value = "/list")
  21.     public ModelAndView listUser(@RequestParam(value = "page",defaultValue = "1") Integer page,
  22.                                  @RequestParam(value = "size",defaultValue = "3") Integer size) {
  23.         ModelAndView modelAndView = new ModelAndView();
  24.         PageRequest request = new PageRequest(page-1,size);
  25.         Page<UserDTO> userDTOPage = userService.findAll(request);
  26.         modelAndView.addObject("userDTOPage",userDTOPage);
  27.         modelAndView.setViewName("/admin/user/list");
  28.         return modelAndView;
  29.     }
  30.     @RequestMapping(value = "/search")
  31.     public ModelAndView search(HttpServletRequest request,
  32.                                @RequestParam(value = "page",defaultValue = "1") Integer page,
  33.                                @RequestParam(value = "size",defaultValue = "3") Integer size) {
  34.         ModelAndView modelAndView = new ModelAndView();
  35.         String query = (request.getParameter("query")).trim();
  36.         PageRequest pageRequest = new PageRequest(page-1,size);
  37.         Page<UserDTO> userDTOPage = userService.findSearch(query,pageRequest);
  38.         modelAndView.addObject("userDTOPage",userDTOPage);
  39.         modelAndView.addObject("query",query);
  40.         modelAndView.setViewName("/admin/user/list");
  41.         return modelAndView;
  42.     }
  43. }

默认一页显示3条记录,默认当前页为di



4、实体类

UserDTO.java
  1. package com.liuyanzhao.blog.dto;
  2. import java.util.Date;
  3. /**
  4.  *
  5.  * 数据传输对象(不要使用entity直接来传数据)
  6.  * @author 言曌
  7.  * @date 2017/11/30 下午10:53
  8.  */
  9. public class UserDTO {
  10.     private Integer id;
  11.     private String username;
  12.     private String password;
  13.     private String nickname;
  14.     private String email;
  15.     private String avatar;
  16.     private String website;
  17.     private String phone;
  18.     private Date createTime;
  19.     private Integer status;
  20.     public Integer getId() {
  21.         return id;
  22.     }
  23.     public void setId(Integer id) {
  24.         this.id = id;
  25.     }
  26.     public String getUsername() {
  27.         return username;
  28.     }
  29.     public void setUsername(String username) {
  30.         this.username = username;
  31.     }
  32.     public String getPassword() {
  33.         return password;
  34.     }
  35.     public void setPassword(String password) {
  36.         this.password = password;
  37.     }
  38.     public String getNickname() {
  39.         return nickname;
  40.     }
  41.     public void setNickname(String nickname) {
  42.         this.nickname = nickname;
  43.     }
  44.     public String getEmail() {
  45.         return email;
  46.     }
  47.     public void setEmail(String email) {
  48.         this.email = email;
  49.     }
  50.     public String getAvatar() {
  51.         return avatar;
  52.     }
  53.     public void setAvatar(String avatar) {
  54.         this.avatar = avatar;
  55.     }
  56.     public String getWebsite() {
  57.         return website;
  58.     }
  59.     public void setWebsite(String website) {
  60.         this.website = website;
  61.     }
  62.     public String getPhone() {
  63.         return phone;
  64.     }
  65.     public void setPhone(String phone) {
  66.         this.phone = phone;
  67.     }
  68.     public Date getCreateTime() {
  69.         return createTime;
  70.     }
  71.     public void setCreateTime(Date createTime) {
  72.         this.createTime = createTime;
  73.     }
  74.     public Integer getStatus() {
  75.         return status;
  76.     }
  77.     public void setStatus(Integer status) {
  78.         this.status = status;
  79.     }
  80. }


前台代码


list.jsp 部分代码
  1. <div id="content">
  2.                 <div class="table-responsive">
  3.                     <form class="form-inline" method="get" action="/admin/user/search">
  4.                         <div class="form-group">
  5.                             <label for="Search" class="sr-only">Search</label>
  6.                             <input type="text" name="query" class="form-control" id="Search" placeholder="Search"
  7.                                    value="${query}">
  8.                         </div>
  9.                         <button type="submit" class="btn btn-default">查询</button>
  10.                         <a href="/admin/user/add">
  11.                             <button type="button" class="btn btn-info">添加</button>
  12.                         </a>
  13.                         <button type="button" class="btn btn-danger" onclick="deleteUserMore()">批量删除</button>
  14.                     </form>
  15.                     <br>
  16.                     <c:choose>
  17.                         <c:when test="${userDTOPage.numberOfElements > 0}">
  18.                             <table class="table table-bordered">
  19.                                 <tr>
  20.                                     <th><input type="checkbox" id="allSelect" onclick="DoCheck()"></th>
  21.                                     <th>ID</th>
  22.                                     <th>用户名</th>
  23.                                     <th>昵称</th>
  24.                                     <th>邮箱</th>
  25.                                     <th>电话</th>
  26.                                     <th>个人主页</th>
  27.                                     <th>创建时间</th>
  28.                                     <th>状态</th>
  29.                                     <th>操作</th>
  30.                                 </tr>
  31.                                 <c:forEach var="user" items="${userDTOPage.content}">
  32.                                     <tr>
  33.                                         <td><input type="checkbox" name="ids" value="${user.id}"></td>
  34.                                         <td>${user.id}</td>
  35.                                         <td>${user.username}</td>
  36.                                         <td>${user.nickname}</td>
  37.                                         <td>${user.email}</td>
  38.                                         <td>${user.phone}</td>
  39.                                         <td><a href="${user.website}" target="_blank">${user.website}</a></td>
  40.                                         <td>${user.createTime}</td>
  41.                                         <td>
  42.                                             <c:choose>
  43.                                                 <c:when test="${user.status==1}">
  44.                                                     <span class="text-success">正常</span>
  45.                                                 </c:when>
  46.                                                 <c:when test="${user.status==0}">
  47.                                                     <span class="text-danger">禁用</span>
  48.                                                 </c:when>
  49.                                                 <c:otherwise>
  50.                                                     ${user.status}
  51.                                                 </c:otherwise>
  52.                                             </c:choose>
  53.                                         </td>
  54.                                         <td>
  55.                                             <a href="/admin/user/profile/${user.id}">
  56.                                                 <button type="button" class="btn btn-success btn-xs">查看</button>
  57.                                             </a>
  58.                                             <button type="button" class="btn btn-danger btn-xs"
  59.                                                     onclick="deleteUser(${user.id})">删除
  60.                                             </button>
  61.                                             <a href="/admin/user/edit/${user.id}">
  62.                                                 <button type="button" class="btn btn-primary btn-xs">编辑</button>
  63.                                             </a>
  64.                                         </td>
  65.                                     </tr>
  66.                                 </c:forEach>
  67.                             </table>
  68.                             <%--总共页数:${userDTOPage.totalPages} <br>--%>
  69.                             <%--记录总数:${userDTOPage.totalElements} <br>--%>
  70.                             <%--当前页号:${userDTOPage.number} <br>--%>
  71.                             <%--是否为首页:${userDTOPage.first} <br>--%>
  72.                             <%--是否为尾页:${userDTOPage.last} <br>--%>
  73.                             <%--每页显示的数量:${userDTOPage.numberOfElements} <br>--%>
  74.                             <%--分页 start--%>
  75.                             <nav aria-label="Page navigation">
  76.                                 <ul class="pagination">
  77.                                     <c:choose>
  78.                                         <c:when test="${userDTOPage.totalPages <= 3 }">
  79.                                             <c:set var="begin" value="1"/>
  80.                                             <c:set var="end" value="${userDTOPage.totalPages }"/>
  81.                                         </c:when>
  82.                                         <c:otherwise>
  83.                                             <c:set var="begin" value="${userDTOPage.number+1-1 }"/>
  84.                                             <c:set var="end" value="${userDTOPage.number+1 + 2}"/>
  85.                                             <c:if test="${begin < 2 }">
  86.                                                 <c:set var="begin" value="1"/>
  87.                                                 <c:set var="end" value="3"/>
  88.                                             </c:if>
  89.                                             <c:if test="${end > userDTOPage.totalPages}">
  90.                                                 <c:set var="begin" value="${userDTOPage.totalPages-2 }"/>
  91.                                                 <c:set var="end" value="${userDTOPage.totalPages}"/>
  92.                                             </c:if>
  93.                                         </c:otherwise>
  94.                                     </c:choose>
  95.                                         <%--如果当前为首页,隐藏上一页--%>
  96.                                     <c:choose>
  97.                                         <c:when test="${userDTOPage.first}">
  98.                                             <%--当前页为第一页,隐藏上一页按钮--%>
  99.                                         </c:when>
  100.                                         <c:otherwise>
  101.                                             <li>
  102.                                                 <a href="?page=${userDTOPage.number}" aria-label="Previous">
  103.                                                     <span aria-hidden="true">&laquo;</span>
  104.                                                 </a>
  105.                                             </li>
  106.                                         </c:otherwise>
  107.                                     </c:choose>
  108.                                         <%--显示第一页的页码--%>
  109.                                     <c:if test="${begin >= 2 }">
  110.                                         <li><a href="?page=1">1</a></li>
  111.                                     </c:if>
  112.                                         <%--显示点点点--%>
  113.                                     <c:if test="${begin  > 2 }">
  114.                                         <li class="disabled"><a></a></li>
  115.                                     </c:if>
  116.                                         <%--打印 页码--%>
  117.                                     <c:forEach begin="${begin }" end="${end }" var="i">
  118.                                         <c:choose>
  119.                                             <c:when test="${i eq userDTOPage.number+1}">
  120.                                                 <li class="active"><a href="?page=${i}">${i}<span
  121.                                                         class="sr-only">(current)</span></a></li>
  122.                                             </c:when>
  123.                                             <c:otherwise>
  124.                                                 <li><a href="?page=${i}">${i}</a></li>
  125.                                             </c:otherwise>
  126.                                         </c:choose>
  127.                                     </c:forEach>
  128.                                         <%-- 显示点点点 --%>
  129.                                     <c:if test="${end < userDTOPage.totalPages-1 }">
  130.                                         <li class="disabled"><a></a></li>
  131.                                     </c:if>
  132.                                         <%-- 显示最后一页的数字 --%>
  133.                                     <c:if test="${end < userDTOPage.totalPages}">
  134.                                         <li>
  135.                                             <a href="?page=${userDTOPage.totalPages}">${userDTOPage.totalPages}</a>
  136.                                         </li>
  137.                                     </c:if>
  138.                                         <%--如果当前页为尾页,隐藏下一页--%>
  139.                                     <c:choose>
  140.                                         <c:when test="${userDTOPage.number+1 eq userDTOPage.totalPages}">
  141.                                             <%--到了尾页隐藏,下一页按钮--%>
  142.                                         </c:when>
  143.                                         <c:otherwise>
  144.                                             <li>
  145.                                                 <a href="?page=${userDTOPage.number+2}" aria-label="Next">
  146.                                                     <span aria-hidden="true">&raquo;</span>
  147.                                                 </a>
  148.                                             </li>
  149.                                         </c:otherwise>
  150.                                     </c:choose>
  151.                                 </ul>
  152.                             </nav>
  153.                             <%--分页 end--%>
  154.                         </c:when>
  155.                         <c:otherwise><%--如果没有文章--%>
  156.                             <div class="alert alert-warning">
  157.                                 <a href="#" class="close" data-dismiss="alert">
  158.                                     &times;
  159.                                 </a>
  160.                                 <strong>警告!</strong>这里什么都没有。哼,小坏坏!
  161.                             </div>
  162.                         </c:otherwise>
  163.                     </c:choose>
  164.                 </div>
  165.             </div>



search.jsp

这个search.jsp 和 list.jsp 基本相同,只是下面的分页链接不同

一个是 <a href="?page=${i}">${i}</a>

一个是 <a href="?query=${query}&page=${i}">${i}</a>

这里就不贴代码了



其中分页部分需要注意这个就行了
总共页数:${userDTOPage.totalPages} 

记录总数:${userDTOPage.totalElements}
当前页号:${userDTOPage.number}
是否为首页:${userDTOPage.first}
是否为尾页:${userDTOPage.last}
每页显示的数量:${userDTOPage.numberOfElements}




其他分页内容


SpringBoot + Spring Data JPA + Thmeleaf 分页实现仿哔哩哔哩

SpringBoot Spring Data JPA Thymeleaf 实现关注者和粉丝,互相关注分页显示


SSM + JSP 自定义分页



本文地址:https://liuyanzhao.com/6869.html
  • 微信
  • 交流学习,资料分享
  • weinxin
  • 个人淘宝
  • 店铺名:言曌博客咨询部

  • (部分商品未及时上架淘宝)
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:2   待审核评论数:0
  1. avatar 锟斤拷锟斤拷锟斤拷

    List userDTOList = User2UserDTOConverter.convert(userPage.getContent());这个方法没有???在哪写的???

  2. avatar xuezhongyu01

    List userDTOList = User2UserDTOConverter.convert(userPage.getContent());可以使用page.map方法