【问题标题】:Restlet + JAXRS extension - how to use filters?Restlet + JAXRS 扩展 - 如何使用过滤器?
【发布时间】:2016-01-17 16:54:07
【问题描述】:

我在 Restlet + JAXRS 扩展中实现了一个 REST 服务。 在某个时候,我不得不将 CORS 标头添加到响应中。 我有很多 REST 调用,并在此过程中手动添加标题:

        return Response.status(200).header("Access-Control-Allow-Origin", "*").
                header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type").
                header("Access-Control-Expose-Headers", "Location, Content-Disposition").
                header("Access-Control-Allow-Methods", "POST, PUT, GET, DELETE, HEAD, OPTIONS").
                entity(fsJSON).build();

但我想使用过滤器将这些标题添加到所有响应中,而无需手动添加。我发现了很多在 JAX-RS 中使用过滤器的例子,比如:

https://jersey.java.net/documentation/latest/filters-and-interceptors.html

http://javatech-blog.blogspot.it/2015/04/jax-rs-filters-example.html

http://blog.dejavu.sk/2014/02/04/filtering-jax-rs-entities-with-standard-security-annotations/

但我不明白如何将它们与 Restlet + JAX-RS 环境集成。例如,我在任何地方都看不到 ContainerResponseFilter 类。 谁能帮帮我?

【问题讨论】:

    标签: web-services rest jersey cors restlet


    【解决方案1】:

    在 Restlet 中创建 JaxRS 应用程序时,您会创建一个 JaxRsApplication(请参阅此链接:http://restlet.com/technical-resources/restlet-framework/guide/2.2/extensions/jaxrs)。此类扩展了 Restlet 的标准应用程序。后者提供了使用getServices 方法在其上配置服务的方法。

    所以在你的情况下,你不需要使用过滤器......

    关于Restlet的CorsService的配置请看这个答案:How to use CORS in Restlet 2.3.1?

    这是在 Restlet JaxRS 应用程序中配置 CORS 的一种方法:

    Component comp = new Component();
    Server server = comp.getServers().add(Protocol.HTTP, 8182);
    
    JaxRsApplication application = new JaxRsApplication(comp.getContext());
    application.add(new ExampleApplication());
    
    CorsService corsService = new CorsService();         
    corsService.setAllowedOrigins(new HashSet(Arrays.asList("*")));
    corsService.setAllowedCredentials(true);
    
    application.getServices().add(corsService);
    component.getDefaultHost().attachDefault(application);
    

    否则,Restlet 的相应扩展不支持 JAX-RS 过滤器。要添加过滤器,您需要将其作为 Restlet 过滤器添加到应用程序前面,如下所述:

    JaxRsApplication application = new JaxRsApplication(comp.getContext());
    application.add(new ExampleApplication());
    
    MyRestletFilter filter = new MyRestletFilter();
    filter.setNext(application);
    
    component.getDefaultHost().attachDefault(filter);
    

    希望对你有帮助 蒂埃里

    【讨论】:

    • 我添加了关于 JAX-RS 扩展的一般过滤器的解释...
    猜你喜欢
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-16
    • 1970-01-01
    相关资源
    最近更新 更多