JSESSIONID cookie 何时添加到响应中

When is the JSESSIONID cookie added to the response

我有一个 JSF 2.0 应用程序,我们称它为 "MyApp",带有一个 SessionScoped bean,它使用以下代码获取会话并在初始化时设置路径...

HttpServletRequest request = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();   //Get request from external context
HttpSession session = request.getSession(false);   //Get session and don't create one if it doesn't exist
session.getServletContext().getSessionCookieConfig().setPath(""); //Set the path in the session's cookie

我的问题是更新的路径 ("") 不会显示在响应会话 cookie 中,JSESSIONID,直到对应用程序的第二个请求。第一个请求在响应中使用默认路径获取 JSESSIONID cookie,其中包括应用程序的根上下文(“/MyApp”)。如果我重新加载页面,第二个请求将得到一个包含更新路径 ("") 的 JSESSIONID cookie 的响应。

我似乎找不到任何关于何时创建默认 JSESSIONID cookie 并将其添加到响应的文档。我不确定是否在第一个响应的 JSESSIONID cookie 中设置了更新的会话路径,或者它是否被页面的默认 JSESSIONID cookie 设置和覆盖。

问题:

  1. 默认的 JSESSIONID cookie 何时添加到响应中?
  2. 是否可以禁止创建页面的默认 JSESSIONID cookie?

When does the default JSESSIONID cookie get added to the response?

首次创建 HTTP 会话时。例如。当 JSF 需要将新创建的会话作用域 bean 放在那里时。因此,如果您在这样一个应该操纵会话的 bean 中编写一些代码,那么您基本上已经来不及了。

你的代码片段也是有力的证据。如果会话真的没有创建,那么 request.getSession(false) 会返回 null 并且随后调用 session.getServletContext() 会抛出 NullPointerException 并且你会问一个非常不同的问题.


Is it possible to disable the page's default JSESSIONID cookie from being created?

我相信你问错了问题。您实际上想问的是如何正确设置会话 cookie 路径。

您应该在 web.xml 中配置会话 cookie 路径,如下所示:

<session-config>
    <cookie-config>
        <path>/</path>
    </cookie-config>
</session-config>

如果您真的出于某种不清楚的原因而打算以编程方式进行,而问题中没有详细说明,那么您应该在 为第一个 HTTP 会话创建之前进行此操作时间。换句话说,您绝对不应该在会话范围的 JSF 托管 bean 中执行此操作,也不应该从 HttpSession 本身获取所需的 ServletContext

最明智的地方是servlet context listener or, if you really need it to be "JSF-ish", then an eagerly initialized application scoped bean. Please note that this is an application-wide setting, not a session-wide setting. It being a property of ServletContext (and not of HttpSession) already hints that. Thus, once you set it, it affects all newly created session cookies. Depending on the concrete functional requirement which you told nothing about,可能还有更好的方法。例如。一个额外的 cookie。