[英]How to delete a cookie on server with JAX-RS NewCookie?
我想刪除服務器上的cookie(通過將Expires
設置為過去)。 我怎么能用javax.ws.rs.core.NewCookie
做到這一點? 我正在嘗試這個,但它不起作用:
return Response.ok()
.entity("hello world!")
.cookie(
new NewCookie(
"foo",
"",
"/",
".example.com",
1,
"no comment",
0, // maxAge
false
)
)
.build();
此代碼段生成此HTTP標頭:
Set-Cookie:foo=;Version=1;Comment="no comment";Domain=.example.com;Path=/
此標頭不會從服務器中刪除cookie。 什么是可能的解決方法?
這是它的工作原理(相當臟的方法):
return Response.ok()
.header(
"Set-Cookie",
"foo=deleted;Domain=.example.com;Path=/;Expires=Thu, 01-Jan-1970 00:00:01 GMT"
);
我不能嘗試提議,但它應該工作(因為它是java servlet API刪除cookie的常見工作)。
步驟1.訪問HttpServletResponse。 為此,在您的服務中聲明如下:
@Context
HttpServletResponse _currentResponse;
步驟2.讓客戶端通過設置到期時間來刪除cookie
Cookie userCookie = new Cookie(cookieName, "");
_currentResponse.setContentType("text/html");
userCookie.setMaxAge(0);
_currentResponse.addCookie(userCookie);
這對我有用! 請注意,我將最大年齡設置為0,將過期日期設置為當前時間。
NewCookie mycookie= new NewCookie("mycookie", null, "/", "", NewCookie.DEFAULT_VERSION, null, 0, new Date(), false, false);
return Response.ok().cookie(mycookie).build();
這也有效:
NewCookie mycookie = new NewCookie("mycookie", null, "/", null, null, 0, false, true);
return Response.ok().cookie(mycookie).build();
從響應頭中提取:
set-cookie: mycookie=;Version=1;Path=/;Max-Age=0;HttpOnly
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.