Intercept JAX-RS Request: Register a ContainerRequestFilter with tomcat
java, jax-rs, rest, tomcat, web-services
Solution
You're using JAX-RS 2.0 APIs (request filters, name binding, ...) in your classes but Jersey 1 proprietary init params in your `web.xml` (package starting with `com.sun.jersey`, Jersey 2 uses `org.glassfish.jersey`). Take a look at this answer and at these articles:
- Registering Resources and Providers in Jersey 2
- Binding JAX-RS Providers to Resource Methods
Problem
I am trying to intercept a request to my JAX-RS webservice by a ContainerRequestFilter. I want to use it with a custom annotation, so I can decorate certain methods of the webservice. This should enable me to handle requests to this methods based on the information whether they are made on a secure channel or not, before the actual method is executed. I tried different approaches, searched several posts and then implemented mostly based on the answer by Alden in this post. But I can't get it working. I have a method test in my webservice decorated with my custom annotation Ssl. ``` @POST @Path("/test") @Ssl public static Response test(){ System.out.println("TEST ..."); } ``` The annotation looks like this: ``` @NameBinding @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) public @interface Ssl {} ``` Then I setup a filter implementation ``` import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; import javax.ws.rs.ext.Provider; @Ssl @Provider public class SslInterceptor implements ContainerRequestFilter { @Override public void filter(ContainerRequestContext requestContext) throws IOException { System.out.println("Filter executed."); } } ``` But the filter is never executed nor there occur any error messages or warnings. The test method runs fine anyway. To resolve it, I tried to register the filter in the web.xml as described here. ``` <servlet> <servlet-name>Jersey Web Application</servlet-name> <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class> <init-param> <param-name>com.sun.jersey.config.property.resourceConfigClass</param-name> <param-value>com.sun.jersey.api.core.PackagesResourceConfig</param-value> </init-param> <init-param> <param-name>com.sun.jersey.config.property.packages</param-name> <param-value>com.my.packagewithfilter</param-value> </init-param> <init-param> <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name> <param-value>com.my.packagewithfilter.SslInterceptor</param-value> </init-param> <init-param> <param-name>jersey.config.server.provider.packages</param-name> <param-value>com.my.packagewithfilter</param-value> </init-param> </servlet> ``` But that also doesn't work. What am I missing? Any ideas how to make that filter work? Any help is really appreciated!