简单介绍 RequestContextHolder 是怎么获取到当前请求的

简单介绍 RequestContextHolder 是怎么获取到当前请求的

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

简单介绍 RequestContextHolder 是怎么获取到当前请求的_第1张图片

其中FrameworkServlet中的processRequest方法给 RequestContextHolder 赋值

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

		long startTime = System.currentTimeMillis();
		Throwable failureCause = null;

		LocaleContext previousLocaleContext = LocaleContextHolder.getLocaleContext();
		LocaleContext localeContext = buildLocaleContext(request);
		// 获取之前请求的参数
		RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
		// 重新建立请求参数
		ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);

		WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
		asyncManager.registerCallableInterceptor(FrameworkServlet.class.getName(), new RequestBindingInterceptor());

   		// 初始化上下文
		initContextHolders(request, localeContext, requestAttributes);
    	.....
    	省略
        .....
	}
private void initContextHolders(HttpServletRequest request,
			@Nullable LocaleContext localeContext, @Nullable RequestAttributes requestAttributes) {

		if (localeContext != null) {
			LocaleContextHolder.setLocaleContext(localeContext, this.threadContextInheritable);
		}
		if (requestAttributes != null) {
            // requestAttributes 为 ServletRequestAttributes 类型
			RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
		}
		if (logger.isTraceEnabled()) {
			logger.trace("Bound request context to thread: " + request);
		}
	}

因此说明在 调用getRequestAttributes()方法后 可以强转为 ServletRequestAttributes

		HttpServletRequest servletRequest = null;
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof ServletRequestAttributes) {
            servletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
        }

你可能感兴趣的:(java)