Spring Boot 2.X 如何优雅的解决跨域问题?

一、什么是源和跨域

源(origin)就是协议、域名和端口号。

对https://www.baidu.com/index.html进行跨域比较:
URL是否跨域原因
https://www.baidu.com/more/index.html不跨域三要素相同
https://map.baidu.com/跨域域名不同
http://www.baidu.com/index.html跨域协议不同
https://www.baidu.com:81/index.html跨域端口号不同

二、什么是同源策略?

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

同源策略又分为以下两种:

  1. DOM同源策略:禁止对不同源页面DOM 进行操作。这里主要场景是iframe跨域的情况,不同域名的iframe是限制互相访问的。

  2. XMLHttpRequest同源策略:禁止使用XHR对象向不同源的服务器地址发起HTTP请求。

三、Spring Boot跨域解决方案

本例使用Spring Boot 2.1.2.RELEASE演示,分别用8080和8081端口启动,部分代码如下:

跨域页面:testOtherDomain.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>不同域名-Java碎碎念</title>
</head>
<body>
<button id="b1">点我测试</button>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
    $("#b1").click(function () {
        $.ajax({
            url: "http://localhost:8081/hello",
            type: "post",
            success:function (res) {
                console.log(res);
            }
        })
    });
</script>
</body>
</html>

接口类:HelloController

package com.example.helloSpringBoot.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String HelloSpring (){
        return "hello Java碎碎念!";
    }
}

未解决跨域前运行截图:

640?wx_fmt=png
运行截图

在Spring Boot 2.X应用程序中可以使用注解@CrossOrigin,也可以通过使用WebMvcConfigurer对象来定义全局CORS配置。

  1. @CrossOrigin注解示例代码

package com.example.helloSpringBoot.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @CrossOrigin
    @RequestMapping("/hello")
    public String HelloSpring (){
        return "hello Java碎碎念!";
    }
}
  1. WebMvcConfigurer对象示例代码

package com.example.helloSpringBoot.config;

import org.springframework.context.annotation.Bean;
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 MyConfiguration {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/*")
                          .allowedOrigins("*")
                          .allowCredentials(true)
                          .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
                          .maxAge(3600);
            }
        };
    }
}

按照上面两种方式的一种配置完成后,即可实现对跨域的支持,运行成功截图如下:

640?wx_fmt=png
运行成功截图

完整源码地址:https://github.com/suisui2019/helloSpringBoot

推荐阅读

限时领取免费Java相关资料,涵盖了Java、Redis、MongoDB、MySQL、Zookeeper、Spring Cloud、Dubbo/Kafka、Hadoop、Hbase、Flink等高并发分布式、大数据、机器学习等技术。

640?wx_fmt=jpeg
Java碎碎念公众号

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot解决跨域问题有多种方式,以下是其中的两种: 1. 使用 @CrossOrigin 注解 在 Spring Boot 的 Controller 层中,可以使用 @CrossOrigin 注解来解决跨域问题。例如: ``` @RestController public class MyController { @CrossOrigin @GetMapping("/hello") public String hello() { return "Hello, world!"; } } ``` 使用 @CrossOrigin 注解可以实现简单的跨域请求,但是如果需要更细粒度的控制,就需要使用其他的方式。 2. 自定义 CorsFilter Spring Boot 中可以自定义 CorsFilter 来处理跨域请求。CorsFilter 是一个过滤器,可以在请求处理之前拦截请求,并进行相应的处理。例如: ``` @Configuration public class CorsConfig { @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(Arrays.asList("*")); // 允许所有域名 config.setAllowedMethods(Arrays.asList("*")); // 允许所有 HTTP 方法 config.setAllowedHeaders(Arrays.asList("*")); // 允许所有请求头 config.setMaxAge(1800L); // 预检请求的有效期,单位为秒 source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } } ``` 上面的代码中,我们通过 CorsConfiguration 来配置允许的域名、HTTP 方法、请求头和预检请求的有效期等信息。然后将这个配置注册到 UrlBasedCorsConfigurationSource 中,并返回一个 CorsFilter 对象,这样就可以处理跨域请求了。 以上两种方式都可以用来解决跨域问题,具体使用哪种方式可以根据实际情况来决定。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值