Springboot CORS

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");

    }
}

转载于:https://my.oschina.net/u/1760791/blog/979315

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值