SpringMVC的RequestContextHolder分析

本文详细解析了RequestContextHolder在Spring框架中的作用,特别是在Service层如何通过它获取Request和Response对象,提供了具体的代码示例,并介绍了封装工具类的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为什么要分析这个RequestContextHolder?
首先,我们一般获取request和response都是在过滤器Filter,或者拦截器,或者controller层获取

但如果在service获取request和response,正常来说在service层是没有request的,当我们需要在service层获取request和response时,我们可以在RequestContextHolder中获取。

        //两个方法在没有使用JSF的项目中是没有区别的
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
//                                            RequestContextHolder.getRequestAttributes();
        //从session里面获取对应的值
        String str = (String) requestAttributes.getAttribute("name",RequestAttributes.SCOPE_SESSION);

        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        HttpServletResponse response = ((ServletRequestAttributes)requestAttributes).getResponse();

一般封装工具类

	/**
	 * 获取request
	 */
	public static HttpServletRequest getRequest() {
		return getRequestAttributes().getRequest();
	}

	/**
	 * 获取response
	 */
	public static HttpServletResponse getResponse() {
		return getRequestAttributes().getResponse();
	}

	/**
	 * 获取session
	 */
	public static HttpSession getSession() {
		return getRequest().getSession();
	}

	public static ServletRequestAttributes getRequestAttributes() {
		RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
		return (ServletRequestAttributes) attributes;
	}

可参考文章:https://blog.youkuaiyun.com/u012706811/article/details/53432032

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值