OpenLayers跨域请求WFS服务在Tomcat环境下的实现

简介:

由于项目的地图数据放在不同的服务器上面,因此进行POI搜索和路径导航的时候需要进行跨域检索,容器环境用的是Tomcat 7.0.53.配置跨域请求的步骤为:

1. 下载Proxy.cgi,或者到Openlayers的安装目录中,安装盘符\OpenLayers-2.13.1\examples中查找,或者直接拷贝本文下面的代码到proxy.cgi文件中。并修改allowedHosts,添加需要访问的远程服务器地址:端口和本地IP地址:端口。最后把proxy.cgi文件放在CGI文件夹中,拷贝到网站WEB-INF目录下,如图所示

下面是proxy.cgi源码,其中192.168.1.18:8090','192.168.1.50:8080','192.168.1.49:8080','192.168.1.18:8080','localhost:8090'是本文添加的远程服务器地址和本地地址。

#!/usr/bin/envpython
 
 
"""Thisis a blind proxy that we use to get around browser
restrictionsthat prevent the Javascript from loading pages not on the
sameserver as the Javascript.  This hasseveral problems: it's less
efficient,it might break some sites, and it's a security risk because
peoplecan use this proxy to browse the web and possibly do bad stuff
withit.  It only loads pages via http andhttps, but it can load any
contenttype. It supports GET and POST requests."""
 
importurllib2
importcgi
importsys, os
 
#Designed to prevent Open Proxy type stuff.
 
allowedHosts= ['www.openlayers.org', 'openlayers.org',
                'labs.metacarta.com','world.freemap.in',
                'prototype.openmnnd.org','geo.openplans.org',
                'sigma.openplans.org', 'demo.opengeo.org',
                'www.openstreetmap.org','sample.azavea.com',
                'v2.suite.opengeo.org','v-swe.uni-muenster.de:8080',
                'vmap0.tiles.osgeo.org','www.openrouteservice.org',
                'maps.wien.gv.at','192.168.1.18:8090','192.168.1.50:8080','192.168.1.49:8080','192.168.1.18:8080','localhost:8090']
 
method= os.environ["REQUEST_METHOD"]
 
ifmethod == "POST":
    qs = os.environ["QUERY_STRING"]
    d = cgi.parse_qs(qs)
    if d.has_key("url"):
        url = d["url"][0]
    else:
        url ="http://www.openlayers.org"
else:
    fs = cgi.FieldStorage()
    url = fs.getvalue('url',"http://www.openlayers.org")
 
try:
    host = url.split("/")[2]
    if allowedHosts and not host inallowedHosts:
        print "Status: 502 BadGateway"
        print "Content-Type:text/plain"
        print
        print "This proxy does not allowyou to access that location (%s)." % (host,)
        print
        print os.environ
 
    elif url.startswith("http://") orurl.startswith("https://"):
   
        if method == "POST":
            length =int(os.environ["CONTENT_LENGTH"])
            headers ={"Content-Type": os.environ["CONTENT_TYPE"]}
            body = sys.stdin.read(length)
            r = urllib2.Request(url, body,headers)
            y = urllib2.urlopen(r)
        else:
            y = urllib2.urlopen(url)
       
        # print content type header
        i = y.info()
        if i.has_key("Content-Type"):
            print "Content-Type: %s"% (i["Content-Type"])
        else:
            print "Content-Type:text/plain"
        print
       
        print y.read()
       
        y.close()
    else:
        print "Content-Type:text/plain"
        print
        print "Illegal request."
 
exceptException, E:
    print "Status: 500 UnexpectedError"
    print "Content-Type: text/plain"
    print
    print "Some unexpected error occurred.Error text was:", E


2. 修改tomcat配置文件web.xml,很多代码的该文件中是存在的,只不过是添加了注释,把注释去掉即可。修改如下

   

 <servlet>
        <servlet-name>cgi</servlet-name>
        <servlet-class>org.apache.catalina.servlets.CGIServlet</servlet-class>
        <init-param>
          <param-name>debug</param-name>
          <param-value>0</param-value>
        </init-param>
        <init-param>
          <param-name>cgiPathPrefix</param-name>
          <param-value>WEB-INF/cgi</param-value>
        </init-param>
		<init-param>
			<param-name>executable</param-name>
			<param-value>C:/Python27/python.exe</param-value>
		</init-param>
		<init-param>
			<param-name>passShellEnvironment</param-name>
			<param-value>true</param-value>
		</init-param>
         <load-on-startup>5</load-on-startup>
    </servlet>



  <!-- ================ Built In Servlet Mappings ========================= -->


  <!-- The servlet mappings for the built in servlets defined above.  Note  -->
  <!-- that, by default, the CGI and SSI servlets are *not* mapped.  You    -->
  <!-- must uncomment these mappings (or add them to your application's own -->
  <!-- web.xml deployment descriptor) to enable these services              -->

    <!-- The mapping for the default servlet -->
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

	<servlet-mapping>
		<servlet-name>cgi</servlet-name>
		<url-pattern>/cgi/*</url-pattern>
	</servlet-mapping>

其中有一个节点要注意,该节点配置了Python的路径,如果电脑没有安装python需要安装,并且配置好路径。

<init-param>

        <param-name>executable</param-name>

        <param-value>C:/Python27/python.exe</param-value>

   </init-param>

3. 修改tomcat配置目录中content.xml文件,在Content节点中添加privileged="true"属性。

<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the ApacheSoftware Foundation (ASF) under one or more
  contributor licenseagreements.  See the NOTICE filedistributed with
  this work for additionalinformation regarding copyright ownership.
  The ASF licenses thisfile to You under the Apache License, Version 2.0
  (the"License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at
 
     http://www.apache.org/licenses/LICENSE-2.0
 
  Unless required byapplicable law or agreed to in writing, software
  distributed under theLicense is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES ORCONDITIONS OF ANY KIND, either express or implied.
  See the License for thespecific language governing permissions and
  limitations under theLicense.
-->
<!-- The contents of this file will be loaded for each webapplication -->
<Context privileged="true">
 
    <!-- Default set ofmonitored resources -->
   <WatchedResource>WEB-INF/web.xml</WatchedResource>
 
    <!-- Uncomment thisto disable session persistence across Tomcat restarts -->
    <!--
    <Managerpathname="" />
    -->
 
    <!-- Uncomment thisto enable Comet connection tacking (provides events
         on sessionexpiration as well as webapp lifecycle) -->
    <!--
    <ValveclassName="org.apache.catalina.valves.CometConnectionManagerValve"/>
    -->
 
</Context>

4. 配置完成,开始你的跨域访问吧。


相关文章
|
8月前
|
Arthas 监控 Java
Arthas 可以用于监控和诊断在 Windows 系统下部署的 Tomcat 服务
Arthas 可以用于监控和诊断在 Windows 系统下部署的 Tomcat 服务
904 2
|
8月前
|
JavaScript Java 应用服务中间件
centos部署vue项目(java,tomcat环境的搭建)
centos部署vue项目(java,tomcat环境的搭建)
160 0
|
5天前
|
网络协议 Java 应用服务中间件
centos7环境下tomcat8的安装与配置
本文介绍了在Linux环境下安装和配置Tomcat 8的详细步骤。首先,通过无网络条件下的文件交互软件(如Xftp 6或MobaXterm)下载并解压Tomcat安装包至指定路径,启动Tomcat服务并测试访问。接着,修改Tomcat端口号以避免冲突,并部署Java Web应用项目至Tomcat服务器。最后,调整Linux防火墙规则,确保外部可以正常访问部署的应用。关键步骤包括关闭或配置防火墙、添加必要的端口规则,确保Tomcat服务稳定运行。
|
3月前
|
应用服务中间件 Apache Windows
免安装版的Tomcat注册为windows服务
免安装版的Tomcat注册为windows服务
152 3
|
4月前
|
Java 应用服务中间件 Windows
windows服务器重装系统之后,Tomcat服务如何恢复?
windows服务器重装系统之后,Tomcat服务如何恢复?
78 10
|
5月前
|
应用服务中间件 Linux 网络安全
【Azure 应用服务】App Service for Linux 环境中为Tomcat页面修改默认的Azure 404页面
【Azure 应用服务】App Service for Linux 环境中为Tomcat页面修改默认的Azure 404页面
|
5月前
|
Java 应用服务中间件 Windows
【App Service for Windows】为 App Service 配置自定义 Tomcat 环境
【App Service for Windows】为 App Service 配置自定义 Tomcat 环境
|
5月前
|
Java 应用服务中间件 Windows
【Azure 应用服务】App Service for Windows 环境中为Tomcat自定义4xx/5xx页面
【Azure 应用服务】App Service for Windows 环境中为Tomcat自定义4xx/5xx页面
|
7月前
|
IDE Java 应用服务中间件
Tomcat部署的服务有部分中文是乱码如何处理
【6月更文挑战第9天】Tomcat部署的服务有部分中文是乱码如何处理
834 5
|
6月前
|
Java 应用服务中间件 Linux
Tomcat安装部署[单机软件],可以让用户开发的WEB应用程序,变成可以被访问的网页,Tomcat的使用需要jdk环境
Tomcat安装部署[单机软件],可以让用户开发的WEB应用程序,变成可以被访问的网页,Tomcat的使用需要jdk环境