spring处理跨域问题

it2026-02-10  2

跨域(CORS)是什么?

CORS是一个W3C标准,全称是”跨域资源共享”(Cross-origin resource sharing),允许浏览器向跨源服务器。它通过服务器增加一个特殊的Header[Access-Control-Allow-Origin]来告诉客户端跨域的限制,如果浏览器支持CORS、并且判断Origin通过的话,就会允许XMLHttpRequest发起跨域请求。

请求头示范:

CROS Header解释Access-Control-Allow-Origin: http://www.xxx.com允许http://www.xxx.com域(自行设置,这里只做示例)发起跨域请求Access-Control-Max-Age:86400设置在86400秒不需要再发送预校验请求ccess-Control-Allow-Methods:GET, POST, OPTIONS, PUT, DELETE设置允许跨域请求的方法Access-Control-Allow-Headers: content-type允许跨域请求包含content-typeAccess-Control-Allow-Credentials: true设置允许Cookie

怎么解决?

1)请求接口中贴上注解@CrossOrigin

可以贴在类上,也可以贴在方法上,

也可以写一个controller贴上这个注解,所有的接口类都继承这个这个controller,这样也可以实现

这个得在spring4.2,jdk1.8以上才能使用,又一定的版本 限制,并且每个都贴,开发稍微麻烦

2)编写配置类实现

import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class CorsConfig extends WebMvcConfigurerAdapter { //请求方式 static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" }; @Override public void addCorsMappings(CorsRegistry registry) { //分别代表的是所有的请求,所有的origins,允许cookie,GET,POST,PUT,DELETE方法,设置在3600秒不需要再发送预校验请求 registry.addMapping("/**").allowedOrigins("*").allowCredentials(true).allowedMethods(ORIGINS).maxAge(3600); } }

3)编写过滤器的方式

@Component public class CORSFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) response; // 设置允许Cookie res.addHeader("Access-Control-Allow-Credentials", "true"); // 允许http://www.xxx.com域(自行设置,这里只做示例,设置的是全部)发起跨域请求, res.addHeader("Access-Control-Allow-Origin", "*"); // 设置允许跨域请求的方法 res.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT"); // 允许跨域请求包含content-type res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN"); if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) { return; } chain.doFilter(request, response); } @Override public void destroy() { } @Override public void init(FilterConfig filterConfig) throws ServletException { } }

4)springboot集成设置(设置bean对象使用)

@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Bean public WebMvcConfigurer webMvcConfigurer() { return new WebMvcConfigurer() { @Override public void addCorsMappings(CorsRegistry registry) { //这里默认我是开始全部,设置参数内容看上文就行了 registry.addMapping("/**").allowedHeaders("*").maxAge(3600).allowedMethods("GET","PUT","POST","DELETE"); } }; } }

 

最新回复(0)