Java Spring ソート ページ 処理メモ


~~~java
@Controller
public class UserController {
	@Autowired
	UserService userservice;
	/**
	 * ページング初期表示　
	 * @param model
	 * @param page
	 * @param size
	 * @return
	 */
	@GetMapping("/users")
    public String getUsers(Model model,
                           @RequestParam(defaultValue = "0") int page,
                           @RequestParam(defaultValue = "5") int size) {
        PageResult<User> pageResult = userservice.getUsers(page, size);
        List<User> users = pageResult.getDatas();
        int totalPages = pageResult.getTotalPages();
        long totalElements = pageResult.getTotalElements();

        model.addAttribute("users", users);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);
        model.addAttribute("totalElements", totalElements);

        return "users";
	}

	/**
	 * ソート
	 * @param sortBy
	 * @param sortDirection
	 * @param page
	 * @param size
	 * @param model
	 * @return
	 */
   @GetMapping("/sorted")
	public String getUsers(@RequestParam(defaultValue = "id") String sortBy,
	                       @RequestParam(defaultValue = "asc") String sortDirection,
	                       @RequestParam(defaultValue = "0") int page,
	                       @RequestParam(defaultValue = "5") int size,
	                       Model model) {
	   
	    Page<User> pageResult = userservice.getUsersSorted(sortBy, sortDirection, page, size);
	    List<User> users = pageResult.getContent();
	    int totalPages = pageResult.getTotalPages();
	    long totalElements = pageResult.getTotalElements();
	
	    model.addAttribute("users", users);
	    model.addAttribute("sortBy", sortBy);
	    model.addAttribute("sortDirection", sortDirection);
	    model.addAttribute("currentPage", page);
	    model.addAttribute("totalPages", totalPages);
	    model.addAttribute("totalElements", totalElements);
	
	    return "users";
	}

}
~~~

~~~Java
@SuppressWarnings("unchecked")
@Service
@Transactional
public class UserService {
	@Autowired
	UserRepository userRepository;
	/**
	 * 初期表示
	 * @param pageNumber
	 * @param pageSize
	 * @return
	 */
	public PageResult<User> getUsers(int pageNumber, int pageSize) {
	
	    PageRequest pageable = PageRequest.of(pageNumber, pageSize);
	    Page<User> page = userRepository.findAll(pageable);
	
	    List<User> users = page.getContent();
	    int totalPages = page.getTotalPages();
	    long totalElements = page.getTotalElements();
	
	    return new PageResult<>(users, pageNumber, pageSize, totalElements, totalPages);
	}
    /**
     * ソート
     * @param sortBy
     * @param sortDirection
     * @param page
     * @param size
     * @return
     */
    public Page<User> getUsersSorted(String sortBy, String sortDirection, int page, int size) {
        Sort sort;
        if (sortDirection.equalsIgnoreCase("desc")) {
            sort = Sort.by(sortBy).descending();
        } else {
            sort = Sort.by(sortBy).ascending();
        }

        Pageable pageable = PageRequest.of(page, size, sort);
        Page<User> userPage = userRepository.findAll(pageable);
		/*        
		List<User> users = userPage.getContent();
		int totalPages = userPage.getTotalPages();
		long totalElements = userPage.getTotalElements();
		   */     
        return userPage;
    }
}
~~~
~~~java
public interface UserRepository extends JpaRepository <User, Long> {
	//Page<User> findAll();
	Page<User> findAll(Pageable pageable);
	
	@Query("SELECT u FROM User u ORDER BY u.name +:sortDirection")
	   List<User> findAllSortedByName(@Param("sortDirection") String sortDirection);
	
	 @Query("SELECT u FROM User u ORDER BY u.age +:sortDirection")
	List<User> findAllByOrderByName(@Param("sortDirection") String sortDirection);
}
~~~

~~~html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title class>User List</title>
	<script th:src="@{/js/user.js}" type="text/javascript"></script>
	<link th:href="@{/css/style.css}" rel="stylesheet" type="text/css" />
</head>
<body>
    <h1 class="title">User List</h1>
    
    <table class="utable">
        <tr class="utr">

            <th class="uth" onclick="sortTableer('id')" th:classappend="${sortBy == 'id'} ? 'active' : ''">ID</th>
			<th class="uth" onclick="sortTableer('name')" th:classappend="${sortBy == 'name'} ? 'active' : ''">Name</th>
			<th class="uth" onclick="sortTableer('age')" th:classappend="${sortBy == 'age'} ? 'active' : ''">Age</th>
        </tr>
        <tr class="utr" th:each="user : ${users}">
            <td class="utd" th:text="${user.id}"></td>
            <td class="utd" th:text="${user.name}"></td>
            <td class="utd" th:text="${user.age}"></td>
        </tr>
    </table>
    
    <div class="pagination-container"  classth:if="${totalPages > 1}">
        <ul class="pagination">
            <li th:class="${currentPage == 0 ? 'disabled' : ''}">
                <a th:href="@{/users(page=0)}">First</a>
            </li>
            
			<li th:class="${currentPage > 0 ? '' : 'disabled'}">
			    <a th:href="@{/users(page=${currentPage > 0 ? (currentPage - 1) : 0})}">Previous</a>
			    
            <li th:each="pageNumber : ${#numbers.sequence(0, totalPages-1)}"
			    th:class="${pageNumber == currentPage ? 'active' : ''}">
			    <a th:href="@{/users(page=${pageNumber})}" th:text="${pageNumber + 1}"></a>
			</li>

            <li th:class="${currentPage < totalPages - 1 ? '' : 'disabled'}">
    			<a th:href="@{/users(page=${currentPage < totalPages - 1 ? (currentPage + 1) : totalPages - 1})}">Next</a>
			</li>
            
            <li th:class="${currentPage == totalPages - 1 ? 'disabled' : ''}">
                <a th:href="@{/users(page=${totalPages - 1})}">Last</a>
            </li>
        </ul>
    </div>
</body>
</html>

~~~