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

查看:90
本文介绍了泽西岛:我可以在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

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

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