springboot跨域支持可使用两种方式:一种是xml配置,另一种是使用java文件配置。
一、使用xml配置文件
1. 创建xml配置文件
创建一个spring-mvc.xml文件,将其放入maven项目的resources目录下。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:annotation-driven />
<mvc:cors>
<mvc:mapping path="/customers"
allowed-origins="http://localhost:8484, http://localhost:9000"
allowed-methods="POST, GET, PUT, DELETE"
allowed-headers="Content-Type"
exposed-headers="header-1, header-2"
allow-credentials="false"
max-age="6000" />
</mvc:cors>
</beans>
2. 在Application上导入配置文件
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ImportResource;
@SpringBootApplication
@ImportResource("classpath:spring-mvc.xml")
public class SpringBootCorsXmlConfigApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootCorsXmlConfigApplication.class, args);
}
}
二、使用java配置
全局跨域java配置类
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
//base package
@ComponentScan("com.springboot.corsjavaconfig")
public class AppConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/customers")
.allowedOrigins("http://localhost:8484", "http://localhost:9000")
.allowedMethods("POST", "GET", "PUT", "DELETE")
.allowedHeaders("Content-Type")
.exposedHeaders("header-1", "header-2")
.allowCredentials(false)
.maxAge(6000);
}
}
对于Spring Boot 2.x则改为实现WebMvcConfigure
/**
* 添加跨域配置
*
* @author yu 2019/4/12.
*/
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedHeaders("*")
.allowCredentials(true)
.allowedMethods("POST", "GET", "PUT", "DELETE","OPTIONS");
}
}