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

验证代码: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"); }
复制代码
相关文章
相关标签/搜索