防止用户重复登陆

时间:2022-08-22 14:44:48

 先创建一个监听类:

/*
 * SessionListener.java
 *
 * Created on 2008年1月2日, 下午1:37
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package comm;

import javax.servlet.http.*;
import java.util.*;
import javax.servlet.http.HttpSession;
import basedata.EmployeeInfo;
public class SessionListener implements HttpSessionListener{
   private static java.util.Hashtable hUserName = new Hashtable();
   public void sessionCreated(HttpSessionEvent se){
        System.out.println("Session Created.");
   }
   public void sessionDestroyed(HttpSessionEvent se){
      hUserName.remove(se.getSession());
      System.out.println("Session Destroyed.");
   }
     /*
      * isAlreadyEnter-用于判断用户是否已经登录以及相应的处理方法
      * @param sUserName String-登录的用户名称
      * @return boolean-该用户是否已经登录过的标志
      */
   public synchronized static boolean isLogined(HttpSession session,String sUserName){
         boolean flag = false;
         if(hUserName.containsKey(sUserName)){
              flag = true;
              HttpSession vsession = (HttpSession)hUserName.get(sUserName);
              try {
                    vsession.invalidate();
                   } catch (Exception ex){}
                } else{
                   flag = false;
                   }
                   hUserName.remove(sUserName);
                   hUserName.put(sUserName,session);
                   return flag;
               }
   public synchronized static boolean isOnline(HttpSession session){
         boolean flag = true;
         EmployeeInfo user = (EmployeeInfo) session.getAttribute("sessionUers");
         HttpSession vsession = (HttpSession) hUserName.get(user.getName());
         if (session.getId().equals(vsession.getId())) {
             flag = true;
           } else {
           flag = false;
             } return flag;
             }
          }
然后在web.xml中配置这个:

                   <listener>
                  <listener-class>comm.SessionListener</listener-class>
                  </listener>