从应用服务器获取的cookie数量是否为1?

Is the number of cookies obtained from application server is 1?

通常,容器将 cookie 作为响应的一部分发送。我在 JSF 中创建了一个简单的登录表单并尝试将其提交给 JSF bean。

在我的 bean 的操作方法中,我尝试使用以下代码检索从服务器获得的 cookie。

FacesContext ctx = FacesContext.getCurrentInstance();
Map cookieMap = ctx.getExternalContext().getRequestCookieMap();

据我所知,我知道我们得到了一个 cookie,即 JSESSIONID。我已经使用以下代码检查了一些服务器。

if (cookieMap != null && !cookieMap.isEmpty()) {
            Iterator iterator = cookieMap.keySet().iterator();
            while (iterator.hasNext()) {
                Cookie cookie = (Cookie) cookieMap
                        .get((String) iterator.next());
                System.out.printf("Cookie get name %s, cookie get value %s ",
                        cookie.getName(), cookie.getValue());
            }
        }

以下是从不同服务器抓取的结果。

  1. VMware vFabric tc Server Developer Edition
output : Cookie get name JSESSIONID, cookie get value 3B88AE51A991800566A4C3A05AC36C37
  1. Tomcat v7.0 Server
Cookie get name JSESSIONID, cookie get value 115B310C64B68C3E25C49391236AE978
  1. Jetty server
Cookie get name JSESSIONID, cookie get value 115B310C64B68C3E25C49391236AE978

根据以上统计,我编写了如下代码,将 cookie 传递给 url 连接方法,如下所示。

private void openConnection(URL url, Cookie jsessionid){
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.disconnect();
    conn.setUseCaches(false);
    conn.setDefaultUseCaches(false);
    conn.setDoOutput(true);
    if (jsessionid != null) {
        conn.addRequestProperty("Cookie", jsessionid.getName() + "="
                + jsessionid.getValue());
    }
    conn.connect();
    //some other code
}

一位高级开发人员改进了上述代码片段,如下所示将 cookieMap 中的 cookie 迭代添加到 RequestProperty。

if(cookieMap !=null && !cookieMap.isEmpty()){
    Iterator iterator = cookieMap.keySet().iterator();
    while (iterator.hasNext()) {
          Cookie cookie = (Cookie) cookieMap.get((String)iterator.next());
          conn.addRequestProperty("Cookie",
                      cookie.getName() + "=" + cookie.getValue());
    }
}

我没有在其他应用程序服务器上尝试过此操作,但我猜其他应用程序服务器(如 Weblogic、GlassFish)也会提供相同的输出,即 1 个名为 JSESSIONID 的 cookie。如果我错了,请纠正我。我想知道从a容器中获取的cookie数量是否为1个或更多。

高级开发人员正确改进了您的代码,因为应用程序服务器可能会发送多个 cookie。它仅取决于为您的请求提供服务的 Web 应用程序;例如,您可以同时接收身份验证 cookie(由 JSESSIONID 表示)和 persistent cookie。通过此改进,您的应用程序将发回所有收到的 cookie。

例如,Web 应用程序可能希望记住您在第一次访问网站时选择的用户语言。此信息应由一个特殊的 cookie 返回,该 cookie 不依赖于用户稍后访问该站点时是否已通过身份验证。

I didn't try this with other application servers but I guess, other application servers like Weblogic, GlassFish, would also give the same output, i.e.., 1 cookie with name JSESSIONID.

没错。但是,如上所述,您可能会收到其他类型的 cookie 以及 JSESSIONID。