目標:tomcat服務器提供的接口,不能在其他域中訪問的時候,需要增 Access-Control-Allow-Origin:*
直接配置的方法很多,但是我一個沒有成功過,所以只能自己寫攔截器了。
1. 編寫攔截器代碼
新建一個類,實現Filter接口,代碼如下
package com.itxc.filter; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CORSFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; httpResponse.addHeader("Access-Control-Allow-Origin", "*"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }
2. 配置web.xml
<filter> <filter-name>CorsFilter</filter-name> <filter-class>com.itxc.filter.CORSFilter</filter-class> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
3. 刪除你之前為了這個功能配置的亂起八糟的配置吧
搞定,收工