Spring Boot如何解决跨域问题?

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 {
    @Bean
    public 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 {
    @Override
    public 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>

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

代码仓库

3.测试

请注意:localhost和127.0.0.1虽然都指向本机,但也属于跨域。

复制代码
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.引用

相关推荐
AAA修煤气灶刘哥12 分钟前
面试必问的CAS和ConcurrentHashMap,你搞懂了吗?
后端·面试
reasonsummer40 分钟前
【办公类-116-01】20250929家长会PPT(Python快速批量制作16:9PPT相册,带文件名,照片横版和竖版)
java·数据库·python·powerpoint
SirLancelot11 小时前
MinIO-基本介绍(一)基本概念、特点、适用场景
后端·云原生·中间件·容器·aws·对象存储·minio
ss2731 小时前
手写MyBatis第89弹:动态SQL解析与执行时机深度剖析
java·服务器·windows
Light601 小时前
LinkedList 头尾插入与随机访问的隐蔽陷阱—— 领码课堂|Java 集合踩坑指南(6):
java·开发语言·性能优化·deque·双向链表·linkedlist·fail-fast
golang学习记2 小时前
Go 1.25 新特性:正式支持 Git 仓库子目录作为 Go 模块
后端
Penge6662 小时前
一文读懂 ucrypto.Md5
后端
心之伊始2 小时前
深入理解 AbstractQueuedSynchronizer(AQS):构建高性能同步器的基石
java·开发语言
静渊谋3 小时前
攻防世界-Check
java·安全·网络安全
代码充电宝3 小时前
LeetCode 算法题【简单】49. 字母异位词分组
java·算法·leetcode·面试·哈希算法