1 16 17 package org.springframework.web.context.request; 18 19 38 public abstract class RequestContextHolder { 39 40 private static final ThreadLocal requestAttributesHolder = new ThreadLocal (); 41 42 private static final ThreadLocal inheritableRequestAttributesHolder = new InheritableThreadLocal (); 43 44 45 48 public static void resetRequestAttributes() { 49 requestAttributesHolder.set(null); 50 inheritableRequestAttributesHolder.set(null); 51 } 52 53 59 public static void setRequestAttributes(RequestAttributes attributes) { 60 setRequestAttributes(attributes, false); 61 } 62 63 69 public static void setRequestAttributes(RequestAttributes attributes, boolean inheritable) { 70 if (inheritable) { 71 inheritableRequestAttributesHolder.set(attributes); 72 requestAttributesHolder.set(null); 73 } 74 else { 75 requestAttributesHolder.set(attributes); 76 inheritableRequestAttributesHolder.set(null); 77 } 78 } 79 80 85 public static RequestAttributes getRequestAttributes() { 86 RequestAttributes attributes = (RequestAttributes) requestAttributesHolder.get(); 87 if (attributes == null) { 88 attributes = (RequestAttributes) inheritableRequestAttributesHolder.get(); 89 } 90 return attributes; 91 } 92 93 99 public static RequestAttributes currentRequestAttributes() throws IllegalStateException { 100 RequestAttributes attributes = getRequestAttributes(); 101 if (attributes == null) { 102 throw new IllegalStateException ("No thread-bound request found: " + 103 "Are you referring to request attributes outside of an actual web request? " + 104 "If you are actually operating within a web request and still receive this message," + 105 "your code is probably running outside of DispatcherServlet/DispatcherPortlet: " + 106 "In this case, use RequestContextListener or RequestContextFilter to expose the current request."); 107 } 108 return attributes; 109 } 110 111 } 112 | Popular Tags |