Springboot通過配置WebMvcConfig處理Cors非同源訪問跨域問題
關(guān)于Cors跨域的問題,前端有代理和jsonp的常用方式解決這種非同源的訪問拒絕策略,什么是同源?即域名一致端口一致但是端口下訪問的接口api不同的兩種或者幾種的互相訪問叫做同源訪問,但是若是接口不一致或者域名不一致(這里泛指IP不一致),那么對應(yīng)的就屬于非同源訪問,瀏覽器會拒絕發(fā)出請求,直接回復(fù)404,有時候我也見過恢復(fù)202的就是發(fā)出去了但是被后端的Mvc處理hander鏈給拒絕了。那么配置MVC是后端處理Cors問題的一種解決思路。
之前學(xué)習(xí)過MVC的處理鏈路,從一次請求發(fā)過來到回復(fù)數(shù)據(jù)總共11次處理:
請求發(fā)送到服務(wù)器端時是由我們的MVC進(jìn)行處理的,而統(tǒng)一調(diào)配任務(wù)流程的則是我們的請求分發(fā)器,注意這里請求到處理器之后回去尋找處理器適配器(符合校驗處理的請求才能被允許例如接口含有的合法api,以及跨域原則),之前我們的微信小程序開發(fā)過程中是沒有考慮跨域問題的,原因是我們知道小程序的請求處理都是由微信后臺進(jìn)行分發(fā)處理的,也就是在微信的后臺時就做了前端的跨域處理,大概是采用動態(tài)代理的方式解決了小程序的跨域。
那么我們先看看MVC的配置接口 WebMvcConfigurer 的源代碼:
public interface WebMvcConfigurer { default void configurePathMatch(PathMatchConfigurer configurer) { } default void configureContentNegotiation(ContentNegotiationConfigurer configurer) { } default void configureAsyncSupport(AsyncSupportConfigurer configurer) { } default void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { } default void addFormatters(FormatterRegistry registry) { } default void addInterceptors(InterceptorRegistry registry) { } default void addResourceHandlers(ResourceHandlerRegistry registry) { } default void addCorsMappings(CorsRegistry registry) { } default void addViewControllers(ViewControllerRegistry registry) { } default void configureViewResolvers(ViewResolverRegistry registry) { } default void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) { } default void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) { } default void configureMessageConverters(List<HttpMessageConverter<?>> converters) { } default void extendMessageConverters(List<HttpMessageConverter<?>> converters) { } default void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) { } default void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) { } @Nullable default Validator getValidator() { return null; } @Nullable default MessageCodesResolver getMessageCodesResolver() { return null; } }
它的內(nèi)部是具備一些處理器解析器以及映射的添加與配置的方法的,那么我們要解決Cros跨域問題就是要考慮addCorsMappings 配置Cros映射,所以我們點進(jìn)去看看這注冊Cros的 CorsRegistry 的源碼:
public class CorsRegistry { private final List<CorsRegistration> registrations = new ArrayList(); public CorsRegistry() { } public CorsRegistration addMapping(String pathPattern) { CorsRegistration registration = new CorsRegistration(pathPattern); this.registrations.add(registration); return registration; } protected Map<String, CorsConfiguration> getCorsConfigurations() { Map<String, CorsConfiguration> configs = CollectionUtils.newLinkedHashMap(this.registrations.size()); Iterator var2 = this.registrations.iterator(); while(var2.hasNext()) { CorsRegistration registration = (CorsRegistration)var2.next(); configs.put(registration.getPathPattern(), registration.getCorsConfiguration()); } return configs; } }
從上述代碼中不難發(fā)現(xiàn),內(nèi)部有一個不可改變的 CorsRegistration 數(shù)組鏈表,以及增加映射的方法,主要還是看看它具備的元素 CorsRegistration 含有什么配置項:
public class CorsRegistration { private final String pathPattern; private CorsConfiguration config; public CorsRegistration(String pathPattern) { this.pathPattern = pathPattern; this.config = (new CorsConfiguration()).applyPermitDefaultValues(); } public CorsRegistration allowedOrigins(String... origins) { this.config.setAllowedOrigins(Arrays.asList(origins)); return this; } public CorsRegistration allowedOriginPatterns(String... patterns) { this.config.setAllowedOriginPatterns(Arrays.asList(patterns)); return this; } public CorsRegistration allowedMethods(String... methods) { this.config.setAllowedMethods(Arrays.asList(methods)); return this; } public CorsRegistration allowedHeaders(String... headers) { this.config.setAllowedHeaders(Arrays.asList(headers)); return this; } public CorsRegistration exposedHeaders(String... headers) { this.config.setExposedHeaders(Arrays.asList(headers)); return this; } public CorsRegistration allowCredentials(boolean allowCredentials) { this.config.setAllowCredentials(allowCredentials); return this; } public CorsRegistration maxAge(long maxAge) { this.config.setMaxAge(maxAge); return this; } public CorsRegistration combine(CorsConfiguration other) { this.config = this.config.combine(other); return this; } protected String getPathPattern() { return this.pathPattern; } protected CorsConfiguration getCorsConfiguration() { return this.config; } }
我們可以發(fā)現(xiàn)內(nèi)部是具備允許放行:請求頭,請求路徑,請求方法,請求源策略的方法的,所以我們在這里的 重寫addCorsMappings方法配置一個 CorsRegistry 添加相應(yīng)的路徑方法與請求策略放行不就可以解決跨域的問題了?
我們寫一個WebMvcConfig配置類實現(xiàn)剛剛研究的WebMvcConfigurer接口重寫addCrosMappings配置CrosRegistry即可(或者在api與Controller控制類上打上@CrossOrigin注解也可以解決問題(注解默認(rèn)放行所有來源的請求)):
/** * 配置前端跨域訪問請求 */ @Configuration public class WbMvcConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedHeaders("Content-Type","X-Request-With","Access-Control-Request-Method","Access-Control-Request-Headers","token") .allowedMethods("*") .allowedOriginPatterns("*") /*注意當(dāng)這個配置為真是我們不能將允許源設(shè)置為*而是將源路徑設(shè)置為*即可*/ .allowCredentials(true); } @Bean public FormContentFilter httpPutFormContentFilter(){ return new FormContentFilter(); } }
我們利用axios寫一個簡單的請求發(fā)送按鈕:
<input type="button" value="get" class="get"> <script> document.querySelector(".get").onclick = function () { // 跨域一般是是后端解決的事情 axios.get("http://127.0.0.1:8080/all").then( function (response) { console.log(response) } ) } </script>
再用SpringBoot寫一個簡單的controller的api:
@RestController public class testController { @Autowired private ProductServiceImpl productService; @GetMapping("/all") @ResponseBody public List<Product> all() { Page<Product> page = productService.page(1L); List<Product> productList = new LinkedList<>(); productList.add(page.getRecords().iterator().next()); return productList; } }
這里我們在瀏覽器打開5050端口下的這個html文件就可以點擊按鈕訪問接口了:
這里可以看到請求訪問數(shù)據(jù)成功了!
到此這篇關(guān)于Springboot通過配置WebMvcConfig處理Cors非同源訪問跨域問題的文章就介紹到這了,更多相關(guān)Springboot Cors非同源訪問跨域內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java實現(xiàn)液晶數(shù)字字體顯示當(dāng)前時間
這篇文章主要為大家詳細(xì)介紹了java實現(xiàn)液晶數(shù)字字體顯示當(dāng)前時間,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-12-12淺談Arrays.asList() 和ArrayList類型區(qū)別
下面小編就為大家?guī)硪黄狝rrays.asList() 和ArrayList類型區(qū)別。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-10-10Java Jedis NOAUTH Authentication required問題解決方法
這篇文章主要介紹了Java Jedis NOAUTH Authentication required問題解決方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-07-07關(guān)于HashMap的put方法執(zhí)行全過程
這篇文章主要介紹了關(guān)于HashMap的put方法執(zhí)行全過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06解決springboot運行出現(xiàn)錯誤:找不到或無法加載主類com.xxxx.xxxx.Application問題
文章介紹了在服務(wù)器上運行一個未使用的Java項目時遇到的“找不到或無法加載主類”錯誤,并提供了兩種解決方法:通過Maven install或build …、Goals輸入install并跳過測試來重新構(gòu)建項目2024-11-11SpringCloud微服務(wù)開發(fā)基于RocketMQ實現(xiàn)分布式事務(wù)管理詳解
分布式事務(wù)是在微服務(wù)開發(fā)中經(jīng)常會遇到的一個問題,之前的文章中我們已經(jīng)實現(xiàn)了利用Seata來實現(xiàn)強(qiáng)一致性事務(wù),其實還有一種廣為人知的方案就是利用消息隊列來實現(xiàn)分布式事務(wù),保證數(shù)據(jù)的最終一致性,也就是我們常說的柔性事務(wù)2022-09-09