在Tomcat中配置跨域访问,可以通过修改Tomcat的配置文件或者在代码中进行设置。
<!-- ==================== Default MIME Type Mappings ==================== -->
在该代码块下面添加以下代码:
<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</param-value>
</init-param>
<init-param>
<param-name>cors.allowed.headers</param-name>
<param-value>Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers</param-value>
</init-param>
这样配置允许所有的域名跨域访问,同时也可以按需修改allowed.methods和allowed.headers。
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,HEAD,OPTIONS,PUT");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers");
同样地,这样设置也允许所有的域名跨域访问,可以根据实际需求修改allowed.methods和allowed.headers。
配置完成后,重启Tomcat使配置生效。