Request filter not working in Jersey 2 on Embedded Jetty
-
21-12-2019 - |
Question
I'm unable to get my request filter triggered. I run jetty 9.1 as an embedded server.
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.ext.Provider;
@Provider
public class MyFilter implements ContainerRequestFilter {
@Override
public void filter(ContainerRequestContext arg0) throws IOException {
System.out.println("HEY HO");
}
}
I registered this class in the ResourceConfig, also tried to register the package. It's just ignored. Is it a bug, or am I missing something?
This is how I start Jetty:
Weld weld = new Weld();
WeldContainer container = weld.initialize();
URI baseUri = UriBuilder.fromUri("http://localhost/").port(8080).build();
ResourceConfig config = ResourceConfig.forApplicationClass(MyApplication.class);
Server server = JettyHttpContainerFactory.createServer(baseUri, config);
(MyApplication extends ResourceConfig and calls this.package(...)
and this.register(MyFilter.class)
in the constructor.
Solution
The problem is that the class that defines the REST endpoint cannot be instantiated because - in my case - the instantiation depends on stuff that must be set up in the request filter.
However, the endpoint class is instanciated before the filter is called. In order to run the filter first, it has to be annotated @PreMatching
.
@Provider
@PreMatching
public class MyFilter implements ContainerRequestFilter {
...
}
OTHER TIPS
To enable cross-origin requests in a self-contained Jetty jar file with Jersey REST services (to allow calls from Swagger-UI). Create a CORSResponseFilter class:
public class CORSResponseFilter implements ContainerResponseFilter {
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
MultivaluedMap headers = responseContext.getHeaders();
headers.add("Access-Control-Allow-Origin", "*");
//headers.add("Access-Control-Allow-Origin", "http://podcastpedia.org"); //allows CORS requests only coming from podcastpedia.org
headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
headers.add("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia");
}
}
And reference it in your main App class:
public class App {
public static void main(String[] args) throws Exception {
URI baseUri = UriBuilder.fromUri("http://localhost/").port(8080).build();
ResourceConfig config = new ResourceConfig(API.class);
config.register(CORSResponseFilter.class);
Server jettyServer = JettyHttpContainerFactory.createServer(baseUri, config);
try {
jettyServer.start();
jettyServer.join();
} finally {
jettyServer.destroy();
}
}
}
By the similar way we have to embed the filter with jetty and jersey. hope this will use full.