主流的網站都是限制用戶單點登錄的,為什么要實現單點登錄?
1、避免單賬號多用戶操作占用大量數據庫連接,減輕webserver的壓力;
2、安全防范,強制下線非法用戶;
傳統的web服務器(如tomcat)對session有專門的管理,我們通過session來控制用戶的登錄生存周期。單點登錄原理如下:
1、將當前的session以Collections的形式緩存在application當中,用戶產生新的session,即清除用戶之前的session,保證collection里面的usersession都是唯一的;
2、實現效果每次用戶登錄都會擠掉之前用戶的登錄,每個用戶只能唯一在線;
1 ServletContext application = request.getSession().getServletContext(); 2 Collection<HttpSession> sessions = null; 3 if (application.getAttribute("usercount") == null) { 4 sessions = new ArrayList<HttpSession>(); 5 application.setAttribute("usercount", sessions); 6 } else { 7 sessions = (Collection<HttpSession>) application 8 .getAttribute("usercount"); 9 } 10 new LoginManager().login(sessions, session); 11 SessionHandler.handleSession(session);
1 public static boolean isLogin(HttpServletRequest request) { 2 TuserEntity tuser = getUser(request); 3 4 if(tuser!=null){ 5 Map<String, HttpSession> map = (Map<String, HttpSession>) request.getSession() 6 .getServletContext().getAttribute("sessionMap"); 7 if(map.get(tuser.getLogname())==null){ 8 request.getSession().invalidate(); 9 return false; 10 } 11 } 12 return getUser(request) != null; 13 }
LoginManager.java
1 public class LoginManager { 2 3 public HttpSession login(Collection<HttpSession> sessions, 4 HttpSession session) { 5 ArrayList<HttpSession> sessionde = new ArrayList<HttpSession>(); 6 7 for (HttpSession s : sessions) { 8 try { 9 int historyuser = ((TuserEntity) s.getAttribute("user_session")).getId(); 10 int nowuser = ((TuserEntity) session.getAttribute("user_session")) 11 .getId(); 12 if (historyuser == nowuser) { 13 14 sessions.remove(s); // 移除集合中的重復session元素 15 16 if(!s.equals(session)){ 17 s.invalidate();// 廢棄之前登陸的session 18 } 19 break; 20 } 21 22 } catch (Exception e) { 23 //e.printStackTrace(); 24 sessionde.add(s); 25 } 26 27 } 28 for (int i = 0; i < sessionde.size(); i++) { 29 sessions.remove((HttpSession) sessionde.get(i)); 30 } 31 sessions.add(session); 32 return null; 33 } 34 }
新增和廢棄ServletContext里面的sessionMap的用戶session
1 public static void handleSession(HttpSession session) { 2 try { 3 Map<String, HttpSession> sessionMap = (Map<String, HttpSession>) session.getServletContext().getAttribute("sessionMap"); 4 TuserEntity tuser = (TuserEntity) session.getAttribute(Keys.USER_SESSION_KEY); 5 if(sessionMap.get(tuser.getLogname())!=null){ 6 sessionMap.remove(tuser.getLogname()); 7 } 8 sessionMap.put(tuser.getLogname(), session); 9 } catch (Exception e) { 10 System.out.println("session error!"); 11 } 12 }
1 public void sessionDestroyed(HttpSessionEvent se) { 2 Map<String, HttpSession> sessionMap = (Map<String, HttpSession>) se.getSession().getServletContext().getAttribute("sessionMap"); 3 TuserEntity tuser = (TuserEntity) se.getSession().getAttribute(Keys.USER_SESSION_KEY); 4 if(tuser!=null){ 5 sessionMap.remove(tuser.getLogname()); 6 } 7 }