SpringMVC的ModelAndView传值

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

1.

        @RequestMapping(value = "/home")
	public ModelAndView home(HttpServletRequest request, HttpServletResponse response){
		List list=new ArrayList();
		list.add("aaa");
		list.add("bbb");
		list.add("ccc");
		return new ModelAndView("back/index", "list", list);//直接将值和路径放到构造方法中返回
	}
2.
        @RequestMapping(value = "/home")
	public ModelAndView home(HttpServletRequest request, HttpServletResponse response){
		List list=new ArrayList();
		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,也可以返回单个值,如下是代码实现:

        @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

        @RequestMapping(value = "/home")
	public ModelAndView home(HttpServletRequest request, HttpServletResponse response){
		Map map=new HashMap();
		map.put("PK", "北京");
		map.put("SH", "上海");
		ModelAndView mav=new ModelAndView();
		mav.setViewName("back/index");//返回路径
		mav.addObject("map", map);
		return mav;
	}
4.

        @RequestMapping(value = "/home")
	public ModelAndView home(HttpServletRequest request, HttpServletResponse response){
		Map map=new HashMap();
		map.put("PK", "北京");
		map.put("SH", "上海");
		return new ModelAndView("back/index","map", map).addObject("msg", "我要返回值");
	}
以上四种返回方法,在项目中都是很有用的,希望可以帮助到大家,谢谢!

你可能感兴趣的:(SpringMVC)