Jersey:我可以在 ContainerResponseFilter 中添加 cookie 吗? [英] Jersey: Can I add a cookie in ContainerResponseFilter?

查看:27
本文介绍了Jersey:我可以在 ContainerResponseFilter 中添加 cookie 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ContainerResponseFilter,我尝试在其中设置一个 cookie,如下所示:

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));
}

但这会产生以下错误:

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

这里不能设置cookie吗?如果是,我该怎么做?

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

推荐答案

是的,这似乎有点奇怪,这是不允许的.不知道为什么不允许这样做.我已经用 Jersey 和 Resteasy 进行了测试.使用 Resteasy,所发生的只是未设置 cookie(无异常).我在想某些操作会将 cookie 设置为标头,并且在到达过滤器时,不会对 cookie 进行进一步的操作.

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"));

NewCookietoString() 将返回它在标题中的外观

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

Set-Cookie: Hello=World;Version=1

这篇关于Jersey:我可以在 ContainerResponseFilter 中添加 cookie 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆