什么是跨域问题?
跨域问题来源于JavaScript的"同源策略",即只有 协议+主机名+端口号 (如存在)相同,则允许相互访问。也就是说JavaScript只能访问和操作自己域下的资源,不能访问和操作其他域下的资源。跨域问题是针对JS和ajax的,html本身没有跨域问题。
查看浏览器开发者工具Console报错:
Failed to load http://a.a.com:8080/A/FromServlet?userName=123: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://b.b.com:8080' is therefore not allowed access.
案例:
http://www.abc.com/a/b
调用 http://www.abc.com/d/c
(非跨域)
http://www.abc.com/a/b
调用 http://www.def.com/a/b
(跨域:域名不一致)
http://www.abc.com:8080/a/b
调用 http://www.abc.com:8081/d/c
(跨域:端口不一致)
http://www.abc.com/a/b
调用 https://www.abc.com/d/c
(跨域:协议不同)
localhost 和 127.0.0.1 也可能存在跨域问题
解决跨域问题
常用方式:设置过滤器
1、引入servlet-api的依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
2,编写跨域处理的过滤器
package com.gxa.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
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 req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request= (HttpServletRequest) req;
HttpServletResponse response= (HttpServletResponse) res;
/* 允许跨域的主机地址 */
response.setHeader("Access-Control-Allow-Origin", "*");
/* 允许跨域的请求方法GET, POST, HEAD 等 */
response.setHeader("Access-Control-Allow-Methods", "*");
/* 重新预检验跨域的缓存时间 (s) */
response.setHeader("Access-Control-Max-Age", "3600");
/* 允许跨域的请求头 */
response.setHeader("Access-Control-Allow-Headers", "*");
/* 是否携带cookie */
response.setHeader("Access-Control-Allow-Credentials", "true");
//判断前端发送的是否是预请求,如果是,直接返回,并且告诉他允许的请求方式
if("OPTIONS".equalsIgnoreCase(request.getMethod())) {
return;
}
chain.doFilter(request,response);
}
@Override
public void destroy() {
}
}
3,在web.xml中注册过滤器
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>com.gxa.filter.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
这样,前后端就可以解决跨域问题了
标签:www,abc,http,跨域,问题,Ajax,com,response From: https://blog.51cto.com/qiux/6938041