简体   繁体   中英

Use Jersey2 ContainerRequestFilter with filter notation in web.xml

I am trying to add a Jersey2 ContainerRequestFilter to a webapp via web.xml. Currently I always use the notation with a servlet as described here :

<servlet>
    <servlet-name>MyApplication</servlet-name>
    <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
    <init-param>
        ...
    </init-param>
</servlet>
...
<servlet-mapping>
    <servlet-name>MyApplication</servlet-name>
    <url-pattern>/myApp/*</url-pattern>
</servlet-mapping>

Now in a different case, I dont have a servlet but a wicket app running on tomcat, that I want to use my filter with. So I tried to use the alternative filter notation, described in the same article as above (example 4.10):

    <filter>
        <filter-name>MyApplication</filter-name>
        <filter-class>org.glassfish.jersey.servlet.ServletContainer</filter-class>
        <init-param>
            ...
        </init-param>
    </filter>
    ...
    <filter-mapping>
        <filter-name>MyApplication</filter-name>
        <url-pattern>/myApp/*</url-pattern>
    </filter-mapping>

I successfully used it with the Jersey1 filter notation but am unable to make it work with the Jersey2 filter (this one is more up to date, so I prefer it over the older one).

Unfortunately I found the documenation of this feature being rather poor. Can anyone help if this might work and if so, how to do it?

As mentioned by @peeskillet in the comments, I had to add the @Provider annotation on top of the Filter for it to be picked up by the Jersey. Adding this answer for anyone who is trying to find the solution. The same can be done for the ContainerResponseFilter also.

import java.io.IOException;

import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;


@Provider
public class LoggingFilter implements ContainerRequestFilter,ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        //DO Stuff
    }

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
            throws IOException {
        //DO Stuff
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM