Java 跨域問題的處理方式
問題
在頁面上要使用 Ajax 請求去獲取另外一個服務(wù)的數(shù)據(jù),由于瀏覽器的 同源策略,所以直接請求會得到一個 Error。
Failed to load https://www.baidu.com/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
大概就是這樣的一個錯誤,關(guān)鍵詞是 Access-Control-Allow-Origin,一般出現(xiàn)這個都是跨域問題。
解決方案
解決跨域問題的方式有很多,但這里之說 Cors 的方案。
在后臺添加一個 Filter 過濾器
/**
* 使用自定義的 Filter 攔截器實現(xiàn)跨域請求、
* 適用于所有的 Java Web 項目并且不局限于某個框架
* 注:此處的 @Component 僅為讓 Spring 知道這個 Bean, 不然攔截器不會加載
*
* @author rxliuli
*/
public class CustomCorsFilterConfig implements Filter {
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//允許所有來源
String allowOrigin = "*";
//允許以下請求方法
String allowMethods = "GET,POST,PUT,DELETE,OPTIONS";
//允許以下請求頭
String allowHeaders = "Content-Type,X-Token,Authorization";
//允許有認(rèn)證信息(cookie)
String allowCredentials = "true";
String origin = request.getHeader("Origin");
//此處是為了兼容需要認(rèn)證信息(cookie)的時候不能設(shè)置為 * 的問題
response.setHeader("Access-Control-Allow-Origin", origin == null ? allowOrigin : origin);
response.setHeader("Access-Control-Allow-Methods", allowMethods);
response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
response.setHeader("Access-Control-Allow-Headers", allowHeaders);
//處理 OPTIONS 的請求
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return;
}
filterChain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
在 web.xml 文件中添加攔截器配置(注:如果可能就配置成第一個 Filter)
<!--cors 跨域訪問--> <filter> <filter-name>customCorsFilterConfig</filter-name> <filter-class>CustomCorsFilterConfig</filter-class> </filter> <filter-mapping> <filter-name>customCorsFilterConfig</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
Spring Web 的解決方案
配置一個每次請求都過濾一次的 Filter 就好了
@Configuration
public class CorsConfig {
@Bean
public OncePerRequestFilter corsFilter() {
return new OncePerRequestFilter() {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//允許所有來源
String allowOrigin = "*";
//允許以下請求方法
String allowMethods = "GET,POST,PUT,DELETE,OPTIONS";
//允許以下請求頭
String allowHeaders = "Content-Type,X-Token,Authorization";
//允許有認(rèn)證信息(cookie)
String allowCredentials = "true";
String origin = request.getHeader("Origin");
//此處是為了兼容需要認(rèn)證信息(cookie)的時候不能設(shè)置為 * 的問題
response.setHeader("Access-Control-Allow-Origin", origin == null ? allowOrigin : origin);
response.setHeader("Access-Control-Allow-Methods", allowMethods);
response.setHeader("Access-Control-Allow-Credentials", allowCredentials);
response.setHeader("Access-Control-Allow-Headers", allowHeaders);
//處理 OPTIONS 的請求
if ("OPTIONS".equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return;
}
filterChain.doFilter(request, response);
}
};
}
}
使用示例
下面是一些簡單的使用 fetch 進(jìn)行跨域請求的示例:
- 簡單 fetch 請求,和正常使用 fetch 并無區(qū)別
fetch(url) .then(res => res.json()) .then(json => console.log(json))
- 表單請求
var fd = new FormData()
fd.append('username', 'rx')
fd.append('password', 'rx')
fetch(url, {
method: 'POST',
body: fd,
})
.then(res => res.json())
.then(json => console.log(json))
- 需要認(rèn)證的請求
fetch(url, {
/**
* 關(guān)鍵就在這里,代表用戶是否應(yīng)該在跨域的情況下發(fā)送 cookies 和 HTTP Basic authentication 等驗信息以及服務(wù)端能否返回 Set-Cookie(服務(wù)端 Session 需要使用這個向 cookie 中設(shè)置 sessionId)。
* 包含三個可選值:omit(從不發(fā)送), same-origin(同源才發(fā)送), include(總會發(fā)送)
* 參考鏈接:<https://developer.mozilla.org/zh-CN/docs/Web/API/Request/credentials>
*/
credentials: 'include',
})
.then(res => res.json())
.then(json => console.log(json))
注:如果想要服務(wù)端返回 Set-Cookie(SessionId 也需要通過這個響應(yīng)屬性去設(shè)置) 就必須設(shè)置這個請求參數(shù)!
那么,之后在前端跨域請求的時候就可以愉快地玩耍啦(v^_^)v
以上就是Java 跨域問題的處理方式的詳細(xì)內(nèi)容,更多關(guān)于Java 跨域的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
詳解Servlet入門級設(shè)置(超詳細(xì) IDEA2020版)
這篇文章主要介紹了詳解Servlet入門級設(shè)置(超詳細(xì) IDEA2020版),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11
MyBatis中resultMap和resultType的區(qū)別詳解
這篇文章主要介紹了MyBatis中resultMap和resultType的區(qū)別詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07
詳解Spring的兩種代理方式:JDK動態(tài)代理和CGLIB動態(tài)代理
這篇文章主要介紹了詳解Spring的兩種代理方式:JDK動態(tài)代理和CGLIB動態(tài)代理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04
SpringMVC整合,出現(xiàn)注解沒有起作用的情況處理
這篇文章主要介紹了SpringMVC整合,出現(xiàn)注解沒有起作用的情況及處理,具有很好的參考價值,希望對大家有所幫助。2023-05-05
logback如何去掉DubboMonitor煩人的INFO日志
這篇文章主要介紹了logback如何去掉DubboMonitor煩人的INFO日志方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
logback的使用和logback.xml詳解(小結(jié))
Logback是由log4j創(chuàng)始人設(shè)計的另一個開源日志組件,這篇文章主要介紹了logback的使用和logback.xml詳解(小結(jié)),非常具有實用價值,需要的朋友可以參考下2018-11-11
Spring?Boot?@Autowired?@Resource屬性賦值時機探究
這篇文章主要為大家介紹了Spring?Boot?@Autowired?@Resource屬性賦值時機,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07

