Springboot跨域處理的多種方式小結(jié)
測試工具 IDEA
什么是跨域
當(dāng)一臺服務(wù)器資源從另一臺服務(wù)器(不同 的域名或者端口)請求一個(gè)資源或者接口,就會(huì)發(fā)起一個(gè)跨域 HTTP 請求。
瀏覽器出于安全考慮,會(huì)限制跨域訪問,就是不允許跨域請求資源,要求協(xié)議,IP和端口必須都相同,其中有一個(gè)不同就會(huì)產(chǎn)生跨域問題,這就是同源策略。
跨域舉例
| 請求方 | 響應(yīng)方 | 是否跨域 | 原因 |
|---|---|---|---|
| http://www.ming.com | http://www.ming.com/test.html | 否 | 協(xié)議、域名、端口相同 |
| http://www.ming.com | https://www.ming.com/test.html | 是 | 協(xié)議不同 |
| http://www.ming.com | http://www.minggod.com/test.html | 是 | 主域名不同 |
| http://www.ming.com | http://haha.ming.com/test.html | 是 | 主域名相同、子域名不同 |
| http://www.ming.com:8080 | http://www.ming.com:8090/test.html | 是 | 端口不同 |
跨域訪問實(shí)例
后端測試代碼
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CorsController {
@GetMapping("/cors")
public String hello(){
return "hello cors";
}
}用瀏覽器打開,我這里配置的端口是8090

在前端項(xiàng)目中用axios訪問時(shí)
<template>
<span>跨域請求:{{result}}</span>
</template>
<script>
import axios from 'axios';
export default {
name: "Cors",
data(){
return {
result:""
}
},
methods:{
getTest(){
axios.get("http://localhost:8090/cors").then(res=>{
console.log(res.data)
this.result=res.data
})
}
},
created() {
this.getTest();
}
}
</script>
<style scoped>
</style>
報(bào)錯(cuò)中的關(guān)鍵詞
Access-Control-Allow-Origin
跨域處理(后端)
說明:
這里是針對Springboot 2.4.0以后的寫法,之前的版本寫法是.allowedOrigins(*)
2.4.0之后會(huì)報(bào)錯(cuò)替換成.allowedOriginPatterns即可
代碼中會(huì)有注釋說明
1.添加跨域配置類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsFilter corsFilter() {
//1. 添加 CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//放行哪些原始域
config.addAllowedOriginPattern("*");//2.4.0后的寫法
// config.addAllowedOrigin("*");
//是否發(fā)送 Cookie
config.setAllowCredentials(true);
//放行哪些請求方式
config.addAllowedMethod("*");
//放行哪些原始請求頭部信息
config.addAllowedHeader("*");
//暴露哪些頭部信息
config.addExposedHeader("*");
//2. 添加映射路徑
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**",config);
//3. 返回新的CorsFilter
return new CorsFilter(corsConfigurationSource);
}
}重啟后端服務(wù)后,刷新前端頁面正常訪問,效果如下

2. 重寫WebMvcConfigurer
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
//是否發(fā)送Cookie
.allowCredentials(true)
//放行哪些原始域
//.allowedOrigins("*")
.allowedOriginPatterns("*")//2.4.0后的寫法
.allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"})
.allowedHeaders("*")
.exposedHeaders("*");
}
}
3. 注解 @CrossOrigin
類上注解
@RestController
@CrossOrigin("*")
public class CorsController {
@GetMapping("/cors")
public String hello(){
return "hello cors";
}
}方法上注解
方法可以單獨(dú)跨域,沒有 @CrossOrigin(“*”) 注解的方法則不行
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CorsController {
@GetMapping("/cors")
@CrossOrigin("*")
public String hello(){
return "hello cors";
}
@GetMapping("/cors1")
public String hello1(){
return "hello cors1";
}
}4.自定義過濾器
可以正??缬?/p>
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.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
@Component
public class MyCorsFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest httpServletRequest = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("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");
response.setHeader("Access-Control-Allow-Credentials", "true");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
}5.手動(dòng)設(shè)置響應(yīng)頭(局部跨域)
此方案聽說可以用,但明哥自己測試了,不能用,依然有問題,不建議!
@GetMapping("/cors1")
public String hello1(HttpServletResponse response){
response.addHeader("Access-Allow-Control-Origin","*");
return "hello cors1";
}小結(jié)
這節(jié)總結(jié)了“ Springboot跨域處理 ”,希望能對大家有所幫助。
到此這篇關(guān)于Springboot跨域處理的幾種方式的文章就介紹到這了,更多相關(guān)Springboot跨域處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot實(shí)現(xiàn)前后端分離國際化的示例詳解
Springboot國際化可以幫助使用者在不同語言環(huán)境中構(gòu)建應(yīng)用程序,這樣應(yīng)用程序可以有效地適應(yīng)不同語言文化背景下的用戶需求。本文主要介紹了SpringBoot實(shí)現(xiàn)前后端分離國際化的方法,需要的可以參考一下2023-02-02
解析SpringCloud簡介與微服務(wù)架構(gòu)
這篇文章主要介紹了SpringCloud簡介與微服務(wù)架構(gòu),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01
SpringMVC RESTful支持實(shí)現(xiàn)過程演示
這篇文章主要介紹了SpringMVC RESTful支持實(shí)現(xiàn)過程演示,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
Mybatis實(shí)現(xiàn)動(dòng)態(tài)建表代碼實(shí)例
這篇文章主要介紹了Mybatis實(shí)現(xiàn)動(dòng)態(tài)建表代碼實(shí)例,解釋一下,就是指根據(jù)傳入的表名,動(dòng)態(tài)地創(chuàng)建數(shù)據(jù)庫表,以供后面的業(yè)務(wù)場景使用,2023-10-10
而使用 Mybatis 的動(dòng)態(tài) SQL,就能很好地為我們解決這個(gè)問題,需要的朋友可以參考下
MybatisPlus多數(shù)據(jù)源及事務(wù)解決思路
這篇文章主要介紹了MybatisPlus多數(shù)據(jù)源及事務(wù)解決思路,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01
使用Java快速搭一個(gè)可用的Agent的完整實(shí)例
很多人第一次接觸Agent框架,容易把它理解成更復(fù)雜一點(diǎn)的模型SDK,但真正進(jìn)入業(yè)務(wù)場景后,你會(huì)發(fā)現(xiàn)問題根本不在怎么調(diào)模型,而在怎么讓模型穩(wěn)定地參與業(yè)務(wù)流程,這篇文章從Java開發(fā)者視角出發(fā),介紹AgentScope是什么、適合解決什么問題,需要的朋友可以參考下2026-03-03
Java的微信開發(fā)中使用XML格式和JSON格式數(shù)據(jù)的示例
這篇文章主要介紹了Java微信開發(fā)中使用XML格式和JSON格式數(shù)據(jù)的示例,注意一下json-lib所需要的jar包,需要的朋友可以參考下2016-02-02

