1. 什么是跨域
2. Spring Boot 3解决跨域问题的方法概述
-
使用@CrossOrigin注解 -
全局配置跨域 -
使用过滤器(Filter) -
使用CORS配置类
3. 使用@CrossOrigin注解解决跨域问题
示例代码
public class ExampleController {public ResponseEntity<String> greeting() {return ResponseEntity.ok("Hello, World!");}}
4. 全局配置跨域
示例代码
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;@Configurationpublic class WebConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {registry.addMapping("/**").allowedOrigins("http://example.com").allowedMethods("GET", "POST", "PUT", "DELETE").allowedHeaders("*").allowCredentials(true);}}
5. 使用过滤器解决跨域问题
示例代码
import org.springframework.context.annotation.Configuration;import org.springframework.web.filter.CorsFilter;import org.springframework.context.annotation.Bean;import org.springframework.core.Ordered;import org.springframework.core.annotation.Order;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;public class CorsConfig {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);}}
6. 使用CORS配置类解决跨域问题
示例代码
import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.web.SecurityFilterChain;import org.springframework.web.cors.CorsConfiguration;import org.springframework.web.cors.UrlBasedCorsConfigurationSource;import org.springframework.web.filter.CorsFilter;public class SecurityConfig {public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {http.cors().and().csrf().disable();return http.build();}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);}}
在此配置中,我们首先禁用了CSRF保护(仅在确实需要时),然后配置了CORS过滤器。
7. 总结
在Spring Boot 3中,有多种方法可以解决跨域问题,包括使用@CrossOrigin注解、全局配置、过滤器和CORS配置类等。选择合适的方法取决于具体的需求和项目的复杂性。

点“在看”支持码农呀,谢谢啦

本篇文章来源于微信公众号: 新生代码农
微信扫描下方的二维码阅读本文

Comments NOTHING