2

I am working in an Spring MVC project, where to get values from session we have used..

session = request.getSession(false);
Object obj = (Object) session.getAttribute("sessionVeriable");

Where as request is HttpServletRequest class object passed from controller.

My point is why HttpServletRequest object is passed why not HttpSession directly. Is there any difference getting session object from HttpServletRequest and directly from HttpSession?

Amogh
  • 4,453
  • 11
  • 45
  • 106
  • 1
    possible duplicate of [Spring MVC - Session differences](http://stackoverflow.com/questions/25873446/spring-mvc-session-differences) – tmarwen Oct 16 '14 at 08:36

1 Answers1

8

session = request.getSession(false); returns a session only if there is one associated with the request. E.g. a RESTful application would most certainly work without sessions. That in turn means that the code you provided could theoretically throw a NullPointerException.

Having a HttpSession instance passed to a method means that a session will be created if none is already associated with the request. If the request parameter is not used for something else it's the better choice in your case.

For the sake of completeness: session = request.getSession(); would effectively be the same as having a HttpSession parameter.

Dennis C
  • 24,511
  • 12
  • 71
  • 99
a better oliver
  • 26,330
  • 2
  • 58
  • 66