Spring3 Security 中配置会话管理

账户登录时,要求一个账户同时只能一人登录,配置中的步骤有三个:

1.在web.xml中配置HttpSessionEventPublisher

<listener>
     <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>

2.在security.xml中配置session management

session-management标签放在http标签中
<session-management invalid-session-url="/login?invalid_session">
            <concurrency-control max-sessions="1" error-if-maximum-exceeded="false" expired-url="/login?expired"/>
</session-management>

其中的"max-session"属性表示最大session会话数量,默认是1;"error-if-maximum-exceeded"属性默认是false,表示同一账号,先登录的,会被后登录者强制下线,为true时,表示一旦有用户登录,其他用户将无法登录。

3.重写user登录相关类中的equals和hashCode方法,若扩展了UserDetails,也要重写其equals和hashCode方法

User.java

@Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof User)) return false;

        User that = (User) o;

        if (guid != null ? !guid.equals(that.guid) : that.guid != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        return guid != null ? guid.hashCode() : 0;
    }

StUserDetails.java

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof StUserDetails)) return false;

        StUserDetails that = (StUserDetails) o;

        if (grantedAuthorities != null ? !grantedAuthorities.equals(that.grantedAuthorities) : that.grantedAuthorities != null)
            return false;
        if (user != null ? !user.equals(that.user) : that.user != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = user != null ? user.hashCode() : 0;
        result = 31 * result + (grantedAuthorities != null ? grantedAuthorities.hashCode() : 0);
        return result;
    }

初学,若有错误之处,望大家指教!



原文地址:https://www.cnblogs.com/lzw-st/p/5459435.html