java如何理解SpringMVC工作流?
目前,我想扩展我对SpringMVC的了解,因此我正在调查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();
}
}
}
但我不能理解的是在手术后。我看了看我的firebug,我注意到我的帖子数据只是用户输入的数据,这对我来说很好
但当我检查控制器上的数据时。所有者信息仍然完整。我从JSP中查找生成的HTML,但看不到有关所有者对象的一些隐藏信息。我不确定Spring从何处收集关于所有者对象的信息
这是否意味着Spring正在为每个线程请求缓存模型对象
这是针对SpringMVC2.5的
# 1 楼答案
此行为的关键是
@SessionAttributes("pet")
,这意味着模型的pet
属性将在会话中持久化。在setupForm
中执行以下操作:这意味着:创建一个
Pet
对象,将其添加到请求中指定的所有者(@RequestParam("ownerId") int ownerId
),这可能就是设置宠物所有者属性的地方在
processSubmit
方法中,您在方法签名中声明@ModelAttribute("pet") Pet pet
,这意味着您需要先前存储在会话中的Pet
对象。Spring检索此对象,然后将其与JSP中设置的任何对象合并。因此,需要填写所有者id更多信息请参见Spring documentation