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)publicCustomergetCustomer(@PathParam("id")intid){Customercustomer=customerDB.get(id);if(customer==null){thrownewWebApplicationException(Response.Status.NOT_FOUND);}returncustomer;}
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access