web後端跨域問題解決方案
阿新 • • 發佈:2019-01-29
1、首先寫一個工具類
2、在web.xml裡配置package com.custom.common.utils; 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 httpServletResponse= (HttpServletResponse) servletResponse; httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); httpServletResponse.setHeader("Access-Control-Allow-Methods", "*"); filterChain.doFilter(servletRequest, servletResponse); } @Override public void destroy() { } }
<!--跨域Start--> <filter> <filter-name>cors</filter-name> <filter-class>com.custom.common.utils.CorsFilter</filter-class> </filter> <filter-mapping> <filter-name>cors</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!--跨域End-->