我知道我可以通過像這樣的過濾器添加Cors支持:https://spring.io/guides/gs/rest-service-cors/。Spring 4.1 MVC是否支持Cors?
該指南在創建時,我不知道和以後的版本是否帶有一個Cors內置的實現......
我知道我可以通過像這樣的過濾器添加Cors支持:https://spring.io/guides/gs/rest-service-cors/。Spring 4.1 MVC是否支持Cors?
該指南在創建時,我不知道和以後的版本是否帶有一個Cors內置的實現......
我不知道任何內置彈簧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設置後(有時失敗,沒有的話)
希望這有助於,好運氣
Spring框架4.1不僅具有內置的CORS支持SockJS和允許specify a list of allowed origins用於Websocket和SockJS。
一流的CORS支持從Spring Framework 4.2 GA開始提供。有關更多詳細信息,請參閱this blog post。
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>
爲我工作...非常感謝! – 2015-12-05 16:36:48
爲我工作,更喜歡Aalkhodiry的方式,但使用此。 – dzgeek 2017-07-02 14:51:28