Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 721
Leonel Avatar asked Jul 23 '10 17:07

Leonel


People also ask

How do you inject request in scoped bean?

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.

Is HttpServletRequest request scope?

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.

How do you access HTTP request and response objects in controller methods?

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.

What is request-scoped bean?

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).


1 Answers

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

like image 199
samitgaur Avatar answered Oct 06 '22 14:10

samitgaur