Spring MVC 从4.2版本开始增加了对CORS的支持,可以全局配置,也可以对类或方法配置;可以通过Java代码,也可以通过xml配置方式。
对于低版本的Spring MVC 可以通过Filter 往response写http header来实现
还有一种更省事的办法是在Nginx上加入支持。
Java配置
新建一个类,做跨域的配置
@Configuration
@EnableWebMvc
public class CorsConfigureAdapter extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
super.addCorsMappings(registry);
registry.addMapping("/**");
}
}
在Controller上或方法上使用@CrossOrigin注解
@CrossOrigin(maxAge = 3600)
@RestController
@RequestMapping("/account")
public class AccountController {
@CrossOrigin("http://domain2.com")
@RequestMapping("/{id}")
public Account retrieve(@PathVariable Long id) {
// ...
}
@RequestMapping(method = RequestMethod.DELETE, path = "/{id}")
public void remove(@PathVariable Long id) {
// ...
}
}
基于XML的配置
<mvc:cors>
<mvc:mapping path="/**" />
</mvc:cors>
这个配置和上面JAVA方式的第一种作用一样。
同样,你可以做更复杂的配置:
<mvc:cors>
<mvc:mapping path="/api/**" allowed-origins="http://domain1.com, http://domain2.com" allowed-methods="GET, PUT" allowed-headers="header1, header2, header3" exposed-headers="header1, header2" allow-credentials="false" max-age="123" />
<mvc:mapping path="/resources/**" allowed-origins="http://domain1.com" />
</mvc:cors>
SpringMVC 3 支持跨域
SpringMVC 3不支持以上方法,通过Filter的方式实现。
@Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}
web.xml
里配置
<filter>
<filter-name>cors</filter-name>
<filter-class>test.cors.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Nginx支持跨域请求
需要在配置里添加add_header Access-Control*
指令,如:
location /{
add_header 'Access-Control-Allow-Origin' 'http://other.subdomain.com';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' 'GET';
...
the rest of your configuration here
...
}