您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關java項目中使用Cors實現后端跨域的法,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
代碼如下:
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即可
<filter> <filter-name>corsFilter</filter-name> <filter-class>com.lvluo.web.filter.CorsFilter</filter-class> </filter> <filter-mapping> <filter-name>corsFilter</filter-name> <url-pattern>/api/*</url-pattern> </filter-mapping>
前端測試的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實現后端跨域的法有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。