![](/img/trans.png)
[英]Spring MVC Controller Test passing due to not finding model attribute
[英]Spring MVC: Passing a Model as an argument to a controller method VS instantiating it explicitly
我在MVC Controller
類中創建了兩個測試方法。 在第一種方法中, Model
作為參數傳遞,在第二種方法中,我直接實例化它。 在這兩種方法中,我向Model
實例添加了一個屬性:
@RequestMapping("/test-modelParam")
public String testMethod1(Model model) {
model.addAttribute("testname", "testvalue");
return "/testview";
}
@RequestMapping("/test-modelInstantiatedExplicitly")
public ModelAndView testMethod2() {
ModelAndView mav = new ModelAndView("/testview");
mav.addObject("testname", "testvalue");
return mav;
}
在兩種情況下都會正確填充視圖。
這兩種方法有什么區別嗎? 如果是這樣,在哪里使用一個而不是另一個?
最終,沒有任何區別最終會在ModelAndView
結束。
當使用Model
或ModelMap
作為方法參數時,它將預先填充一些值
@ModelAttribute
注釋方法的結果 @SessionAttribute
可供控制器使用 簡而言之,它是可用於該方法的預先填充的模型。
始終創建Model
,並將其與使用ModelAndView
添加/創建的Model
合並。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.