O'Reilly logo

RESTful Java with JAX-RS 2.0, 2nd Edition by Bill Burke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 7. Server Responses and Exception Handling

So far, the examples given in this book have been very clean and tidy. The JAX-RS resource methods we have written have looked like regular vanilla Java methods with JAX-RS annotations. We haven’t talked a lot about the default behavior of JAX-RS resource methods, particularly around HTTP response codes in success and failure scenarios. Also, in the real world, you can’t always have things so neat and clean. Many times you need to send specific response headers to deal with complex error conditions. This chapter first discusses the default response codes that vanilla JAX-RS resource methods give. It then walks you through writing complex responses using JAX-RS APIs. Finally, it goes over how exceptions can be handled within JAX-RS.

Default Response Codes

The default response codes that JAX-RS uses are pretty straightforward. There is pretty much a one-to-one relationship to the behavior described in the HTTP 1.1 Method Definition specification.[7].] Let’s examine what the response codes would be for both success and error conditions for the following JAX-RS resource class:

@Path("/customers")
public class CustomerResource {

   @Path("{id}")
   @GET
   @Produces("application/xml")
   public Customer getCustomer(@PathParam("id") int id) {...}

   @POST
   @Produces("application/xml")
   @Consumes("application/xml")
   public Customer create(Customer newCust) {...}

   @PUT
   @Path("{id}")
   @Consumes("application/xml")
   public void update(@PathParam("id") int id, Customer ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required