SpringMVC+Spring Data JPA +Bootstrap 分頁實現和模糊查詢分頁

言曌發表於2018-03-17

本文將介紹使用 SpringMVC + Spring Data JPA 實現分頁功能。

Spring Data JSP 裡面一個一個 Pageable 的類可以幫我們實現分頁,非常好用。

先看效果圖

使用者列表分頁

SpringMVC+Spring Data JPA +Bootstrap 分頁實現和模糊查詢分頁

 

使用者查詢(根據使用者名稱,暱稱,email,個人主頁,手機號)模糊查詢 分頁

SpringMVC+Spring Data JPA +Bootstrap 分頁實現和模糊查詢分頁

 

 

如果是首頁不顯示上一頁,如果是尾頁不顯示下一頁。

 

分頁的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}

 

 

本文地址:https://liuyanzhao.com/6869.html

相關文章