在 JAX-RS 中不返回响应 object 时将 headers 添加到 HTTP 响应

Adding headers to HTTP response when not returning a Response object in JAX-RS

我正在使用 CXF 3.1.4 和 JAX-RS 创建 REST 服务。我创建了一个在客户端和服务器之间共享的接口:

public interface SubscriptionsService {

    @POST
    @Path("/subscriptions")
    SubscriptionResponse create(SubscriptionRequest request);
}

public class SubscriptionResponse {
    private String location;
}

客户端是使用 JAXRSClientFactoryBean 创建的,服务器是使用 JAXRSServerFactoryBean 创建的。

上面定义的 create() 方法应该 return 一个 Location header 但我不知道该怎么做。

因为你需要 return SubscriptionResponse object 而不是 Response object, you can inject the HttpServletResponse in your JAX-RS enpoint class using the Context annotation and set the 201 status code and the Location header:

@Context 
HttpServletResponse response;

@POST
@Path("/subscriptions")
public SubscriptionResponse create(SubscriptionRequest subscriptionRequest) {
    
    // Persist your subscripion to database

    SubscriptionResponse subscriptionResponse = ...
    URI createdUri = ...
    
    // Set HTTP code to "201 Created" and set the Location header
    response.setStatus(HttpServletResponse.SC_CREATED);
    response.setHeader("Location", createdUri.toString());
     
    return subscriptionResponse;
}

当returning一个Response object, you can and use the Response API to add the Locationheader时,如下:

@POST
@Path("/subscriptions")
public Response create(SubscriptionRequest subscriptionRequest) {

    // Persist your subscripion to database
    
    URI createdUri = ...
    return Response.created(createdUri).build();
}

有关详细信息,请查看 Response.created(URI) 方法文档。