Spring MVC 从 Controller向页面传值的方式

Spring MVC 从 Controller向页面传值的方式

Spring MVC  Controller向页面传值的方式

验证代码:https://files.cnblogs.com/files/peiyangjun/20180104_springMVC_easyui.zip

在实际开发中,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传到页面中去

        

 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; 

    }

复制代码

                        

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

}

复制代码

转载:https://www.cnblogs.com/peiyangjun/p/8183438.html

猜你喜欢

转载自blog.csdn.net/kelly921011/article/details/88530285