目标: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. 删除你之前为了这个功能配置的乱起八糟的配置吧
搞定,收工
时间: 2024-10-20 14:12:27