Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Leonel picture Leonel · Jul 23, 2010 · Viewed 111.7k times · Source

I'm trying to set up a request-scoped bean in Spring.

I've successfully set it up so the bean is created once per request. Now, it needs to access the HttpServletRequest object.

Since the bean is created once per request, I figure the container can easily inject the request object in my bean. How can I do that ?

Answer

samitgaur picture samitgaur · Jul 24, 2010

Spring exposes 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 method RequestContextHolder.currentRequestAttributes().

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

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

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.


Spring Javadoc: RequestContextHolder | ServletRequestAttributes