系统环境
Apache-tomcat-8.0.9
Python2.6
JDK1.8
Eclipse 4.5.0
在Eclipse中新建Dynamic Web project,myweb
1、在WEB-INF下新建文件夹cgi-bin
2、在cgi-bin文件夹下新建脚本文件cgitest.cgi,如下:
#!C:\Python26\python.exe
print 'Content-type: text/plain'
print
def hw(n):
if n==1:
return 1
else:
return 2*n
print hw(3);
print 'Hello, CGI'
“#!C:\Python26\python.exe”是被指定必须存在的Pound Bang行;
“print 'Content-type: text/plain' ”: 这表明页面是普通的文本,如何页面为HTML,这一行就应该这么写;
a. 打开web.xml文件,找到这一段被注释的节点(如下),如果你从没自己修改过,那应该是被注释的,你还需要添加一些参数。
<servlet>
<servlet-name>cgi</servlet-name>
<servlet-class>org.apache.catalina.servlets.CGIServlet</servlet-class>
<init-param>
<param-name>clientinputTimeout</param-name>
<param-value>100</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>passShellEnvironment</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>cgiPathPrefix</param-name>
<param-value>WEB-INF/cgi-bin</param-value>
</init-param>
<init-param>
<param-name>executable</param-name>
<param-value>C:/Python26/python.exe</param-value>
</init-param>
<load-on-startup>5</load-on-startup>
</servlet>
解释几个重要的参数:
“passShellEnvironment”: 与Python解析器解析CGI脚本有关,但是一定要配置好Python的环境变量;
“cgiPathPrefix”: 与Server能够访问的脚本目录有关,与第二步内容相对应;
“executable”: (这是我的安装路径)与Python解析器有关,没有解析器,Server怎么解析呢~
b. 找到第二段被注释的节点:
<servlet-mapping>
<servlet-name>cgi</servlet-name>
<url-pattern>/cgi-bin/*</url-pattern>
</servlet-mapping>
这里的/cgi-bin/*指定了浏览器访问的地址,与前面
WEB-INF/cgi-bin相对应。
c. 配置权限:
打开context.xml,添加:privileged="true"
<Context privileged="true">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
</Context>
4、运行脚本
在浏览器里输入:http://localhost:8080/myweb/cgi-bin/cgitest.cgi