Spring Boot如何解决跨域问题?

embedded/2024/9/23 10:13:42/

1.什么是跨域?

跨域请求,就是说浏览器在执行脚本文件的ajax请求时,脚本文件所在的服务地址和请求的服务地址不一样。说白了就是ip、网络协议、端口都一样的时候,就是同一个域,否则就是跨域。这是由于Netscape提出一个著名的安全策略——同源策略造成的,这是浏览器对JavaScript施加的安全限制。是防止外网的脚本恶意攻击服务器的一种措施。

2.代码工程

实验目标

让Spring Boot应用支持跨域

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><parent><artifactId>springboot-demo</artifactId><groupId>com.et</groupId><version>1.0-SNAPSHOT</version></parent><modelVersion>4.0.0</modelVersion><artifactId>cors</artifactId><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-autoconfigure</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>
</project>

第一种跨域解决方法

使用 @CrossOrigin 注解可以轻松的实现跨域,此注解既可以修饰类,也可以修饰方法。当修饰类时,表示此类中的所有接口都可以跨域;当修饰方法时,表示此方法可以跨域,它的实现如下

package com.et.cors.controller;import org.springframework.web.bind.annotation.*;import java.util.HashMap;
import java.util.Map;@RestController
public class HelloWorldController {//@CrossOrigin@GetMapping("/hello")public String hello() {System.out.println("get hello");return "get hello";}@CrossOrigin@PostMapping("/hello")public String hello2() {System.out.println("post hello");return "post hello";}
}

第二种跨域解决方法

通过 CorsFilter 跨域,“*”代表全部。”**”代表适配所有接口。  其中addAllowedOrigin(String origin)方法是追加访问源地址。如果不使用”*”(即允许全部访问源),则可以配置多条访问源来做控制。 例如:

config.addAllowedOrigin("http://www.liuhaihua.cn/"); 
config.addAllowedOrigin("http://test.liuhaihua.cn/");
package com.et.cors.filter;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;@Configuration
public class MyCorsFilter {@Beanpublic CorsFilter corsFilter() {CorsConfiguration config = new CorsConfiguration();config.addAllowedOrigin("*");config.setAllowCredentials(true);config.addAllowedMethod("*");config.addAllowedHeader("*");UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();corsConfigurationSource.registerCorsConfiguration("/**", config);return new CorsFilter(corsConfigurationSource);}
}

第三种跨域解决方法

重写 WebMvcConfigurer

package com.et.cors.config;import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**") .allowCredentials(true) .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*");}
}

index.html

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Title</title>
</head><script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>function btnClick() {$.get('http://localhost:8088/hello', function (msg) {$("#app").html(msg);});}function btnClick2() {$.post('http://localhost:8088/hello', function (msg) {$("#app").html(msg);});}
</script><body><div id="app"></div>
<input type="button" onclick="btnClick()" value="get_button">
<input type="button" onclick="btnClick2()" value="post_button"></body>
</html>

以上只是一些关键代码,所有代码请参见下面代码仓库

代码仓库

  • GitHub - Harries/springboot-demo: a simple springboot demo with some components for example: redis,solr,rockmq and so on.(cors)

3.测试

请注意:localhost和127.0.0.1虽然都指向本机,但也属于跨域。
  • 启动Spring Boot应用
  • 访问http://127.0.0.1:8088/index.html
  • 点击第一个按钮,出现跨域问题
Access to XMLHttpRequest at 'http://localhost:8088/hello' from origin 'http://127.0.0.1:8088' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
  • 点击第二个按钮,添加注解@CrossOrigin,未出现跨域

4.引用

  • CorsConfiguration (Spring Framework 4.2.9.RELEASE API)
  • Spring Boot如何解决跨域问题? | Harries Blog™

http://www.ppmy.cn/embedded/108014.html

相关文章

(十五)SpringCloudAlibaba-Sentinel持久化到Nacos

前言 在前面我们已经将Sentinel配置的规则持久化到系统的文件中。本章节我们将Sentinel持久化到Nacos中; 传送门(Sentinel数据持久化到文件)https://blog.csdn.net/weixin_45876411/article/details/140742963 默认情况下 Sentinel 只能接收到 Nacos 推送的消息&#xff0c;但…

关于武汉高芯coin417G2红外机芯的二次开发

文章目录 前言一、外观和机芯参数二、SDK的使用1、打开相机2、回调函数中获取全局温度和图像3、关闭相机 前言 最近工作中接触了一款基于武汉高芯科技有限公司开发的红外模组,即coin417g2(测温型)9.1mm镜头.使用此模组,开发了一套红外热成像检测桌面应用程序.下面简单记录下该…

rancher搭建k8s及jenkins自动化部署

1、准备环境 角色IP用途k8s-rancher-master192.168.3.63master节点k8s-rancher-node01192.168.3.64node节点k8s-rancher-node02192.168.3.66node节点k8s-rancher-server192.168.2.33rancher-server节点注: 服务器名需要配置不同,相同服务器名不能加入node节点 在所有节点进行…

【深入解析】AI工作流中的HTTP组件:客户端与服务端执行的区别

在当今快速发展的技术环境中&#xff0c;AI工作流的设计和实现变得愈发重要。尤其是在处理HTTP组件时&#xff0c;前端执行与后端执行之间的区别&#xff0c;往往会对系统的安全性和数据的准确性产生深远的影响。今天&#xff0c;我们就来深入探讨这一话题&#xff0c;揭示前端…

学习Linux

1. 操作系统是计算机软件的一种&#xff0c;它主要负责&#xff1a; 作为用户和计算机硬件之间的桥梁&#xff0c;调度和管理计算机硬件进行工作&#xff08;作用&#xff09; 2.计算机有了操作系统&#xff0c;就相当于拥有了灵魂 3.操作系统可以&#xff1a;调度CPU进行工作…

VUE3父子组件传参

defineProps和defineEmits的使用场景‌ ‌父组件向子组件传递数据‌&#xff1a;子组件可以通过defineProps接收来自父组件的数据&#xff0c;并在子组件的模板中使用这些数据。‌2‌子组件向父组件发送事件‌&#xff1a;子组件可以通过defineEmits触发事件&#xff0c;并将数…

fastadmin 清除插件缓存报错

Argument 1 passed to Symfony\Component\VarExporter\VarExporter::export() must be an instance of Symfony\Component\VarExporter\mixed, array given, called in F:\work\awebsite\oeob\vendor\karsonzhang\fastadmin-addons\src\addons\Service.php on line 404 我用的…

SpringCloud之Sleuth(Micrometer)+ZipKin分布式链路追踪

&#xff08;学习笔记&#xff09; 1、分布式链路追踪概述 问题&#xff1a;在微服务框架中&#xff0c;一个由客户端发起的请求在后端系统中会经过多个不同的的服务节点调用来协同产生最后的请求结果&#xff0c;每一个前段请求都会形成一条复杂的分布式服务调用链路&#xf…