RequestContextHolder

阅读数:56 评论数:0

跳转到新版页面

分类

python/Java

正文

一、概述

RequestContextHolder顾名思义,即持有上下文的Request容器,可以把它看作是一个工具类。

二、使用

// RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
// currentRequestAttributes 避免 null 提示
RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
 
// 获取请求体 request
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
 
// 获取响应体 response
HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse();
 
// 获取请求头 headers
Enumeration<String> headerNames = request.getHeaderNames();
// 根据请求体参数从 request 中获取 header 请求头值
Map<String, String> headers = new HashMap<>();
if (headerNames.hasMoreElements()) {
    String name = headerNames.nextElement();
    headers.put(name, request.getHeader(name));
}

三、Springboot中的RequestContextHolder

1、静态成员

requestAttributesHolder 请求属性持有者
inheritableRequestAttributesHolder  可被子类继承的请求属性持有者

2、静态方法

resetRequestAttributes 重置请求属性
setRequestAttributes 设置请求属性
getRequestAttributes 获得请求属性
currentRequestAttributes  当前请求属性

(1)setRequestAttributes

	public static void setRequestAttributes(@Nullable RequestAttributes attributes) {
		setRequestAttributes(attributes, false);
	}

	public static void setRequestAttributes(@Nullable RequestAttributes attributes, boolean inheritable) {
		if (attributes == null) {
			resetRequestAttributes();
		}
		else {
			if (inheritable) {
				inheritableRequestAttributesHolder.set(attributes);
				requestAttributesHolder.remove();
			}
			else {
				requestAttributesHolder.set(attributes);
				inheritableRequestAttributesHolder.remove();
			}
		}
	}

3、springboot什么时候设置请求属性

Spring MVC的核心是DispatcherServlet,它负责将分发请求,DispatcherServlet继承自FrameworkServlet,而FrameworkServlet中的service、doGet、doPost等方法都会调用processRequest方法。

	protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		...

		initContextHolders(request, localeContext, requestAttributes);

		try {
			doService(request, response);
		}
		catch
            
		...
            
		finally {
			resetContextHolders(request, previousLocaleContext, previousAttributes);
            
            ...
                
		}
	}

//...
	private void initContextHolders(HttpServletRequest request,
			@Nullable LocaleContext localeContext, @Nullable RequestAttributes requestAttributes) {

		...
            
		if (requestAttributes != null) {
			RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
		}
	}



相关推荐