Common Gateway Interface (CGI)

As mentioned in the previous section, Tomcat is primarily meant to be a Servlet/JSP container, but it also has the capabilities that one would expect any traditional web server to have. One of these is support for the Common Gateway Interface (CGI). Traditional web servers provide a means for running an external program in response to a browser request, typically used to process a web-based form. This mechanism is named the Common Gateway Interface, or CGI for short. CGI is called common because it can invoke programs in almost any programming or scripting language: Perl, Python, awk, Unix shell scripting, and even Java are all supported options. In reality, you probably wouldn't run Java applications as a CGI due to the startup overhead; elimination of this overhead was what led to the original design of the servlet specification. Servlets are almost always more efficient than CGIs because you're not starting up a new operating-system-level process every time somebody clicks on a link or a button. You can consult a good book on web site management for details on writing CGI scripts.

Tomcat includes an optional CGI servlet that allows you to run legacy CGI scripts; the assumption is that most new backend processing will be done by user-defined servlets and JSPs. A simple CGI is shown in Example 2-13.

Example 2-13. CGI demonstration

#! /usr/bin/python # Trivial CGI demo print "content-type: text/html" print "" print "<html><head>Welcome</head>" print "<body><h1>Welcome ...

Get Tomcat: The Definitive Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.