views:

362

answers:

2

Just looking at the petclinic sample application, and trying to learn form handling.

It seems the form maps to an entity 1:1 correct? Is there any other configuration that has to be done, or will spring just know that all the form inputs map to the entity because that 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();
        }
    }

}
A: 

On the jsp you have to spring form tags and bind each variable to the modal attribute using the tags and also have to specify the modalattribute name in the form tag. Tag ref

Teja Kantamneni
+2  A: 

Note the @SessionAttributes annotation on the class:

  • When the original GET request comes, the newly created Visit is stored in a session.
  • When the subsequent POST comes, object stored in the session is updated with the input values from the form.
  • When Visit is finally persisted, status.setComplete() removes the session attribute.

Without @SesssionAttributes, Visit would be recreated using the form input values when POST comes.

axtavt