How to allow Cross Domain Ajax calls to an Application in Spring Boot Application

18 / Nov / 2015 by Ekansh Rastogi 0 comments

You can allow Cross Domain Ajax calls to an application by just registering a new filter and then configure it to Allow-Origin : {your domain’s} or you can use a wild card “*”  to allow the calls from all domains.

You can even Define the Custom Headers your application supports by defining them in a comma separated format , e.g Access-Control-Allow-Headers: “header-1,header-2,header3”

package com.ekiras.filter;

import org.springframework.stereotype.Component;

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

@Component
public class CorsFilter implements Filter {

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, X-Custom-Header");
        chain.doFilter(req, res);
    }

    public void init(FilterConfig filterConfig) {}

    public void destroy() {}

}

 

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *