【问题标题】:Setting empty (blank) cookies in jsp在jsp中设置空(空白)cookie
【发布时间】:2014-01-02 20:42:18
【问题描述】:

我正在使用 cookie 在客户端存储一些数据。

我存储在 cookie 中的数据来自可以为空的数据库。我正在检查它是否为空,并基于它为变量赋值。

if(rs.getString("publicationDateFrom") == null || rs.getString("publicationDateFrom").equals(""))
 str[8] = "";
else
 str[8] = rs.getString("publicationDateFrom").trim();

在 JSP 中

publicationDateFrom = new Cookie("publicationDateFrom",str[8]);
publicationDateFrom.setMaxAge(60*60*24*exTime); 
publicationDateFrom.setPath("/");
response.addCookie( publicationDateFrom );

如果str[8] 为空,为什么我的cookie 显示"" 的值。它的字符串长度是2

【问题讨论】:

  • 因为,您正在检查您的请求变量是否为空或为空。但是,即使是空的,您的 cookie 也会被创建。这就是创建名为“publicationDateFrom”的空 cookie 的原因。
  • 如果在 JSP 中打印 str[8],会打印什么值?
  • 当我使用 log 时它什么也没显示,字符串长度为 0
  • @ParkashKumar 我想创建空 cookie,但它不是空的,它包含两个双引号
  • 检查所有可以使用的合法值,虽然你没有使用这个方法docs.oracle.com/javaee/6/api/javax/servlet/http/…但是值部分必须是合法的。

标签: java jsp cookies


【解决方案1】:

看起来它依赖于浏览器

根据这些Docs

空值在所有浏览器上的行为方式可能不同。

【讨论】:

  • 这是我在此答案之前评论的内容,请参阅评论here
【解决方案2】:

Refer this

使用 JSP 设置 Cookie:

Setting cookies with JSP involves three steps:

(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.

Cookie cookie = new Cookie("key","value");

Keep in mind, neither the name nor the value should contain white space or any of the following characters:

[ ] ( ) = , " / ? @ : ;

(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours.

cookie.setMaxAge(60*60*24); 

(3) Sending the Cookie into the HTTP response headers: You use response.addCookie to add cookies in the HTTP response header as follows:

response.addCookie(cookie);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多