比如我在service层方法中想要拿到request对象,可以通过controller层来传递,这是一种方法,还有就是RequestContextHolder:
/**
* Holder class to expose the web request in the form of a thread-bound
* {@link RequestAttributes} object. The request will be inherited
* by any child threads spawned by the current thread if the
* {@code inheritable} flag is set to {@code true}.
*
翻译过来是通过线程绑定的方式暴露request对象,如果将Inheritable标志设置为true,则当前线程产生的任何子线程都将继承该请求。
既要绑定request对象到线程,又要有继承性的限制,可以想到threadlocal,并且RequestContextHolder也是这么实现的:
public static void setRequestAttributes(RequestAttributes attributes, boolean inheritable) {
if (attributes == null) {
resetRequestAttributes();
}
else {
<-- 默认是false -->
if (inheritable) {
inheritableRequestAttributesHolder.set(attributes);
requestAttributesHolder.remove();
}
else {
requestAttributesHolder.set(attributes);
inheritableRequestAttributesHolder.remove();
}
}
}
其中定义了两个threadLocal:
private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
new NamedThreadLocal<RequestAttributes>("Request attributes");
private static final ThreadLocal<RequestAttributes> inheritableRequestAttributesHolder =
new NamedInheritableThreadLocal<RequestAttributes>("Request context");
后者用在如果要在当前线程创建子线程并且还要继承当前线程中的变量的场景。
然后就可以通过如下方式拿到request了:
HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
Enumeration<String> names = request.getServletContext().getAttributeNames();
while (names.hasMoreElements()) {
System.out.println(names.nextElement());
}
那ThreadLocal是怎么保证不同线程中变量互不影响呢:
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
ThreadLocalMap getMap(Thread t) {
return t.threadLocals;
}
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
注意:ThreadLocal不存东西,它只是作为key放入ThreadLocalMap里,然后 每个线程都有一个类型为ThreadLocalMap的threadLocals属性
RequestContextHolder就能拿到每个线程的不同的request了
937

被折叠的 条评论
为什么被折叠?



