1. 程式人生 > >Spring MVC 從 Controller向頁面傳值的方式

Spring MVC 從 Controller向頁面傳值的方式

用戶 () 傳參數 control let att model enter 設定

Spring MVC Controller向頁面傳值的方式

在實際開發中,Controller取得數據(可以在Controller中處理,當然也可以來源於業務邏輯層),傳給頁面,常用的方式有:

1、利用ModelAndView頁面傳值

後臺程序如下:

    @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); }

頁面程序如下:

    <body>

    <h1>recive Data From Controller</h1>

    <br
> 用戶名:${user.userName } <br> 密碼:${user.password } </body> </html>

註意:

ModelAndView總共有七個構造函數,其中構造函中參數model就可以傳參數。具體見ModelAndView的文檔,model是一個Map對象,在其中設定好key與value值,之後可以在視圖中取出。

從參數定義Map<String, ?> model ,可知,任何Map的對象,都可以作為ModeAndView的參數。

2、 ModelMap作為函數參數調用方式

@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");

}

3、使用@ModelAttribute註解

方法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");

    }
View Code

方法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; 

    }
View Code

4、 使用@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");

}
View Code

Spring MVC 從 Controller向頁面傳值的方式