request.getSession(false)的认知

来源:互联网 发布:mysql防止高并发 编辑:程序博客网 时间:2024/05/17 09:06

为什么要使用request.getSession(false),有什么作用。

分析:

作用:

getSession(boolean create)意思是返回当前reqeust中的HttpSession ,如果当前reqeust中的HttpSession 为null,当create为true,就创建一个新的Session,否则返回null;

通俗理解:

HttpServletRequest.getSession(ture) 等同于 HttpServletRequest.getSession()
HttpServletRequest.getSession(false) 等同于 如果当前Session没有就为null;

示例:

时常我们经常使用的方式是:

HttpSession session = request.getSession();// 如果session不存在的话你又创建了一个! String user_name = session.getAttribute("user_name");  

以上使用方法会出现问题就是session不存在就会再创建一个。
需要注意的地方是request.getSession() 等同于 request.getSession(true),除非我们确认session一定存在或者sesson不存在时明确有创建session的需要,否则尽量使用request.getSession(false)。在使用request.getSession()函数,通常在action中检查是否有某个变量/标记存放在session中。这个场景中可能出现没有session存在的情况,正常的判断应该是这样:

HttpSession session = request.getSession(false);  if (session != null) {      String user_name = session.getAttribute("user_name");  } 

工具类

如果项目中用到了Spring(其实只要是Java的稍大的项目,Spring是一个很好的选择),对session的操作就方便多了。如果需要在Session中取值,可以用WebUtils工具(org.springframework.web.util.WebUtils)的getSessionAttribute(HttpServletRequest request, String name)方法,看看的源码:

/**  * Check the given request for a session attribute of the given name.  * Returns null if there is no session or if the session has no such attribute.  * Does not create a new session if none has existed before!  * @param request current HTTP request  * @param name the name of the session attribute  * @return the value of the session attribute, or <code>null</code> if not found  */  public static Object getSessionAttribute(HttpServletRequest request, String name) {      Assert.notNull(request, "Request must not be null");      HttpSession session = request.getSession(false);      return (session != null ? session.getAttribute(name) : null);  }  

注:Assert是Spring工具包中的一个工具,用来判断一些验证操作,本例中用来判断reqeust是否为空,若为空就抛异常。
使用工具类就写成一下形式:

HttpSession session = request.getSession(false);  String user_name = WebUtils.getSessionAttribute(reqeust, "user_name");  

转载自:http://blog.csdn.net/xxd851116/article/details/4296866

阅读全文
0 0
原创粉丝点击