views:

233

answers:

2

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 ?

+2  A: 

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

Samit G.
+2  A: 

Request-scoped beans can be autowired with the request object.

private @Autowired HttpServletRequest request;
skaffman
Works like a charm. Thanks !
Leonel
Is there an old fashioned XML way for this?
cherouvim
@cherouvim: I don't think so, no. The current request object is not visible as a bean reference.
skaffman
ok, I'll use the autowiring magic then. Thanks.
cherouvim