Author

Author- Ram Ranjeet Kumar

Saturday, February 25, 2023

Sorting With Spring Boot, Thyemeleaf, Spring Data JPA, Hibernate, HTML and MySQL

 




In the previous post, we developed a Spring Boot Web Application(User Management System) with Thyemeleaf, HTML, Spring Data JPA, Maven and MySql Database. Also Implement the Pagination In the Application

Here in this  we are going to implement sorting concept in this Web Application.

What is in this article ?

  • We sort data in Ascending and in Descending order.
  • Perform sorting task in all given field name.

Code Implementation


UserDao.java

package com.example.userWebApp;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserDao extends JpaRepository<User,Integer> {
}

UserService.java

package com.example.userWebApp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

@Service
public class UserService {

@Autowired
private UserDao userDao;

public Page<User> getAllUser(int pageNumber, String sortFieldName, String sortDir){

// Sort sort = Sort.by("name").descending();

Sort sort = sortDir.equalsIgnoreCase(Sort.Direction
.ASC.name()) ?
Sort.by(sortFieldName).ascending() : Sort.by(sortFieldName)
.descending();

Pageable pageable = PageRequest.of(pageNumber - 1,4,sort);//12/3==4
Page<User> page = userDao.findAll(pageable);
return page;
}

}

Add below code in controller class

UserController.java

 @GetMapping("/")
public String homePage(Model model){
// return new ModelAndView("home","any",userDao.findAll());
return pageWiseDisplayUserList(1,model,"name","asc");

}


// /page/{pageNumber}?sortField=name&sortDir=asc
@GetMapping("/page/{pageNumber}")
public String pageWiseDisplayUserList(@PathVariable("pageNumber") Integer currentPage, Model model,
@RequestParam("sortField") String sortField,
@RequestParam("sortDir") String sortDir){

Page<User> page = userService.getAllUser(currentPage,
sortField,sortDir);

        int totalPages = page.getTotalPages();
long totalElements = page.getTotalElements();
List <User> list = page.getContent();
model.addAttribute("currentPage",currentPage);
model.addAttribute("totalPages",totalPages);
model.addAttribute("totalElements",totalElements);
model.addAttribute("any",list);
model.addAttribute("sortField",sortField);
model.addAttribute("sortDir",sortDir);
String checkDirection = sortDir.equals("asc") ?"desc":
"asc";
        model.addAttribute("checkDirection",checkDirection);

return "home";
}


Complete Controller code
package com.example.userWebApp;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class UserController {

@Autowired
private UserDao userDao;
@Autowired
private UserService userService;

@GetMapping("/")
public String homePage(Model model){
// return new ModelAndView("home","any",userDao.findAll());
return pageWiseDisplayUserList(1,model,"name","asc");

}


// /page/{pageNumber}?sortField=name&sortDir=asc
@GetMapping("/page/{pageNumber}")
public String pageWiseDisplayUserList(@PathVariable("pageNumber") Integer currentPage, Model model,
@RequestParam("sortField") String sortField,
@RequestParam("sortDir") String sortDir){

Page<User> page = userService.getAllUser(currentPage,
sortField,sortDir);
        int totalPages = page.getTotalPages();
long totalElements = page.getTotalElements();
List <User> list = page.getContent();
model.addAttribute("currentPage",currentPage);
model.addAttribute("totalPages",totalPages);
model.addAttribute("totalElements",totalElements);
model.addAttribute("any",list);
model.addAttribute("sortField",sortField);
model.addAttribute("sortDir",sortDir);
String checkDirection = sortDir.equals("asc") ?
"desc" : "asc";
        model.addAttribute("checkDirection",checkDirection);

return "home";
}

@PostMapping("/save")
public String saveUser(@ModelAttribute User user){
userDao.save(user);
return "redirect:/";
}

@GetMapping("/add")
public String addNewUser(){
return "addnewuser";
}

@RequestMapping("/update/{id}")
public String updateUser(@PathVariable Integer id, Model model){
User returnedUser = userDao.findById(id).get();
model.addAttribute("any",returnedUser);
return "update";
}

@RequestMapping("/delete/{id}")
public String deleteUser(@PathVariable Integer id){
userDao.delete(userDao.findById(id).get());
return "redirect:/";
}
}

Add the below code in home.html page

home.html

Add below code in html table section where field name is mentioned.

<tr>
<th><a th:href="@{'/page/' + ${currentPage} + '?sortField=id&sortDir='+
${checkDirection} }">User Id</a></th>

<th>
<a th:href="@{'/page/' + ${currentPage} + '?sortField=name&sortDir='+
${checkDirection} }">User Name</a>

</th>
<th><a th:href="@{'/page/' + ${currentPage} + '?sortField=phone&sortDir='+
${checkDirection} }">User Phone</a></th>

<th style="color:yellow">Action</th>
</tr>

Add below code in html other table part where pagination code is implemented.
<table>
<tr>
<td>
<b>
<span th:each = "i:${#numbers.sequence(1,totalPages)}">
<a th:if="${i != currentPage}" th:href="@{'/page/'+${i}} +
'?sortField='+${sortField}+'&sortDir='+ ${checkDirection}">[[${i}]]</a>
<b style="color:#CD5C5C">
<span th:unless="${i != currentPage}">[[${i}]]</span>
        </b>
</span>
</b>
</td>
</tr>
</table>

<br>
<table border="1">
<tr>
<!-- First Page Code -->
<td>
<a th:if="${currentPage > 1}" th:href="@{'/page/1' + '?sortField='+
${sortField}+'&sortDir='+ ${checkDirection}}">First Page</a>

<span th:unless="${currentPage > 1}">First Page</span>
</td>

<!-- Next Page Code -->
<td>
<a th:if="${currentPage < totalPages }" th:href="@{'/page/' +
${currentPage + 1 } + '?sortField='+${sortField}+'&sortDir='+ ${checkDirection} }">
Next Page</a>
<span th:unless="${currentPage < totalPages }">Next Page</span>
</td>

<!-- Previous Page Code -->
<td>
<a th:if="${currentPage > 1 }" th:href="@{'/page/' + ${currentPage - 1 }
+ '?sortField='+${sortField}+'&sortDir='+ ${checkDirection} }">Previous Page</a>
<span th:unless="${currentPage > 1 }">Previous Page</span>
</td>

<!-- Last Page Code -->
<td>
<a th:if="${currentPage < totalPages }" th:href="@{'/page/' +
${totalPages} + '?sortField='+${sortField}+'&sortDir='+ ${checkDirection} }">Last Page</a>
<span th:unless="${currentPage < totalPages }">Last Page</span>
</td>
</tr>

</table>



Complete html code


<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>User Management</title>
</head>
<body style="background: #b3b3cc">
<center>
<h1 style="color:white">User Management</h1>
<a style="color:green" th:href="@{/add}">Add New User</a><br><br>
<table border="2" style="color:black">
<tr>
<th>
<a th:href="@{'/page/' + ${currentPage} + '?sortField=id&sortDir='+ 
${checkDirection} }">User Id</a></th>
<th>
<a th:href="@{'/page/' + ${currentPage} + '?sortField=name&sortDir='+ 
${checkDirection} }">User Name</a></th>

<th>
<a th:href="@{'/page/' + ${currentPage} + '?sortField=phone&sortDir='+ 
${checkDirection} }">User Phone</a></th>
<th style="color:yellow">Action</th>
</tr>
<tr th:each ="u:${any}">
<th th:text="${u.id}"></th>
<th th:text="${u.name}"></th>
<th th:text="${u.phone}"></th>
<th>
<table>
<tr>
<td><a style="color:blue" th:href="@{/update/{id} (id=${u.id})}">Update</a></td>
<td><a style="color:red"  th:href="@{/delete/{id} (id=${u.id})}">Delete</a></td>

                    </tr>
</table>
</th>
</tr>
</table>
<br>

<table>
<tr>
<td>
<b>
<span th:each = "i:${#numbers.sequence(1,totalPages)}">
<a th:if="${i != currentPage}" th:href="@{'/page/'+${i}} + '?sortField='
+${sortField}+'&sortDir='+ ${checkDirection}">[[${i}]]</a>
<b style="color:#CD5C5C">
<span th:unless="${i != currentPage}">[[${i}]]</span>
</b>
</span>

</b>
</td>
</tr>
</table>

<br>
<table border="1">
<tr>
<!-- First Page Code -->
<td>
<a th:if="${currentPage > 1}" th:href="@{'/page/1' + '?sortField='+${sortField}+
'&sortDir='+ ${checkDirection}}">First Page</a>
<span th:unless="${currentPage > 1}">First Page</span>
</td>
            <!--            Next Page Code             -->
<td>
<a  th:if="${currentPage < totalPages }" th:href="@{'/page/' + ${currentPage + 1 } +
 '?sortField='+${sortField}+'&sortDir='+ ${checkDirection} }">Next Page</a>
<span th:unless="${currentPage < totalPages }">Next Page</span>
</td>
<!-- Previous Page Code -->
<td>
<a th:if="${currentPage > 1 }" th:href="@{'/page/' + ${currentPage - 1 } + 
'?sortField='+${sortField}+'&sortDir='+ ${checkDirection} }">Previous Page</a>
<span th:unless="${currentPage > 1 }">Previous Page</span>
</td>       <!--            Last Page Code             -->
<td>
<a th:if="${currentPage < totalPages }" th:href="@{'/page/' + ${totalPages} + 
'?sortField='+${sortField}+'&sortDir='+ ${checkDirection} }">Last Page</a>
<span th:unless="${currentPage < totalPages }">Last Page</span>
</td>
</tr>

</table>

<br>
<table border="1">
<tr>
<td><b>Total Record: </b> [[${totalElements}]] </td>
<td><b>Current Page: </b> [[${currentPage}]] </td>
<td><b>Total Page: </b> [[${totalPages}]] </td>
</tr>
</table>

</center>
</body>
</html>

Thank You!

No comments:

Post a Comment