Is there a static way to get the HttpServletRequest of the current request

Spring Monkey picture Spring Monkey · Feb 26, 2009 · Viewed 35.1k times · Source

I am using Spring annotations, I can pass the HttpRequestContext from the Controller to the Service.

I am looking for a static way or any better solution than passing RequestContext around.

Answer

Abbadon picture Abbadon · Oct 12, 2014

If you are using spring you can do the following:

public static HttpServletRequest getCurrentHttpRequest(){
    RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
    if (requestAttributes instanceof ServletRequestAttributes) {
        HttpServletRequest request = ((ServletRequestAttributes)requestAttributes).getRequest();
        return request;
    }
    logger.debug("Not called in the context of an HTTP request");
    return null;
}