简体   繁体   English

如何使用JAX-RS NewCookie删除服务器上的cookie?

[英]How to delete a cookie on server with JAX-RS NewCookie?

I want to delete cookie on server (by means of setting Expires to the past). 我想删除服务器上的cookie(通过将Expires设置为过去)。 How can I do this with javax.ws.rs.core.NewCookie ? 我怎么能用javax.ws.rs.core.NewCookie做到这一点? I'm trying this, but it doesn't work: 我正在尝试这个,但它不起作用:

return Response.ok()
  .entity("hello world!")
  .cookie(
    new NewCookie(
      "foo",
      "",
      "/",
      ".example.com",
      1,
      "no comment",
      0, // maxAge
      false
    )
  )
  .build();

This snippet produces this HTTP header: 此代码段生成此HTTP标头:

Set-Cookie:foo=;Version=1;Comment="no comment";Domain=.example.com;Path=/

This header doesn't delete the cookie from the server. 此标头不会从服务器中删除cookie。 What is a possible workaround? 什么是可能的解决方法?

This is how it works (rather dirty approach): 这是它的工作原理(相当脏的方法):

return Response.ok()
  .header(
    "Set-Cookie",
    "foo=deleted;Domain=.example.com;Path=/;Expires=Thu, 01-Jan-1970 00:00:01 GMT"
  );

I cannot try proposed, but it should work (since it is common work around for java servlet API to remove cookie). 我不能尝试提议,但它应该工作(因为它是java servlet API删除cookie的常见工作)。

Step 1. Get access to HttpServletResponse. 步骤1.访问HttpServletResponse。 To do it declare in your service something like: 为此,在您的服务中声明如下:

@Context
HttpServletResponse _currentResponse;

Step 2. Let the client side chance to remove cookie by set expiration time 步骤2.让客户端通过设置到期时间来删除cookie

Cookie userCookie = new Cookie(cookieName, "");
_currentResponse.setContentType("text/html");
userCookie.setMaxAge(0);
_currentResponse.addCookie(userCookie);

This worked for me! 这对我有用! Note that I'm setting the max age to 0 and the expiration date to the current time. 请注意,我将最大年龄设置为0,将过期日期设置为当前时间。

NewCookie mycookie= new NewCookie("mycookie", null, "/", "", NewCookie.DEFAULT_VERSION, null, 0, new Date(), false, false);
return Response.ok().cookie(mycookie).build();

this works as well: 这也有效:

NewCookie mycookie = new NewCookie("mycookie", null, "/", null, null, 0, false, true);
return Response.ok().cookie(mycookie).build();

extract from response header: 从响应头中提取:

set-cookie: mycookie=;Version=1;Path=/;Max-Age=0;HttpOnly

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM