Java Reference
In-Depth Information
@Provider
class AlertFilter implements ContainerRequestFilter,
ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext)
throws IOException {
alert(requestContext);
}
@Override
public void filter(ContainerRequestContext crc, ContainerResponseContext crc1) throws
IOException {
alert(crc);
}
public void alert(ContainerRequestContext context) {
try(InputStream in = context.getEntityStream();) {
if (in != null) {
InputStreamReader inreader = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(inreader);
String text = "";
while ((text = reader.readLine()) != null) {
System.out.println(text);
}
}
} catch (IOException ex) {
// Error handling
}
}
}
■
Both filter methods in the implementation are required because each accepts different parameters,
and implementing the
ContainerRequestFilter
and
ContainerResponseFilter
require it.
Note
Note that the
AlertFilter
class is decorated with the
@Provider
annotation. That is because all filters and
interceptors are provider classes and must be annotated as such. The filter must implement
ContainerRequestFilter
and
ContainerResponseFilter
since it is a server-side filter implementation. These two classes provide information
regarding the filter, such as URIs, headers, and so on.
Filters are grouped into chains, and each of the extension points contains their own filter chain. The filters in
the chain are executed in order of precedence via priority. To learn more about setting the priority, please refer to the
“Filter and Interceptor Priorities” section. If a request filter needs to be executed upon receiving a request but before
a resource is matched, then the
@PreMatching
annotation can be placed on that filter.