方式一:添加CORS过滤器
在项目中添加配置类,自动运行过滤请求
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 CorsConfig2 {
@Bean
public CorsFilter corsFilter(){
CorsConfiguration corsConfiguration = new CorsConfiguration();
// 允许那些域访问
corsConfiguration.addAllowedOrigin("*");
//请求头
corsConfiguration.addAllowedHeader("*");
//请求头方式 GET POST 等类型
corsConfiguration.addAllowedMethod("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//映射路径
source.registerCorsConfiguration("/**",corsConfiguration);
//创建CorsFilter
return new CorsFilter(source);
}
}
方式二:实现WebMvcConfigure接口,重写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("/**") // 所有的当前站点的请求地址,都支持跨域访问。
.allowedOrigins("*") // 所有的外部域都可跨域访问。
.allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")// 当前站点支持的跨域请求方式
.allowCredentials(true) // 是否支持跨域用户凭证,支持cookie
.maxAge(3600)// 跨域允许时间。 时间单位是秒。
.allowedHeaders("*");
System.out.println("跨域已释放");
}
}
总结
以上就是今天要讲的内容,本文仅仅简单介绍了2种解决Java跨域问题的使用。