Spring Boot如何解决跨域问题?

server/2024/10/5 10:31:23/

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/server/113871.html

相关文章

[Docker]当下实测可用Docker镜像源

在daemon.json配置文件中加入如下镜像源&#xff1a; { "registry-mirrors" : [ "https://hub.dftianyi.top" ] } 修改后&#xff0c;记得重启docker 至于daemon.json配置文件位置参考网上&#xff0c;或如下地方&#xff1a; Mac&#xff1a;/Us…

在Linux下查看HBA卡的速率和状态

平时在Linux下映射存储&#xff0c;都是映射哪台就给哪台插线&#xff0c;然后在存储端扫描WWPN&#xff0c;简单粗暴&#xff0c;没技术含量。当然&#xff0c;光交下也可以看。 1&#xff0c;查看当前卡的品牌&#xff0c;常用的卡有两种&#xff0c;Emulex和Qlogic。 lspc…

Unity3D中控制3D场景中游戏对象显示层级的详解

前言 在Unity3D开发中&#xff0c;控制游戏对象的显示层级&#xff08;也称为渲染顺序或渲染层级&#xff09;是一个常见的需求&#xff0c;特别是在处理复杂的3D场景时&#xff0c;如角色、道具、UI元素等的可见性和渲染顺序的管理变得尤为重要。Unity通过几种不同的机制来实…

【机器人工具箱Robotics Toolbox开发笔记(十一)】 机器人动力学分析

​动力学是研究物体运动与力之间关系的学科,对于机器人而言,其核心在于分析产生运动所需的力。在机器人动力学分析中,主要有两种方法: 牛顿-欧拉法:这种方法基于牛顿的运动定律和欧拉的动力学方程,通过计算作用在机器人连杆上的力和力矩,推导出机器人的动力学方程。它直…

Android SSE 单向接收数据

Server-Sent Events&#xff08;SSE&#xff09;是一种在客户端和服务器之间实现单向实时通信的技术。它允许服务器向客户端推送数据&#xff0c;但客户端无法使用 SSE 向服务器发送数据。这使得其适用于需要持续接收服务器数据的应用场景&#xff08;如实时通知、股票行情、社…

SpringMvc的具体操作,如何配置springMvc(完整教程)

第一步&#xff1a;引入依赖 <dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-w…

在前端中Proj4.js使用简单介绍

Proj4 是一个用于处理 JavaScript 里的几何图形和坐标计算的库。虽然这个库的知名度不如其他几何处理库如 Turf.js&#xff0c;但它提供了用于多边形、点、线等几何对象的计算功能&#xff0c;类似于 GIS&#xff08;地理信息系统&#xff09;的某些功能。 一、基础知识 在使…

【软件设计】常用设计模式--概述

学习设计模式是提高软件开发技能的重要步骤。下面是一些最常用的设计模式&#xff0c;以及它们的基本概念和使用场景&#xff1a; 1. 单例模式&#xff08;Singleton Pattern&#xff09; 概念: 确保一个类只有一个实例&#xff0c;并提供全局访问点。 使用场景: 适用于需要全…