2011-01-11 73 views
3

我目前想擴展我對Spring MVC的知識,所以我正在研究Spring發佈版本的示例Web應用程序。我基本上檢查Petclinic應用程序。幫助瞭解Spring MVC工作流程

在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(); 
     } 
    } 
} 

但是我不明白的是在POST操作過程中。我看着我的螢火蟲,我注意到我的發佈數據只是用戶輸入的數據,對我來說很好。

alt text

但是,當我檢查我的控制器上的數據。所有者信息仍然完整。我從JSP中查看生成的HTML,但看不到有關Owner對象的一些隱藏信息。我很不確定Spring在哪裏收集所有者對象的信息。

這是否意味着Spring爲每個線程請求緩存模型對象?

alt text

很抱歉,如果我的職位是有點漫長,但我只是想了解更多的Spring MVC的。順便說一句,這仍然是Spring MVC 2.5。

回答

5

此行爲的關鍵是@SessionAttributes("pet")這意味着模型的pet屬性將在會話中保留。在setupForm請執行下列操作:

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

這意味着:創建一個Pet對象,將其添加到請求(@RequestParam("ownerId") int ownerId)指定的所有者,這可能是在寵物主人屬性被設置。

processSubmit方法中,您在方法簽名中聲明@ModelAttribute("pet") Pet pet,這意味着您希望先前存儲在會話中的Pet對象。 Spring檢索這個對象,然後將它與JSP中設置的任何東西進行合併。因此,填寫的所有者ID。在Spring documentation

+1

更多信息...在「會話狀態」(而不是在HttpSession中直接)存儲在能夠與SessionStatus.setComplete(),而不影響的HttpSession狀態的其他部分被清除。 – 2011-12-20 10:01:28