Friday, September 28, 2012

Cross Origin Resource Sharing (CORS) for Java Web Applications

When we have to include web resource from different origins then CORS comes into picture.

CORS defines how browsers and servers communicate when accessing sources across origins using HTTP headers to allow both the browser and the server to know enough about each other to determine if the request or response should succeed or fail.

Consider we have a web app app1 and app2. If we have to include resource from app2 into app1 using ajax, then we have to implement CORS into app2 web application.

Because when we make an ajax call from app1 it will get converted to CORS request call by browser. so those request should be handled at app2.

To implement it we have to configure 1 filter into app2.
com.thetransactioncompany.cors.CORSFilter

To include above filter you have to download and copy jar cors-filter-1.3.2.jar into app2/webcontent/WEB-INF/lib.

download it from : http://software.dzhuvinov.com/cors-filter-configuration.html

then you have to configure filter into web.xml
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>

<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>x-requested-with</param-value>
</init-param>
</filter>

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

Example:

Consider you have 2 web application whose context roots are app1 and app2.

You have app1/page1.html and you want to insert the content from app2/page2.html to app1/page1.html.

app2/page2.html
<html>
<body>
app2 page2.html content here
</body>
</html>

app1/page1.html
<html>
<head>
<script type="text/javascript" src="./js/jquery-1.6.2.min.js"></script>

<script>
jQuery(document).ready(function(){
jQuery("#div1").load("/app2/page2.html");
});
</script>
</head>
<body>
<div1 id="div1">
</div1>
</body>
</html>

Above code will insert the content from app2/page2.html into div1 of app1/page1.html.

For java web application, make sure you have filter mapping for html as below for above example to work.
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>