How to sort data in the table using spring boot and JSP, In this tutorial, I will cover some methods for data sorting, Sort data from the backend spring boot only, and create an option(link or button) to sort the data on the JSP page.

How can we sort data from the backend Spring boot?

Java has built-in methods such as Collections.sort() or Arrays.sort() that can help to sort the data and display it in the table view by following the below steps.

  • Get the data from a database object or file.
  • Store data in collections like List, Set, and Map.
  • Implement Collections.sort() or Arrays.sort(), or use a sorting algorithm.

Example:

List<Person> dataList= // Get datafrom database or API
Collections.sort(dataList, Comparator.comparing(data::param));

Sort HTML Table data on the JSP page

Create a jquery or JS script that contains the logic to sort the data according to the data type of the table column. Below is the jquery script that can sort any types data,

<script>
$(function() {
   const ths = $("th");
   let sortOrder = 1;

   ths.on("click", function() {
     const rows = sortRows(this);
     rebuildTbody(rows);
     updateClassName(this);
     sortOrder *= -1; 
   })

   function sortRows(th) {
     const rows = $.makeArray($('tbody > tr'));
     const col = th.cellIndex;
     const type = th.dataset.type;
     rows.sort(function(a, b) {
       return compare(a, b, col, type) * sortOrder;      
     });
     return rows;
   }

   function compare(a, b, col, type) {
     let _a = a.children[col].textContent;
     let _b = b.children[col].textContent;
     if (type === "number") {
       _a *= 1;
       _b *= 1;
     } else if (type === "string") {
       
       _a = _a.toLowerCase();
       _b = _b.toLowerCase();
     }

     if (_a < _b) {
       return -1;
     }
     if (_a > _b) {
       return 1;
     }
     return 0;
   }

   function rebuildTbody(rows) {
     const tbody = $("tbody");
     while (tbody.firstChild) {
       tbody.remove(tbody.firstChild);
     }

     let j;
     for (j=0; j<rows.length; j++) {
       tbody.append(rows[j]);
     }
   }

   function updateClassName(th) {
     let k;
     for (k=0; k<ths.length; k++) {
       ths[k].className = "";
     }
     th.className = sortOrder === 1 ? "asc" : "desc";   
   }
   
 });
</script>

Complete page code  and output

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="sf"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jstl/core_rt" prefix="crt"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="s"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>User List</title>
<script>
$(function() {
   const ths = $("th");
   let sortOrder = 1;

   ths.on("click", function() {
     const rows = sortRows(this);
     rebuildTbody(rows);
     updateClassName(this);
     sortOrder *= -1; 
   })

   function sortRows(th) {
     const rows = $.makeArray($('tbody > tr'));
     const col = th.cellIndex;
     const type = th.dataset.type;
     rows.sort(function(a, b) {
       return compare(a, b, col, type) * sortOrder;      
     });
     return rows;
   }

   function compare(a, b, col, type) {
     let _a = a.children[col].textContent;
     let _b = b.children[col].textContent;
     if (type === "number") {
       _a *= 1;
       _b *= 1;
     } else if (type === "string") {
       
       _a = _a.toLowerCase();
       _b = _b.toLowerCase();
     }

     if (_a < _b) {
       return -1;
     }
     if (_a > _b) {
       return 1;
     }
     return 0;
   }

   function rebuildTbody(rows) {
     const tbody = $("tbody");
     while (tbody.firstChild) {
       tbody.remove(tbody.firstChild);
     }

     let j;
     for (j=0; j<rows.length; j++) {
       tbody.append(rows[j]);
     }
   }

   function updateClassName(th) {
     let k;
     for (k=0; k<ths.length; k++) {
       ths[k].className = "";
     }
     th.className = sortOrder === 1 ? "asc" : "desc";   
   }
   
 });
</script>

</head>
<body >

<div class="container" >

<h2 style="padding: 30px">Parking List</h2>
<%@include file="businessMessage.jsp" %>
<table class="table bg-light text-dark" id="myTable">
  <thead>
    <tr>
      <th scope="col" data-type="string">Parking Name</th>
      <th scope="col" data-type="string">Address</th>
      <th scope="col" data-type="number">Number of Slots</th>    
      <c:choose>
      <c:when test="${sessionScope.user.userRole=='Admin'}">   
      <th scope="col">Action</th>
      </c:when>
      </c:choose>
      <th scope="col">View Parking Slot</th>
      <th scope="col">Book</th>
    </tr>
  </thead>
  <tbody>
  <c:forEach items="${list}" var="li" varStatus="u">
    <tr>     
      <td>${li.parkingName}</td>
      <td>${li.address}</td>
      <td>${li.numberOfSlot}</td>
     
      <c:choose>
      <c:when test="${sessionScope.user.userRole=='Admin'}">  
       <td> 
      <a href="${pageContext.request.contextPath}/parkingEdit?id=${li.id}">Edit</a>
      <a href="${pageContext.request.contextPath}/parkingDelete?id=${li.id}">Delete</a> 
      </td>
      </c:when>
      </c:choose>     
      
       <td>      
      <a href="${pageContext.request.contextPath}/viewparkingSlot?id=${li.id}">View</a>    
      </td>
      <td>      
      <a href="${pageContext.request.contextPath}/booking?id=${li.id}">Book</a>    
      </td>
    </tr>
   </c:forEach>
  </tbody>
</table>

</div>

</body>
</html>