Home > other >  Thymleaf how to take an input and then redirect to another page
Thymleaf how to take an input and then redirect to another page

Time:10-26

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.

CodePudding user response:

The following simple code will direct you to a URL that is generated from a concatenation of the base address of the <form>'s action attribute and the value of its first <input>:

document.querySelector("form").addEventListener("submit",function(ev){
 ev.preventDefault();
 this.action="/product/" this.querySelector("input").value;
 console.log(this.action); 
 // in real code: uncomment next line!
 // this.submit()
})
<form>
   Look up by id: <input type="text" value="123" />
</form>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

In the real code you will delete the console.log() und uncomment the following line: this.submit().

Alternatively you could also do:

document.querySelector("form").addEventListener("submit",function(ev){
 ev.preventDefault();
 location = "/product/" this.querySelector("input").value;
})

This will redirect you to the page without actually submitting the form.

CodePudding user response:

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.

  • Related