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註解

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章