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";
}
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";
}
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)
Typo in "@RequestParam("firstName") String lastName". firstName -> lastName
nice catch