In a a POST request handling method (annotated with @RequestMapping
) of a Spring MVC controller, you can access the form values POST-ed from the form in two ways (correct?).
Use @ModelAttribute
You can use a model object (command) class that bundles all the form values together and use an argument annotated @Valid
@ModelAttribute
to pass in the form values. This seems to be the common way of processing forms.
@RequestMapping(value = { "thing/{thing}/part/" }, method = RequestMethod.POST)
public String processForm(
@PathVariable("thing") final String thing,
@ModelAttribute(value = "command") @Valid final Command command,
final BindingResult bindingResult) {
if (!bindingResult.hasErrors()) {
final String name = command.getName();
final long time = command.getTime().getTime();
// Process the form
return "redirect:" + location;
} else {
return "form";
}
}
Use @RequestParam
.
You can annotate individual method arguments with @RequestParam
.
@RequestMapping(value = { "thing/{thing}/part/" }, method = RequestMethod.POST)
public String processForm(
@PathVariable("thing") final String thing,
@RequestParam(value = "name", required=true) final String name,
@RequestParam(value = "time", required=true) final Date time,
final HttpServletResponse response) {
// Process the form
return "redirect:" + location;
}
Why Use @ModelAttribute
So why bother using @ModelAttribute
, given that it has the inconvenience of having to create an auxiliary command class? What are the limitations of using a @RequestParam
.