Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RequestContextHolder.getRequestAttributes() is null sometimes

Tags:

java

spring

In my Java Spring project I use

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder
                                         .getRequestAttributes())
                                         .getRequest();

which defined in a static method to get request and get some session attributes. spring-RequestContextListener is already exist in my web.xml. The question is when some single thread invoke that, everything is fine for now.

But when using java8 parallelStream, RequestContextHolder.getRequestAttributes() can be null sometimes and I do not know why.

like image 436
G.walker Avatar asked Sep 02 '26 06:09

G.walker


1 Answers

Is your project spring or spring boot? if it is spring boot, expose a bean with either RequestContextListener or RequestContextFilter

@Bean
  public RequestContextListener requestContextListener() {
    return new RequestContextListener();
  }

also make sure you don't have any @Configuration classes anotated with @EnableWebMvc. this will remove spring boot autoconfiguration cababilities.

like image 67
arvin_v_s Avatar answered Sep 04 '26 20:09

arvin_v_s



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!