写了一个前端vue调用后端Java的接口,报“Access-Control-Allow-Origin”问题。
原因是因为在Java后端接口没有处理Access-Control-Allow-Origin.
① 下载处理Access-Control-Allow-Origin的2个Jar包,
然后放入 WebRoot\WEB-INF\lib下
②在web.xml文件添加如下
1 23 14CORS 4com.thetransactioncompany.cors.CORSFilter 56 9cors.supportedHeaders 7Content-Type,Accept,Origin 810 13cors.supportedMethods 11GET, POST, HEAD, PUT, DELETE, OPTIONS 1215 18CORS 16/* 1719 22AccessControlFilter 20com.xx.xx.filter.AccessControlFilter 2123 26AccessControlFilter 24* 25
③ 在 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 @Override15 public void init(FilterConfig req) throws ServletException {16 System.out.println("Access Control Allow Init");17 }18 19 @Override20 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 @Override28 public void destroy() {29 System.out.println("Access Control Allow Destroy");30 }31 32 }
最后验证,运行成功!