【问题标题】:How to separate sessions for new browser instance of IE8 using servlet?如何使用 servlet 为 IE8 的新浏览器实例分离会话?
【发布时间】:2013-04-25 10:28:58
【问题描述】:

我面临创建新会话并同时维护前一个会话的问题。

我的代码在一个 Servlet 中。它适用于除 IE 之外的所有其他浏览器,也适用于 IE7 和更低版本,但不适用于 IE8 和 IE9。我很清楚 IE8 和 IE9 对每个新请求使用相同的会话;但我想为我的 Java EE 应用程序的每个新初始请求创建一个新会话。 当会话为空时,我第一次为创建新的HTTPSession 编写了代码,并且还为新会话添加了代码。

如何为新会话编码更改,而不在每个页面上维护任何隐藏变量值或通过 URL 发送会话 ID?有没有其他方法可以分隔两个或多个会话?

我的 Servlet 代码快照如下所示:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    process(request, response);
}

private void process (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String strErrorMsg = null;
    response.setContentType ( "text/html" );
    HttpSession session = null;
    Cookie cookies[] = request.getCookies();

    if (session == null) {
        ServletContext appContext = getServletContext();
        WebProcessContextBuilder builder =  WebProcessContextBuilder.getInstance();
        ProcessContext objContext = null;
        try {
            session = request.getSession(true);
            // Code for setting some initial session attributes and forwarding request 
            // to first window to display.
        }
    }

    if (session != null && session.isNew()) {
        // Code for new session to forward my request with saving session id 
        // as well as setting session attributes
    } else {
        // code for showing alert message like "Session active in another window or tab.";
    }
}

使用上面的代码,当我第二次尝试加载新应用程序时,我总是收到一条错误消息。这是因为我得到的会话不等于 null 并且在 IE8 和 IE9 的情况下 session.isNew 总是错误的。在其他地方它工作正常。

【问题讨论】:

    标签: java session servlets


    【解决方案1】:

    这看起来不对:

    HttpSession session = null;
    Cookie cookies[] = request.getCookies();
    
    if (session == null) {
    

    这里怎么会不为空呢?

    我认为应该是:

    // Try to get the session, but don't create one if there isn't one
    HttpSession session = request.getSession(false);
    Cookie cookies[] = request.getCookies();
    
    if (session == null) {
    

    【讨论】:

    • 感谢保罗的回复。仅在首次登录的情况下,您绝对正确。但是对于第二次访问相同的 url,它会复制相同的会话。这是我面临的主要问题是如何将它们分开......
    • session == null 将在那时始终为真。您将null 分配给session,然后在比较之前不要更改它。因此,在 if 块内,如果之前不存在会话,您将创建一个新会话 - 这不是您想要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-07-22
    • 1970-01-01
    • 1970-01-01
    • 2019-12-05
    • 2016-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多