如何理解Spring MVC工作流?

Mar*_*ada 3 java spring spring-mvc

我目前想扩展我对Spring MVC的知识,所以我正在调查spring发布的示例Web应用程序.我基本上检查了Petclinic应用程序.

在GET方法中,Pet对象被添加到模型属性中,因此JSP可以访问javabean属性.我想我理解这个.

@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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我无法理解的是在POST操作期间.我抬头看着我的萤火虫,我注意到我的帖子数据只是用户输入的数据,对我来说很好.

替代文字

但是当我检查控制器上的数据时.所有者信息仍然完整.我查看了JSP中生成的HTML,但是我看不到有关Owner对象的一些隐藏信息.我不确定Spring在哪里收集所有者对象的信息.

这是否意味着Spring正在为每个线程请求缓存模型对象?

替代文字

这适用于Spring MVC 2.5.

gab*_*uzo 5

此行为的关键是@SessionAttributes("pet")这意味着pet模型的属性将保留在会话中.在setupForm您执行以下操作:

    Pet pet = new Pet();
    owner.addPet(pet);
    model.addAttribute("pet", pet);
Run Code Online (Sandbox Code Playgroud)

这意味着:创建一个Pet对象,将其添加到request(@RequestParam("ownerId") int ownerId)中指定的所有者,这可能是pet owner属性设置的位置.

在该processSubmit方法中,您@ModelAttribute("pet") Pet pet在方法签名中声明,这意味着您需要Pet先前存储在会话中的对象.Spring检索此对象,然后将其与JSP中设置的任何内容合并.因此,填写所有者ID.

Spring文档中的更多信息