过滤器和拦截器处理跨域问题
1、过滤器,固定格式,只需要添加下面的配置类即可
<!-- For Maven -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
import org. springframework. context. annotation. Bean ;
import org. springframework. context. annotation. Configuration ;
import org. springframework. web. cors. CorsConfiguration ;
import org. springframework. web. cors. UrlBasedCorsConfigurationSource ;
import org. springframework. web. filter. CorsFilter ; @Configuration
public class CorsConfig { @Bean public CorsFilter corsFilter ( ) { CorsConfiguration corsConfiguration = new CorsConfiguration ( ) ; corsConfiguration. addAllowedOrigin ( "*" ) ; corsConfiguration. addAllowedHeader ( "*" ) ; corsConfiguration. addAllowedMethod ( "*" ) ; corsConfiguration. setAllowCredentials ( true ) ; corsConfiguration. setMaxAge ( 3600L ) ; UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource ( ) ; source. registerCorsConfiguration ( "/**" , corsConfiguration) ; return new CorsFilter ( source) ; }
}
CorsConfiguration 是 Spring 提供的一个现成的类,用于配置跨域请求的相关设置。不需要我们自己实现UrlBasedCorsConfigurationSource 这是 Spring 提供的一个类,用于将 CorsConfiguration
应用于特定的 URL 路径。CorsFilter 这是 Spring 提供的一个过滤器,用于处理跨域请求。
2、拦截器,在配置类中重写addCorsMappings
方法
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 CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings ( CorsRegistry registry) { registry. addMapping ( "/**" ) . allowedOriginPatterns ( "*" ) . allowedMethods ( "GET" , "POST" , "PUT" , "DELETE" , "OPTIONS" , "HEAD" ) . allowCredentials ( true ) . maxAge ( 3600 ) . allowedHeaders ( "*" ) ; }
}