DEV Community

Cover image for Thymeleaf form-handling is underrated.
Raja Anbazhagan
Raja Anbazhagan

Posted on Edited on

Thymeleaf form-handling is underrated.

Single-page applications may have sleek forms and, AJAX calls to supply details to the server. But it cannot beat the simplicity of form-submissions. With templating libraries like thymeleaf and its support towards Spring-MVC makes form handling hassle-free.

A typical way to handle form parameters is through @RequestParam annotation. For example, the following snippet is to take three form parameters to a POST endpoint.

@RequestMapping(value = "/", method = RequestMethod.POST)
public String handleForm(@RequestParam("firstName") String firstName,
    @RequestParam("lastName") String lastName, @RequestParam("role")
    Role role) {
  logger.info("first Name : {}", firstName);
  logger.info("Last Name : {}", lastName);
  logger.info("Role: {}", role);
  return "users";
}
Enter fullscreen mode Exit fullscreen mode

But this would be cumbersome when the form has too many parameters. For this reason, Spring MVC lets you wrap the parameters into a Form-Backed bean.

To do this, you need to define a class that would represent the FORM elements as POJO. Then use this class as a @ModelAttribute.

@RequestMapping(value = "/", method = RequestMethod.POST)
public String createUser(@ModelAttribute UserInfo userInfo) {
  logger.info("first Name : {}", firstName);
  logger.info("Last Name : {}", lastName);
  logger.info("Role: {}", role);
  return "users";
}
Enter fullscreen mode Exit fullscreen mode

Here is a simple tutorial and demo on Thymeleaf Form Handling in Spring Boot. This post explains how to keep model along with forms.

Top comments (2)

Collapse
 
lyrod profile image
Lyrod •

Typo in "@RequestParam("firstName") String lastName". firstName -> lastName

Collapse
 
raja_anbazhagan profile image
Raja Anbazhagan •

nice catch