SpringMVC的ModelAndView传值方法

时间:2022-09-27 14:13:28

springmvc提供的modelandview可以很方便的将后台的值传到前台,前台页面直接使用el表达式进行获取,获取方式:

1、

?
1
2
3
4
5
6
7
8
@requestmapping(value = "/home")
  public modelandview home(httpservletrequest request, httpservletresponse response){
      list<string> list=new arraylist<string>();
      list.add("aaa");
      list.add("bbb");
      list.add("ccc");
      return new modelandview("back/index", "list", list);//直接将值和路径放到构造方法中返回
  }

2、

?
1
2
3
4
5
6
7
8
9
10
11
@requestmapping(value = "/home")
  public modelandview home(httpservletrequest request, httpservletresponse response){
      list<string> list=new arraylist<string>();
      list.add("aaa");
      list.add("bbb");
      list.add("ccc");
      modelandview mav=new modelandview();
      mav.setviewname("back/index");//返回路径
      mav.addobject("list", list);//使用modelandview的addobject方法将list放进去
      return mav;
  }

1和2返回的都是一个list,也可以返回单个值,如下是代码实现:

?
1
2
3
4
5
6
7
@requestmapping(value = "/home")
public modelandview home(httpservletrequest request, httpservletresponse response){
modelandview mav=new modelandview();
mav.setviewname("back/index");//返回路径
mav.addobject("msg", "我要返回值");
return mav;
}

3、也可以返回一个map

?
1
2
3
4
5
6
7
8
9
10
@requestmapping(value = "/home")
public modelandview home(httpservletrequest request, httpservletresponse response){
map<string, string> map=new hashmap<string, string>();
map.put("pk", "北京");
map.put("sh", "上海");
modelandview mav=new modelandview();
mav.setviewname("back/index");//返回路径
mav.addobject("map", map);
return mav;
}

4、

?
1
2
3
4
5
6
7
@requestmapping(value = "/home")
public modelandview home(httpservletrequest request, httpservletresponse response){
map<string, string> map=new hashmap<string, string>();
map.put("pk", "北京");
map.put("sh", "上海");
return new modelandview("back/index","map", map).addobject("msg", "我要返回值");
}

以上四种返回方法,在项目中都是很有用的,希望可以帮助到大家,谢谢!

这篇springmvc的modelandview传值方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/carse/article/details/61920028