Cross domain REST/Jersey web services with CORS

给你一囗甜甜゛ 提交于 2019-12-05 15:27:05

All the information for your server side configuration can be found at enable-cors.org.

There is no need to change any code clientside, but I would recommend checking the Browsers capability for CORS before using it. Testing code can be found, e.g., here.

I have chosen to solve this problem by providing the server CORS response at the Jersey container level. This might offer more convenience for some applications since it can apply for all responses from the container without modification to the resource handling code.

First one has to create a container response filter that will inject the appropriate header(s). For example for a container that indicates Access-Control-Allow-Origin:* for any response:

class CORSFilter implements ContainerResponseFilter {
    @Override
    public ContainerResponse filter(ContainerRequest request, ContainerResponse response) {
        response.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
        return response;
    }       
}

Then the filter must be added be added to the Jersey response filter chain. This can be done through the resource config in use for the application.

...
DefaultResourceConfig rc = new ClasspathResourceConfig();
rc.getContainerResponseFilters().add(new CORSFilter());

// now create a simple lightweight server using this resource config.
HttpServer server = HttpServerFactory.create(uri,rc);
...

Steps which I used to enable CORS Filter in my Jersey based embedded Jetty application.

jetty-servlet version - 2.12

  1. Added cors-filter dependency in pom
      <dependency>
       <groupId>com.thetransactioncompany</groupId>
       <artifactId>cors-filter</artifactId>
       <version>2.1.2</version>
      </dependency>
  1. Add the corsfilter to ServletContextHandler of your application.
 
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); 

context.addFilter(CORSFilter.class, "/*", EnumSet.of(DispatcherType.INCLUDE,DispatcherType.REQUEST)); 

server.setHandler(context);//set handle to your server
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!