Allow cross domain java (CORS Filter)

Posted: September 30, 2013 in web

to allow cross doamin on clients using ajax just to the ff:

on your web.xml add these:

....
    <filter>
        <filter-name>CORS</filter-name>
        <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
        <init-param>
            <param-name>cors.supportedHeaders</param-name>
            <param-value>Origin, Accept, Content-Type,
                X-Requested-With</param-value>
        </init-param>		
    </filter>
    <filter-mapping>
        <!-- CORS Filter mapping -->
        <filter-name>CORS</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping> 
...

then add a dependency from com.thetransactioncompany : cors-filter

on my case it was cors-filter-1.7.1.jar

client:

var xhr = $.ajax({
            type: "POST",
            url: "http://someserver:8080/services/account/test3",
            data: JSON.stringify({"nNumber":"2344"}),
            contentType: "application/json; charset=utf-8",
            dataType: "json",            
            beforeSend: function() {
                $.mobile.loading('show');
            },
            complete: function() {
                $.mobile.loading('hide');
            },
            success: function(data) {
                $.mobile.loading('hide');
                console.log(data);
            },
            error: function(d, msg) {
                xhr.abort();
            }
        });

That’s it.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s