Thursday, November 6, 2014

Enabling CORS with Jersey

CORS is a framework for allowing a webpage from one site to call e.g. REST services on site.

In Java, there are open source frameworks that provides filters to support this easily e.g. http://software.dzhuvinov.com/cors-filter.html

However, for Jersey, it is actually very simple and these Servlet Filter based frameworks can be too overcomplicated / heavyweight for the need.

To enable CORS in Jersey is just a matter of implementing and registering a ContainerResponseFilter with the following:


public class SimpleCorsResponseFilter implements ContainerResponseFilter {
   @Override
   public ContainerResponse filter(ContainerRequest req, ContainerResponse resp) {
       MultivaluedMap<String, Object> headers = resp.getHttpHeaders();
       headers.add("Access-Control-Allow-Origin", "*");
       headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
       headers.add("Access-Control-Allow-Headers", "Content-Type");
       return resp;
   }
}

To register this with Jersey, add the following Servlet init-params in the web.xml


<init-param>
   <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
   <param-value>xxx.yyy.zzz.SimpleCorsResponseFilter</param-value>
</init-param>

Note: code was written for Jersey version 1.17

References:

No comments:

Post a Comment