Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jersey: Can I add a cookie in ContainerResponseFilter?

I have a ContainerResponseFilter and I tried to set a cookie in it as follows:

@Override
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {
    String cookieName = "ExampleCookie";
    String cookieValue = "SomeData";
    logger.info("Setting cookie " + cookieName + " with value " + cookieValue + " into cookies " + JsonUtils.objectToJson(containerResponseContext.getCookies()));
    containerResponseContext.getCookies().put(cookieName, new NewCookie(cookieName, cookieValue));
}

But this give the following error:

Caused by: java.lang.UnsupportedOperationException: null
    at java.util.AbstractMap.put(AbstractMap.java:203) ~[na:1.7.0_67]

It is not possible to set the cookie here? If it is, how would I do it?

like image 629
David Williams Avatar asked Apr 29 '15 20:04

David Williams


1 Answers

Yeah seems a bit odd that this is not allowed. Not sure why this is not allowed. I've tested both with Jersey and Resteasy. With Resteasy, all that happens is that the cookie is not set (no Exception). I'm thinking some operation sets the cookies as headers, and by the time the filter is reached, no further operation is done with the cookies.

The only work around I can think of is to simply set the header yourself

responseContext.getHeaders().add("Set-Cookie", new NewCookie("Hello", "World"));

The toString() of NewCookie will return how it should look in the header

Set-Cookie: Hello=World;Version=1
like image 124
Paul Samsotha Avatar answered Nov 13 '22 22:11

Paul Samsotha