In Spring, get the request object anywhere in Java

Looking at the source codes of RequestContextListener and RequestContextHolder, it is not difficult to see that they are implemented using ThreadLocal.

 

What is ThreadLocal? Looking at the meaning of the word, it is not a thread, it is not a Thread, but a thread local variable. In fact, the function is very simple, that is to provide a copy of the variable value for each thread that uses the variable, so that each thread can be independent. It can change its own copy without conflicting with copies of other threads. From the thread's point of view, it is as if each thread fully owns the variable.

 

Each HTTP request is an independent thread with an independent ThreadLocal. Using this feature, we can use ThreadLocal to temporarily access values ​​in the HTTP request life cycle, and transfer values ​​between different classes.

 

The RequestContextListener is achieved through this feature.

 

The operation method is as follows:

 

Step 1: In web.xml, add the following listeners.

 

Xml code   Favorite code
  1. <listener>  
  2.     <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>    
  3. </listener>  

 

Step 2: Write a static getRequest method.

  

Java code   Favorite code
  1. import org.springframework.web.context.request.RequestContextHolder;  
  2. import org.springframework.web.context.request.ServletRequestAttributes;  
  3. /** 
  4.  * Get the current request object 
  5.  * @return 
  6.  */  
  7. public static HttpServletRequest getRequest(){  
  8.     try{  
  9.         return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();  
  10.     }catch(Exception e){  
  11.         return null;  
  12.     }  
  13. }  

 

In this way, during the web request process, this static method can be called anywhere to obtain the request object.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326687832&siteId=291194637