JAVA跨域CORS
写了一个前端vue调用后端Java的接口,报“Access-Control-Allow-Origin”问题。
原因是因为在Java后端接口没有处理Access-Control-Allow-Origin.
① 下载处理Access-Control-Allow-Origin的2个Jar包,下载地址
然后放入 WebRoot\WEB-INF\lib下
②在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 }
最后验证,运行成功!