java 跨域_SpringBoot设置允许跨域请求的方法

跨域请求

何谓跨域请求?简单来说,是浏览器的一种自我保护机制。Web请求连接中,有三大要素:地址ip、端口port、协议http/https,只要其中有一个不一致,浏览器将视其为跨域请求。

9b1f98a86caa2e2b422fb840257bfad9.png

跨域请求

跨域请求不是一个新鲜的概念,或者说是一个落后的概念,网络安全的维护,已经不再是简单地进行跨域请求的限制,作为互联网研发的一员,我们时常觉得浏览器应该废弃跨区请求的限制。如何解除跨域请求的限制呢?

允许跨域配置

Java是目前后端最热门的开发语言,而SpringBoot作为后端接口开发目前最热门的框架,跨域运行的设置,十分简单。

1db88c9ccbd0d4c7f594c4d6ad1967d3.png

SpringBoot代码编写

方案一

重新配置 CorsFilter

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;/*** 实现基本的跨域请求* @author IT小村**/@Configurationpublic class CorsConfig {    private CorsConfiguration buildConfig() {        CorsConfiguration corsConfiguration = new CorsConfiguration();        corsConfiguration.addAllowedOrigin("*"); // 允许任何域名使用        corsConfiguration.addAllowedHeader("*"); // 允许任何头        corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)        return corsConfiguration;    }    @Bean    public CorsFilter corsFilter() {        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();        source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置        return new CorsFilter(source);    }}

方案二

实现 WebMvcConfigurer 接口,重写 addCorsMappings 方法。

import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.CorsRegistry;import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;/*** 实现基本的跨域请求* @author IT小村**/@Configurationpublic class WebAppConfigurer implements WebMvcConfigurer {    @Override    public void addCorsMappings(CorsRegistry registry) {        registry.addMapping("/**")                .allowedOrigins("*")                .allowCredentials(true)                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE","OPTIONS")                .maxAge(3600);    }}

其他

开发中跨域问题的频繁出现,主要原因在于互联网的高速发展,互联网产品更新迭代频繁,研发们不得推出高内聚低耦合的前后端分离开发模式,以便更加灵活地应对众多的技改需求。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值