Is there a static way to get the current HttpServletRequest in Spring

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.


Solution 1:

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;
}

Solution 2:

Or the java8 way

public static Optional<HttpServletRequest> getCurrentHttpRequest() {
    return Optional.ofNullable(RequestContextHolder.getRequestAttributes())
        .filter(ServletRequestAttributes.class::isInstance)
        .map(ServletRequestAttributes.class::cast)
        .map(ServletRequestAttributes::getRequest);
}