Spring form processing, mapping an object to form input

Just look at the loop example application and try to learn about form processing.

It seems that the form matches entities 1: 1 correctly? Is there any other configuration that needs to be done, or will spring know that all form inputs are mapped to the object, because this is what was added to the model in the GET request?

@Controller @RequestMapping("/owners/*/pets/{petId}/visits/new") @SessionAttributes("visit") public class AddVisitForm { private final Clinic clinic; @Autowired public AddVisitForm(Clinic clinic) { this.clinic = clinic; } @InitBinder public void setAllowedFields(WebDataBinder dataBinder) { dataBinder.setDisallowedFields("id"); } @RequestMapping(method = RequestMethod.GET) public String setupForm(@PathVariable("petId") int petId, Model model) { Pet pet = this.clinic.loadPet(petId); Visit visit = new Visit(); pet.addVisit(visit); model.addAttribute("visit", visit); return "pets/visitForm"; } @RequestMapping(method = RequestMethod.POST) public String processSubmit(@ModelAttribute("visit") Visit visit, BindingResult result, SessionStatus status) { new VisitValidator().validate(visit, result); if (result.hasErrors()) { return "pets/visitForm"; } else { this.clinic.storeVisit(visit); status.setComplete(); return "redirect:/owners/" + visit.getPet().getOwner().getId(); } } } 
+1
source share
2 answers

Note the @SessionAttributes annotation for the class:

  • When the initial GET request arrives, the newly created Visit is stored in the session.
  • When the next POST occurs, the object stored in the session is updated with the input values ​​from the form.
  • When Visit finally saved, status.setComplete() removes the session attribute.

Without @SesssionAttributes , Visit will be recreated using form input values ​​when POST arrives.

+2
source

In jsp you need spring form tags and bind each variable to a modal attribute using tags, and also specify the name of the modal attribute in the form tag. Tag opt out

0
source

Source: https://habr.com/ru/post/1300807/


All Articles