3

我正在尝试为我的 iPhone 应用程序实现注销功能,该应用程序在客户端使用 jQuery 移动、JS,在服务器端使用 java。目前我要做的是清除cookie并重定向到我的index.html中的#loginpage标签(我只有1个HTML文件,其中不同页面有多个标签)。我现在为 clearCookie 做的是:

Cookie readCookie = null;
for (Cookie cookie : httpRequest.getCookies()) {
    if (cookie.getName().equals("CookieForLogin")) {
        readCookie = cookie;
        break;
    }
}

readCookie.setMaxAge(0);
httpResponse.addCookie(readCookie);

但是这段代码并没有清除 cookie。我已经尝试过 JS 方法,即将到期日期设置为以前的某个日期,在网上给出,但它们也不起作用。我也没有响应方法HttpServletResponse。如何清除在客户端设置的 cookie 以及如何重定向到特定标签?

4

3 回答 3

5

Cookie 与特定路径相关联。您需要确保在删除 cookie 期间设置与创建 cookie 期间相同的路径。它默认为 URL 中当前请求的文件夹(因此只能在同一文件夹或其所有子文件夹中使用)。您最好明确指定路径,否则它将取决于 URL 中当前请求的文件夹。cookie 路径信息类似于请求 cookie 标头中不可用的 maxage。

假设您按如下方式创建了 cookie,

Cookie cookie = new Cookie("CookieForLogin", cookieForLogin);
cookie.setPath("/somePath");
cookie.setMaxAge(maxAgeInSeconds);
// ...
response.addCookie(cookie);

它需要按如下方式删除:

Cookie cookie = new Cookie("CookieForLogin", null);
cookie.setPath("/somePath");
cookie.setMaxAge(0);
// ...
response.addCookie(cookie);

/somePath只是示例。您也可以只使用/,只要在两种情况下都相同。

请注意,这同样适用于 cookie 的SecureHTTP-only标志。如果您最初true在 cookie 创建期间将其设置为,那么您也应该true在 cookie 删除期间将其设置为,即默认为false.

也就是说,我不确定将登录用户存储为 cookie 有什么用处。您基本上还允许最终用户操纵其价值。而是将登录用户存储为会话属性并session.invalidate()在注销时调用。

于 2013-04-12T14:34:08.557 回答
1

void setMaxAge(int expiry)

我们可以使用方法删除cookie,称为setMaxAge()

Cookie c = new Coookie("x", "10");

如果将 maxage 设置为 0

c.setMaxAge(0); //it causes the cookie to be deleted.

如果将 maxage 设置为负值

c.setMaxAge(-1);
// cookie is not stored persistently and will be deleted end of the browsing session.
于 2018-10-03T22:11:14.573 回答
0

获取最大年龄

public int getMaxAge() 获取此 Cookie 的最大年龄(以秒为单位)。默认返回-1,表示cookie会一直持续到浏览器关闭。

返回: 一个整数,指定 cookie 的最大年龄(以秒为单位);如果为负,则表示 cookie 一直存在到浏览器关闭另请参见:setMaxAge(int)

//Java API 文档

简而言之,您需要设置 cookie 年龄:

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 killMyCookie = new Cookie("mycookie", null);
 killMyCookie.setMaxAge(0);
 killMyCookie.setPath("/");
 response.addCookie(killMyCookie);
于 2013-04-12T18:29:01.380 回答