Spring Boot 配置CROS Filter
Posted 在奋斗的大道
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring Boot 配置CROS Filter相关的知识,希望对你有一定的参考价值。
一、什么是CORS?
CORS是一个W3C标准,全称是”跨域资源共享”(Cross-origin resource sharing),允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。
它通过服务器增加一个特殊的Header[Access-Control-Allow-Origin]来告诉客户端跨域的限制,如果浏览器支持CORS、并且判断Origin通过的话,就会允许XMLHttpRequest发起跨域请求。
CORS Header
- Access-Control-Allow-Origin: http://www.xxx.com
- Access-Control-Max-Age:86400
- Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, DELETE
- Access-Control-Allow-Headers: content-type
- Access-Control-Allow-Credentials: true
含义解释:
二、SpringBoot跨域请求处理方式
方式一、直接采用SpringBoot的注解@CrossOrigin(也支持SpringMVC)
Controller层在需要跨域的类或者方法上加上该注解即可
实战:
备注说明:Spring 版本必须大于等于4.2
方法二、处理跨域请求的Configuration
增加一个配置类CrossOriginConfig.java。继承WebMvcConfigurerAdapter或者实现WebMvcConfigurer接口
实战:
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* AJAX请求跨域
*/
@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" };
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowCredentials(true)
.allowedMethods(ORIGINS)
.maxAge(3600);
}
方法三、采用过滤器(filter)的方式(推荐)
增加一个CORSFilter 类,并实现Filter接口即可
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
/**
*
* @ClassName: CorsFilter
* @Description: SpringBoot 跨域处理拦截器
*/
@Component
public class CROSFilter implements Filter {
public static final Logger logger = LoggerFactory.getLogger(CROSFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest reqs = (HttpServletRequest) req;
/*
* 跨域设置允所有请求跨域
* 如果允许指定的客户端跨域设置: http://127.0.0.1:8020
*/
response.setHeader("Access-Control-Allow-Origin","*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
if (((HttpServletRequest) req).getMethod().equals("OPTIONS")) {
response.getWriter().println("ok");
return;
}
chain.doFilter(req, res);
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
解决遇到的错误
1、Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.
解决办法:
response.setHeader("Access-Control-Allow-Headers", "Content-Type");
2、Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
解决办法:
if (((HttpServletRequest) req).getMethod().equals("OPTIONS")) {
response.getWriter().println("ok");
return;
}
以上是关于Spring Boot 配置CROS Filter的主要内容,如果未能解决你的问题,请参考以下文章
Spring Boot参考教程Spring Boot配置Servlet,Filter,Listener,Interceptor
Spring Boot使用嵌入式容器,自定义Filter如何配置?
Spring Boot使用嵌入式容器,那怎么配置自定义Filter呢