在jsp中设置空(空白)cookie

时间:2014-01-02 12:17:06

标签: java jsp cookies

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

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

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

IN JSP

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

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

2 个答案:

答案 0 :(得分:1)

它看起来像浏览器依赖

根据这些Docs

在所有浏览器中,空值的行为可能不一样。

答案 1 :(得分:0)

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);