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?
session = request.getSession(false);
returns a session only if there is one associated with the request. Eg 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.