防止同一个账号在多台电脑登录

1.实现HttpSessionListener  接口对session 进行监听

package com.tms.listener;

import com.tms.bean.UserSession;
import com.tms.constant.SystemConst;
import com.tms.service.system.RedisCacheService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
* Created by gjp on 2017/10/19.
* 防止同一账号在多台机器上登录
*/
@Component
public class SessionListener implements HttpSessionListener {
    static final Logger logSession = LoggerFactory.getLogger(SessionListener.class);

    @Resource
    private RedisCacheService<String> redisCacheService;


    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
       HttpSession start = httpSessionEvent.getSession();

       logSession.info("createId={}",start.getId());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        String id =httpSessionEvent.getSession().getId();
        deleteById(id);

        logSession.info("destroyed session id:"+id);
    }

    public boolean isCheckRepeatUser(UserSession newSession,HttpSession session){
        boolean flag =false;
        Set<String> keys = redisCacheService.keys(SystemConst.REPEAT_USER_LOGIN+"*");
        if(null != keys){
            for(String item:keys){
                   if(!flag) {
                       String userId = redisCacheService.getRedisCache(item);
                       if (!StringUtils.isEmpty(userId)) {
                           if (newSession.getUserId().equals(userId) &&
                                   !(SystemConst.REPEAT_USER_LOGIN+session.getId()).equals(item)) {
                               int len = item.length();
                               String key = item.substring(SystemConst.REPEAT_USER_LOGIN.length(), len);
                               //用户重复
                               addRepeatUserId(userId, key, TimeUnit.HOURS);
                               flag = true;
                               break;
                           }
                       }
                   }
            }
        }

        addUserSession(session.getId(),newSession);

        return  flag;
    }

    /**
     * 添加已经重复Session
     * @param item 值
     * @param key 键
     * @param hours 小时
     */
    private void addRepeatUserId(String item, String key, TimeUnit hours) {
                redisCacheService.setRedisCache( SystemConst.REPEAT_USER_LOGIN_TRUE +key,
                item, 24, hours);
    }

    /**
     * 删除已经重复Session
     * @param sessionId
     */
     public void deleteRepeatUserId(String sessionId) {
        redisCacheService.deleteById(sessionId,SystemConst.REPEAT_USER_LOGIN_TRUE);
    }

    public String getRepeatUserId(final String sessionId){
         return  redisCacheService.getRedisCache(SystemConst.REPEAT_USER_LOGIN_TRUE+sessionId);
    }


    /**
     * 删除过期session
     * @param sessionId
     */
    public void deleteById(final String sessionId){
        redisCacheService.deleteById(sessionId,SystemConst.REPEAT_USER_LOGIN);
        redisCacheService.deleteById(sessionId,SystemConst.REPEAT_USER_LOGIN_TRUE);


    }

    private void addUserSession(final String sessionId,final UserSession session){
        redisCacheService.setRedisCache(SystemConst.REPEAT_USER_LOGIN+sessionId,session.getUserId(),
                24, TimeUnit.HOURS);
    }


}


2.当用户登录成功后,执行SessionListener 对象中的isCheckRepeatUser() 方法,
检查,并且标记是否有同一个账号在不同机器上登录的情况。

3.如果用户退出时,删除对应的sessionid 记录。

@Resurce
private SessionListener sessionListener;

@CheckSession(method = "LoginController.fgLogout")
    @RequestMapping("/logout")
    public ModelAndView fgLogout(){
        ModelAndView mav = new ModelAndView("/front/login");
        HttpSession session = getSession();
        Enumeration<String> enumeration = session.getAttributeNames();
        if(null != enumeration ) {
            while (enumeration.hasMoreElements()) {
                session.removeAttribute(enumeration.nextElement());
            }
        }


       sessionListener.deleteById(session.getId());
        return mav;
    }

猜你喜欢

转载自gjp014.iteye.com/blog/2397468