RequestContextHolder持有上下文的Request容器,可以通过RequestContextHolder的静态方法getRequestAttributes()获取Request相关的变量,如request, response等。
RequestAttributes ra = RequestContextHolder.getRequestAttributes();
HttpServletRequest request =((ServletRequestAttributes)ra).getRequest();
通过这种方式,就不需要在接收或传递参数的时候通过定义HttpRequest或HttpResponse来获取参数了。
在一个web项目中,我们常常需要获取请求request和响应response,获取到HttpServletRequest对象还是比较常见的;
有两种方式来获取HttpServletRequest:
1、将HttpServletRequest作为方法的参数从Controller层一直放下传递,这样太繁琐也很麻烦,如果只是需要获取HttpServletRequest,不推荐使用第一种;
2、使用RequestContextHolder,可以通过 RequestContextHolder.getRequestAttributes()来获取RequestAttributes对象,再通过getRequest()获取的对象向下转型,如上面的代码;
这里直接看看RequestContextHolder源码
public abstract class RequestContextHolder {
private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
new NamedThreadLocal<RequestAttributes>("Request attributes");
private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder =
new NamedInheritableThreadLocal<RequestAttributes>("Request context");
public static void resetRequestAttributes() {
requestAttributesHolder.remove();
inheritableRequestAttributesHolder.remove();
}
public static void setRe