If the RESTful Service methods need to provide additional metadata with a response then we should return an instance of the javax. ws. rs. core. Response from the service methods. The Response. Response Builder class provides a convenient way to create a Response instance using a builder pattern.
The JAX-RS Response class allows a resource method to have control over the return status code sent to the consumer and to specify HTTP message headers, cache control directives and cookies in the response.
Entity providers supply mapping services between representations and their associated Java types. The two types of entity providers are MessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReader is used to map an HTTP request entity body to method parameters. On the response side, a return value is mapped to an HTTP response entity body by using a MessageBodyWriter. If the application needs to supply additional metadata, such as HTTP headers or a different status code, a method can return a Response that wraps the entity and that can be built by using Response.ResponseBuilder.
All of the standard types are supported automatically for HTTP request and response entity bodies. We need to write an entity provider only if you are not choosing one of those standard types.
Example
In this example, we are going to modify our last example to demonstrate how we can send different response codes. In our last example we created a service method OrderService#getInvalidOrderItemByItemId to capture the bad request but we were still sending default success code in the response. In this example, we are going to return response with status code 400 Bad Request.
Note we have also modified our test. This time we have to handle BadRequestException, which is expected in the second method call.
Example Project
Dependencies and Technologies Used:
jersey-core-server 2.22.1: Jersey core server implementation.
jersey-container-servlet 2.22.1: Jersey core Servlet 3.x implementation.
jersey-test-framework-provider-jdk-http 2.22.1: Jersey Test Framework - JDK HTTP container.