江蘇省建設廳網(wǎng)站模板建站網(wǎng)頁
SpringMVC中Model和ModelAndView的區(qū)別
兩者的區(qū)別:
在SpringMVC中,Model和ModelAndView都是用于將數(shù)據(jù)傳遞到視圖層的對象
Model是”模型“的意思,是MVC架構中的”M“部分,是用來傳輸數(shù)據(jù)的。
理解成MVC架構中的”M“和”V“,其中包含”Model“和”View“兩部分,主要功能是:設置轉向地址,將底層獲取的數(shù)據(jù)進行存儲(或者封裝),最后將數(shù)據(jù)傳遞給View。
Model只是用來傳輸數(shù)據(jù)的,并不會進行業(yè)務的尋址。ModelAndView 卻是可以進行業(yè)務尋址的,就是設置對應的要請求的靜態(tài)文件,這里的靜態(tài)文件指的是類似JSP的文件。
Model是每次請求中都存在的默認參數(shù),利用其addAttribute()方法即可將服務器的值傳遞到JSP頁面中。
ModelAndView包含Model和View兩部分,使用時需要自己實例化,利用ModelMap用來傳值,也可以設置View的名稱。
其次,兩者還有一個最大的區(qū)別,每次發(fā)起請求后Spring MVC會自動創(chuàng)建Model對象,而ModelAndView需要我們自己創(chuàng)建
總結:
雖然Model和ModelAndView都可以用于將數(shù)據(jù)傳遞到視圖層,但ModelAndView更加強大,因為它不僅可以傳遞數(shù)據(jù),還可以指定要呈現(xiàn)的視圖。如果你只需要傳遞數(shù)據(jù)而不關心視圖,則可以使用Model。但如果你需要同時傳遞數(shù)據(jù)和指定視圖,則應該使用ModelAndView。
Model在Controller層的寫法
@Controller //代表這個類會被Spring接管,被這個注解的類中所有方法,如果返回值是String,并且有具體的頁面可以跳轉,那么就會被視圖解析器解析
public class IndexController {@RequestMapping("/demo") //意為請求 localhost:8080/demopublic String demo(Model model){//封裝數(shù)據(jù)(向模型中添加數(shù)據(jù),可以jsp頁面直接取出并渲染)model.addAttribute("Content","Hello");//會被視圖解析器處理return "Hello"; //返回到哪個頁面 }
}
model方法是可以返回一個對象的。model.addAttribute(String s,Object o),返回對象要創(chuàng)建一個實體對象生成getter和Setter,還有同String()方法
ModelAndView在Controller層的寫法
@Controller
@RequestMapping
public class IndexController {@RequestMapping("/demo2")public ModelAndView demo2(){ModelAndView modelAndView = new ModelAndView();//返回到那個前端文件modelAndView.setViewName("hello"); modelAndView.addObject("ContentOne","HelloOne");modelAndView.addObject("ContentTwo","HelloTwo");System.out.println(modelAndView);return modelAndView;}
}