JAX-RS Building Responses Photo

JAX-RS Building Responses

1. ResponseBuilder

If it is necessary to return additional information in response to an HTTP request, Response, and Response.ResponseBuilder is used.  

Example 1.1. Returning Location header and 201 status code in response

The method post() creates a new resource and returns a 201 (Created) status code and a Location header whose value is the URI to the newly created resource.

@POST
public Response post(String content) {
    URI createdUri = ...;
    String createdContent = ...;
    Response.ResponseBuilder responseBuilder = Response.created(createdUri);
    return responseBuilder.entity(createdContent).build();
}

2. Conditional GETs Responses

JAX-RS supports conditional GET with the Request interface. The methods of Request gives the possibility to evaluate whether the current state of the resource matches any preconditions in the request. A Request instance can be injected into a class field or method parameter using the @Context annotation.

Example 2.1. Conditional GET support

The update() method of the example demonstrates how to get an ETag and call the request.evaluatePreconditions with that ETag. If a client request has an If-None-Match header with a value that contains the same ETag that was calculated then the evaluatePreconditions returns a pre-filled out response, with the 304 status code and ETag set, that may be built and returned. Otherwise, evaluatePreconditions return null, and the normal response can be returned.

@PUT
public Response update(@Context Request request) {
    EntityTag tag = getCurrentTag();
    Response.ResponseBuilder responseBuilder = request.evaluatePreconditions(tag);
    if (responseBuilder != null)
        return responseBuilder.build();
    else
        return doUpdate();
}
Read also:
Trustpilot
Trustpilot
Comments