ASPCode.net logo
  • Home 
  • Blogs 
  • Tags 
Blog
  1. Home
  2. Articles
  3. Java Spring Thymeleaf Sorting

Java Spring Thymeleaf Sorting

Posted on May 9, 2024  (Last modified on October 11, 2024) • 3 min read • 483 words
Java
 
Spring
 
Java
 
Spring
 
Share via
ASPCode.net
Link copied to clipboard

Video is in Swedish

On this page
  • Sorting with Java Spring and Thymeleaf
  • Prerequisites
  • Step 1: Create the Project Structure
  • Step 2: Create the Book Entity
  • Step 3: Create the Book Repository
  • Step 4: Create the Controller
  • Step 5: Create the Thymeleaf Template
  • Step 6: Run the Application
  • Video
  • Sourcecode

Sorting with Java Spring and Thymeleaf  

In this article, we will explore how to implement sorting functionality in a web application using Java Spring and Thymeleaf. We will create a simple example of a book list that can be sorted by title or author.

Prerequisites  

  • Java 8 or higher
  • Spring Boot 2.x or higher
  • Thymeleaf 3.x or higher
  • Maven or Gradle for project management

Step 1: Create the Project Structure  

Create a new Spring Boot project using your preferred build tool (Maven or Gradle). Add the necessary dependencies to your pom.xml file (for Maven) or build.gradle file (for Gradle):

<!-- Maven -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

<!-- Gradle -->
dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
}

Step 2: Create the Book Entity  

Create a new Java class Book.java to represent a book entity:

@Entity
public class Book {
    @Id
    private Long id;
    private String title;
    private String author;

    // getters and setters
}

Step 3: Create the Book Repository  

Create a new interface BookRepository.java that extends Spring’s JpaRepository:

public interface BookRepository extends JpaRepository<Book, Long> {
}

Step 4: Create the Controller  

Create a new Java class BookController.java to handle HTTP requests:

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookRepository bookRepository;

    @GetMapping
    public String getBooks(Model model) {
        List<Book> books = bookRepository.findAll();
        model.addAttribute("books", books);
        return "books";
    }

    @GetMapping("/{sortField}")
    public String getSortedBooks(@PathVariable String sortField, Model model) {
        List<Book> books;
        if (sortField.equals("title")) {
            books = bookRepository.findAllByOrderByTitleAsc();
        } else if (sortField.equals("author")) {
            books = bookRepository.findAllByOrderByAuthorAsc();
        } else {
            books = bookRepository.findAll();
        }
        model.addAttribute("books", books);
        return "books";
    }
}

Step 5: Create the Thymeleaf Template  

Create a new HTML file books.html in the src/main/resources/templates directory:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Book List</title>
</head>
<body>
    <h1>Book List</h1>
    <table>
        <thead>
            <tr>
                <th th:text="#{title}">Title</th>
                <th th:text="#{author}">Author</th>
            </tr>
        </thead>
        <tbody>
            <tr th:each="book : ${books}">
                <td th:text="${book.title}">Title</td>
                <td th:text="${book.author}">Author</td>
            </tr>
        </tbody>
    </table>

    <form th:action="@{/books/{sortField}(sortField)}" method="get">
        <select name="sortField" th:value="${#request.getParameter('sortField')}">
            <option value="title">Title (A-Z)</option>
            <option value="author">Author (A-Z)</option>
        </select>
        <input type="submit" value="Sort">
    </form>
</body>
</html>

Step 6: Run the Application  

Run your Spring Boot application using your preferred build tool. Open a web browser and navigate to http://localhost:8080/books. You should see a list of books that can be sorted by title or author.

In this example, we used Thymeleaf’s th:each attribute to iterate over the book list and display each book’s title and author. We also used Thymeleaf’s th:text attribute to display the book’s title and author in the table cells.

By using Spring Boot’s @GetMapping annotation, we can handle HTTP GET requests for sorting the book list by title or author. The BookRepository interface provides a simple way to interact with the database and retrieve the sorted book list.

This is just a basic example of how to implement sorting functionality in a web application using Java Spring and Thymeleaf. You can customize this example to fit your specific use case and requirements.

Video  

Swedish

Sourcecode  

Sourcecode
 
 Java Integration Tests Gradle
Git Command Line 
On this page:
  • Sorting with Java Spring and Thymeleaf
  • Prerequisites
  • Step 1: Create the Project Structure
  • Step 2: Create the Book Entity
  • Step 3: Create the Book Repository
  • Step 4: Create the Controller
  • Step 5: Create the Thymeleaf Template
  • Step 6: Run the Application
  • Video
  • Sourcecode
Follow me

I code in Java, C#, Golang, SQL and more

     
© 2024 Systementor AB
ASPCode.net
Code copied to clipboard