出处:http://blog.csdn.net/xxd851116/archive/2009/06/25/4296866.aspx
J2EE很基础的东西,记下来。
getSession(boolean create)意思是返回当前reqeust中的HttpSession ,如果当前reqeust中的HttpSession 为null,当create为true,就创建一个新的Session,否则返回null;
简而言之:
HttpServletRequest.getSession(ture) 等同于ttpServletRequest.getSession()
HttpServletRequest.getSession(false) 等同于 如果当前Session没有就为null;
【问题和bug】:
我周围很多同事是这样写的;
view plaincopy to clipboardprint?
HttpSession session = request.getSession(); // a new session created if no session exists, 哈哈!完蛋啦!如果session不存在的话你又创建了一个!
String user_name = session.getAttribute("user_name");
需要注意的地方是request.getSession() 等同于 request.getSession(true),除非我们确认session一定存在或者sesson不存在时明确有创建session的需要,否则尽量使用request.getSession(false)。在使用request.getSession()函数,通常在action中检查是否有某个变量/标记存放在session中。这个场景中可能出现没有session存在的情况,正常的判断应该是这样:
view plaincopy to clipboardprint?
HttpSession session = request.getSession(false);
if (session != null) {
String user_name = session.getAttribute("user_name");
}
分享到:
评论