Home > Back-end >  Show Output of Controller method via Thymeleaf
Show Output of Controller method via Thymeleaf

Time:02-19

I just started working on Thymeleaf and wanted to connect a Spring Boot application with HTML using Thymeleaf. I had my "normal" controllers without Thymeleaf like this:

 @GetMapping(path = "/{id}")
    public BookEntity getBookById(@PathVariable Long id) {
        return bookService.getById(id);
    }



@GetMapping
        public List<BookEntity> getAllBooks() {
            return bookService.findAll();
        }

Now that Im using Thymeleaf I created some new Controllers like this:

 @GetMapping(path = "/book/{id}")
    public String getBookById(@PathVariable("id") Long id, Model model) {
        BookEntity book= bookService.getById(id);
        model.addAttribute("book", book);
        return "book/{id}";
    }
    
@GetMapping("/book/all")
    public String AllBooks(Model model) {
        List<BookEntity> books = bookService.findAll();
        model.addAttribute("books", books);

        return "books";
    }

I also created a book.html file in resources/templates like this:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
    <title>Books</title>
</head>
<body>
<h4>Select action to do something</h4>
<form th:action="@{/book/{id}(id=book.getId())" method="get">
    <label for="id">id:</label><br>
    <input type="number" id="id" name="id" placeholder="id" required>
    <input type="submit" value="Submit">
</form>


</body>
</html>

But this isnt working I wanted to submit the book Id (in the input) and in return I get the Book with the right id. I tried to use ModelAndView instead of Model and return a ModelAndView but it didnt work. Can anyone tell what am I doing wrong. Thanks in advance

CodePudding user response:

The String return type you use in a @Controller (as opposed to the @RestController you used before) indicates the name of the Thymeleaf template.

Normally, I would use 2 templates:

  • book-list.html to show the list of books
  • book.html to show the details of a single book

Those files need to be in src/main/resources/templates. Assuming you have that, your controller becomes:

    @GetMapping(path = "/books/{id}")
    public String getBookById(@PathVariable("id") Long id, Model model) {
        BookEntity book = bookService.getById(id);
        model.addAttribute("book", book);
        return "book";
    }
    
@GetMapping("/books")
    public String AllBooks(Model model) {
        List<BookEntity> books = bookService.findAll();
        model.addAttribute("books", books);

        return "book-list";
    }

In book-list.html, you can do something like this:

<tr th:each="book: ${books}">
    <td th:text="${book.id}" />
    <td th:text="${book.name}" />
    <td><a th:href="@{/books/{id}(id=book.id)">View details</a></td>
</tr>

In book.html, you can show the details of the book:

<div>
  <h1 th:text="${book.name}"></h1>
  ...
</div>

Now opening your browser to http://localhost:8080/books should show the list of books with hyperlinks to navigate to the details of the book.

CodePudding user response:

First you have to understand without extracting books how can you get book id. You have to extract books and put book_id in anchor tag link href. If you click on the link tag, you find that perticular book data.

Here down is code:

Suppose Entity is:

@Entity
public class Book {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private Integer page;
    
    // getter setter
}

Contorller

@GetMapping(path = "/books/{id}")
public String getBookById(@PathVariable("id") Long id, Model model) {
    BookEntity book = bookService.getById(id);
    model.addAttribute("book", book);
    return "book";
}
    
@GetMapping("/books")
public String AllBooks(Model model) {
   List<BookEntity> books = bookService.findAll();
   model.addAttribute("books", books);
   return "books";
}

Here down is two templates book.html and books.html. Path of this both file is src/main/resources/templates.

books.html

<tr th:each="book: ${books}">
    <td th:text="${book.id}" />
    <td th:text="${book.name}" />
    <td th:text="${book.page}" />
    <td><a th:href="@{/books/{id}(id=book.id)">Go To Book</a></td>
</tr>

book.html

<div>
  Book Name: <label th:text="${book.name}"></label>
  How Many Pages: <label th:text="${book.page}"></label>
</div>
  • Related