HttpServletRequest throws error when used within Aspect

I have a method which has an aspect. When I try to @Autowire HttpServletRequest, and use request.getHeader(something), I get this error -

No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

How do I fix this? I tried using RequestContextHolder, but upon debugging I still see null. How do I use the RequestContextListener when my project has no web.xml.

Upvotes: 1

Views: 329

Answers (2)

Aspect annotations spins a new thread which is different from the one httpservlet is available in. This is why request was not available within the @ASpect. To resolve it, call the request object BEFORE the aspect method, cache it and call the same method as before.

Upvotes: 0

Pratiyush Kumar Singh
Pratiyush Kumar Singh

Reputation: 1997

Request Header can be accessed using HttpServletRequest below way.

private static HttpServletRequest getRequest() {
    return((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
}

public static String getApiTraceId() {
    return getRequest().getHeader(something);
}

Upvotes: 0

Related Questions