Chapter 26. Examples for Chapter 12

In Chapter 12, you learned how filters and interceptors can be used to augment your JAX-RS service classes. In this chapter, we through how to build and run some of the examples shown in that chapter. Specifically, we’ll go write a ContainerResponseFilter, a DynamicFeature, and an implementation of a WriterInterceptor. If you want to see examples of a ClientRequestFilter and a ContainerRequestFilter bound via a @NameBinding, check out Chapter 29.

Example ex12_1 : ContainerResponseFilter and DynamicFeature

ex12_1 implements the @MaxAge and CacheControlFilter example in the section DynamicFeature.

The Server Code

The @MaxAge, CacheControlFilter, and MaxAgeFeature classes were explained pretty well in DynamicFeature, so I’m not going to go into them again here. We applied the @MaxAge annotation to the CustomerResource.getCustomer() method:

src/main/java/com/restfully/shop/services/CustomerResource

   @GET
   @Path("{id}")
   @Produces("application/xml")
   @MaxAge(500)
   public Customer getCustomer(@PathParam("id") int id)
   {
      Customer customer = customerDB.get(id);
      if (customer == null)
      {
         throw new WebApplicationException(Response.Status.NOT_FOUND);
      }
      return customer;
   }

Applying this annotation to this method will cause the CacheControlFilter to be bound to this method when it is executed. The filter will cause a Cache-Control header to be added to the HTTP response with a max age of 500 seconds. Let’s also take a look at how these classes are registered:

Get RESTful Java with JAX-RS 2.0, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.