【Java】Tomcat跨域配置
1、Tomcat 7 跨域配置
Tomcat 7 前几个版本是不支持,所以引入cors-filter-1.7.jar,java-property-utils-1.9.jar。
链接:https://pan.baidu.com/s/1UDJ1RnDx8vCAQV8pwLxQNw
提取码:3ao1
配置项目中 web.xml
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.allowOrigin</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, POST, HEAD, PUT, DELETE</param-value>
</init-param>
<init-param>
<param-name>cors.supportedHeaders</param-name>
<param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
</init-param>
<init-param>
<param-name>cors.exposedHeaders</param-name>
<param-value>Set-Cookie</param-value>
</init-param>
<init-param>
<param-name>cors.supportsCredentials</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2、Tomcat8 跨域配置
修改 web.xml
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
<init-param>
<param-name>cors.allowed.origins</param-name>
<param-value>*</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.methods</param-name>
<param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
范围
1、如果使Tomcat下所有项目都支持跨域,则修改 tomcat根目录\conf\web.xml
2、如果只是使某一个项目支持跨域,则修改此项目的web.xml文件。注意需要引入tomcat根目录\lib\catalina.jar
官方文档
注:Tomcat7后面版本也支持跨域,可以检查lib\catalina.jar
中是否包含org.apache.catalina.filters.CorsFilter
好学若饥,谦卑若愚