栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring Boot 配置CROS Filter

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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;
 

@Configuration
public class CorsConfig extends WebMvcConfigurerAdapter {
    static final String ORIGINS[] = new String[] { "GET", "POST", "PUT", "DELETE" };
    @Override
    public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("

@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;  
        
        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;
        }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/390097.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号