Jersey 2.3设置ContainerRequestFilter的优先级

时间:2014-11-18 08:20:27

标签: java jersey jax-rs web.xml jersey-2.0

public class MyApplication extends ResourceConfig {

    public MyApplication() {
       /* // Register resources and providers using package-scanning.
        packages("com.keylesson.service");

        // Register my custom provider - not needed if it's in my.package.
        register(TestFilter.class);
        register(TestFilter2.class);*/
    }
}

取消注释后的上面的代码能够执行两个过滤器类,但顺序是TestFilter2,然后是TestFilter。这个Resourceconfig方法我不太喜欢,我想为Jersey2.3使用旧式web.xml。过滤器的球衣1.x init-params在jersey2.3中不起作用。任何人都可以帮助我使用jersey2.3的示例web.xml来保证过滤器的执行吗?还有序列testfilter,然后是testfilter2?

1 个答案:

答案 0 :(得分:19)

您可以为过滤器配置优先级。几个选项

选项1:

使用@Priority作为过滤器类,传入一个值(例如@Priority(1))。数字越小,优先级越高(不需要web.xml或Application子类中的任何特殊内容)

@Priority(6000)
public class MyFilter1 ... {}

@Priority(6001)
public class MyFilter2 ... {}

请参阅Priorities

选项2:

通过可注入的Configurable以编程方式将其配置到应用程序中。像

这样的东西
@ApplicationPath("/")
public class MyApplication extends Application {
    public MyApplication(@Context Configurable configurable) {
        configurable.register(MyFilter1.class, 1000);
        configurable.register(MyFilter2.class, 1001);
    }
}

ResourceConfig只是在没有注入register的情况下调用Configurable。请参阅API以了解重载register

public ResourceConfig register(Object component, int bindingPriority)

e.g。

public class MyApplication extends ResourceConfig {
    public MyApplication() {
        ...
        register(TestFilter.class, 6000);
        register(TestFilter2.class, 6001);*/
    }
}

注意:

仅仅是一个FYI,有Priorites类的内置常量。

public final class Priorities {
    private Priorities() { }

    public static final int AUTHENTICATION = 1000;
    public static final int AUTHORIZATION = 2000;
    public static final int HEADER_DECORATOR = 3000;
    public static final int ENTITY_CODER = 4000;
    public static final int USER = 5000;
}

框架的某些内置组件使用它们,因此在给出优先级的数字时可能需要考虑这些。你可以使用这些

@Priority(Priorities.USER)
// or @Priority(Priorities.USER + 1)
public class MyFilter ... {}