跨域及解决方案
跨域:
指的是浏览器不能执行其他网站的脚本。它是由浏览器的同源策略造成的,是浏览器施加的安全限制。(通常在Ifream,ajax请求外网服务器产生该问题出现)
所谓的同源指:域名、协议、端口均相同。
例如:
http://ww.123.com/index.html 调用 http://www.123.com/server.php(非跨域)
http://www.123.com/index.html 调用 http://www.456.com/server.php(主域名不同:123/456,跨域)
http://abc.123.com/index.html 调用 http://def.123.com/server.php(子域名不同:abc/def,跨域)
http://www.123.com:8080/index.html 调用 http://www.123.com:8081/server.php(端口不同,跨域)
http://www.123.com/index.html 调用 https://www.123.com/server.php(协议不同,跨域)
注意:localhost和127.0.01都指向本机,但也属于跨域。
解决方案:
一、注解方式
Spring版本需要4.2以上,只需在spring-context.xml文件中添加如下配置即可,然后初始化时扫描这个文件<!-- 解决跨域请求问题,spring版本需4.2以上 -->
1 <mvc:cors> 2 <mvc:mapping path="/**/**" 3 allowed-origins="*" 4 allowed-methods="POST, GET, OPTIONS, DELETE, PUT" 5 allowed-headers="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With" 6 allow-credentials="true" /> 7 </mvc:cors> 8 9 <servlet> 10 <servlet-name>mvc-dispatcher</servlet-name> 11 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 12 <init-param> 13 <param-name>contextConfigLocation</param-name> 14 <param-value> 15 classpath:config/spring-*.xml 16 </param-value> 17 </init-param> 18 <load-on-startup>1</load-on-startup> 19 </servlet>
例:No 'Access-Control-Allow-Origin' header is present on the requested resource.'Ajax跨域访问解决方案问题
由于请求头部没有允许头为Access-Control-Allow-Origin的标签的请求,异常不出跨域问题
解决机制为,在允许的头设置里面新增Access-Control-Allow-Origin
二、拦截器方式
这种方法需要实现 Filter的doFilter方法,如下,即在web.xml文件中添加过滤器的配置,其中“ssm.util.filter.CORSFilter”是CORSFilter的引用位置
1 public class CORSFilter implements Filter { 2 3 @Override 4 public void init(FilterConfig var1) throws ServletException {} 5 6 @Override 7 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { 8 HttpServletResponse response = (HttpServletResponse) servletResponse; 9 response.addHeader("Access-Control-Allow-Origin", "*"); 10 filterChain.doFilter(servletRequest, servletResponse); 11 } 12 13 public void destroy() {} 14 }
<!--解决跨域访问-->
1 <filter> 2 <filter-name>CORSFilter</filter-name> 3 <filter-class>ssm.util.filter.CORSFilter</filter-class> 4 </filter> 5 <filter-mapping> 6 <filter-name>CORSFilter</filter-name> 7 <url-pattern>/*</url-pattern> 8 </filter-mapping>
参考博客:https://blog.csdn.net/lankezhou/article/details/72491019