gpt4 book ai didi

java - RESTEasy Singleton 中的 CookieParam

转载 作者:行者123 更新时间:2023-11-30 04:13:52 24 4
gpt4 key购买 nike

我以这种方式注入(inject)我的 cookie 参数(使用 javax.ws.rs.CookieParam)

@CookieParam("parameterCookie")私有(private)字符串参数Cookie;

我在使用 Resteasy 注入(inject)该参数时遇到问题

错误

It is illegal to inject a @CookieParam into a singleton

这是一个 BaseResource,我无法修改所有资源以接受所有方法上的该参数(这会花费很多)。我如何在 Resteasy 中注入(inject) CookieParam 而不修改所有资源?

最佳答案

您可以通过注入(inject) HttpHeaders 来解决此问题:

import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.junit.Before;
import org.junit.Test;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

public class CookieTest {
static final String COOKIE_NAME = "parameterCookie";

Dispatcher dispatcher;

@Before
public void setUp() throws Exception {
dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(new Resource());
}

@Test
public void name_StateUnderTest_ExpectedBehavior() throws Exception {
String cookieValue = String.valueOf(System.currentTimeMillis());

MockHttpResponse response = new MockHttpResponse();
MockHttpRequest request = MockHttpRequest.get("/")
.cookie(COOKIE_NAME, cookieValue);

dispatcher.invoke(request, response);

assertThat(response.getContentAsString(), is(COOKIE_NAME + "=" + cookieValue));
}

@Path("/")
public static class Resource {
@Context HttpHeaders headers;

@GET @Path("/")
public String getCookie(){
return headers.getCookies().get(COOKIE_NAME).toString();
}
}
}

关于java - RESTEasy Singleton 中的 CookieParam,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18913797/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com