SpringBoot如何配置CROS Filter
一、什么是CORS?
CORS是一個(gè)W3C標(biāo)準(zhǔn),全稱是”跨域資源共享”(Cross-origin resource sharing),允許瀏覽器向跨源服務(wù)器,發(fā)出XMLHttpRequest請(qǐng)求,從而克服了AJAX只能同源使用的限制。
它通過服務(wù)器增加一個(gè)特殊的Header[Access-Control-Allow-Origin]來告訴客戶端跨域的限制,如果瀏覽器支持CORS、并且判斷Origin通過的話,就會(huì)允許XMLHttpRequest發(fā)起跨域請(qǐng)求。
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跨域請(qǐng)求處理方式
方式一
直接采用SpringBoot的注解@CrossOrigin(也支持SpringMVC)
Controller層在需要跨域的類或者方法上加上該注解即可
實(shí)戰(zhàn):

備注說明:Spring 版本必須大于等于4.2
方法二
處理跨域請(qǐng)求的Configuration
增加一個(gè)配置類CrossOriginConfig.java。
繼承WebMvcConfigurerAdapter或者實(shí)現(xiàn)WebMvcConfigurer接口
實(shí)戰(zhàn):
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
* AJAX請(qǐng)求跨域
*/
@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)的方式(推薦)
增加一個(gè)CORSFilter 類,并實(shí)現(xiàn)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;
/*
* 跨域設(shè)置允所有請(qǐng)求跨域
* 如果允許指定的客戶端跨域設(shè)置: 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
}
}解決遇到的錯(cuò)誤
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;
}總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
mybatis自動(dòng)建表的實(shí)現(xiàn)方法
這篇文章主要介紹了mybatis自動(dòng)建表的實(shí)現(xiàn)方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
Spring?Boot?Shiro?auto-configure工作流程詳解
這篇文章主要為大家介紹了Spring?Boot?Shiro?auto-configure工作流程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
java實(shí)現(xiàn)學(xué)生選課系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)學(xué)生選課系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-02-02
SpringBoot整合mybatis-plus進(jìn)階詳細(xì)教程
本文主要對(duì)mybatis-plus的條件構(gòu)造器、AR模式、插件、逆向工程、自定義全局操作、公共字段自動(dòng)填充等知識(shí)點(diǎn)進(jìn)行講解,需要的朋友參考下吧2021-09-09
使用Lucene實(shí)現(xiàn)一個(gè)簡(jiǎn)單的布爾搜索功能
Lucene是一個(gè)全文搜索框架,而不是應(yīng)用產(chǎn)品。因此它并不像www.baidu.com 或者google Desktop那么拿來就能用,它只是提供了一種工具讓你能實(shí)現(xiàn)這些產(chǎn)品。接下來通過本文給大家介紹使用Lucene實(shí)現(xiàn)一個(gè)簡(jiǎn)單的布爾搜索功能2017-04-04

