【问题标题】:set path of JSESSIONID cookie created with HttpServletRequest.getSession(true)设置使用 HttpServletRequest.getSession(true) 创建的 JSESSIONID cookie 的路径
【发布时间】:2016-01-05 12:27:14
【问题描述】:

我正在使用 HttpServletRequest.getSession(true) 在我的 Web 应用程序的一个 servlet 中创建一个会话,该会话还创建一个 cookie JSESSIONID。我想更改与此 cookie 关联的路径。我正在尝试通过 setPath 方法执行此操作,但它不起作用。我正在使用tomcat6。提前致谢。下面是我正在使用的代码

HttpSession session = httpRequest.getSession(true);
Cookie[] cookies = httpRequest.getCookies();
if(cookies != null) {
    for (Cookie c : cookies)
    {
        if(c.getName().equals("JSESSIONID"))
        {
            c.setPath("somepath");
        }
    }
}

【问题讨论】:

    标签: java jakarta-ee tomcat6


    【解决方案1】:

    您已更改 cookie 路径,但未将修改后的 cookie 附加到响应中。所以在客户端,这种变化永远不会被识别出来。

    修改后的cookie像httpResponse.addCookie(c)这样添加到响应中。

    试试这个代码:

    HttpSession session = httpRequest.getSession(true);
    Cookie[] cookies = httpRequest.getCookies();
    if(cookies != null) {
        for (Cookie c : cookies)
        {
            if(c.getName().equals("JSESSIONID"))
            {
                c.setPath("somepath");
                httpResponse.addCookie(c);
            }
        }
    }
    

    但是它不会删除具有旧路径的现有 cookie,而是会创建一个具有新路径的新 cookie。

    很遗憾,我无法找到删除现有 cookie 的方法。我试图通过将旧 cookie 设置为 maxAge-1 来删除它,但没有奏效。这是我到目前为止尝试过的代码:

    String jSessionId = null;
    
    HttpSession session = request.getSession(false);
    if(session == null) {
        session = request.getSession(true);
    }
    
    Cookie[] cookies = request.getCookies();
    if(cookies != null) {
        for (Cookie c : cookies)
        {
            if(c.getName().equals("JSESSIONID"))
            {
                jSessionId = c.getValue();
    
                c.setValue(null);
                c.setMaxAge(0);
                response.addCookie(c);
            }
        }
    }
    
    if(jSessionId != null) {
        Cookie c = new Cookie("JSESSIONID", jSessionId);
        c.setPath("/servlet/sayhello");
        c.setHttpOnly(true);
        response.addCookie(c);
    }
    

    拥有 2 个不同的 cookie 没有大问题。因此,如果您对拥有两个 cookie 感到满意,可以使用第一个代码 sn-p。

    【讨论】:

    • 感谢您的回复。我已经尝试过上述方法,但它不足以满足我的目的。相反,我所做的如下 if(httpResponse.containsHeader("SET-COOKIE")){ String sessionid = httpRequest.getSession().getId(); httpResponse.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + ";Path=path+";" );
    猜你喜欢
    • 2012-03-18
    • 2023-04-01
    • 2016-12-10
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 2012-06-01
    • 2014-02-15
    • 2012-05-25
    相关资源
    最近更新 更多