【问题标题】:addCookie() not working in Tomcat 7addCookie() 在 Tomcat 7 中不起作用
【发布时间】:2014-06-19 11:27:38
【问题描述】:

目前我正在将我的应用程序从 Tomcat 6 迁移到 Tomcat 7。在我的流程中,有一部分是在 servlet 的方法中将 cookie 从 servlet 添加到 jsp。但它既没有添加 cookie,也没有抛出任何异常。为了交叉检查,我尝试在 jsp 中强制添加 cookie。但得到了相同的结果。

servlet.java

public void logon( String username, String password, String ip, HttpServletResponse response) throws Exception, LogonFailure {
    System.out.println(" Input Received ::"+response);
        System.out.println("Attachment :::"+getNextAttachment());

        AuthenticatorTicketWrapper wrapper = new AuthenticatorTicketWrapper( username, password, ip, "" + getNextAttachment(), this );

        // if no exception thrown then we must of managed to log on.
        String userID =  "" + this.getNextID();
        System.out.println("User Id within Logon method ::"+userID);
        wrapper.setUserName(userID);
        //wrapper.set

        m_Cache.put( userID, wrapper );
        // add cookie to the users browser



        try {
            System.out.println("Cookiename in the logon method :"+cookieName);
            response.addCookie( new Cookie(this.cookieName + this.CREATION_ID, userID) );
            response.addCookie( new Cookie(this.cookieName + this.CREATION_KEY, wrapper.getUserCookieKey() ) );
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("Failed Add cookie, Exception " + se);
        }


    }

catalina.policy

// Permission the examples/samples - see the context xml files
grant codeBase "file:${catalina.home}/webapps/CreationWeb/-" {
      permission java.security.AllPermission;
};

如果我遗漏了什么,请告诉我吗?

【问题讨论】:

  • cookieName 来自哪里以及在哪里定义?
  • setMaxAge() 会帮助你我认为.. 在response.addCookie();之前尝试一下
  • cookieName 来自一个全局变量。我已经使用调试器进行了检查,并且即将到来。让我用 setMaxAge() 检查一下。
  • 好的,像这样:cookie.setMaxAge(60*60); //1 hour

标签: java jsp tomcat servlets cookies


【解决方案1】:

我之前使用如下代码在tomcat 7中设置cookie

    Cookie userCookie = new Cookie("someName", "someValue");
    userCookie.setMaxAge(99999999999); 
    userCookie.setPath("/");
    resp.addCookie(userCookie);

在上面的例子中,resp 是 HttpServletResponse。此代码已经过测试并适用于 tomcat 7 和 JDK 1.7

【讨论】:

  • 你试过setMaxAge(99999999999);吗?它将设定什么年龄?
  • 文档的链接位于:docs.oracle.com/javaee/6/api/javax/servlet/http/… 它需要一个 int 参数,该参数对应于 cookie 的生命周期(以秒为单位)。我只是使用了一个任意大的数字作为我不想很快过期的 cookie
  • 但是如果有人是新人,那么请提供一些适当且易于理解的格式,例如(60*60*24) // 24 hours
  • 相同的代码在 Tomcat 6 中运行良好。恐怕我是否错过了任何配置。我已经检查了 60*60*24 的年龄。
  • 这可能是浏览器方面的问题吗?我刚刚在本地环境中使用 JDK 1.6 和 Tomcat 7 对其进行了测试,并且它正在使用默认的 Tomcat 设置。我不必编辑任何设置,只需安装并启动它。这让我相信它要么是浏览器问题,要么响应永远不会返回浏览器?您可能想尝试卸载并重新安装 Tomcat 7,并将所有内容都保留为默认值。
猜你喜欢
  • 2014-03-05
  • 2013-05-28
  • 2014-01-31
  • 2016-12-11
  • 1970-01-01
  • 2019-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多