Java Reference
In-Depth Information
import
import
javax.ws.rs.core.CacheControl
javax.ws.rs.core.CacheControl
;
@MaxAge
@Provider
public
public class
class
CacheControlFilter
CacheControlFilter
implements
implements
ContainerResponseFilter
{
@Context
ResourceInfo info
;
public
public
void
void
filter
(
ContainerRequestContext req
,
ContainerResponseContext res
)
throws
throws
IOException
{
iif
(
req
.
getMethod
().
equals
(
"GET"
)) {
MaxAge max
=
info
.
getMethod
().
getAnnotation
(
MaxAge
.
class
);
CacheControl cc
=
new
new
CacheControl
();
cc
.
setMaxAge
(
max
.
value
());
req
.
getHeaders
().
add
(
"Cache-Control"
,
cc
);
}
}
}
If we bound
CacheControlFilter
via a name binding, the filter class would have to inject
ResourceInfo
, then look up the
@MaxAge
annotation of the JAX-RS method so it could de-
termine the actual max age value to apply to the
Cache-Control
header. This is less efficient
at runtime than our
DynamicFeature
implementation. Sure, in this case the overhead prob-
ably will not be noticeable, but if you have more complex initialization scenarios the over-
head is bound to become a problem.
Exception Processing
So what happens if a filter or interceptor throws an exception? On the server side, the JAX-
RS runtime will process exceptions in the same way as if an exception were thrown in a
JAX-RS method. It will try to find an
ExceptionMapper
for the exception and then run it. If
an exception is thrown by a
ContainerRequestFilter
or
ReaderInterceptor
and mapped
by an
ExceptionMapper
, then any bound
ContainerResponseFilter
must be invoked. The
JAX-RS runtime ensures that at most one
ExceptionMapper
will be invoked in a single re-
quest processing cycle. This avoids infinite loops.
On the client side, if the exception thrown is an instance of
WebApplicationException
,
then the runtime will propagate it back to application code. Otherwise, the exception is
wrapped in a
javax.ws.rs.client.ProcessingException
if it is thrown before the re-
quest goes over the wire. The exception is wrapped in a
javax.ws.rs.client.ResponseProcessingException
when processing a response.