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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With