当前位置: 代码网 > it编程>编程语言>Java > Springboot处理跨域的实现方式(附Demo)

Springboot处理跨域的实现方式(附Demo)

2025年04月01日 Java 我要评论
springboot处理跨域的方式1. 基本知识跨域指的是在一个域下的网页试图访问另一个域下的资源由于浏览器的同源策略,默认情况下,javascript 只能在相同的域中进行请求跨域通常涉及以下概念:

springboot处理跨域的方式

1. 基本知识

跨域指的是在一个域下的网页试图访问另一个域下的资源

由于浏览器的同源策略,默认情况下,javascript 只能在相同的域中进行请求

跨域通常涉及以下概念:

  • origin: 包括协议、域名和端口号
    比如 http://example.com:80
  • same-origin policy: 浏览器的安全策略,限制一个源的文档或脚本如何能与另一个源的资源进行交互
  • cors: 允许跨域请求的机制
    服务器通过设置特定的响应头来告知浏览器哪些源是允许访问的

在 spring boot 中,处理跨域的方式有几种,以下是主要的几种方式:

  1. 使用 @crossorigin 注解: 这种方式较为简单,适用于控制器层
  2. 配置全局跨域设置: 这种方式适用于全局配置,可以在 web 配置类中设置
  3. 自定义 corsconfiguration: 适用于更复杂的跨域配置需求,可以在配置类中自定义

以下为demo示例

2. @crossorigin

可以在控制器类或方法上添加 @crossorigin 注解

注解的参数可以配置允许的源(origins)、允许的请求方法(methods)、允许的请求头(allowedheaders)、是否允许凭证(allowcredentials)等

import org.springframework.web.bind.annotation.crossorigin;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;

@restcontroller
@requestmapping("/api")
public class mycontroller {

    @crossorigin(origins = "http://example.com")
    @getmapping("/data")
    public string getdata() {
        return "data from server";
    }
}

如果不使用 @crossorigin 注解,浏览器会阻止跨域请求,因为默认的同源策略不允许不同源之间的请求

3. 全局跨域设置

配置 webmvcconfigurer 来全局设置跨域

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;

/**
 * 配置类,用于全局设置 cors(跨域资源共享)配置
 */
@configuration
public class webconfig implements webmvcconfigurer {

    /**
     * 配置跨域请求的映射规则
     * 
     * @param registry 用于注册 cors 配置的注册表
     */
    @override
    public void addcorsmappings(corsregistry registry) {
        // 添加跨域映射规则
        registry.addmapping("/**")  // 允许所有路径的跨域请求
                .allowedorigins("http://example.com")  // 允许来自 http://example.com 的跨域请求
                .allowedmethods("get", "post", "put", "delete")  // 允许的请求方法
                .allowedheaders("*")  // 允许所有请求头
                .allowcredentials(true);  // 允许携带凭证(如 cookies)
    }
}

4. 自定义 corsconfiguration

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 customcorsconfig implements webmvcconfigurer {

    @bean
    public corsconfigurationsource corsconfigurationsource() {
        corsconfiguration configuration = new corsconfiguration();
        configuration.setallowedorigins(arrays.aslist("http://example.com"));
        configuration.setallowedmethods(arrays.aslist("get", "post", "put", "delete"));
        configuration.setallowedheaders(arrays.aslist("*"));
        configuration.setallowcredentials(true);

        urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource();
        source.registercorsconfiguration("/**", configuration);

        return source;
    }
}

5. 实战

以下展示项目中的跨域

用 @autoconfiguration 进行自动配置

实现webmvcconfigurer 接口,并通过 filterregistrationbean 注册自定义的跨域过滤器 corsfilter 和其他过滤器

import org.springframework.boot.autoconfigure.autoconfiguration;
import org.springframework.boot.autoconfigure.condition.conditionalonproperty;
import org.springframework.boot.web.servlet.filterregistrationbean;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.web.filter.corsfilter;
import org.springframework.web.servlet.config.annotation.webmvcconfigurer;
import org.springframework.web.cors.corsconfiguration;
import org.springframework.web.cors.urlbasedcorsconfigurationsource;

@configuration
@autoconfiguration
@enableconfigurationproperties(webproperties.class)
public class webautoconfiguration implements webmvcconfigurer {

    /**
     * 创建一个 corsfilter 过滤器的 bean,配置跨域设置
     *
     * @return 配置了跨域设置的 filterregistrationbean
     */
    @bean
    public filterregistrationbean<corsfilter> corsfilterbean() {
        // 创建 corsconfiguration 对象
        corsconfiguration config = new corsconfiguration();
        config.setallowcredentials(true);  // 允许携带凭证(如 cookies)
        config.addallowedoriginpattern("*"); // 允许所有来源的请求(注意:生产环境中通常不建议使用 *,应具体配置允许的域)
        config.addallowedheader("*"); // 允许所有请求头
        config.addallowedmethod("*"); // 允许所有 http 方法(get, post, put, delete 等)

        // 创建 urlbasedcorsconfigurationsource 对象
        urlbasedcorsconfigurationsource source = new urlbasedcorsconfigurationsource();
        source.registercorsconfiguration("/**", config); // 对所有路径配置跨域设置

        // 创建并返回一个 filterregistrationbean 实例,注册 corsfilter
        return createfilterbean(new corsfilter(source), integer.min_value);
    }

    /**
     * 创建 demofilter bean,演示模式
     * 
     * @return 配置了 demofilter 的 filterregistrationbean
     */
    @bean
    @conditionalonproperty(value = "demo", havingvalue = "true")
    public filterregistrationbean<demofilter> demofilter() {
        // 创建并返回一个 filterregistrationbean 实例,注册 demofilter
        return createfilterbean(new demofilter(), integer.min_value);
    }

    /**
     * 创建 filterregistrationbean 实例的通用方法
     * 
     * @param filter 需要注册的过滤器实例
     * @param order  过滤器的执行顺序
     * @return 配置了过滤器的 filterregistrationbean 实例
     */
    public static <t extends filter> filterregistrationbean<t> createfilterbean(t filter, integer order) {
        filterregistrationbean<t> bean = new filterregistrationbean<>(filter);
        bean.setorder(order);  // 设置过滤器的顺序
        return bean;
    }
}

总结

处理方式适用场景配置位置灵活性配置难度
@crossorigin 注解单个控制器或方法控制器层
全局配置(webmvcconfigurer)全局设置配置类(webconfig)
自定义 corsconfiguration复杂跨域需求配置类(customcorsconfig)

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com