JAX-RS Building Responses

RESTful

JAX-RS Building Responses


1. ResponseBuilder

If it is necessary to return additional information in response to a HTTP request, Response and Response.ResponseBuilder are 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. An 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 demonstrate 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 returns 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();
}

  

Sources: Jersey Tutorial - Root Resource Classes.

See also How to build RESTful Web Services using Jersey



0 comments
Leave your comment: