SpringMVC作用域传值.
1. 把作用域对象当作方法参数
2. request作用域传值的三种方式 (在JSP 页面中 可以通过 Request作用域获得值)
2.1 Map当作参数(解耦)
2.1.1 Spring会给Map接口注入BindingAwareModelMap
2.2 Model 当作参数(解耦:解除和原生Servlet的耦合)
2.2.1 Spring会给Model接口注入BindingAwareModelMap
index.jsp
<body>
3.1 通过request对象获取
4.1 不能把application当作方法参数,通过request获取
1. 把作用域对象当作方法参数
2. request作用域传值的三种方式 (在JSP 页面中 可以通过 Request作用域获得值)
2.1 Map当作参数(解耦)
2.1.1 Spring会给Map接口注入BindingAwareModelMap
@Controller public class DemoController { @RequestMapping("scope") public String scope(Map<String,Object> map){ // Map的本质也是 req.setAttribute("msg", "消息"); map.put("msg", "map方式的参数"); return "index.jsp"; // 默认的方式的是请求转发 } }
2.2 Model 当作参数(解耦:解除和原生Servlet的耦合)
2.2.1 Spring会给Model接口注入BindingAwareModelMap
@Controller public class DemoController { @RequestMapping("scope") public String scope(Model model){ model.addAttribute("msg", "Model消息");// 还是存放在 Request里面 return "index.jsp"; } }2.3 request当作参数(原生Servlet API)
index.jsp
<body>
msg:${msg}<br/> session:${sessionScope.msg}<br/> application:${applicationScope.msg} </body>DemoController.java
@Controller public class DemoController { // 如何向JSP页面传递值呢? @RequestMapping("scope") public String scope(HttpServletRequest req){ req.setAttribute("msg", "消息"); req.getSession().setAttribute("msg", "session的消息"); req.getServletContext().setAttribute("msg", "application的消息"); return "index.jsp"; } }3. session两种方式
3.1 通过request对象获取
@RequestMapping("scope") public String scope(HttpServletRequest req){ HttpSession session = req.getSession(); session.setAttribute("", ""); return "index.jsp"; }3.2 直接把Session当作方法参数
@RequestMapping("scope") public String scope(HttpSession session){ session.setAttribute("", ""); return "index.jsp"; }4. application作用域
4.1 不能把application当作方法参数,通过request获取
@RequestMapping("scope") public String scope(HttpServletRequest req){ ServletContext application = req.getServletContext(); application.setAttribute("", ""); return "index.jsp"; }