Pages

Thursday, February 21, 2013

Enable CORS in a Spring MVC REST API for ExtJS

Let's say you want to run your ExtJS application on example.com, but run your REST API at example-api.com . Normally, you cannot do this without resorting to JSONP (GETs only), or a server proxy, due to security restrictions. However, it can be done safely using CORS, which modern browsers support.

I've been using Java Spring Roo for creating my REST API. Unfortunately, it does not support CORS out of the box. Here's how to set it up.

In your maven pom.xml file, inside dependencies, add:


        <dependency>
            <groupId>com.thetransactioncompany</groupId>
            <artifactId>cors-filter</artifactId>
            <version>1.3.2</version>
        </dependency>


Open src/main/webapp/WEB-INF/web.xml and add:


    <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, HEAD, POST, PUT, DELETE, OPTIONS</param-value>
</init-param>

<init-param>
   <param-name>cors.supportedHeaders</param-name>
   <param-value>Content-Type, X-Requested-With, Origin, Accept</param-value>
</init-param>

    </filter>

    <filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
    </filter-mapping>

Your ExtJS REST proxy should now work!