Jersey: Can I add a cookie in ContainerResponseFilter?

旧时模样 提交于 2019-12-19 05:34:57

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/29954305/jersey-can-i-add-a-cookie-in-containerresponsefilter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!