Spring Boot 中如何解决跨域问题

Spring Boot 中跨域问题是什么

    在Spring Boot中,跨域问题是指在浏览器上发送跨源请求时可能会遇到的问题。跨源请求是指通过浏览器发送请求到不同域的服务器。同源策略是浏览器的一种安全机制,限制了跨域请求的行为。如果请求的域与当前页面的域不同,浏览器会阻止请求的发送,从而导致跨域问题。

在Spring Boot中,可以通过配置和注解来解决跨域问题。以下是一些常用的解决方法:

  1. 在后端配置允许跨域请求的响应头信息。可以使用@CrossOrigin注解在控制器方法上设置允许跨域的域名、方法和头信息。

  2. 在Spring Security配置中配置允许跨域请求的规则。可以通过配置WebSecurityConfigurerAdapter类来实现。

  3. 使用WebMvcConfigurer接口来添加全局的跨域配置。可以重写addCorsMappings方法来设置允许跨域的规则。

  4. 在前端发送请求时,通过设置请求头信息来允许跨域请求。例如,在发送AJAX请求时,可以通过设置xhr.setRequestHeader('Access-Control-Allow-Origin', '*')来允许跨域请求。

需要注意的是,由于安全原因,浏览器限制了某些类型的跨域请求。例如,XMLHttpRequest对象只能发送同源的请求,而不能发送跨域请求。可以使用CORS(跨域资源共享)来允许跨域请求,但是需要服务器端和客户端都进行配置。

应用

     在 Spring Boot 中解决跨域问题,通常是为了允许不同来源的请求访问你的应用程序。跨域问题(CORS,即跨源资源共享)在 Web 开发中很常见,特别是在前端和后端分离的应用架构中。以下是解决跨域问题的几种常见方法:

1. **使用 `@CrossOrigin` 注解**

Spring Boot 提供了一个简单的方式来处理跨域请求,通过在控制器或方法上使用 `@CrossOrigin` 注解来配置跨域访问:

#### a. **全局配置**

如果你想要全局配置所有的跨域请求,可以在配置类中使用 `@CrossOrigin` 注解:


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 WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://example.com") // 允许的域
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 允许的方法
                .allowedHeaders("*") // 允许的头部
                .allowCredentials(true); // 允许携带凭证
    }
}

#### b. **局部配置**

你也可以在特定的控制器或方法上配置跨域:


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 backend";
    }
}


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 backend";
    }
}

 2. **使用 `CorsConfiguration` 类**

对于更复杂的跨域配置,你可以使用 `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 WebConfig implements WebMvcConfigurer {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("http://example.com")
                        .allowedMethods("GET", "POST", "PUT", "DELETE")
                        .allowedHeaders("*")
                        .allowCredentials(true);
            }
        };
    }
}

3. **使用 Spring Boot 的默认配置**

如果你使用的是 Spring Boot 2.4 或更高版本,你可以在 `application.properties` 或 `application.yml` 中配置跨域:

#### a. **`application.properties`**


spring.web.cors.allowed-origins=http://example.com
spring.web.cors.allowed-methods=GET,POST,PUT,DELETE
spring.web.cors.allowed-headers=*
spring.web.cors.allow-credentials=true

#### b. **`application.yml`**


spring:
  web:
    cors:
      allowed-origins: "http://example.com"
      allowed-methods: GET,POST,PUT,DELETE
      allowed-headers: "*"
      allow-credentials: true

4. **使用 `CorsFilter`**

如果需要更高级的控制,您可以创建一个 `CorsFilter` 组件:


import org.springframework.core.Ordered;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("http://example.com");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

 5. **使用 WebFlux**

如果你的应用程序使用 WebFlux,可以使用类似的方法配置跨域:


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.config.CorsRegistry;
import org.springframework.web.reactive.config.WebFluxConfigurer;

@Configuration
public class WebFluxConfig implements WebFluxConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://example.com")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

总结

  1. 在你的 Spring Boot 项目中,找到主配置类(通常是带有 @SpringBootApplication 注解的类)。
  2. 在该配置类上添加 @Configuration 注解。
  3. 在该配置类中添加一个名为 corsConfigurationSource 的方法,并使用 @Bean 注解进行标记。
  4. corsConfigurationSource 方法中创建一个 CorsConfiguration 实例,并进行相应的配置,如允许的请求源、允许的请求方法等。
  5. corsConfigurationSource 方法中创建一个 UrlBasedCorsConfigurationSource 实例,并将上一步中创建的 CorsConfiguration 实例添加到该实例中。
  6. urlPatterns 中添加一个路径匹配模式,指定需要跨域支持的路径。
  7. corsConfigurationSource 方法的最后,将 UrlBasedCorsConfigurationSource 实例返回。
  8. 重新启动你的 Spring Boot 应用程序,跨域问题应该已经解决了。

  • 14
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值