今天就跟大家聊聊有關java項目中使用Cors實現(xiàn)后端跨域的法,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據(jù)這篇文章可以有所收獲。
網(wǎng)站建設哪家好,找創(chuàng)新互聯(lián)!專注于網(wǎng)頁設計、網(wǎng)站建設、微信開發(fā)、微信平臺小程序開發(fā)、集團企業(yè)網(wǎng)站建設等服務項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了諸暨免費建站歡迎大家使用!
代碼如下:
package com.lvluo.web.filter.CorsFilter; 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.springframework.http.HttpHeaders; public class CorsFilter implements Filter { public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method"; public static final String OPTIONS = "OPTIONS"; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpServletResponse httpResponse = (HttpServletResponse) response; if (isCorsRequest(httpRequest)) { httpResponse.setHeader("Access-Control-Allow-Origin", "*"); httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE"); httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); // response.setIntHeader("Access-Control-Max-Age", 1728000); httpResponse .setHeader( "Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Authorization"); if (isPreFlightRequest(httpRequest)) { return; } } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) { } public void destroy() { } public boolean isCorsRequest(HttpServletRequest request) { return (request.getHeader(HttpHeaders.ORIGIN) != null); } /** * Returns {@code true} if the request is a valid CORS pre-flight one. */ public boolean isPreFlightRequest(HttpServletRequest request) { return (isCorsRequest(request) && OPTIONS.equals(request.getMethod()) && request .getHeader(ACCESS_CONTROL_REQUEST_METHOD) != null); } }
接著在web.xml配置filter即可
corsFilter com.lvluo.web.filter.CorsFilter corsFilter /api/*
前端測試的JS代碼,其中客戶端的
$.ajax({ headers : { 'Authorization' :'Bearer iBoxSO9QdrHR0' }, url: 'http://localhost:8080/service/api/ping', type: 'GET', dataType: 'json', success : function(result){ $("#result").html(result.code); } })
看完上述內容,你們對java項目中使用Cors實現(xiàn)后端跨域的法有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。