0

I try in Spring to get the HttpSession like this. I know, there are better ways to do so, but this is a legacy code, so I have to handle it.

private static HttpSession getHttpSession() {
    ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    HttpSession httpSession = requestAttributes.getRequest().getSession();
    return httpSession;
}

In the second line I get a NPE. The null is returned from getRequest() so getSession() crashes.

The method works fine in general. But there is a case where it's not. I can't image the case where Spring can't get a session from a request.

Is there a special behavior I should know about this method?

Thanks! Robert.

newNovice
  • 55
  • 1
  • 8
Robert Moszczynski
  • 1,081
  • 2
  • 16
  • 26
  • Calling this method before the `RequestContext` has been populated will lead to this. The population is only available (by default) if the request is already inside the `DispatcherServlet` if you want to use it outside of that register a `RequestContextListener` for early population of the `RequestContext`. – M. Deinum Jul 23 '15 at 10:22
  • @M.Deinum The problem is I have already registered it. – Robert Moszczynski Jul 23 '15 at 10:57
  • Also it isn't about not being able to get the session from the request there is no request at all. It will only work when the `RequestContext` is set. It is set in a `ThreadLocal` so if you spawn an new thread it will not work either because they aren't inherited. Either way you are executing some code outside the scope of a `RequestContext`. And I would put a big `@Deprecated` on there because I wouldn't suggest the use of that code at all. – M. Deinum Jul 23 '15 at 11:20

0 Answers0