多个用户之间的会话冲突

时间:2016-11-18 13:24:48

标签: java

我使用java 1.7和旧的echoStudido框架。 我在位于GlassFish服务器上的Web服务中有一个这样的sessionManager类:

@Singleton
@LocalBean
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class SessionManager {
    private static final int MAX_SIZE = 1000;
    private long ttl = 30 * 60 * 1000L;
    private HashMap<String, UserSession> sessions = new HashMap<String, UserSession>();

public UserSession getSession(String sessionId) {
    synchronized (this) {
        UserSession session = sessions.get(sessionId);
        if (session == null) {
            return null;
        }
        session.setLastAccess(new Date());
        return session;
    }
}

public String addSession(Integer userId, String userName) {
    String sessionId = UUID.randomUUID().toString();
    UserSession session = new UserSession(sessionId, userId, userName);
    synchronized (this) {
        if (sessions.size() >= MAX_SIZE) {
            logger.log(Level.SEVERE,
                    "session pool has exceeded the capacity of {0}"
                    + "-session creation rejected for user {1}",
                    new Object[]{MAX_SIZE, userName});
            return null;
        }
        sessions.put(sessionId, session);
    }
    return sessionId;
}

public UserSession removeSession(String sessionId) {
    synchronized (this) {
        return sessions.remove(sessionId);
    }
}
}

这是查看bean类的方法:

@Stateless
@WebService(serviceName="MyAppWebService", portName="PortalPort")
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public class PortalBean {

private static final String SESSION_ID_ATTRIBUTE_NAME
        = "com.myapp.portal.sessionId";

public String getSessionId() {
    return (String) getSession().getAttribute(SESSION_ID_ATTRIBUTE_NAME);
}

private String getValidSessionId() {
    String sessionId = getSessionId();
    if (sessionId == null) {
        return null;
    }
    return sessionId;
}

public void setSessionId(String sessionId) {
    getSession().setAttribute(SESSION_ID_ATTRIBUTE_NAME, sessionId);
}
....
}

在登录过程中,我在bean类中运行此代码:

String sessionId = sessionManager.addSession(user.getId(), user.getEmail());

然后:

setSessionId(sessionId);

当两个用户登录时,如果我单击logout(sessionManager.removeSession(sessionId);)并运行removeSession方法,则也会删除其他用户的会话。

代码出了什么问题?

0 个答案:

没有答案