Springboot设置跨域的三种方式
方式一(精细配置)
在需要跨域的整个Controller或者单个方法上添加@CrossOrigin注解
方式二(全局配置)
第一种写法
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 {
private CorsConfiguration buildConfig() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
corsConfiguration.addAllowedHeader("*"); // 2允许任何头
corsConfiguration.addAllowedMethod("*"); // 3允许任何方法(post、get等)
return corsConfiguration;
}
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", buildConfig()); // 4
return new CorsFilter(source);
}
}
第二种写法
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
.maxAge(3600)
.allowCredentials(true);
}
}
方式三(通过filter)
@Component
@WebFilter(urlPatterns = "/*", filterName = "authFilter") //这里的“/*” 表示的是需要拦截的请求路径
public class PassHttpFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException { }
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletResponse httpResponse = (HttpServletResponse)servletResponse;
httpResponse.setHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpResponse.addHeader("Access-Control-Allow-Origin", "http://127.0.0.1:8080");
filterChain.doFilter(servletRequest, httpResponse);
}
@Override
public void destroy() { }
}
相关文章
- SpringBoot扫描包提示找不到mapper的问题
- SpringBoot 跨域 Access-Control-Allow-Origin
- Java Demo示例:Springboot解决Access-Control-Allow-Origin跨域问题、浏览器同源策略详解
- springboot集成kafka及kafka web UI的使用
- Springboot跨域和SpringCloud跨域
- 【SpringBoot笔记10】SpringBoot框架集成Druid数据源
- 【SpringBoot笔记14】SpringBoot框架之RestTemplate对象及其常用方法
- 【SpringBoot笔记20】SpringBoot跨域问题之CORS的四种解决方案
- SpringBoot跨域问题解决
- 【最全最详细】SpringBoot 中实现跨域的几种方式
- springboot单元测试采坑记录
- Kotlin — Springboot 与 Kotlin构建Web应用程序
- Springboot项目Aop、拦截器、过滤器横向对比
- 【springboot】自动加载分析
- 【springboot】15、文件上传
- 【Springboot】Springboot集成 Druid
- 【java】springboot和springcloud区别