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 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:

src/main/java/com/restfully/shop/services/ShoppingApplication.java ...

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