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”);