【问题标题】:How add and read cookies from the same servlet in different如何从不同的 servlet 添加和读取 cookie
【发布时间】:2014-05-13 18:27:49
【问题描述】:

从 index.html 页面中的表单(您在其中写年龄和姓名)我能够(使用 POST)调用我的 servlet01,它测试我是成年人还是未成年人(只需写出类似 out. println("你是成年人") 或 out.println("你是未成年人") 如果年龄小于...)

现在我要更改 servlet01:它应该记住与 cookie 相同的信息(年龄和姓名),并且: a) 当用户是成年人时,servlet01 应该要求也插入地址。该地址需要保存在另一个 cookie 上,始终使用 servlet01 并生成一份报告,其中显示姓名、年龄和地址;

b) 当用户是未成年人时,servlet01 应该将用户重定向到 servlet02。 Servlet02 应该读取 cookie(年龄和姓名)并显示“用户:”+姓名+“年龄:”+年龄+“您是未成年人”

这就是我所做的: servlet01 http://pastebin.com/aFMSkeZ4

servlet02 http://pastebin.com/YqMZpqJd

【问题讨论】:

  • 那么,您的问题到底是什么?
  • 我在解决 a) 部分时遇到了困难。我不知道如何从同一个 servlet 设置和调用 cookie:第一次检查参数 age 和 name(并设置 age_cookie 和 name_cookie),第二次我应该提出一个表单来插入地址,然后将该参数保存为饼干……我迷路了……

标签: java html servlets cookies


【解决方案1】:

每个HttpServletRequest 都有一个Cookie 对象数组;您可以使用request.getCookies() 访问它们。

通过遍历这个数组,你可以根据它的name找到你之前填充的cookie,然后读取它的value

通过使用 response.addCookie(...) 将其添加到响应中来设置 cookie。

【讨论】:

    【解决方案2】:

    要添加新的 cookie,您可以使用如下方法:

    public void setCookie(HttpServletRequest request, HttpServletResponse response){
        final String cookieName = "my_cool_cookie";
        final String cookieValue = "my cool value here !";  // you could assign it some encoded value
        final Boolean useSecureCookie = new Boolean(false);
        final int expiryTime = 60 * 60 * 24;  // 24h in seconds
        final String cookiePath = "/";
    
        Cookie myCookie = new Cookie(cookieName, cookieValue);
        cookie.setSecure(useSecureCookie.booleanValue());  // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL
        cookie.setMaxAge(expiryTime);  // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.
        cookie.setPath(cookiePath);  // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories
        response.addCookie(myCookie);
    }
    

    并读取您可以使用的 cookie 值:

    Cookie[] cookies = request.getCookies();
    
    for (int i = 0; i < cookies.length; i++) {
      String name = cookies[i].getName();
      String value = cookies[i].getValue();
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 2016-07-19
      • 1970-01-01
      • 2016-04-23
      • 2022-11-03
      • 1970-01-01
      • 2011-06-17
      相关资源
      最近更新 更多