SpringBoot 三步骤轻松解决跨域
来源:互联网 发布:万能网络摄像机客户端 编辑:程序博客网 时间:2024/06/07 03:29
1、添加maven依赖注解
<!--跨域需要的jar包--> <dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>java-property-utils</artifactId> <version>1.9.1</version> </dependency> <dependency> <groupId>com.thetransactioncompany</groupId> <artifactId>cors-filter</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency>
2、添加跨域请求配置类CorsConfig
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;@Configurationpublic class CorsConfig { private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); corsConfiguration.addAllowedOrigin("*"); // 1 corsConfiguration.addAllowedHeader("*"); // 2 corsConfiguration.addAllowedMethod("*"); // 3 return corsConfiguration; } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", buildConfig()); // 4 return new CorsFilter(source); }}
3、在接收到OPTIONS请求时候,需要返回状态码为202,并且设置响应头部(根据需求变更)
HttpServletResponse httpResponse = response; httpResponse.setCharacterEncoding("UTF-8"); httpResponse.setContentType("application/json; charset=utf-8"); httpResponse.setHeader("Access-Control-Allow-Origin","*"); httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); httpResponse.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,PATCH,PUT"); httpResponse.setHeader("Access-Control-Max-Age", "3600"); httpResponse.setHeader("Access-Control-Allow-Headers", "Origin,X-Requested-With,x-requested-with,X-Custom-Header," + "Content-Type,Accept,Authorization"); String method = request.getMethod(); if ("OPTIONS".equalsIgnoreCase(method)){ logger.info("OPTIONS请求"); httpResponse.setStatus(HttpServletResponse.SC_ACCEPTED); }
阅读全文
0 0
- SpringBoot 三步骤轻松解决跨域
- springBoot三分钟轻松撩到redis
- springboot解决跨域问题
- SpringBoot解决跨域问题
- SpringBoot(六):SpringBoot使用CROS解决跨域问题
- Spring跨域问题轻松解决
- 后端(springboot)解决跨域问题
- springboot项目解决跨域请求
- SpringBoot后台解决浏览器跨域问题
- springboot 解决跨域问题(options)
- 3个步骤轻松解决Java开发包的统一
- springboot中通过cors协议解决跨域问题
- springboot -- 通过cors协议解决跨域问题
- SpringBoot学习笔记(十):解决跨域问题
- springBoot之拦截器解决前端跨域问题
- SpringBoot(三)
- 三、解决Springboot集成ActivitiModel提示输入密码的问题
- SpringBoot轻松实现文件上传
- 算法6 Same Tree
- Log4j2简单配置
- 看图说话排序算法之冒泡排序
- 关于Matlab编程的一些小总结
- 关闭窗口的同时刷新父页面
- SpringBoot 三步骤轻松解决跨域
- mac 日常
- LeetCode: Max Area of Island
- 捕捉界面中的按键
- mysql的提交问题
- Keras FAQ:Frequently Asked Keras Questions
- js replace 替换全部
- ABAP参数传递USING和CHANGIN用法总结
- 常量指针与指针常量的区别(转帖)