我最近遇到了这个问题并找到了这个解决方案。您可以使用过滤器添加这些标题:
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 {
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",
"X-Requested-With,Origin,Content-Type, Accept");
}
filterChain.doFilter(request, response);
}
}
不要忘记将过滤器添加到您的 spring 上下文中:
<bean id="corsFilter" class="my.package.CorsFilter" />
以及 web.xml 中的映射:
<filter>
<filter-name>corsFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
更进一步,您可以指定一个 Spring 配置文件来启用或禁用此过滤器,如下所示:
<beans profile="!cors">
<bean id="corsFilter" class="my.package.FilterChainDoFilter" />
</beans>
<beans profile="cors">
<bean id="corsFilter" class="my.package.CorsFilter" />
</beans>
(提供类似于 CorsFilter 但仅filterChain.doFilter(request, response);
在 doFilterInternal(..) 中执行的 FilterChainDoFilter)