Jersey ContainerRequestFilter not triggered

本小妞迷上赌 提交于 2019-11-27 07:46:06
koyaga

Okay, I didn't get that the jersey.config.server.provider.packages init param needs to reference not only service classes (API endpoints) but ALL the classes including filters.

Now it works :

<init-param>  
  <param-name>jersey.config.server.provider.packages</param-name>  
  <param-value>com.hck.debate.rest.controller;com.hck.debate.rest.security</param-value>
</init-param>
<init-param>
    <param-name>com.sun.jersey.spi.container.ContainerRequestFilters</param-name>
    <param-value>com.hck.debate.rest.security.AuthFilter</param-value>
</init-param>
uris

I also had to add the @Provider JAX-RS annotation to my filters.
This makes the filter discoverable during JAX-RS scanning phase.

@Provider
public class MyAppFilter implements ContainerRequestFilter {
    // filter logic
}

Some hints:

  1. Make sure you're using JAX-RS version 2.17.
  2. Make sure you're using the right imports in your filter:

    • import javax.ws.rs.container.ContainerRequestContext;
    • import javax.ws.rs.container.ContainerRequestFilter;
  3. Add the @Provider annotation

The minimum requirements to work filters with jersey:

  • add @Provider annotation to filter class
  • the namespace of filter class has to be included in 'jersey.config.server.provider.packages' init-param

Any other settings aren't required (e.g. 'com.sun.jersey.spi.container.ContainerRequestFilters' init-param or ResourceConfig)

virtuvious

I had the same problem for JAX-RS 2 , jersey and the below annotation fixed it

 @PreMatching
AshishKumar

We were missing the below call in our ResourceConfig implementation class:

register(CorrelationIdFilter.class);

Instead of using the @Provider annotation (which did not work in my case), you can register your ContainerRequestFilter manually with your JerseyServletFactory:

JerseyServletFactory jerseyServletFactory = new JerseyServletFactory(config);
HttpServlet myServiceServlet = jerseyServletFactory.create(myResource);

// Register your ContainerRequestFilter like this
jerseyServletFactory.addRequestFilter(new MyFilter());

httpServer.register(myServiceServlet, "/api");
httpServer.start();

Instead of javax.ws.rs, i used com.sun.jersey and it worked

import com.sun.jersey.spi.container.ContainerRequestFilter import com.sun.jersey.spi.container.ContainerRequest

Dropwizard users need to do this

environment.jersey().getResourceConfig()
           .getContainerRequestFilters()
           .add(filter);

If you were stuck like me, note that TomEE 1.7.X uses JAX-RS 1.1, which does not include ContainerRequestFilter.

For anybody having this problem in MULE ESB. Remember to register path with:

<jersey:resources doc:name="REST">
   <component doc:name="rest component">
     <spring-object bean="endpoit"/>
   </component>
   <jersey:package packageName="path @Provider-s"/>
</jersey:resources >
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!