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:

Can only make ajax requests to:

For example:

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 {

    public void init(FilterConfig filterConfig) 
    throws ServletException {

    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");
            "Origin, X-Requested-With, Content-Type, Accept");

        if (request.getMethod().equals("OPTIONS")) {
        chain.doFilter(request, servletResponse);

    public void destroy() {


No comments: