2015-10-19 94 views
1

我有一個Restlet + JAXRS擴展實現的REST服務。 在某個時候,我不得不將CORS頭添加到響應中。 我有很多REST調用,並手工添加標題,因爲這是工作:Restlet + JAXRS擴展 - 如何使用過濾器?

 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類。 任何人都可以幫助我?

回答

0

在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); 

否則JAX-RS過濾器不受的Restlet相應的擴展支持。要添加過濾器,你需要將其添加爲應用程序的前面的Restlet過濾器,如下所述:

JaxRsApplication application = new JaxRsApplication(comp.getContext()); 
application.add(new ExampleApplication()); 

MyRestletFilter filter = new MyRestletFilter(); 
filter.setNext(application); 

component.getDefaultHost().attachDefault(filter); 

希望它可以幫助你, 蒂埃裏

+0

我加了有關常規有關過濾器的說明JAX-RS擴展... –

+0

它完美地工作,謝謝。 – Muntaner