信息发布→ 登录 注册 退出

教你用Java SpringBoot如何解决跨域

发布时间:2026-01-11

点击量:
目录
  • 跨域
    • 什么是跨域
  • CORS
    • SpringBoot解决跨域方案
      • 1.使用@CrossOrigin注解
      • 2.Spring框架全局配置CORS配置
    • 具体实现
      • 1.使用@CrossOrigin注解
        • 1.1目录结构
        • 1.2运行结果
      • 2.使用@CrossOrigin注解
        • 2.1Spring MVC CORS 使用WebMvcConfigurerAdapter配置!
        • 2.3Spring Boot CORS 使用WebMvcConfigurer配置
        • 2.4CORS 使用Spring Security配置
    • 代码获取
      • 参考链接
        • 总结

          跨域

          什么是跨域

          请求url的协议,域名,端口三者之间任意一个与当前页面url不同的即为跨域。

          CORS

          CORS(Cross-origin resource sharing-跨源资源共享)允许网页从其他域向浏览器请求额外的资源

          SpringBoot解决跨域方案

          1.使用@CrossOrigin注解

          该注解添加在你想要让某接口允许跨域的的,类上面,或者实现方法上面。

          该注解包含的属性:orgins,allowdHeaders,methods,exposedHeaders,allowCreden,maxAge。

          2.Spring框架全局配置CORS配置

          2.1Spring MVC CORS 使用WebMvcConfigurerAdapter配置!

          2.2Spring Boot CORS 使用WebMvcConfigurer配置!

          2.3CORS 使用Spring Security配置!

          具体实现

          1.使用@CrossOrigin注解

          1.1目录结构

          DemoApplication.java

          package com.example.crossdomain.demo;
          import org.springframework.boot.SpringApplication;
          import org.springframework.boot.autoconfigure.SpringBootApplication;
          @SpringBootApplication
          public class DemoApplication {
              public static void main(String[] args) {
                  SpringApplication.run(DemoApplication.class, args);
              }
          }
          

          CorsTestController.java

          package com.example.crossdomain.demo.controller;
          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;
          @RequestMapping("/demo")
          @RestController
          @CrossOrigin("https://blog.csdn.net") // 只有指定域名可以访问该类下所有接口
          public class CorsTestController {
              @GetMapping("/sayHello")
              public String sayHello(){
                  return "Hello world";
              }
          }
          

          1.2运行结果


          2.使用@CrossOrigin注解

          2.1Spring MVC CORS 使用WebMvcConfigurerAdapter配置!

          2.1.1目录结构

          2.2.2添加CorsConfiguration.java

          package com.example.crossdomain.demo.config;
          import org.springframework.context.annotation.Configuration;
          import org.springframework.web.servlet.config.annotation.CorsRegistry;
          import org.springframework.web.servlet.config.annotation.EnableWebMvc;
          import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
          import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
          @Configuration
          @EnableWebMvc
          public class CorsConfiguration extends WebMvcConfigurerAdapter {
              @Override
              public void addCorsMappings(CorsRegistry registry) {
                  registry.addMapping("/**")
                          .allowedMethods("GET", "POST");
              }
          }
          

          2.2.3运行结果


          2.3Spring Boot CORS 使用WebMvcConfigurer配置

          package com.example.crossdomain.demo.config;
          import org.springframework.context.annotation.Bean;
          import org.springframework.context.annotation.Configuration;
          import org.springframework.web.servlet.config.annotation.*;
          @Configuration
          public class CorsConfiguration
          {
              @Bean
              public WebMvcConfigurer corsConfigurer()
              {
                  return new WebMvcConfigurerAdapter() {
                      @Override
                      public void addCorsMappings(CorsRegistry registry) {
                          registry.addMapping("/**");
                      }
                  };
              }
          }
          

          2.4CORS 使用Spring Security配置

          2.4.1目录结构


          2.4.2添加WebSecurityConfig.java

          package com.example.crossdomain.demo.config;
          
          import org.springframework.context.annotation.Bean;
          import org.springframework.security.config.annotation.web.builders.HttpSecurity;
          import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
          import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
          import org.springframework.web.cors.CorsConfiguration;
          import org.springframework.web.cors.CorsConfigurationSource;
          import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
          import java.util.Arrays;
          @EnableWebSecurity
          public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
              @Override
              protected void configure(HttpSecurity http) throws Exception {
                  http.cors();
              }
              @Bean
              CorsConfigurationSource corsConfigurationSource()
              {
                  CorsConfiguration corsConfiguration = new CorsConfiguration();
                  corsConfiguration.addAllowedOrigin("*");	//同源配置,*表示任何请求都视为同源,若需指定ip和端口可以改为如“localhost:8080”,多个以“,”分隔;
                  corsConfiguration.addAllowedHeader("*");//header,允许哪些header,本案中使用的是token,此处可将*替换为token;
                  corsConfiguration.addAllowedMethod("*");	//允许的请求方法,PSOT、GET等
                  UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
                  source.registerCorsConfiguration("/**", corsConfiguration);
                  return source;
              }
          }
          

          2.4.3运行结果


          代码获取

          码云

          参考链接

          什么是跨域?跨域解决方法

          Spring boot 入门之CORS 跨域配置详解

          总结

          本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!

          在线客服
          服务热线

          服务热线

          4008888355

          微信咨询
          二维码
          返回顶部
          ×二维码

          截屏,微信识别二维码

          打开微信

          微信号已复制,请打开微信添加咨询详情!