我是靠谱客的博主 火星上眼神,最近开发中收集的这篇文章主要介绍RequestContextHolder中为何能获取HttpServletRequest,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
可以通过RequestContextHolder随时随地获取HttpServletRequest 和 HttpServletResponse,那么参数是什么时候进行初始化的呢,又是如何进行初始化?
在RequestContextHolder初始化过程中有个非常关键的类——RequestContextFilter,通过底下RequestContextFilter源码可以看出,RequestContextFilter类继承了OncePerRequestFilter类,所以每次接收到请求处理之前,都会调用拦截器的initContextHolders方法。在initContextHolders方法中调用RequestContextHolder类中的setRequestAttributes方法
public class RequestContextFilter extends OncePerRequestFilter {
private boolean threadContextInheritable = false;
public RequestContextFilter() {
}
private void initContextHolders(HttpServletRequest request, ServletRequestAttributes requestAttributes) {
LocaleContextHolder.setLocale(request.getLocale(), this.threadContextInheritable);
RequestContextHolder.setRequestAttributes(requestAttributes, this.threadContextInheritable);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Bound request context to thread: " + request);
}
}
private void resetContextHolders() {
LocaleContextHolder.resetLocaleContext();
RequestContextHolder.resetRequestAttributes();
}
}
RequestContextHolder中定义了俩个ThreadLoal<RequestAttributes>线程变量 ,setRequestAttributes方法中会给inheritableRequestAttributesHolder变量或者requestAttributesHolder 变量赋值,所以代码中可以随时获取HttpServletRequest值
public abstract class RequestContextHolder {
private static final boolean jsfPresent = ClassUtils.isPresent("javax.faces.context.FacesContext", RequestContextHolder.class.getClassLoader());
private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal("Request attributes");
private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder = new NamedInheritableThreadLocal("Request context");
public RequestContextHolder() {
}
public static void resetRequestAttributes() {
requestAttributesHolder.remove();
inheritableRequestAttributesHolder.remove();
}
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();
}
}
最后
以上就是火星上眼神为你收集整理的RequestContextHolder中为何能获取HttpServletRequest的全部内容,希望文章能够帮你解决RequestContextHolder中为何能获取HttpServletRequest所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复