欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-10-13 09:06:10
tomcat服务器提供的接口,不能在其他域中访问的时候,需要增 access-control-allow-origin:* 以下操作均在需要被访问的项目中设置 1、编写...

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>