寫了一個前端vue調用後端Java的接口,報「Access-Control-Allow-Origin」問題。前端
緣由是由於在Java後端接口沒有處理Access-Control-Allow-Origin.vue
① 下載處理Access-Control-Allow-Origin的2個Jar包,下載地址java
而後放入 WebRoot\WEB-INF\lib下web
②在web.xml文件添加以下後端
1 <!-- 跨域處理 開始--> 2 <filter> 3 <filter-name>CORS</filter-name> 4 <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class> 5 <init-param> 6 <param-name>cors.supportedHeaders</param-name> 7 <param-value>Content-Type,Accept,Origin</param-value> 8 </init-param> 9 <init-param> 10 <param-name>cors.supportedMethods</param-name> 11 <param-value>GET, POST, HEAD, PUT, DELETE, OPTIONS</param-value> 12 </init-param> 13 </filter> 14 <filter-mapping> 15 <filter-name>CORS</filter-name> 16 <url-pattern>/*</url-pattern> 17 </filter-mapping> 18 <filter> 19 <filter-name>AccessControlFilter</filter-name> 20 <filter-class>com.xx.xx.filter.AccessControlFilter</filter-class> 21 </filter> 22 <filter-mapping> 23 <filter-name>AccessControlFilter</filter-name> 24 <url-pattern>*</url-pattern> 25 </filter-mapping> 26 <!-- 跨域處理 結束 -->
③ 在 com.xx.xx.filter包下新建AccessControlFilter.class文件跨域
1 package com.cdsoft.platform.filter; 2 import java.io.IOException; 3 4 import javax.servlet.Filter; 5 import javax.servlet.FilterChain; 6 import javax.servlet.FilterConfig; 7 import javax.servlet.ServletException; 8 import javax.servlet.ServletRequest; 9 import javax.servlet.ServletResponse; 10 import javax.servlet.http.HttpServletResponse; 11 12 13 public class AccessControlFilter implements Filter { 14 @Override 15 public void init(FilterConfig req) throws ServletException { 16 System.out.println("Access Control Allow Init"); 17 } 18 19 @Override 20 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) 21 throws IOException, ServletException { 22 HttpServletResponse response = (HttpServletResponse)resp; 23 response.setHeader("Access-Control-Allow-Origin", "*"); 24 chain.doFilter(req, resp); 25 } 26 27 @Override 28 public void destroy() { 29 System.out.println("Access Control Allow Destroy"); 30 } 31 32 }
最後驗證,運行成功!app