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传到页面中去

        

@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

相关文章:

  • 2022-12-23
  • 2021-08-23
  • 2021-11-05
  • 2022-12-23
  • 2022-02-20
  • 2021-07-10
猜你喜欢
  • 2022-01-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-07
相关资源
相似解决方案