Handling form submission in Spring MVC means binding HTTP POST data to a Java object, validating it, and responding appropriately — either re-showing the form with errors or proceeding after success.
Key Points: • @PostMapping marks the controller method that processes the submitted form data. • @ModelAttribute binds individual form fields to the properties of a Java object automatically. • @Valid triggers bean validation against annotations like @NotNull or @Size on the model object. • A BindingResult parameter, declared immediately after the validated object, captures validation errors instead of throwing an exception. • @RequestParam is useful for grabbing individual fields directly when a full model object isn't needed. • On success, the method typically returns a redirect to avoid duplicate submissions on page refresh (the Post/Redirect/Get pattern).
Example: A registration form posts to /register, binds to a User object via @ModelAttribute, and if BindingResult.hasErrors() is true the method returns back to the registration view with error messages instead of proceeding.
Code Example:
@PostMapping("/register")
public String register(@Valid @ModelAttribute User user,
BindingResult result) {
if (result.hasErrors()) {
return "registerForm";
}
userService.save(user);
return "redirect:/success";
}Interview Tip: A concise interview answer is:
"I use @PostMapping with @ModelAttribute to bind form fields onto a Java object, add @Valid to trigger bean validation, and capture errors with a BindingResult parameter right after it. If there are errors I return back to the form view, otherwise I process the data and redirect to avoid duplicate submissions."