Skip to content

Instantly share code, notes, and snippets.

@zbo2018
Last active January 31, 2019 10:45
Show Gist options
  • Save zbo2018/a86887f97456882389adff3e8806b434 to your computer and use it in GitHub Desktop.
Save zbo2018/a86887f97456882389adff3e8806b434 to your computer and use it in GitHub Desktop.
设置session超时时间、getSession用法
getSession用法
需求原因:
现实中经常会遇到以下3中用法:
HttpSession session = request.getSession();
HttpSession session = request.getSession(true);
HttpSession session = request.getSession(false);
概括:
request.getSession(true) 等同 request.getSession():若存在会话则返回该会话,否则新建一个会话。
request.getSession(false):若存在会话则返回该会话,否则返回NULL
使用:
向Session中保存登录信息时,一般建议:HttpSession session =request.getSession();
从Session中获取登录信息时,一般建议:HttpSession session =request.getSession(false);
更简洁的方式:
spring工具:org.springframework.web.util.WebUtils
WebUtils.getSessionAttribute(HttpServletRequest request, String name);
WebUtils.setSessionAttribute(HttpServletRequest request, String name, Object value);
session.setMaxInactiveInterval(30*60);//单位秒
session.setMaxInactiveInterval(-1);//单位秒。为零或负数,表示会话将永远不会超时
//session超时时间
int maxInactiveInterval = session.getMaxInactiveInterval();
//session创建时间
long creationTime = session.getCreationTime();
//session最新链接时间
long lastAccessedTime = session.getLastAccessedTime();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment