SpringBoot解决跨域方案

跨域,是指浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的(CV)

关于浏览器为什么有同源策略这个东西,个人感觉水很深,大家感兴趣就自己去研究吧。

 

下面总结几种出现跨域情况:

▶ 不同域名

http://www.a.com/index.html 调用 http://www.b.com/server.do

▶ 同域名、不同端口

http://www.a.com:8080/index.html 调用 http://www.a.com:8081/server.do

▶ 同域名、不同协议

http://www.a.com/index.html 调用 https://www.a.com/server.do

▶ 主域名相同、不同子域名

http://www.a.com/index.html 调用 https://cn.a.com/server.do

 

SpringBoot解决跨域的三种方式

OPTION ONE:配置过滤器支持CORS(跨域资源共享)

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;

@Component
public class CorsFilter 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, HEAD");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
        chain.doFilter(req, res);
    }
    public void init(FilterConfig filterConfig) {}
    public void destroy() {}
}

OPTION TWO:配置addCorsMappings支持CORS(跨域资源共享)

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

@Configuration
public class SpringMvcConfig extends WebMvcConfigurationSupport {

	@Override
	protected void addCorsMappings(CorsRegistry registry) {
		registry.addMapping("/**")
				.allowedOrigins("*")
				.allowedMethods("POST", "GET", "PUT", "DELETE")
				.allowCredentials(true)
				.allowedHeaders("*")
				.maxAge(3600)
				.allowedHeaders(
						"Access-Control-Allow-Headers",
						"access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
	}
}

OPTION THREE:使用@CrossOrigin注解

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值