同一个容器下,不同的项目间的SESSION是不能共享的

Case Review:

当前项目A下要跳转到项目B的页面中,并且要从A里面传一些值过去。

值被放在A的SESSION中,但是B中未获取到。

解决方案:

1. 直接在跳转到B项目下的地址后面加入参数,例如?test=test

2. 共享当前SESSION。

//项目A下
request.getSession().getServletContext().setAttribute("session", request.getSession());
//项目B下
request.getSession.getServletContext().getContext("项目A").getAttribute("session");

根源:

是容器在实现request.getSession()方法时,是从Context中获取和创建的,所以不同的项目间才会出现SESSION不共享。<--  这只针对TOMCAT6.0 作出的结论,可能不同的容器实现机制会不同。

protected Session doGetSession(boolean create) {

    // There cannot be a session if no context has been assigned yet
    if (context == null)
        return (null);

    // Return the current session if it exists and is valid
    if ((session != null) && !session.isValid())
        session = null;
    if (session != null)
        return (session);

    // Return the requested session if it exists and is valid
    Manager manager = null;
    if (context != null)
        manager = context.getManager();
    if (manager == null)
        return (null);      // Sessions are not supported
    if (requestedSessionId != null) {
        try {
            session = manager.findSession(requestedSessionId);
        } catch (IOException e) {
            session = null;
        }
        if ((session != null) && !session.isValid())
            session = null;
        if (session != null) {
            session.access();
            return (session);
        }
    }

    // Create a new session if requested and the response is not committed
    if (!create)
        return (null);
    if ((context != null) && (response != null) &&
        context.getCookies() &&
        response.getResponse().isCommitted()) {
        throw new IllegalStateException
          (sm.getString("coyoteRequest.sessionCreateCommitted"));
    }

    // Attempt to reuse session id if one was submitted in a cookie
    // Do not reuse the session id if it is from a URL, to prevent possible
    // phishing attacks
    if (connector.getEmptySessionPath() 
            && isRequestedSessionIdFromCookie()) {
        session = manager.createSession(getRequestedSessionId());
    } else {
        session = manager.createSession(null);
    }

    // Creating a new session cookie based on that session
    if ((session != null) && (getContext() != null)
           && getContext().getCookies()) {
        Cookie cookie = new Cookie(Globals.SESSION_COOKIE_NAME,
                                   session.getIdInternal());
        configureSessionCookie(cookie);
        response.addCookieInternal(cookie, context.getUseHttpOnly());
    }

    if (session != null) {
        session.access();
        return (session);
    } else {
        return (null);
    }

}

猜你喜欢

转载自lvjun106.iteye.com/blog/1838345