JS跨域请求外部服务器的资源

编程学习 2021-07-04 19:20www.dzhlxh.cn编程入门
这篇文章主要介绍了JS跨域请求外部服务器的资源,非常不错,具有参考借鉴价值,需要的朋友参考下吧

tomcat服务器提供的接口,不能在其他域中访问的时候,需要增 Access-Control-Allow-Origin:*

以下操作均在需要被访问的项目中设置

1、编写拦截器代码

 package com.soft.filter;
/**
 * Created by Administrator on 2017/2/6.
 */
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 httpResponse = (HttpServletResponse) servletResponse;
    httpResponse.addHeader("Access-Control-Allow-Origin", "*");
    filterChain.doFilter(servletRequest, servletResponse);
  }
  @Override
  public void destroy() {
  }
}

2、配置web.xml

<filter>
  <filter-name>CorsFilter</filter-name>
  <filter-class>com.omiaozu.manager.filter.CORSFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>CorsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板