SpringMVC 之 ModelAndView和ModelAttribute的使用
ModelAndView解釋 :
This class merely holds both to make it possible for a controller to return both model and view in a single return value.
這類控制器可以同時返回檢視和模型資料.
ModelAndView使用:
ModelAndView() Default constructor for bean-style usage: populating bean properties instead of passing in constructor arguments. |
ModelAndView(StringviewName) Convenient constructor when there is no model data to expose. |
ModelAndView(StringviewName,Map<String,?>model) Creates new ModelAndView given a view name and a model. |
ModelAndView(StringviewName,StringmodelName, ObjectmodelObject) Convenient constructor to take a single model object. |
ModelAndView(Viewview) Convenient constructor when there is no model data to expose. |
ModelAndView(Viewview,Map<String,?>model) Creates new ModelAndView given a View object and a model. |
ModelAndView(Viewview,StringmodelName,ObjectmodelObject) Convenient constructor to take a single model object. |
ModelAttribute的使用:
在方法定義上使用 @ModelAttribute 註解:
Spring MVC在呼叫目標處理方法前,會在每個目標方法前,先逐個呼叫在方法級上標註了@ModelAttribute 的方法。 在方法的入參前使用 @ModelAttribute 註解:
流程:1.執行@ModelAttribute註解的方法: 從資料庫取出相關物件,自動把物件放到request的map中
2.SpringMvc 從map中取出相關物件,並把前臺相關的表單屬性賦值給這個物件
轉載於:https://my.oschina.net/giegie/blog/425908