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 ?
As singleton beans are injected only once per their lifetime you need to provide scoped beans as proxies which takes care of that. @RequestScope is a meta-annotation on @Scope that 1) sets the scope to "request" and 2) sets the proxyMode to ScopedProxyMode.
It is possible to autowire HttpServletRequest also into non request-scoped beans, because for HttpServletRequest Spring will generate a proxy HttpServletRequest which is aware how to get the actual instance of request. So it is safe to autowire request even if your controller is singleton scoped.
To access HttpRequest from controller you just need to define HttpServletRequest and HttpServletResponse as parameters in a function signature of your Controller. by doing this you allowing Spring MVC to pass these objects to you controller method.
A request-scoped bean is an object managed by Spring, for which the framework creates a new instance for every HTTP request. The app can use the instance only for the request that created it. Any new HTTP request (from the same or other clients) creates and uses a different instance of the same class (figure 2).
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With