驗證代碼:https://files.cnblogs.com/files/peiyangjun/20180104_springMVC_easyui.ziphtml
在實際開發中,Controller取得數據(能夠在Controller中處理,固然也能夠來源於業務邏輯層),傳給頁面,經常使用的方式有:spring
一、利用ModelAndView頁面傳值session
後臺程序以下:app
@RequestMapping(value="/reciveData",method=RequestMethod.GET)
public ModelAndView StartPage() { ModelMap map=new ModelMap(); User user=new User(); user.setPassword("123456"); user.setUserName("ZhangSan"); map.put("user", user); return new ModelAndView("reciveControllerData",map); }
頁面程序以下:ide
<body> <h1>recive Data From Controller</h1> <br> 用戶名:${user.userName } <br> 密碼:${user.password } </body> </html>
注意:函數
ModelAndView總共有七個構造函數,其中構造函中參數model就能夠傳參數。具體見ModelAndView的文檔,model是一個Map對象,在其中設定好key與value值,以後能夠在視圖中取出。ui
從參數定義Map<String, ?> model ,可知,任何Map的對象,均可以做爲ModeAndView的參數。this
二、 ModelMap做爲函數參數調用方式spa
@RequestMapping(value="/reciveData2",method=RequestMethod.GET)
public ModelAndView StartPage2(ModelMap map) { User user=new User(); user.setPassword("123456"); user.setUserName("ZhangSan"); map.put("user", user); return new ModelAndView("reciveControllerData"); }
三、使用@ModelAttribute註解code
方法1:@modelAttribute在函數參數上使用,在頁面端能夠經過HttpServletRequest傳到頁面中去
@RequestMapping(value="/reciveData3",method=RequestMethod.GET)
public ModelAndView StartPage3(@ModelAttribute("user") User user) { user.setPassword("123456"); user.setUserName("ZhangSan"); return new ModelAndView("reciveControllerData"); }
方法2:@ModelAttribute在屬性上使用
@RequestMapping(value="/reciveData4",method=RequestMethod.GET)
public ModelAndView StartPage4() { sthname="LiSi"; return new ModelAndView("reciveControllerData"); } /*必定要有sthname屬性,並在get屬性上取加上@ModelAttribute屬性*/ private String sthname; @ModelAttribute("name") public String getName(){ return sthname; }
四、 使用@ModelAttribute註解
/*直接用httpServletRequest的Session保存值。
* */
@RequestMapping(value="/reciveData5",method=RequestMethod.GET)
public ModelAndView StartPage5(HttpServletRequest request) { User user=new User(); user.setPassword("123456"); user.setUserName("ZhangSan"); HttpSession session=request.getSession(); session.setAttribute("user", user); return new ModelAndView("reciveControllerData"); }