同时只能一个账户登录系统,后一个踢出前一个
本人以前的这种需求都是用SpringSecurity实现,纯配置,也没怎么考虑怎么实现。
今天朋友问我不用SpringSecurity怎么实现,想了一下,觉得这样可行,先记下,晚上试试。。。
1.在applicationContext里面方一个Map,key为账户id,value为session。
2.用户在登录的时候,利用contains()方法来判断Map里面是否已经包含了此id的key,如果包含了,从Map删除此session,在将新的session放入。如果没有直接放 入。
3.在Filter里,从application的map取出session和自己的session比较SessionID,相同则继续操作,不同则证明有后来用户登过,跳出系统,给出提示。
在登录的action中:
//判断重复登录
ServletContext application = ServletActionContext.getServletContext();
HashMap<String, HttpSession> sessionMap=(HashMap<String, HttpSession>)application.getAttribute("sessionMap");
if(null!=sessionMap){
sessionMap.remove(enterprise.getUserId());
sessionMap.put(enterprise.getUserId(), session);
application.setAttribute("sessionMap", sessionMap);
}else{
HashMap<String, HttpSession> map=new HashMap<String, HttpSession>();
map.put(enterprise.getUserId(), session);
application.setAttribute("sessionMap", map);
}
public class SafetyFilter implements Filter{
ServletContext application;
public void destroy() {
}
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request=(HttpServletRequest)servletRequest;
HttpServletResponse response=(HttpServletResponse)servletResponse;
String servletPath=request.getServletPath().trim();
System.out.println(servletPath);
//首次登录修改密码 退出系统 不拦截
if(!"/transfer/getSignaCode.shtml".equals(servletPath)
&& !"/safety/updateLogPwd.shtml".equals(servletPath)
&& !"/system/toLogin.shtml".equals(servletPath)
&& !"/qyqt/system/toLogin.shtml".equals(servletPath)){
//判断session超时
if(!path.equals("system")){
Enterprise en=(Enterprise)request.getSession().getAttribute("enterprise");
if(en==null){
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.print("<script>parent.window.location='/qyqt/system/toLogin.shtml';</script>");
return;
}
}
//判断重复登录
HashMap<String, HttpSession> sessionMap=(HashMap<String, HttpSession>)application.getAttribute("sessionMap");
Enterprise user=(Enterprise) request.getSession().getAttribute("enterprise");
if(null!=sessionMap && null!=user){
HttpSession thissession=request.getSession();
HttpSession othersession=sessionMap.get(user.getUserId());
if(!thissession.getId().equals(othersession.getId())){
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.print("<script>parent.window.location='/qyqt/system/toLogin.shtml';</script>");
return;
}
}
}
chain.doFilter(request, response);
}
public void init(FilterConfig arg0) throws ServletException {
application=arg0.getServletContext();
}
}