Thursday, September 01, 2016

Enable Cross Domain Requests on Java Web App

By default, a web page can only make AJAX requests to the same domain that the web page came from.

In other words, JavaScript in:

http://www.smart-soft.com/index.html

Can only make ajax requests to:

http://www.smart-soft.com

For example:

http://www.smart-soft.com/rest-api/products.json

If you would like to make your HTTP service callable from other domains you can achieve this by using the following servlet filter:

public class CorsFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) 
    throws ServletException {
    }

    @Override
    public void doFilter(
       ServletRequest servletRequest,     
       ServletResponse servletResponse, 
       FilterChain chain) 
       throws IOException, ServletException {
           HttpServletRequest request = 
             (HttpServletRequest) servletRequest;

        HttpServletResponse resp = 
            (HttpServletResponse) servletResponse;
        resp.addHeader("Access-Control-Allow-Origin", "*");
        resp.addHeader("Access-Control-Allow-Methods", "GET,POST");
        resp.addHeader("Access-Control-Allow-Headers", 
            "Origin, X-Requested-With, Content-Type, Accept");

        if (request.getMethod().equals("OPTIONS")) {
            resp.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        chain.doFilter(request, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

No comments: