什么情况下会有跨域问题?
1.不同域名。
2.同一域名不同端口号。
3.同一域名不同协议。
4.域名和对应ip等。
采用CORS(跨来源资源共享)解决跨域问题。
web.xml添加如下配置
<filter>
<filter-name>cors</filter-name>
<filter-class>com.rzg.dgztc.filter.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
添加CORSFilter 类
public class CORSFilter implements Filter{
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.addHeader("Access-Control-Allow-Headers", "accessToken, deviceId, authType, Origin, X-Requested-With, Content-Type, Accept");
chain.doFilter(req, res);
}
@Override
public void destroy() {
}
}