Apache servers are used most commonly to serve up HTML, PHP, javascript, images, and other terms you may be familiar with. However, it is quite easy to serve the output from pretty much anything with cgi, including C++, Java, shell script, perl, lisp, etc.
For this article, I’m going to be using Java. The main reason for this is because it requires a bit of finagling with perl to get it to run. Do note however that this is NOT embedding a Java applet in a website. This is redirecting the output from a java application running on the server to the browser. Thus, no browser plugins are required.
For now let’s assume that the Java is compiled and that there is a class named “MyClass” sitting in the directory. In the cgi file, have the following code (I’ll go through line by line below):
#!/usr/bin/perl
print "Content-type: text/html\n\n";
open (JAVA, "java MyClass 2>&1 |");
while ()
{
print $_;
}
close JAVA;
This will run the Java application from the entry point of “MyClass” and redirect the output to the browser.
Let’s step through the code line by line.
#!/usr/bin/perl
This tells cgi which interpreter to use. Since the java interpreter requires arguments, we will be running Java through perl.
print "Content-type: text/html\n\n";
Since Apache doesn’t have “special” support for perl like it does for php, we need to include this little bit of header information to tell the server what it’s serving.
open (JAVA, "java MyClass 2>&1 |");
This is the meat of the action. The open function opens a steam, which here we name “JAVA”. The stream we are opening is from the command java MyClass 2>&1 |. You can probably tell this command runs the Java interpreter on “MyClass”. The extra stuff at the end allows both the stdout and stderr (the output and error streams) to be included in the stream.
while ()
{
print $_;
}
This prints the entire stream, line by line.
close JAVA;
Closes the stream. Just some cleanup.
It seems pretty round-about to run Java from Perl through cgi, but it’s relatively easy to set up.
Additionally, if you are making changes to the source on the fly, you can also compile and get the output of that. Just make another CGI file with identical code as the first, with the exception of the command passed to the open function. Give it javac -version -verbose MyClass.java 2>&1 | or whatever you need to compile, and you’re in business. Personally, I like to add the -version and -verbose flags.
Tweaking the code here, you can do all kinds of neat things with cgi and perl besides being able to serve up the output from Java applications.
