2014-09-04 132 views

回答

3

我不知道任何內置彈簧CORS過濾器,但F.E. apache有一個實現它(我懷疑JBOSS,Glassfish ......沒有)。如果你使用Tomcat,把這個在你的web.xml:

<filter> 
    <filter-name>CorsFilter</filter-name> 
    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class> 
    <init-param> 
     <param-name>cors.allowed.origins</param-name> 
     <param-value>*</param-value> 
    </init-param> 
    <init-param> 
     <param-name>cors.allowed.methods</param-name> 
     <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value> 
    </init-param> 
    <init-param> 
     <param-name>cors.allowed.headers</param-name> 
     <param-value>Content-Type,Authorization, X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value> 
    </init-param> 
    <init-param> 
     <param-name>cors.exposed.headers</param-name> 
     <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value> 
    </init-param> 
    <init-param> 
     <param-name>cors.support.credentials</param-name> 
     <param-value>true</param-value> 
    </init-param> 
    <init-param> 
     <param-name>cors.preflight.maxage</param-name> 
     <param-value>10</param-value> 
    </init-param> 
</filter> 
<filter-mapping> 
    <filter-name>CorsFilter</filter-name> 
    <url-pattern>/*</url-pattern> 
</filter-mapping> 

把params爲您的喜好,不要忘了在客戶端啓用CORS爲好。 此外,如果你使用Spring Security,確保SS filterChain是CorsFilter設置後(有時失敗,沒有的話)

希望這有助於,好運氣

+0

爲我工作...非常感謝! – 2015-12-05 16:36:48

+0

爲我工作,更喜歡Aalkhodiry的方式,但使用此。 – dzgeek 2017-07-02 14:51:28

2

Create this class

public class CORSFilter extends OncePerRequestFilter { 

@Override 
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { 
    response.addHeader("Access-Control-Allow-Origin", "*"); 

    if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) { 
     // CORS "pre-flight" request 
     response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); 
    // response.addHeader("Access-Control-Allow-Headers", "Authorization"); 
     response.addHeader("Access-Control-Allow-Headers", "Content-Type"); 
     response.addHeader("Access-Control-Max-Age", "1"); 
    } 

    filterChain.doFilter(request, response); 
    } 
} 

這添加到您的web.xml

<!-- Add this to your web.xml to enable "CORS" --> 
<filter> 
    <filter-name>cors</filter-name> 
    <filter-class>tk.aalkhodiry.filters.CORSFilter</filter-class> 
</filter> 

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