GET和POST请求是简单请求,AJAX只发起一次,所以设置了响应头和路由就可以实现。而PUT和DELETE等请求是复杂请求,会提前发起一个 OPTIONS 预请求,再发起PUT或DELETE请求,一共会发起两次请求。
写一个过滤器
实现代码:
先另创一个类:
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 { } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletResponse httpResponse = (HttpServletResponse) servletResponse; //*表示允许所有域名跨域 httpResponse.addHeader("Access-Control-Allow-Origin", "*"); httpResponse.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); //允许跨域的Http方法 httpResponse.addHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }
上述代码只是加了三个参数,接下来在web.xml配置:
<!--为了允许跨域访问--> <filter> <filter-name>CorsFilter</filter-name> <filter-class>com.mashang.test.test1.CORSFilter</filter-class> </filter> <filter-mapping> <filter-name>CorsFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
然后问题就解决了