java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot配置CROS Filter

SpringBoot如何配置CROS Filter

作者:在奋斗的大道

这篇文章主要介绍了SpringBoot如何配置CROS Filter问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

一、什么是CORS?

CORS是一个W3C标准,全称是”跨域资源共享”(Cross-origin resource sharing),允许浏览器向跨源服务器,发出XMLHttpRequest请求,从而克服了AJAX只能同源使用的限制。

它通过服务器增加一个特殊的Header[Access-Control-Allow-Origin]来告诉客户端跨域的限制,如果浏览器支持CORS、并且判断Origin通过的话,就会允许XMLHttpRequest发起跨域请求。

CORS Header 

含义解释:

 二、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;
        }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文