The client side filters are similar to server side filters. They can use @Priority . They cannot use name binding and scanning/discovering related annotations such as @Provider. A client filter can also abort the request processing by using ClientRequestContext#abortWith() method.
Like other providers, we have to register filter manually on the client side.
To write a client side filter, we need to implement ClientRequestFilter and/or ClientResponseFilter, they are individually used for request and response respectively.
Let's see an example how to use filters on the client side.
Example
A JAX-RS resource
@Path("/")
public class MyResource {
@GET
@Path("{path:.*}")
public String getResponse(@PathParam("path") String path) {
return "dummy-response for " + path;
}
}
To try examples, run embedded tomcat (configured in pom.xml of example project below):
mvn tomcat7:run-war
Implementing client side Filter
public class LogFilter implements ClientRequestFilter, ClientResponseFilter {
@Override
public void filter(ClientRequestContext reqContext) throws IOException {
System.out.println("-- Client request info --");
log(reqContext.getUri(), reqContext.getHeaders());
}
@Override
public void filter(ClientRequestContext reqContext,
ClientResponseContext resContext) throws IOException {
System.out.println("-- Client response info --");
log(reqContext.getUri(), resContext.getHeaders());
}
private void log(URI uri, MultivaluedMap<String, ?> headers) {
System.out.println("Request URI: " + uri.getPath());
System.out.println("Headers:");
headers.entrySet().forEach(h -> System.out.println(h.getKey() + ": " + h.getValue()));
}
}
Registering Filter and making request
public class MyClient {
public static void main(String[] args) {
Client client = ClientBuilder.newBuilder()
.register(new LogFilter())
.build();
WebTarget allOrderTarget =
client.target("http://localhost:8080/test");
String s = allOrderTarget.request().get(String.class);
System.out.println("response: " + s);
}
} Output-- Client request info -- Request URI: /test Headers: -- Client response info -- Request URI: /test Headers: Server: [Apache-Coyote/1.1] Content-Length: [23] Date: [Fri, 21 Jul 2017 17:04:18 GMT] Content-Type: [text/html] response: dummy-response for test
The above output is on the client side.
Example ProjectDependencies and Technologies Used: - jersey-server 2.25.1: Jersey core server implementation.
- jersey-container-servlet 2.25.1: Jersey core Servlet 3.x implementation.
- JDK 1.8
- Maven 3.3.9
|