JAX-RS Jersey cookie删除失败

时间:2013-10-10 11:00:57

标签: java cookies jersey jax-rs

我无法从请求中删除一些cookie(2),我不知道为什么......

我试过这种方式:

将到期时间设置为0,将值设置为空白,将安全标志设置为false

@GET
@Path("clear-cookies")
public Response clear-cookies(@QueryParam(NEXT) String next) throws Exception {

    Viewable page = getPage();

    // Returns form and remove cookies, setting expiration time to zero.
    return javax.ws.rs.core.Response
        .ok(page)
        .cookie(new NewCookie(NEXT, next))
        .cookie(new NewCookie(FIRST, "", null, null, null, 0, false))
        .cookie(new NewCookie(SECOND, "", null, null, null, 0, false))
        .build();
}

将expiration设置为0,将value设置为null,将secure flag设置为true

@GET
@Path("clear-cookies")
public Response clear-cookies(@QueryParam(NEXT) String next) throws Exception {

    Viewable page = getPage();

    // Returns form and remove cookies, setting expiration time to zero.
    return javax.ws.rs.core.Response
        .ok(page)
        .cookie(new NewCookie(NEXT, next))
        .cookie(new NewCookie(FIRST, null, null, null, null, 0, true))
        .cookie(new NewCookie(SECOND, null, null, null, null, 0, true))
        .build();
}

2 个答案:

答案 0 :(得分:0)

我已经通过描述所有通用参数的通用方法解决了这个问题。至少三个参数必须相等:name(=“ name”)、、 path(=“ /”)和domain(= null):

public static NewCookie createDomainCookie(String value, int maxAgeInMinutes) {
    ZonedDateTime time = ZonedDateTime.now().plusMinutes(maxAgeInMinutes);
    Date expiry = time.toInstant().toEpochMilli();
    NewCookie newCookie = new NewCookie("name", value, "/", null, Cookie.DEFAULT_VERSION,null, maxAgeInMinutes*60, expiry, false, false);
    return newCookie;
}

并使用它进行设置的常用方法:

NewCookie domainNewCookie = RsCookieHelper.createDomainCookie(token, 60);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();

并删除:

NewCookie domainNewCookie = RsCookieHelper.createDomainCookie("", 0);
Response res = Response.status(Response.Status.OK).cookie(domainNewCookie).build();

答案 1 :(得分:-1)

以下内容对我有用,但您需要知道Cookie的名称并逐个删除:

@GET
@Path("clear-cookie")
@Produces(MediaType.TEXT_PLAIN)
public Response clear-cookie(@CookieParam("COOKIE_NAME") javax.ws.rs.core.Cookie cookie) {
    if (cookie != null) {
    NewCookie newCookie = new NewCookie(cookie, null, 0, false);
    return Response.ok("OK").cookie(newCookie).build();
    }
    return Response.ok("OK - No session").build();
}