You are previewing RESTful Java with JAX-RS.

RESTful Java with JAX-RS

Cover of RESTful Java with JAX-RS by Bill Burke Published by O'Reilly Media, Inc.
O'Reilly logo

Complex Responses

Sometimes the web service you are writing can’t be implemented using the default request/response behavior inherent in JAX-RS. For the cases in which you need to explicitly control the response sent back to the client, your JAX-RS resource methods can return instances of javax.ws.rs.core.Response:

public abstract class Response {

   public abstract Object getEntity();
   public abstract int getStatus();
   public abstract MultivaluedMap<String, Object> getMetadata();
...
}

The Response class is an abstract class that contains three simple methods. The getEntity() method returns the Java object you want converted into an HTTP message body. The getStatus() method returns the HTTP response code. The getMetadata() method is a MultivaluedMap of response headers.

Response objects cannot be created directly; instead, they are created from javax.ws.rs.core.Response.ResponseBuilder instances returned by one of the static helper methods of Response:

public abstract class Response { ... public static ResponseBuilder status(Status status) {...} public static ResponseBuilder status(int status) {...} public static ResponseBuilder ok() {...} public static ResponseBuilder ok(Object entity) {...} public static ResponseBuilder ok(Object entity, MediaType type) {...} public static ResponseBuilder ok(Object entity, String type) {...} public static ResponseBuilder ok(Object entity, Variant var) {...} public static ResponseBuilder serverError() {...} public static ResponseBuilder created(URI location) ...

The best content for your career. Discover unlimited learning on demand for around $1/day.