转自:
下文笔者讲述ModelAndView将值传送到JSP页面的四种方法
SpringMVC使用ModelAndView传值的本质: 将传入的值放入到request对象中 然后在相对应的jsp中使用EL表达式将值取出来展示或处理
方式一:直接将值和路径放到构造方法中返回
@RequestMapping(value = "/home") public ModelAndView home(HttpServletRequest request, HttpServletResponse response){ Listlist list=new ArrayList(); list.add("java265.com-1"); list.add("java265.com-3"); list.add("java265.com-2"); return new ModelAndView("back/index", "list", list);//直接将值和路径放到构造方法中返回 }
方式二:使用ModelAndView的addObject方法返回list
@RequestMapping(value = "/home") public ModelAndView home(HttpServletRequest request, HttpServletResponse response){ Listlist list=new ArrayList(); list.add("java265.com-1"); list.add("java265.com-2"); list.add("java265.com-3"); ModelAndView m=new ModelAndView(); m.setViewName("back/index");//返回路径 m.addObject("list", list);//使用ModelAndView的addObject方法将list放进去 return m; }
方式三:使用ModelAndView的addObject方法返回map
@RequestMapping(value = "/home") public ModelAndView home(HttpServletRequest request, HttpServletResponse response){ Map map=new HashMap(); map.put("a", "Java265---1"); map.put("b", "java265.com-2"); ModelAndView mav=new ModelAndView(); mav.setViewName("back/index");//返回路径 mav.addObject("map", map); return mav; }
方式四:ModelAndView返回多个对象
@RequestMapping(value = "/home") public ModelAndView home(HttpServletRequest request, HttpServletResponse response){ Map map=new HashMap(); map.put("a", "Java265---1"); map.put("b", "java265.com-2"); return new ModelAndView("back/index","map", map).addObject("msg", "我要返回值"); }
例
//controller.java @RequestMapping("/test") public ModelAndView test(){ ModelAndView mav=new ModelAndView("hello"); mav.addObject("time", new Date()); mav.getModel().put("name", "caoyc"); return mav; } //jsp页面 time:${requestScope.time} name:${name }
例
//后端代码 @RequestMapping("/index") public ModelAndView page() { ModelAndView view = new ModelAndView("index.jsp"); view.addObject("parameter1", "java教程网www.java265.com"); return view; } //js要写在jsp中 <script> var par =${parameter1}; console.log(par);//打印'随便写点东西' </script> //jsp页面,加载页面时候,将参数直接赋值给标签 <input type="hidden" value="${parameter1}">