/java/

Spring MVC, Angularjs, not allowed by Access-Control-Allow-Origin.

2013-03-12 23:07:19

If You have this error: XMLHttpRequest cannot load http://localhost:8080/xxxxxx. Origin http://localhost is not allowed by Access-Control-Allow-Origin.

You must add this filter:

web.xml


<filter>
<filter-name>cors</filter-name>
<filter-class>com.louis.core.filter.CorsFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

CorsFilter.java

package com.louis.core.filter;

import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;


public class CorsFilter extends OncePerRequestFilter {

 @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        //if (request.getHeader("Access-Control-Request-Method") != null &amp;&amp; "OPTIONS".equals(request.getMethod())) 
        {
            // CORS "pre-flight" request
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.addHeader("Access-Control-Allow-Headers", "Content-Type, X-Requested-With");

            response.addHeader("Access-Control-Max-Age", "1800");//30 min
        }
        filterChain.doFilter(request, response);
    }
}