在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使配置生效。