RequestContextHolder:请求上下文持有者,他是通过ThreadLocal放入当前请求线程中的,通过他的静态方法getRequestAttributes可以获取到RequestAttributes,如果我们是web项目,那么他的子类就是ServletRequestAttributes。我们可以根据processRequest方法中可以看出(以下只是代码片段):
protected final void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
...
RequestAttributes previousAttributes = RequestContextHolder.getRequestAttributes();
ServletRequestAttributes requestAttributes = buildRequestAttributes(request, response, previousAttributes);
// 初始化上下文持有者,传入的requestAttributes就是ServletRequestAttributes的实例
initContextHolders(request, localeContext, requestAttributes);
...
}
ServletRequestAttributes类继承AbstractRequestAttributes。
public class ServletRequestAttributes extends AbstractRequestAttributes {
private final HttpServletRequest request;
@Nullable
private HttpServletResponse response;
@Nullable
private volatile HttpSession session;
private final Map<String, Object> sessionAttributesToUpdate = new ConcurrentHashMap<>(1);
/**
* 获取当前线程中的Request对象
*/
public final HttpServletRequest getRequest() {
return this.request;
}
/**
* 获取当前线程中的Response对象
*/
@Nullable
public final HttpServletResponse getResponse() {
return this.response;
}
/**
* 获取当前线程的session
*/
@Nullable
protected final HttpSession getSession(boolean allowCreate) {
if (isRequestActive()) {
HttpSession session = this.request.getSession(allowCreate);
this.session = session;
return session;
}
else {
// Access through stored session reference, if any...
HttpSession session = this.session;
if (session == null) {
if (allowCreate) {
throw new IllegalStateException(
"No session found and request already completed - cannot create new session!");
}
else {
session = this.request.getSession(false);
this.session = session;
}
}
return session;
}
}
// 根据属性名获取属性值,scope是作用域:
// 0 : request域
// 1:session域
@Override
public Object getAttribute(String name, int scope) {
if (scope == SCOPE_REQUEST) {
if (!isRequestActive()) {
throw new IllegalStateException(
"Cannot ask for request attribute - request is not active anymore!");
}
return this.request.getAttribute(name);
}
else {
HttpSession session = getSession(false);
if (session != null) {
try {
Object value = session.getAttribute(name);
if (value != null) {
this.sessionAttributesToUpdate.put(name, value);
}
return value;
}
catch (IllegalStateException ex) {
// Session invalidated - shouldn't usually happen.
}
}
return null;
}
}
// 设置当前线程的属性,传入域值
@Override
public void setAttribute(String name, Object value, int scope) {
if (scope == SCOPE_REQUEST) {
if (!isRequestActive()) {
throw new IllegalStateException(
"Cannot set request attribute - request is not active anymore!");
}
this.request.setAttribute(name, value);
}
else {
HttpSession session = obtainSession();
this.sessionAttributesToUpdate.remove(name);
session.setAttribute(name, value);
}
}
// 移除属性
@Override
public void removeAttribute(String name, int scope) {
if (scope == SCOPE_REQUEST) {
if (isRequestActive()) {
this.request.removeAttribute(name);
removeRequestDestructionCallback(name);
}
}
else {
HttpSession session = getSession(false);
if (session != null) {
this.sessionAttributesToUpdate.remove(name);
try {
session.removeAttribute(name);
// Remove any registered destruction callback as well.
session.removeAttribute(DESTRUCTION_CALLBACK_NAME_PREFIX + name);
}
catch (IllegalStateException ex) {
// Session invalidated - shouldn't usually happen.
}
}
}
}
// 获取所有的属性名称
@Override
public String[] getAttributeNames(int scope) {
if (scope == SCOPE_REQUEST) {
if (!isRequestActive()) {
throw new IllegalStateException(
"Cannot ask for request attributes - request is not active anymore!");
}
return StringUtils.toStringArray(this.request.getAttributeNames());
}
else {
HttpSession session = getSession(false);
if (session != null) {
try {
return StringUtils.toStringArray(session.getAttributeNames());
}
catch (IllegalStateException ex) {
// Session invalidated - shouldn't usually happen.
}
}
return new String[0];
}
}
@Override
public void registerDestructionCallback(String name, Runnable callback, int scope) {
if (scope == SCOPE_REQUEST) {
registerRequestDestructionCallback(name, callback);
}
else {
registerSessionDestructionCallback(name, callback);
}
}
@Override
public Object resolveReference(String key) {
if (REFERENCE_REQUEST.equals(key)) {
return this.request;
}
else if (REFERENCE_SESSION.equals(key)) {
return getSession(true);
}
else {
return null;
}
}
// 获取sessionid
@Override
public String getSessionId() {
return obtainSession().getId();
}
@Override
public Object getSessionMutex() {
return WebUtils.getSessionMutex(obtainSession());
}
/**
* Update all accessed session attributes through {@code session.setAttribute}
* calls, explicitly indicating to the container that they might have been modified.
*/
@Override
protected void updateAccessedSessionAttributes() {
if (!this.sessionAttributesToUpdate.isEmpty()) {
// Update all affected session attributes.
HttpSession session = getSession(false);
if (session != null) {
try {
for (Map.Entry<String, Object> entry : this.sessionAttributesToUpdate.entrySet()) {
String name = entry.getKey();
Object newValue = entry.getValue();
Object oldValue = session.getAttribute(name);
if (oldValue == newValue && !isImmutableSessionAttribute(name, newValue)) {
session.setAttribute(name, newValue);
}
}
}
catch (IllegalStateException ex) {
// Session invalidated - shouldn't usually happen.
}
}
this.sessionAttributesToUpdate.clear();
}
}
/**
* Determine whether the given value is to be considered as an immutable session
* attribute, that is, doesn't have to be re-set via {@code session.setAttribute}
* since its value cannot meaningfully change internally.
* <p>The default implementation returns {@code true} for {@code String},
* {@code Character}, {@code Boolean} and standard {@code Number} values.
* @param name the name of the attribute
* @param value the corresponding value to check
* @return {@code true} if the value is to be considered as immutable for the
* purposes of session attribute management; {@code false} otherwise
* @see #updateAccessedSessionAttributes()
*/
protected boolean isImmutableSessionAttribute(String name, @Nullable Object value) {
return (value == null || immutableValueTypes.contains(value.getClass()));
}
// 注册回调,当指定的name被销毁之后,会回调
protected void registerSessionDestructionCallback(String name, Runnable callback) {
HttpSession session = obtainSession();
session.setAttribute(DESTRUCTION_CALLBACK_NAME_PREFIX + name,
new DestructionCallbackBindingListener(callback));
}
@Override
public String toString() {
return this.request.toString();
}
}