I've been trying to figure out what the best practice is for form submission with spring and what the minimum boilerplate is to achieve that.
I think of the following as best practise traits
- Validation enabled and form values preserved on validation failure
- Disable form re-submission F5 (i.e. use redirects)
- Prevent the model values to appear in the URL between redirects (
model.clear()
)
So far I've come up with this.
@Controller
@RequestMapping("/")
public class MyModelController {
@ModelAttribute("myModel")
public MyModel myModel() {
return new MyModel();
}
@GetMapping
public String showPage() {
return "thepage";
}
@PostMapping
public String doAction(
@Valid @ModelAttribute("myModel") MyModel myModel,
BindingResult bindingResult,
Map<String, Object> model,
RedirectAttributes redirectAttrs) throws Exception {
model.clear();
if (bindingResult.hasErrors()) {
redirectAttrs.addFlashAttribute("org.springframework.validation.BindingResult.myModel", bindingResult);
redirectAttrs.addFlashAttribute("myModel", myModel);
} else {
// service logic
}
return "redirect:/thepage";
}
}
Is there a way to do this with less boilerplate code or is this the least amount of code required to achieve this?