Spring: how do I add an HttpServletRequest to the bean scope with the request?

I am trying to set up a bean request scope in Spring.

I successfully configured it, so a bean is created once per request. Now he needs to access the HttpServletRequest object.

Since a bean is created once per request, I believe that a container can easily enter a request object into my bean. How can i do this?

+91
java spring servlets
Jul 23 '10 at 17:16
source share
3 answers

Object-oriented beans can be auto-updated with a request object.

private @Autowired HttpServletRequest request; 
+102
Jul 24 '10 at 7:27
source

Spring provides the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes . This wrapper object is bound to ThreadLocal and is obtained by calling the static RequestContextHolder.currentRequestAttributes() method.

ServletRequestAttributes provides the getRequest() method to get the current getSession() request, to get the current session and other methods to get attributes stored in both areas. The following code, although a little ugly, should provide you with the current request object anywhere in the application:

 HttpServletRequest curRequest = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()) .getRequest(); 

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and must be entered into the ServletRequestAttributes type that implements the interface.




Spring Javadoc: RequestContextHolder | ServletRequestAttributes

+125
Jul 24 '10 at 1:00
source

As suggested here , you can also enter HttpServletRequest as a method parameter, for example:

 public MyResponseObject myApiMethod(HttpServletRequest request, ...) { ... } 
+1
Aug 26 '19 at 20:21
source



All Articles