Java Reference
In-Depth Information
To illustrate how you'd use
DynamicFeature
, let's expand on the
CacheControlFilter
re-
sponse filter we wrote earlier in this chapter. The previous incarnation of this class would set
the same
Cache-Control
header value for each and every HTTP request. Let's modify this
filter and create a custom annotation called
@MaxAge
that will allow you to set the
max-age
of the
Cache-Control
header per JAX-RS method:
package
package
com
.
commerce
.
MaxAge
;
@Target
(
ElementType
.
METHOD
)
@Retention
(
RetentionPolicy
.
RUNTIME
)
public
public
@interface
MaxAge
{
int
int
value
();
}
The modification of the filter looks like this:
import
import
javax.ws.rs.container.ContainerResponseFilter
javax.ws.rs.container.ContainerResponseFilter
;
import
import
javax.ws.rs.container.ContainerRequestContext
javax.ws.rs.container.ContainerRequestContext
;
import
import
javax.ws.rs.container.ContainerResponseContext
javax.ws.rs.container.ContainerResponseContext
;
import
import
javax.ws.rs.core.CacheControl
javax.ws.rs.core.CacheControl
;
public
public class
class
CacheControlFilter
CacheControlFilter
implements
implements
ContainerResponseFilter
{
private
private
int
int
maxAge
;
public
public
CacheControlFilter
(
int
int
maxAge
) {
this
this
.
maxAge
=
maxAge
;
}
public
public
void
void
filter
(
ContainerRequestContext req
,
ContainerResponseContext res
)
throws
throws
IOException
{
iif
(
req
.
getMethod
().
equals
(
"GET"
)) {
CacheControl cc
=
new
new
CacheControl
();
cc
.
setMaxAge
(
this
this
.
maxAge
);
res
.
getHeaders
().
add
(
"Cache-Control"
,
cc
);
}
}
}
The
CacheControlFilter
has a new constructor that has a max age parameter. We'll use
this max age to set the
Cache-Control
header on the response. Notice that we do not annot-
ate
CacheControlFilter
with
@Provider
. Removing
@Provider
will prevent this filter
from being picked up on a scan when we deploy our JAX-RS application. Our
Dynam-
icFeature
implementation is going to be responsible for creating and registering this filter: