SpringBoot 中实现跨域的5种方式

1,639次阅读
没有评论

SpringBoot 中实现跨域的5种方式
说明:
之前写过关于跨域相关得总结笔记,这篇文章介绍相较于前面得介绍得更全,可以当作面试题来记忆

之前文章参考参考连接

http://www.shaoming.club/archives/springboot%E8%B7%A8%E5%9F%9F%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%883%E7%A7%8Dmd

ssm跨域问题得解决方案
http://www.shaoming.club/archives/java%E4%B8%AD%E7%9A%84%E8%B7%A8%E5%9F%9F%E9%97%AE%E9%A2%98md

本片文章参考网址:

https://mp.weixin.qq.com/s/2_Zs9PWVMZT1GtEyjGHojg

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

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

二、什么是跨域
举例说明:

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

三、非同源限制
【1】无法读取非同源网页的 Cookie、LocalStorage 和 IndexedDB

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

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

四、java 后端 实现 CORS 跨域请求的方式
对于 CORS的跨域请求,主要有以下几种方式可供选择:

返回新的CorsFilter
重写 WebMvcConfigurer
使用注解 @CrossOrigin
手动设置响应头 (HttpServletResponse)
自定web filter 实现跨域
注意

CorFilter / WebMvConfigurer / @CrossOrigin 需要 SpringMVC 4.2以上版本才支持,对应springBoot 1.3版本以上
上面前两种方式属于全局 CORS 配置,后两种属于局部 CORS配置。如果使用了局部跨域是会覆盖全局跨域的规则,所以可以通过 @CrossOrigin 注解来进行细粒度更高的跨域资源控制。
其实无论哪种方案,最终目的都是修改响应头,向响应头中添加浏览器所要求的数据,进而实现跨域
1.返回新的 CorsFilter(全局跨域)
在任意配置类,返回一个 新的 CorsFIlter Bean ,并添加映射路径和具体的CORS配置路径。

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

  1. 重写 WebMvcConfigurer(全局跨域)
    @Configuration
    public class CorsConfig implements WebMvcConfigurer {
    @Override
    public 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”;
}

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

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

  1. 使用自定义filter实现跨域
    ssm种的写法
    首先编写一个过滤器,可以起名字为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中配置这个过滤器,使其生效

CorsFilter com.mesnac.aop.MyCorsFilter
CorsFilter /*

springboot可以简化
import org.springframework.context.annotation.Configuration;
import javax.servlet.; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebFilter(filterName = “CorsFilter “) @Configuration public class CorsFilter implements Filter { @Override 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-Credentials”, “true”);
response.setHeader(“Access-Control-Allow-Methods”, “POST, GET, PATCH, DELETE, PUT”);
response.setHeader(“Access-Control-Max-Age”, “3600”);
response.setHeader(“Access-Control-Allow-Headers”, “Origin, X-Requested-With, Content-Type, Accept”);
chain.doFilter(req, res);
}
}

esponse.setHeader(“Access-Control-Max-Age”, “3600”);
response.setHeader(“Access-Control-Allow-Headers”, “Origin, X-Requested-With, Content-Type, Accept”);
chain.doFilter(req, res);
}
}

正文完
可以使用微信扫码关注公众号(ID:xzluomor)
post-qrcode
 0
评论(没有评论)

文心AIGC

2024 年 6 月
 12
3456789
10111213141516
17181920212223
24252627282930
文心AIGC
文心AIGC
人工智能ChatGPT,AIGC指利用人工智能技术来生成内容,其中包括文字、语音、代码、图像、视频、机器人动作等等。被认为是继PGC、UGC之后的新型内容创作方式。AIGC作为元宇宙的新方向,近几年迭代速度呈现指数级爆发,谷歌、Meta、百度等平台型巨头持续布局
文章搜索
热门文章
清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开

清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开

清库存!DeepSeek突然补全R1技术报告,训练路径首次详细公开 Jay 2026-01-08 20:18:...
训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享

训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享

训具身模型遇到的很多问题,在数据采集时就已经注定了丨鹿明联席CTO丁琰分享 衡宇 2026-01-08 20:...
「北京版幻方」冷不丁开源SOTA代码大模型!一张3090就能跑,40B参数掀翻Opus-4.5和GPT-5.2

「北京版幻方」冷不丁开源SOTA代码大模型!一张3090就能跑,40B参数掀翻Opus-4.5和GPT-5.2

「北京版幻方」冷不丁开源SOTA代码大模型!一张3090就能跑,40B参数掀翻Opus-4.5和GPT-5.2...
AI金矿上打盹的小红书,刚刚醒了一「点点」

AI金矿上打盹的小红书,刚刚醒了一「点点」

AI金矿上打盹的小红书,刚刚醒了一「点点」 鱼羊 2025-12-26 17:04:08 来源:量子位 一个积...
最新评论
ufabet ufabet มีเกมให้เลือกเล่นมากมาย: เกมเดิมพันหลากหลาย ครบทุกค่ายดัง
tornado crypto mixer tornado crypto mixer Discover the power of privacy with TornadoCash! Learn how this decentralized mixer ensures your transactions remain confidential.
ดูบอลสด ดูบอลสด Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
Obrazy Sztuka Nowoczesna Obrazy Sztuka Nowoczesna Thank you for this wonderful contribution to the topic. Your ability to explain complex ideas simply is admirable.
ufabet ufabet Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
ufabet ufabet You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!
ufabet ufabet Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
热评文章
海信CES发布全新一代RGB-Mini LED,全球首创玲珑4芯真彩背光

海信CES发布全新一代RGB-Mini LED,全球首创玲珑4芯真彩背光

海信CES发布全新一代RGB-Mini LED,全球首创玲珑4芯真彩背光 量子位的朋友们 2026-01-06...
英特尔CES奇袭老黄大本营!英伟达显卡刚涨价,最强酷睿量产出货

英特尔CES奇袭老黄大本营!英伟达显卡刚涨价,最强酷睿量产出货

英特尔CES奇袭老黄大本营!英伟达显卡刚涨价,最强酷睿量产出货 十三 2026-01-06 13:54:54 ...
陈天桥代季峰打响2026大模型第一枪:30B参数跑出1T性能

陈天桥代季峰打响2026大模型第一枪:30B参数跑出1T性能

陈天桥代季峰打响2026大模型第一枪:30B参数跑出1T性能 鹭羽 2026-01-06 14:28:58 来...
OpenAI推理第一人离职,7年打造了o3/o1/GPT-4/Codex

OpenAI推理第一人离职,7年打造了o3/o1/GPT-4/Codex

OpenAI推理第一人离职,7年打造了o3/o1/GPT-4/Codex 衡宇 2026-01-06 13:0...