您的位置:首页 > 产品设计 > UI/UE

request.getSession(true) request.getSession(false) request.getSession()

2017-04-25 10:39 447 查看
request.getSession(true):若存在会话则返回该会话,否则新建一个会话。

request.getSession(false):若存在会话则返回该会话,否则返回NULL(false):

request.getSession():和getSession(true)相同

使用
当向Session中存取登录信息时,一般建议:HttpSession
session =request.getSession();

当从Session中获取登录信息时,一般建议:HttpSession
session =request.getSession(false);

  更简洁的方式

     如果你的项目中使用到了Spring(当然大点的项目都用到了),对session的操作就方便多了。如果需要在Session中取值,可以用WebUtils工具(org.springframework.web.util.WebUtils)的getSessionAttribute(HttpServletRequestrequest,
String name)方法,看看源码:

publicstatic 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);
}

User user = (User)WebUtils.getSessionAttribute(request, “user”);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: