HttpSessionListener进行同名用户剔除登录的方法

 

HttpSessionListener进行同名用户剔除登录的方法

转自:http://www.cnblogs.com/panjun-Donet/archive/2010/06/18/1760484.html

实现原理,利用HttpSessionListener的监视监听功能。用户登录成功后,在HashMap中放置一组sessionId和userName的组队,对HashMap中的键值信息登录实时进行维护,利用HashMap来判断用户是否已经登录,当前是否在线,然后根据需要是否进行session(假session,指的是hashmap中保存的键值信息)剔除。

1、以下是用于用户登录监听的SessionListener java文件源码:

/**
* Created by IntelliJ IDEA.
* User: xj
* Date: 2007-3-21
* Time: 17:28:33
* To change this template use File | Settings | File Templates.
*/
public class SessionListener implements HttpSessionListener {
          private static final Logger m_logger = Logger.getLogger(LogonAction.class);//用于log4j调试
          private static HashMap hashUserName = new HashMap();//保存sessionID和username的映射
          /**以下是实现HttpSessionListener中的方法**/
          public void sessionCreated(HttpSessionEvent sessionEvent){
          }

          public void sessionDestroyed(HttpSessionEvent sessionEvent){
              hashUserName.remove(sessionEvent.getSession().getId());
          }

          /**
           * isLogining-用于判断用户是否已经登录
           * @param        sessionUserName String-登录的用户名
           * @return boolean-该用户是否已经登录的标志
           * */
          public static boolean isLogining(String sessionUserName) throws Exception{
              return hashUserName.containsValue(sessionUserName);
          }

          /*
           * isOnline-用于判断用户是否在线
           * @param session HttpSession-登录的用户名称
           * @return boolean-该用户是否在线的标志
           */
          public static boolean isOnline(HttpSession session) throws Exception{
              return hashUserName.containsKey(session.getId());
          }

          /*
          * createUserSession-用于建立用户session
          * @param sessionUserName String-登录的用户名称
          */
          public static void createUserSession(HttpSession session,String sessionUserName) throws Exception {
              hashUserName.put(session.getId(),sessionUserName);

              if(m_logger.isDebugEnabled()){//log4j调试信息
                  Iterator debugIter = hashUserName.entrySet().iterator();
                  while (debugIter.hasNext()){
                      Map.Entry entry = (Map.Entry)debugIter.next();
                      Object key = entry.getKey();
                      Object val = entry.getValue();
                      m_logger.debug(sessionUserName);
                      m_logger.debug(key.toString());
                      m_logger.debug(val.toString());
                  }
              }//log4j调试信息结束

          }

          /*
          * createUserSession-根据用户名剔除session
          * @param sessionUserName String-登录的用户名称
          */
          public static void removeUserSession(String sessionUserName) throws Exception{
              Iterator iter = hashUserName.entrySet().iterator();
                  while (iter.hasNext()){
                      Map.Entry entry = (Map.Entry)iter.next();
                      Object key = entry.getKey();
                      Object val = entry.getValue();
                      if(((String)val).equals(sessionUserName)){
                        hashUserName.put(key,null);
                          iter.remove();
                        //hashUserName.remove(key);//当使用 fail-fast iterator 对 Collection 或 Map 进行迭代操作过程中尝试直接修改 Collection / Map 的内容时,即使是在单线程下运行,java.util.ConcurrentModificationException 异常也将被抛出。
                      }
                  }
          }

          /*
          * replaceUserSession-用户已经登录则进行session剔除,否则建立新的session
          * @param sUserName String-登录的用户名称
          */
          public static void replaceUserSession(HttpSession session,String sessionUserName) throws Exception {
              if(hashUserName.containsValue(sessionUserName)){//如果该用户已经登录过,则使上次登录的用户掉线(依据使用户名是否在hashUserName中)
                  //遍历原来的hashUserName,删除原用户名对应的sessionID(即删除原来的sessionID和username)
                  Iterator iter = hashUserName.entrySet().iterator();
                  while (iter.hasNext()){
                      Map.Entry entry = (Map.Entry)iter.next();
                      Object key = entry.getKey();
                      Object val = entry.getValue();
                      if(((String)val).equals(sessionUserName)){
                        hashUserName.put(key,null);
                          iter.remove();
                        //hashUserName.remove(key);//当使用 fail-fast iterator 对 Collection 或 Map 进行迭代操作过程中尝试直接修改 Collection / Map 的内容时,即使是在单线程下运行,java.util.ConcurrentModificationException 异常也将被抛出。
                    }
                  }
                  hashUserName.put(session.getId(),sessionUserName);//添加现在的sessionID和username
              }else{//如果该用户没登录过,直接添加现在的sessionID和username
                  hashUserName.put(session.getId(),sessionUserName);
              }

              if(m_logger.isDebugEnabled()){//log4j调试信息
                  Iterator debugIter = hashUserName.entrySet().iterator();
                  while (debugIter.hasNext()){
                      Map.Entry entry = (Map.Entry)debugIter.next();
                      Object key = entry.getKey();
                      Object val = entry.getValue();
                      m_logger.debug(sessionUserName);
                      m_logger.debug(key.toString());
                      m_logger.debug(val.toString());
                  }
              }//log4j调试信息结束

          }
}

2、以下是jsp页面用于判断用户是否已登录(session失效)的部分代码:

<html:html>
<head>
<title>here is title</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<link href="css/maincss.css" rel="stylesheet" type="text/css">
</head>
<body>
<% 
         //UserInfoForm为后台定义的获取用户登录信息及保存用户相关信息的一个java bean,userSession为用户登录Action时根据需要组装的放置用户信息的一个bean对象-UserInfoForm,登录成功后被放到session里(这里的session指HttpSession,即服务端根据每个客户端链接产生的带有唯一sessionId)。
         UserInfoForm userInfoForm = (UserInfoForm)request.getSession().getAttribute("userSession");
         //System.out.println("userName="+userInfoForm.getUserName());
         if(userInfoForm.getUserName()==null||userInfoForm.getUserName().equals("")){//从session获取用户信息失败,用户没有登录或session已经超时,返回到登录页面
             RequestDispatcher dispatcher=request.getRequestDispatcher("login.jsp");
          dispatcher.forward(request,response);
         }else{
             if(!SessionListener.isLogining(userInfoForm.getUserName())){//用户没有登录或session已经超时
                 RequestDispatcher dispatcher=request.getRequestDispatcher("login.jsp");
        dispatcher.forward(request,response);
             }else{
                 if(!SessionListener.isOnline(request.getSession())){//当前用户不在线,即session已经被剔除
                     RequestDispatcher dispatcher=request.getRequestDispatcher("login.jsp");
                     dispatcher.forward(request,response);
                 }
             }
         }
%>
</body>
</html:html>

3. 注意:最后别忘了在web.xml文件中配置监听器SessionListener:

      <listener>
          <listener-class>com.projectsSrcPath.SessionListener</listener-class>
      </listener>

你可能感兴趣的:(HttpSessionListener进行同名用户剔除登录的方法)