58

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.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Spring Monkey
  • 4,988
  • 7
  • 32
  • 34

7 Answers7

133

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;
}
Abbadon
  • 2,513
  • 3
  • 25
  • 33
33

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);
}
Kani
  • 810
  • 1
  • 19
  • 38
Panthro
  • 3,247
  • 2
  • 32
  • 37
12

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;
Zaw Than oo
  • 9,651
  • 13
  • 83
  • 131
6

For reference, this would be the Kotlin way:

    val currentRequest: HttpServletRequest?
        get() = (RequestContextHolder.getRequestAttributes() as? ServletRequestAttributes)?.request
IARI
  • 1,217
  • 1
  • 18
  • 35
4

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

You can add HttpServletRequest as a parameter in controller handler method. Like this:

@GetMapping("/hello")
public String hello(HttpServletRequest request) {
    //...
    return "Hello world!";
}

List of supported controller method arguments and return types can be found here: https://docs.spring.io/spring-framework/docs/current/reference/html/web.html#mvc-ann-methods

Eugene
  • 177
  • 2
  • 5
-1

This is what works for me:

HttpServletRequest request = 
    ((ServletRequestAttributes) Objects.requireNonNull(
        RequestContextHolder.getRequestAttributes()))
    .getRequest();
aboger
  • 2,214
  • 6
  • 33
  • 47