我的休息服务中有以下方法:
@POST
@Path("/create")
@ResponseStatus(HttpStatus.CREATED)
@Consumes(MediaType.WILDCARD)
public String create( .... ) {.... return json;}
所以我想在身体和状态代码CREATED中获得json的回复。
问题是:我无法获得CREATED状态的响应。
状态代码总是正常,所以似乎“@ResponseStatus(HttpStatus.CREATED)”被忽略......
有人可以帮我吗?
我正在使用hibernate 4.1,spring 3.1和resteasy 2.3
答案 0 :(得分:14)
据我所知,用@org.springframework.web.bind.annotation.ResponseStatus
注释方法是不可能实现的。
您可以从方法中返回javax.ws.rs.core.Response
:
return Response
.status(Response.Status.CREATED)
.entity("ok")
.build();
或者您可以注入org.jboss.resteasy.spi.HttpResponse
,并直接设置状态代码。
可能有更多方法可以做到这一点,但我只知道这两个。
工作测试用例:
import org.jboss.resteasy.core.Dispatcher;
import org.jboss.resteasy.core.ServerResponse;
import org.jboss.resteasy.mock.MockDispatcherFactory;
import org.jboss.resteasy.mock.MockHttpRequest;
import org.jboss.resteasy.mock.MockHttpResponse;
import org.jboss.resteasy.spi.HttpResponse;
import org.jboss.resteasy.spi.NotFoundException;
import org.jboss.resteasy.spi.interception.PostProcessInterceptor;
import org.junit.Assert;
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.Response;
public class ResponseTest {
@Path("/")
public static class Service {
@Context HttpResponse response;
@GET
@Path("/1")
public Response createdUsingResponse() throws NotFoundException {
return Response
.status(Response.Status.CREATED)
.entity("ok")
.build();
}
@GET
@Path("/2")
public String created() throws NotFoundException {
response.setStatus(Response.Status.CREATED.getStatusCode());
return "ok";
}
}
public static class Interceptor implements PostProcessInterceptor {
@Context HttpResponse response;
@Override
public void postProcess(ServerResponse response) {
if(this.response.getStatus() != 0){
response.setStatus(this.response.getStatus());
}
}
}
@Test
public void test() throws Exception {
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(new Service());
dispatcher
.getProviderFactory()
.getServerPostProcessInterceptorRegistry()
.register(new Interceptor());
{
MockHttpRequest request = MockHttpRequest.get("/1");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
Assert.assertEquals(201, response.getStatus());
}
{
MockHttpRequest request = MockHttpRequest.get("/2");
MockHttpResponse response = new MockHttpResponse();
dispatcher.invoke(request, response);
Assert.assertEquals(201, response.getStatus());
}
}
}