开发者

Spring form handling, mapping an entity to form inputs

开发者 https://www.devze.com 2022-12-19 21:18 出处:网络
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 spri

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 resul开发者_开发知识库t, 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();
        }
    }

}


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消