用Openlayers访问GeoServer发布的矢量切片是,出现跨域访问问题,即 CORS 头缺少 'Access-Control-Allow-Origin'
本人使用环境的版本是:GeoServer 2.18.1,OpenLayers 6.4.3
解决方法如下:
1.下载 cors-filter.jar 和 java-property-utils.jar,地址如下
https://mvnrepository.com/artifact/com.thetransactioncompany/cors-filter/2.9.1
https://mvnrepository.com/artifact/com.thetransactioncompany/java-property-utils/1.16
2.将下载的两个 jar包 拷贝至 tomcat 的安装路径下的 lib文件夹中,如:D:...apache-tomcat-9.0.41lib
3.添加 tomcat 的 web.xml 文件内容,路径为:D:...apache-tomcat-9.0.41confweb.xml
在 web.xml文件中定位到下面内容,
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
在定位内容的前面,添加下面的补充内容:
<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>
4.重启 tomcat,解决问题