CORS filter for Java applications

方健發表於2014-11-07

http://padcom13.blogspot.com/2011/09/cors-filter-for-java-applications.html
http://stackoverflow.com/questions/5027705/error-in-chrome-content-type-is-not-allowed-by-access-control-allow-headers
Hi there, in today's installment we're going to allow Ajax calls from other domains to be answered and accepted by browsers.

The what This thing (completely forgotten by many) is called Cross Origin Resource Sharing and works with standard Ajax requests your browser can send. You can read about it in depth on Wikipedia or on the http://enable-cors.org/ site.

The how Let's get to the meat - shall we? On the http://enable-cors.org/ site there are many recipes for all kind of servers and they respective configuration but what if you'd like to enable CORS just for a part of your application? If you're lucky enough and you're coding your application in Java then there is a standard mechanism to do just that! It's called filters. Here's the most simple way of implementing CORS response headers:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CORSFilter implements Filter {

    public CORSFilter() { }

    public void init(FilterConfig fConfig) throws ServletException { }

    public void destroy() {    }

    public void doFilter(
        ServletRequest request, ServletResponse response, 
        FilterChain chain) throws IOException, ServletException {

        ((HttpServletResponse)response).addHeader(
            "Access-Control-Allow-Origin", "*"
        );
        ((HttpServletResponse)response).addHeader(
            "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"
        );
        chain.doFilter(request, response);
    }
}

As you can see here all we're doing is adding the Access-Control-Allow-Origin header so that the browser can accept the response sent by server.

You can use this filter as follows in your web.xml:

<web-app>
    <filter>
        <filter-name>CORSFilter</filter-name>
        <filter-class>CORSFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CORSFilter</filter-name>
        <url-pattern>/api/*</url-pattern>
    </filter-mapping>
</web-app>

Have fun!

Posted by Matthias Hryniszak at 6:55 PM
Labels: cors, java

相關文章