通过RequestContextHolder获取会话的HttpServletRequest和HttpServletResponse

我们应用中可以通过RequestContextHolder获取到HttpServletRequest和HttpServletResponse

((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();

在FrameworkServlet.java的processRequest()->initContextHolders()函数中,将HttpServletRequest和HttpServletResponse放入了RequestContextHolder.java中

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);

	try {
		doService(request, response);
	} catch (ServletException | IOException ex) {
		failureCause = ex;
		throw ex;
	} catch (Throwable ex) {
		failureCause = ex;
		throw new NestedServletException("Request processing failed", ex);
	}

	finally {
		//省略额外代码
		...
	}
}

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

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

源码版本:spring-web-5.2.4.RELEASE.jar。

posted @ 2020-08-05 14:24  lee2guang  阅读(610)  评论(0编辑  收藏  举报