java HttpServletRequest.getSession(false) 和 HttpSession 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26399500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Difference between HttpServletRequest.getSession(false) and HttpSession
提问by Amogh
I am working in an Spring MVC project, where to get values from session we have used..
我正在一个 Spring MVC 项目中工作,从我们使用的会话中获取值的位置..
session = request.getSession(false);
Object obj = (Object) session.getAttribute("sessionVeriable");
Where as request
is HttpServletRequest
class object passed from controller.
凡为request
是HttpServletRequest
类对象从控制器传递。
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?
我的观点是HttpServletRequest
为什么不HttpSession
直接传递对象。从 HttpServletRequest 和直接从 HttpSession 获取会话对象有什么区别吗?
回答by a better oliver
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
.
session = request.getSession(false);
仅当存在与请求相关联的会话时才返回会话。例如,一个 RESTful 应用程序肯定可以在没有会话的情况下工作。这反过来意味着您提供的代码理论上可能会抛出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.
将HttpSession
实例传递给方法意味着如果没有与请求关联的会话将被创建。如果该request
参数不用于其他用途,则在您的情况下是更好的选择。
For the sake of completeness: session = request.getSession();
would effectively be the same as having a HttpSession
parameter.
为了完整起见:session = request.getSession();
实际上与具有HttpSession
参数相同。