SpringBoot解決跨域請求攔截問題代碼實(shí)例
前言
同源策略:判斷是否是同源的,主要看這三點(diǎn),協(xié)議,ip,端口。
同源策略就是瀏覽器出于網(wǎng)站安全性的考慮,限制不同源之間的資源相互訪問的一種政策。
比如在域名https://www.baidu.com下,腳本不能夠訪問https://www.sina.com源下的資源,否則將會被瀏覽器攔截。
注意兩點(diǎn):
1.必須是腳本請求,比如AJAX請求。
但是如下情況不會產(chǎn)生跨域攔截
<img src="xxx"/> <a href='xxx"> </a>
2.跨域攔截是前端請求已經(jīng)發(fā)出,并且在后端返回響應(yīng)時檢查相關(guān)參數(shù),是否允許接收后端請求。
在微服務(wù)開發(fā)中,一個系統(tǒng)包含多個微服務(wù),會存在跨域請求的場景。
本文主要講解SpringBoot解決跨域請求攔截的問題。
搭建項(xiàng)目
這里創(chuàng)建兩個web項(xiàng)目,web1 和 web2.
web2項(xiàng)目請求web1項(xiàng)目的資源。
這里只貼關(guān)鍵代碼,完整代碼參考GitHub
WEB2
創(chuàng)建一個Controller返回html頁面
@Slf4j @Controller public class HomeController { @RequestMapping("/index") public String home(){ log.info("/index"); return "/home"; } }
html頁面 home.html
這里創(chuàng)建了一個按鈕,按鈕按下則請求資源:http://localhost:8301/hello
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>web2</title> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"> </script> <script> $(function () { $("#testBtn").click(function () { console.log("testbtn ..."); $.get("http://localhost:8301/hello",function(data,status){ alert("數(shù)據(jù): " + data + "\n狀態(tài): " + status); }); }) }) </script> </head> <body> web2 <button id="testBtn">測試</button> </body> </html>
WEB1
@Slf4j @RestController public class Web1Controller { @RequestMapping("/hello") public String hello(){ log.info("hello "); return "hello," + new Date().toString(); } }
這里配置兩個項(xiàng)目為不同的端口。
WEB1為8301
WEB2為8302
因此是不同源的。
測試
在web1還沒有配置允許跨域訪問的情況下
按下按鈕,將會出現(xiàn)錯誤。顯示Header中沒有Access-Control-Allow-Origin
Access to XMLHttpRequest at 'http://localhost:8301/hello' from origin 'http://localhost:8300' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
WEB1添加允許跨域請求,通過實(shí)現(xiàn)WebMvcConfigurer
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/hello"); } }
再次訪問將會返回正常數(shù)據(jù)。
除了以上的配置外,還可以做更細(xì)致的限制
比如對請求的headers,請求的方法POST/GET...。請求的源進(jìn)行限制。
同時還可以使用注解 @CrossOrigin來替換上面的配置。
@Slf4j @RestController public class Web1Controller { @CrossOrigin @RequestMapping("/hello") public String hello(){ log.info("hello "); return "hello," + new Date().toString(); } }
注解可以用在類上,也可以用在方法上,但必須是控制器類
配置和上面一樣,也是可以對方法,header,源進(jìn)行個性化限制。
@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface CrossOrigin { /** @deprecated */ @Deprecated String[] DEFAULT_ORIGINS = new String[]{"*"}; /** @deprecated */ @Deprecated String[] DEFAULT_ALLOWED_HEADERS = new String[]{"*"}; /** @deprecated */ @Deprecated boolean DEFAULT_ALLOW_CREDENTIALS = false; /** @deprecated */ @Deprecated long DEFAULT_MAX_AGE = 1800L; @AliasFor("origins") String[] value() default {}; @AliasFor("value") String[] origins() default {}; String[] allowedHeaders() default {}; String[] exposedHeaders() default {}; RequestMethod[] methods() default {}; String allowCredentials() default ""; long maxAge() default -1L; }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java快速解析路徑中的參數(shù)(&與=拼接的參數(shù))
這篇文章主要介紹了java快速解析路徑中的參數(shù)(&與=拼接的參數(shù)),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-02-02Springboot之idea之pom文件圖標(biāo)不對問題
這篇文章主要介紹了Springboot之idea之pom文件圖標(biāo)不對問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04Java讀寫鎖ReadWriteLock原理與應(yīng)用場景詳解
這篇文章主要介紹了Java讀寫鎖ReadWriteLock原理與應(yīng)用場景詳解,讀寫狀態(tài)的設(shè)計,寫鎖的獲取與釋放,鎖降級需要的朋友可以參考下2023-02-02

ZooKeeper開發(fā)實(shí)際應(yīng)用案例實(shí)戰(zhàn)

feign post參數(shù)對象不加@RequestBody的使用說明