SpringBoot系列---【统一解决跨域】
注意: CorFilter / WebMvConfigurer / @CrossOrigin 需要 SpringMVC 4.2以上版本才支持,对应springBoot 1.3版本以上。
1.重写WebMvcConfigurer(全局跨域)
import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpHeaders; 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("*"). //允许任何方法(post、get等) allowedMethods("*"). //允许任何请求头 allowedHeaders("*"). //带上cookie信息 allowCredentials(true). //maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果 exposedHeaders(HttpHeaders.SET_COOKIE).maxAge(3600L); } }
2.通过实现Fiter
接口在请求中添加一些Header
来解决跨域的问题
@Component public class CorsFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) response; res.addHeader("Access-Control-Allow-Credentials", "true"); res.addHeader("Access-Control-Allow-Origin", "*"); res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN"); if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) { response.getWriter().println("ok"); return; } chain.doFilter(request, response); } @Override public void destroy() { } @Override public void init(FilterConfig filterConfig) throws ServletException { } }
3.使用注解 @CrossOrigin,加在contrlller类上
愿你走出半生,归来仍是少年!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2021-01-28 SpringBoot系列---【yml配置文件中的值如何注入到java配置类中?】