Implementation of openlayers cross-origin request WFS service in Tomcat Environment

Source: Internet
Author: User

Because the map data of the Project is placed on different servers, cross-origin retrieval is required for poi search and path navigation. The Container environment uses Tomcat 7.0.53. to configure cross-origin requests, follow these steps:

1. Download proxy. cgi, or go to the installation directory of openlayers, find the installation drive letter \ OpenLayers-2.13.1 \ examples, or directly copy the following code to the proxy. cgi file. Modify allowedhosts and add the remote server address: Port and local IP Address: port. Finally put the proxy. cgi file in the CGI folder, copy to the website WEB-INF directory,

The following is proxy. CGI Source Code, where 192.168.1.18: 8090 ', '123. 168.1.50: 8080 ', '2017. 168.1.49: 8080 ', '192. 168.1.18: 8080 ', 'localhost: 8090' is the remote server address and local address added in this article.

#!/usr/bin/envpython  """Thisis a blind proxy that we use to get around browserrestrictionsthat prevent the Javascript from loading pages not on thesameserver as the Javascript.  This hasseveral problems: it's lessefficient,it might break some sites, and it's a security risk becausepeoplecan use this proxy to browse the web and possibly do bad stuffwithit.  It only loads pages via http andhttps, but it can load anycontenttype. It supports GET and POST requests.""" importurllib2importcgiimportsys, 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. Modify the tomcat configuration file web. xml. Many codes exist in this file, except that annotations are added and removed. Modify as follows:

 <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>

Note that the python path is configured for a node. If python is not installed on the computer, install it and configure the path.

<Init-param>

<Param-Name> executable </param-Name>

<Param-value> C:/python27/python.exe </param-value>

</Init-param>

3. modify the content. xml file in the tomcat configuration directory and add the privileged = "true" attribute to the content node.

<?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. The configuration is complete. Start your cross-origin access.


Implementation of openlayers cross-origin request WFS service in Tomcat Environment

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.