Cross domain REST/Jersey web services with CORS

2019-05-04 02:23发布

问题:

I want to make Cross domain REST web services with CORS(Cross-Origin Resource Sharing). I am using Jersey Libraries for making services.

I need to know

  1. What code/configuration changes i need to do from server side perspective?

  2. How to invoke this services from HTML5/js.

Thanks

回答1:

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.



回答2:

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


回答3:

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