Java EE Resin CGIServlet
Материал из Wiki.crossplatform.ru
In this tutorial, we will show how to use Resin's CGIServlet.
The CGI (Common Gateway Interface), is a protocol for calling external software via a web server to deliver dynamic content.Resin enables this protocol through it's CGIServlet.
CGIServlet
Implements CGI calls. The url is assumed to refer to an executable file. The operating system is instructed to execute the program or script. The usual CGI environment variables are set, and the current directory is the value of $RESIN_HOME
In our code example, we will demonstrate how to execute a shell script, Python script, Ruby script and a Perl script.
<?xml version = '1.0' encoding = 'UTF-8'?> <web-app> <description>CGI scripts</description> <servlet> <servlet-name>cgi</servlet-name> <servlet-class>com.caucho.servlets.CGIServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>cgi</servlet-name> <url-pattern>/cgi-bin/*.sh</url-pattern> <url-pattern>/cgi-bin/*.py</url-pattern> <url-pattern>/cgi-bin/*.rb</url-pattern> <url-pattern>/cgi-bin/*.pl</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app>
This is the web.xml file. Here we map all urls with .sh, .py, .rb and .pl extensions to the CGIServlet. Traditionally, the cgi scripts are placed in a directory called cgi-bin.
<html> <head> <title>CGI scripts</title> </head> <body> <pre> Execute: <a href="http://localhost:8080/webapp/cgi-bin/script.sh">shell script</a> <a href="http://localhost:8080/webapp/cgi-bin/script.py">Python script</a> <a href="http://localhost:8080/webapp/cgi-bin/script.rb">Ruby script</a> <a href="http://localhost:8080/webapp/cgi-bin/script.pl">Perl script</a> </pre> </body> </html>
This is the index.jsp page. Here we have four links to four different cgi scripts.
$ ls * index.html cgi-bin: script.pl script.py script.rb script.sh META-INF: resin-war.digest WEB-INF: classes tmp web.xml
This is how the directory structure looks like. Note the cgi-bin directory.
Scripts
Next we will show all four CGI scripts. They all print environment variables.
#!/bin/sh echo "Content-Type: text/html" echo echo "<pre>" env echo "</pre>"
This is the shell CGI script.
#!/usr/bin/python import sys import os from cgi import escape print "Content-type: text/html" print print "<pre>" for k in sorted(os.environ): print "<b>%s: </b>%s" %(escape(k), escape(os.environ[k])) print "</pre>"
This is the Python CGI script.
#!/usr/bin/ruby puts "Content-Type: text/html" puts puts "<pre>" ENV.to_hash.each do |key, value| puts("<b>#{key}</b>: #{value}") end puts "</pre>"
This is the Ruby CGI script.
#!/usr/bin/perl print "Content-type: text/html\n\n"; print "<pre>"; foreach $key (sort keys(%ENV)) { print "<b>$key</b>: $ENV{$key}"; print "<br>"; } print "</pre>";
Finally, this is the Perl CGI script.