mtjmtj7的小站
mtjmtj7的小站
© mtjmtj7
All Rights Reserved.

spring mvc项目中实现登录账号单点登录

思路:新建listener,如果session创建,判断map中是否存在当前用户,如果存在,使session失效;如果不存在,存入map中。如果session被移除,从map中移除。

新建监听器类

/**
 * Application Lifecycle Listener implementation class AdminListener
 *
 */
@WebListener
public class AdminListener implements HttpSessionAttributeListener {

	private Map<String, HttpSession> map = new HashMap<String, HttpSession>();
	
    /**
     * Default constructor. 
     */
    public AdminListener() {
        // TODO Auto-generated constructor stub
    }

	/**
     * @see HttpSessionAttributeListener#attributeRemoved(HttpSessionBindingEvent)
     */
    public void attributeRemoved(HttpSessionBindingEvent event)  { 
    	 String name = event.getName();
    	 
         if (name.equals("admin_now")) {
             Admin admin = (Admin) event.getValue();
             map.remove(admin.getAdminname());
  
         }
    }

	/**
     * @see HttpSessionAttributeListener#attributeAdded(HttpSessionBindingEvent)
     * 新增session,即登录了一个用户
     */
    public void attributeAdded(HttpSessionBindingEvent event)  { 
         String adminName = event.getName();
         if(adminName.equals("admin_now")) {
        	 System.out.println("登录了一个用户");
        	 Admin admin = (Admin)event.getValue();
        	 //如果当前map中存在此用户,使session失效
        	 if(map.get(admin.getAdminname()) != null) {
        		 HttpSession session = map.get(admin.getAdminname() );
        		 session.removeAttribute(admin.getAdminname());
        		 session.invalidate();
        		 System.out.println("已经登录,上一个失效。");
        	 }
        	 else{
            	 System.out.println("第一次登陆,存入map");
            	 map.put(admin.getAdminname(), event.getSession());
        	 }
         }
    }

	/**
     * @see HttpSessionAttributeListener#attributeReplaced(HttpSessionBindingEvent)
     */
    public void attributeReplaced(HttpSessionBindingEvent arg0)  { 
         // TODO Auto-generated method stub
    }

	public Map<String, HttpSession> getMap() {
		return map;
	}

	public void setMap(Map<String, HttpSession> map) {
		this.map = map;
	}
	
}

 

在web.xml配置

   <listener>
       <listener-class>schedule.listener.AdminListener</listener-class>
   </listener>

 

打赏
1
2018-03-06
666 阅读
关键字: ,
  1. root
    admin
    Google Chrome Windows

    评论+1

发表评论