1

I am creating a REST service using CXF 3.1.4 and JAX-RS. I have created an interface that is shared between client and server:

public interface SubscriptionsService {

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

public class SubscriptionResponse {
    private String location;
}

The client is created using JAXRSClientFactoryBean and the server is created using JAXRSServerFactoryBean.

The create() method defined above should return a Location header but I have no idea how to do it.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
bart
  • 2,378
  • 2
  • 19
  • 21

1 Answers1

2

Since you need to return a SubscriptionResponse object instead of a 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;
}

When returning a Response object, you can and use the Response API to add the Location header, as following:

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

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

For more details have a look at the Response.created(URI) method documentation.

Community
  • 1
  • 1
cassiomolin
  • 124,154
  • 35
  • 280
  • 359