Spring Boot 中实现跨域的 5 种方式,你一定要知道!

一、为什么会出现跨域问题

出于浏览器的同源策略限制。同源策略(Sameoriginpolicy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现。

同源策略会阻止一个域的javascript脚本和另外一个域的内容进行交互。所谓同源(即指在同一个域)就是两个页面具有相同的协议(protocol),主机(host)和端口号(port)

二、什么是跨域

当一个请求url的协议、域名、端口三者之间任意一个与当前页面url不同即为跨域5f7832f2c96428150832ad151d631ef7.png

三、非同源限制

  1. 无法读取非同源网页的 Cookie、LocalStorage 和 IndexedDB

  2. 无法接触非同源网页的 DOM

  3. 无法向非同源地址发送 AJAX 请求

  4. 如果您正在学习Spring Boot,那么推荐一个连载多年还在继续更新的免费教程:http://blog.didispace.com/spring-boot-learning-2x/

四、java 后端 实现 CORS 跨域请求的方式

对于 CORS的跨域请求,主要有以下几种方式可供选择:

  1. 返回新的CorsFilter

  2. 重写 WebMvcConfigurer

  3. 使用注解 @CrossOrigin

  4. 手动设置响应头 (HttpServletResponse)

  5. 自定 web filter 实现跨域

注意:

  • CorFilter / WebMvConfigurer / @CrossOrigin 需要 SpringMVC 4.2以上版本才支持,对应springBoot 1.3版本以上

  • 上面前两种方式属于全局 CORS 配置,后两种属于局部 CORS配置。如果使用了局部跨域是会覆盖全局跨域的规则,所以可以通过 @CrossOrigin 注解来进行细粒度更高的跨域资源控制。

  • 其实无论哪种方案,最终目的都是修改响应头,向响应头中添加浏览器所要求的数据,进而实现跨域

1.返回新的 CorsFilter(全局跨域)

在任意配置类,返回一个 新的 CorsFIlter Bean ,并添加映射路径和具体的CORS配置路径。

@Configuration
public class GlobalCorsConfig {@Beanpublic CorsFilter corsFilter() {//1. 添加 CORS配置信息CorsConfiguration config = new CorsConfiguration();//放行哪些原始域config.addAllowedOrigin("*");//是否发送 Cookieconfig.setAllowCredentials(true);//放行哪些请求方式config.addAllowedMethod("*");//放行哪些原始请求头部信息config.addAllowedHeader("*");//暴露哪些头部信息config.addExposedHeader("*");//2. 添加映射路径UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();corsConfigurationSource.registerCorsConfiguration("/**",config);//3. 返回新的CorsFilterreturn new CorsFilter(corsConfigurationSource);}
}

2. 重写 WebMvcConfigurer(全局跨域)

@Configuration
public class CorsConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**")//是否发送Cookie.allowCredentials(true)//放行哪些原始域.allowedOrigins("*").allowedMethods(new String[]{"GET", "POST", "PUT", "DELETE"}).allowedHeaders("*").exposedHeaders("*");}
}

3. 使用注解 (局部跨域)

在控制器(类上)上使用注解 @CrossOrigin:,表示该类的所有方法允许跨域。

@RestController
@CrossOrigin(origins = "*")
public class HelloController {@RequestMapping("/hello")public String hello() {return "hello world";}
}

在方法上使用注解 @CrossOrigin:

@RequestMapping("/hello")@CrossOrigin(origins = "*")//@CrossOrigin(value = "http://localhost:8081") //指定具体ip允许跨域public String hello() {return "hello world";}

4. 手动设置响应头(局部跨域)

使用 HttpServletResponse 对象添加响应头(Access-Control-Allow-Origin)来授权原始域,这里 Origin的值也可以设置为 “*”,表示全部放行。

@RequestMapping("/index")
public String index(HttpServletResponse response) {response.addHeader("Access-Allow-Control-Origin","*");return "index";
}

5. 使用自定义filter实现跨域

首先编写一个过滤器,可以起名字为MyCorsFilter.java

package com.mesnac.aop;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 MyCorsFilter 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");response.setHeader("Access-Control-Max-Age", "3600");response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");chain.doFilter(req, res);}public void init(FilterConfig filterConfig) {}public void destroy() {}
}

在web.xml中配置这个过滤器,使其生效

<!-- 跨域访问 START-->
<filter><filter-name>CorsFilter</filter-name><filter-class>com.mesnac.aop.MyCorsFilter</filter-class>
</filter>
<filter-mapping><filter-name>CorsFilter</filter-name><url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 跨域访问 END  -->

来源:https://blog.csdn.net/weter_drop/

article/details/112135940

9a4d318e7df0a25962182ce5d7ef277b.gif

往期推荐

a63f6754221062ad31ca5ae4bc7fa5b7.png

oppo后端16连问


217e45086e8e6300fd71ad67b38bd675.png

synchronized和ReentrantLock的5个区别!


88e95bce9899fefbc4c2c4c9cddc949e.png

实战!阿里神器 Seata 实现 TCC 模式解决分布式事务


fbae2d9debcce8c4acef5f261a081b5d.gif

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/544192.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

stl:queue 源码_C ++ STL中的queue :: empty()和queue :: size()

stl:queue 源码In C STL, Queue is a type of container that follows FIFO (First-in-First-out) elements arrangement i.e. the elements which inserts first will be removed first. In queue, elements are inserted at one end known as "back" and are delet…

术中导航_密码术中的计数器(CTR)模式

术中导航The Counter Mode or CTR is a simple counter based block cipher implementation in cryptography. Each or every time a counter initiated value is encrypted and given as input to XOR with plaintext or original text which results in ciphertext block. Th…

Android社交类APP动态详情代码实现通用模板

&#xfeff;&#xfeff;Android社交类APP动态详情代码实现通用模板 Android平台上一些比较流行的社交类APP比如微信、陌陌等&#xff0c;都有动态详情页&#xff0c;在该页面&#xff0c;用户发表的动态详情&#xff0c;好友可以发起评论、点赞等等。这种设计在微信和陌陌上大…

聊聊并发编程的12种业务场景

前言并发编程是一项非常重要的技术&#xff0c;无论在面试&#xff0c;还是工作中出现的频率非常高。并发编程说白了就是多线程编程&#xff0c;但多线程一定比单线程效率更高&#xff1f;答&#xff1a;不一定&#xff0c;要看具体业务场景。毕竟如果使用了多线程&#xff0c;…

软件工程编码阶段_软件工程的编码阶段

软件工程编码阶段The coding phase in the software engineering paradigm is usually defined after the designing phase. In this phase, the developers or the coders have to implement the software design practically using any computer language(s) so that the sof…

梳理50道经典计算机网络面试题

我梳理了50道计算机网络面试题&#xff0c;每一道题目都特别经典&#xff0c;大厂也非常喜欢问。相信大家看完&#xff0c;会有新的收获滴~1. 说说HTTP常用的状态码及其含义&#xff1f;思路: 这道面试题主要考察候选人&#xff0c;是否掌握HTTP状态码这个基础知识点。不管是不…

A successful Git branching model

原文&#xff1a;http://nvie.com/posts/a-successful-git-branching-model/ In this post I present the development model that I’ve introduced for all of my projects (both at work and private) about a year ago, and which has turned out to be very successful. I…

一文详解读写锁

作者 | 磊哥来源 | Java面试真题解析&#xff08;ID&#xff1a;aimianshi666&#xff09;转载请联系授权&#xff08;微信ID&#xff1a;GG_Stone&#xff09;读写锁&#xff08;Readers-Writer Lock&#xff09;顾名思义是一把锁分为两部分&#xff1a;读锁和写锁&#xff0c…

ruby array_Ruby中带有示例的Array.keep_if方法

ruby arrayRuby Array.keep_if方法 (Ruby Array.keep_if Method) In the last articles, we have studied the Array methods namely Array.select, Array.reject and Array.drop_while, all these methods are non–destructive methods which means that they do not impose …

[实战]MVC5+EF6+MySql企业网盘实战(2)——用户注册

写在前面 上篇文章简单介绍了项目的结构&#xff0c;这篇文章将实现用户的注册。当然关于漂亮的ui&#xff0c;这在追后再去添加了&#xff0c;先将功能实现。也许代码中有不合适的地方&#xff0c;也只有在之后慢慢去优化了。 系列文章 [EF]vs15ef6mysql code first方式 [实战…

Calico IP_AUTODETECTION_METHOD

在 Calico 中&#xff0c;IP_AUTODETECTION_METHOD 的配置项用于指定 Calico 如何检测容器的 IP 地址。 一、kubernetes-internal-ip模式 其中&#xff0c;kubernetes-internal-ip 是一种特殊的模式&#xff0c;用于在 Kubernetes 环境中检测容器的 IP 地址。具体作用如下&…

下个十年高性能 JSON 库来了:fastjson2!

作者 | 磊哥来源 | Java中文社群&#xff08;ID&#xff1a;javacn666&#xff09;转载请联系授权&#xff08;微信ID&#xff1a;GG_Stone&#xff09;fastjson2 是 fastjson 项目的重要升级&#xff0c;目标是为下一个十年提供一个高性能的 JSON 库&#xff0c;同一套 API 支…

ascii非打印控制字符表_C程序打印ASCII表/图表

ascii非打印控制字符表什么是ASCII码&#xff1f; (What are ASCII Codes?) ASCII stands for American Standard Code for Information Interchange; it is a character encoding standards for information interchange in electronics communication. Each alphabets, spec…

THEOS的第一个TWeak的成功创建

THEOS的第一个TWeak的成功创建THEOS的第一个TWeak的成功创建参考资料:成功的创建一个TWeak的弹出步骤1:安装Xcode和Xcode command line步骤2:安装theosa:下载theos前,设置保存的路径:环境变量b:下载theosc:下载头文件d:下载ldid签名工具e:配置MoblieSubstrate环境f:安装dpkg步骤…

查询中,有没有可能多个索引一起用呢?

其实我们之前所讲的回表&#xff0c;就是两个索引树同时使用&#xff0c;先在二级索引树中搜索到对应的主键值&#xff0c;然后在再去主键索引树中查询完整的记录。但是我今天的问题是&#xff0c;两个不同的二级索引树&#xff0c;会同时生效吗&#xff1f;理论上来说&#xf…

ruby array_Ruby中带有示例的Array.sample()方法

ruby arrayArray.sample()方法 (Array.sample() Method) In this article, we will study about Array.sample() method. You all must be thinking the method must be doing something which is quite different from all those methods which we have studied. It is not as…

ThreadLocal夺命11连问

前言前一段时间&#xff0c;有同事使用ThreadLocal踩坑了&#xff0c;正好引起了我的兴趣。所以近期&#xff0c;我抽空把ThreadLocal的源码再研究了一下&#xff0c;越看越有意思&#xff0c;发现里面的东西还真不少。我把精华浓缩了一下&#xff0c;汇集成了下面11个问题&…

关于静态库、动态库的区别汇总

real framework中不可以使用类别 或 不可以不包含类文件real framework 中直接调用NSClassFromString函数会返回null 需要强制加载指定类 或 直接通过类名引用linux中静态库和动态库的区别一、不同库从本质上来说是一种可执行代码的二进制格式&#xff0c;可以被载入内存中执行…

PHP array_pad()函数与示例

PHP array_pad()函数 (PHP array_pad() function) array_pad() function is used to pad an array to given size with a specified value and returns a new array with a specified value. array_pad()函数用于将数组填充到具有指定值的给定大小&#xff0c;并返回具有指定值…

Spring Boot 优雅配置多数据源

大约在19年的这个时候&#xff0c;老同事公司在做医疗系统&#xff0c;需要和HIS系统对接一些信息&#xff0c;比如患者、医护、医嘱、科室等信息。但是起初并不知道如何与HIS无缝对接&#xff0c;于是向我取经。最终经过讨论采用了视图对接的方式&#xff0c;大致就是HIS系统提…