Search code examples
htmlspring-bootthymeleafrequest-mapping

Thymleaf how to take an input and then redirect to another page


I'm learning Spring boot. I have a list of products with unique ids, and I want to implement a "lookup by id" functionality, but I don't know how to do it, I searched but got totally different stuff.

I already have a @Getmapping method like this:

@Getmapping(/products/{id})

If I manually type in the id in the url I'll get what I what. But I want to have an input box in the HTML page like:

<form>
   Look up by id: <input/>
</form>

and after I submit the form it'll redirect to that page. For example, if I enter input of 1, it'll go to localhost:8080/products/1

I've been searching but all I got was stuff about @Postmapping.


Solution

  • Add a @PostMapping to your controller:

    @Controller
    @RequestMapping("/products")
    public class ProductController {
    
      @GetMapping //Controller method for showing the empty form
      public String index(Model model) {
        model.addAttribute("formData", new SearchFormData()); // Create an empty form data object so Thymeleaf can bind to it
    
        return "index";
      }
    
      @PostMapping
      public String searchById(SearchFormData formData) {
        return "redirect:/products/" + formData.getId(); //Use the value the user entered in the form to do the redirect
      }
    
      @GetMapping("/{id}")
      public String showProduct(@PathVariable("id") long id) {
        ...
      }
    }
    

    With SearchFormData representing the form fields (there is only 1 field in this case):

    public class SearchFormData {
      private long id;
    
      // getters and setters
    

    And update Thymeleaf template like this:

    <form th:action="@{/products}" th:method="post" th:object="${formData}">
      <input th:field="*{id}" type="number">
      <button type="submit">Search</button>
    </form>
    

    Note that the value of th:object needs to match with the name used to add the SearchFormData instance to the model.

    See Form handling with Thymeleaf for more info.