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

JavaSpringServlets

Java Problem Overview


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 ?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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

private @Autowired HttpServletRequest request;

Solution 3 - Java

As suggested here you can also inject the HttpServletRequest as a method param, e.g.:

public MyResponseObject myApiMethod(HttpServletRequest request, ...) {
    ...
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLeonelView Question on Stackoverflow
Solution 1 - JavasamitgaurView Answer on Stackoverflow
Solution 2 - JavaskaffmanView Answer on Stackoverflow
Solution 3 - JavaWillView Answer on Stackoverflow