SpringMVC_day02_3(Spring作用域传值)

本文详细介绍了SpringMVC框架中如何通过不同方式将数据传递到视图层,包括使用Map、Model以及直接利用HttpServletRequest对象等方法。此外还探讨了session及application作用域的数据传递。
                                                                        SpringMVC作用域传值.
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";
	    }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值