CORS is a W3C effort (working draft status at the time of writing) to introduce a standard mechanism for enabling cross-domain requests in web browsers and participating servers (spec is here). I’ve blogged about this already, as it is pretty simple to add basic support for CORS to your HTTP Responses. As our entire stack here is based on Java, especially Java EE, I did a little web search for open source solutions for Java Web Applications… and found the CORS Filter by Vladimir Dzhuvinov.
While it is easy to add a few response headers to your HTTP responses, there are quite a few configuration options that you would have to implement for a configurable solution. Instead of re-inventing the wheel, I just integrated Vladimir’s excellent filter.
Installation is easy: download the zip (Maven artifact available, too), add the lib to your WEB-INF/lib folder and then add a filter and filter-mapping to your web.xml file:
<filter> <filter-name>CORS</filter-name> <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class> <init-param> <param-name>cors.supportedMethods</param-name> <param-value>GET, POST, HEAD, PUT, DELETE, OPTIONS</param-value> </init-param> </filter> <filter-mapping> <filter-name>CORS</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
For our RESTful eCommerce API we also use PUT requests, so I only had to change the default supported methods via the servlet initialization parameters to include PUT as well.
You might be wondering which browsers support CORS. The good news is that up to 87% as of July 2012 support CORS. The biggest trouble maker with this regard in the browser world in still IE, but when it comes to CORS, IE 10 will support CORS as well. Chrome, FireFox and Opera already have suppport for CORS since quite some time.