RequestContextListener


RequestContextListener監聽器用於監聽http請求,每當web應用接收到Http請求,該監聽器就會調用初始化方法,將該請求保存在當前線程的ThreadLocalMap容器中。

public class RequestContextListener implements ServletRequestListener {
//其他代碼

@Override
    public void requestInitialized(ServletRequestEvent requestEvent) {
        if (!(requestEvent.getServletRequest() instanceof HttpServletRequest)) {
            throw new IllegalArgumentException(
                    "Request is not an HttpServletRequest: " + requestEvent.getServletRequest());
        }
        HttpServletRequest request = (HttpServletRequest) requestEvent.getServletRequest();
        ServletRequestAttributes attributes = new ServletRequestAttributes(request);//請求對象賦值給了attributes 對象的Request屬性
 request.setAttribute(REQUEST_ATTRIBUTES_ATTRIBUTE, attributes); 
LocaleContextHolder.setLocale(request.getLocale());
RequestContextHolder.setRequestAttributes(attributes);
}

//其他代碼

當前線程的ThreadLocalMap容器存放的key,就是RequestContextHolder類中的靜態ThreadLocal變量requestAttributesHolder:

public abstract class RequestContextHolder  {
//其他代碼

private static final ThreadLocal<RequestAttributes> requestAttributesHolder =
            new NamedThreadLocal<RequestAttributes>("Request attributes");

//其他代碼

 

當請求處理完畢,會調用RequestContextHolder.resetRequestAttributes()方法,清除容器中的請求。

 

 1 public void requestDestroyed(ServletRequestEvent requestEvent) {
 2 // 其他代碼
 3 
 4 RequestContextHolder.resetRequestAttributes();
 5 
 6 
 7 //其他代碼
 8 
 9 ++++++++++++++++
10 RequestContextHolder.java{
11 //其他代碼
12 /**
13      * Reset the RequestAttributes for the current thread.
14      */
15     public static void resetRequestAttributes() {
16         requestAttributesHolder.remove();
17         inheritableRequestAttributesHolder.remove();
18     }
19 //其他代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM