ConcurrentSessionFilter做的功能比较简单,主要是判断session是否过期以及更新最新访问时间
通过代码HttpSession session = request.getSession(false);判断获取session
1、首先判断session是否存在--------HttpSession session = request.getSession(false)
如果session不存在,直接放过,执行下一个过滤器。
如果存在,则执行第二步
2、根据sessionid从sessionRegistry中获取SessionInformation,从SessionInformation中获取session是否过期
如果没有过期,则更新SessionInformation的访问日期。
如果过期,则执行doLogout()方法,这个方法会将session无效,并将SecurityContext中的Authentication中的权限置空,同时在SecurityContenxtHoloder中清除SecurityContext
然后查看是否有跳转的URL,如果有就跳转,没有就输出提示信息
在ConcurrentSessionFilter有两个重要的类需要知道,一个是sessionRegistry(默认使用sessionRegistryImpl),一个是SessionInformation 。
sessionRegistry顾名思义 session注册表,有维护两个类变量ConcurrentMap<Object,Set<String>> principals 和Map<String, SessionInformation> sessionIds
principals以用户认证信息为key,values值sessionId集合,sessionIds以sessionId为key,以SessionInformation 为values值。
sessionInformation只要存放4个参数,一个是lastRequest;(最近访问时间),一个是sessionId,一个是principal(用户认证权限),一个是expired (是否过期)
这两个类变量的信息会在后面的登陆认证的时候进行赋值
代码如下
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
HttpSession session = request.getSession(false);
if (session != null) {
SessionInformation info = sessionRegistry.getSessionInformation(session.getId());
if (info != null) {
if (info.isExpired()) {
// Expired - abort processing
doLogout(request, response);
String targetUrl = determineExpiredUrl(request, info);
if (targetUrl != null) {
redirectStrategy.sendRedirect(request, response, targetUrl);
return;
} else {
response.getWriter().print("This session has been expired (possibly due to multiple concurrent " +
"logins being attempted as the same user).");
response.flushBuffer();
}
return;
} else {
// Non-expired - update last request date/time
sessionRegistry.refreshLastRequest(info.getSessionId());
}
}
}
chain.doFilter(request, response);
}