开发者

How to understand Spring MVC Workflow?

开发者 https://www.devze.com 2023-02-03 08:13 出处:网络
I currently would like to expand my knowledge on Spring MVC so I am investigating the sample web apps that the spring distribution has.I am basically checking the Petclinic application.

I currently would like to expand my knowledge on Spring MVC so I am investigating the sample web apps that the spring distribution has. I am basically checking the Petclinic application.

In the GET method, the Pet object was added into the model attributes so the JSP can access the javabean properties. I think I understand this one.

@Controller
@RequestMapping("/addPet.do")
@SessionAttributes("pet")
public class AddPetForm {
    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(@RequestParam("ownerId") int ownerId, Model model) {
        Owner owner = this.clinic.loadOwner(ownerId);
        Pet pet = new Pet();
        owner.addPet(pet);
        model.addAttribute("pet", pet);
        return "petForm";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) {
        new PetValidator().validate(pet, result);
        if (result.hasErrors()) {
            return "petForm";
        }
        else {
            this.clinic.storePet(pet);
            status.setComplete();
            return "redirect:owner.do?ownerId=" + pet.getOwner().getId();
        }
    }
}

But the thing that I cannot understand is during the POST operation. I look up at my firebug, and I notice that my post dat开发者_运维技巧a are only the data that was entered by the user which to me is fine.

How to understand Spring MVC Workflow?

But when I inspect the data on my controller. The owner info is still complete. I look up at the generated HTML from the JSP but I cannot see some hidden information about the Owner object. I am quite not sure where does Spring gather the info on the owner object.

Does this mean that Spring is caching the model objects per each thread request?

How to understand Spring MVC Workflow?

This is for Spring MVC 2.5.


The key to this behavior is @SessionAttributes("pet") which means that the pet attribute of the model will be persisted in the session. In setupForm you perform the following operations:

    Pet pet = new Pet();
    owner.addPet(pet);
    model.addAttribute("pet", pet);

Which means: create an Pet object, add it to the owner specified in the request (@RequestParam("ownerId") int ownerId), this is probably where the pet owner attribute gets set.

In the processSubmit method, you declare @ModelAttribute("pet") Pet pet in the method signature which means that you want the Pet object you previously store in the session. Spring retrieves this object and then merge it with whatever had been set in the JSP. Hence a filled owner id.

More information in the Spring documentation

0

精彩评论

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