Response filter
If I understand what you need, it could be achieved with a filter.
Filters can be used to modify any request or response parameters like headers.
The following filter, which implements the ContainerResponseFilter
interface, will add the X-XSS-Protection
header to the HTTP response:
@Provider
public class XssResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext,
ContainerResponseContext responseContext) throws IOException {
responseContext.getHeaders().add("X-XSS-Protection", "1; mode=block");
}
}
Please note the above filter is global, that is, it will be executed for all resource methods.
Name binding
To execute the filter for only some hand-picked resources methods, you can used name binding.
Name binding is a concept that allows to say to a JAX-RS runtime that a specific filter will be executed only for a specific resource method. When a filter or an interceptor is limited only to a specific resource method we say that it is name-bound.
Filters can be assigned to a resource method using the @NameBinding
annotation. The annotation is used as meta annotation for other user implemented annotations that are applied to a providers and resource methods.
A name binding annotation can be defined as following (the name of the annotation is up to you):
@NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface XssProtection { }
Place the above defined annotation on your filter class:
@Provider
@XssProtection
public class XssResponseFilter implements ContainerResponseFilter {
...
}
To assign the filter to a resource method, place the above defined annotation on the resource method:
@GET
@XssProtection
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod() {
...
}
Name binding can be applied on resource classes as well. It means the filter will be executed for all resource methods of that resource class:
@Path("/foo")
@XssProtection
public class MyResource() {
...
}
Note that global filters are always executed, so even for resource methods which have any name binding annotations.
Additional resources
For more details on filters, have a look at Jersey documentation.