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

Viewed 55037

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.

7 Answers

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

I know, it is already answer. I would like to mark as new update. we can inject HttpServletRequest by using @Autowired. It is working fine at springboot.

@Autowired
private HttpServletRequest httpServletRequest;

For reference, this would be the Kotlin way:

    val currentRequest: HttpServletRequest?
        get() = (RequestContextHolder.getRequestAttributes() as? ServletRequestAttributes)?.request

In response to @andrebrait comments above "Or the Java 8 way", the methods are present on the ServletRequestAttributes.class

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

This is what works for me:

HttpServletRequest request = 
    ((ServletRequestAttributes) Objects.requireNonNull(
        RequestContextHolder.getRequestAttributes()))
    .getRequest();
Related