springboot跨域支持可以使用兩種方式:一種是xml配置,另外一種是使用java文件配置。java
建立一個spring-mvc.xml文件,將其放入maven項目的resources目錄下。web
<?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上導入配置文件spring
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); } }
2、使用java配置跨域
全局跨域java配置類spring-mvc
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
springboot
/** * 添加跨域配置 * * @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"); } }