For future developer's reference:
When you get a java.lang.IllegalStateException: No thread-bound request found exception
which suggests using a RequestContextListener
or a RequestContextFilter
.
You have probably run into one of the two following situations.
Situation NO.1
You are not using org.springframework.web.servlet.DispatcherServlet
(E.g. It's not in your web.xml or it is not a Spring MVC application).
Then you probably want to add RequestContextListener
to your web.xml:
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
or RequestContextFilter
(which does the same thing):
<filter>
<filter-name>requestContextFilter</filter-name>
<filter-class>org.springframework.web.filter.RequestContextFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>requestContextFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Then your code should just start working.
Situation NO.2
You want to get access to HttpServletRequest outside its original context, then following code should help:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
Make sure you put the code inside your method rather than inside the method's class!
The difference is as following:
Inside class: it is just an object needs to be created at initialization time, which will throw the exception because there is NO REQUEST AT ALL during this stage!
Inside method: it will be created at run time when there is an actual request coming in. This will work perfectly fine.