Showing posts with label cgi. Show all posts
Showing posts with label cgi. Show all posts

Thursday, August 5, 2010

Using Beanshell Scripts in cgi-bin Directory

In this tutorial, we demonstrate to use Bean Shell Java interpreter as a cgi language. Beanshell is a Java interpreter that can be called dynamically in Java applications or linux console. You can download and install Beanshell in Ubuntu using

# sudo apt-get install bsh

After installing you can test it by typing bsh in linux shell:

root@stdio:/# bsh
BeanShell 2.0b4 - by Pat Niemeyer (pat@pat.net)
bsh % System.out.println("Hello world!");
Hello world!
bsh % double[] d=new double[]{1,2,3.14159};
bsh % for (int i=0;i
System.out.println("d["+i+"] is "+d[i]); 
}
d[0] is 1.0
d[1] is 2.0
d[2] is 3.14159



You have to create a file called .jline-bsh.Interpreter.history in directory /var/www and this file has to be writable rights. You can create and give writable rights like this:

# touch /var/www/.jline-bsh.Interpreter.history
# chmod a+w /var/www/.jline-bsh.Interpreter.history

Now we can create our Beanshell cgi script using a text editor like vim.

# cd /usr/lib/cgi-bin/
stdio:/usr/lib/cgi-bin# vim 1.bsh

A sample 1.bsh file includes these lines of codes:

#!/usr/bin/bsh
System.out.println("Content-type: text/html\n\n");
System.out.println("Hello from java cgi");
System.out.println(System.getenv("QUERY_STRING"));


In first line of this script, we say this script will be handled using /usr/bin/bsh.
Secondly, content type of this file is text/html so browser will display the output as html.
In third line, we send a hello world string to client and finally we write variables which are defined in URL.

In order to run this code, we have to give executable rights to file using

# chmod a+x 1.bsh

Now, we are ready to run this code using our browser. Be sure that your apache server is running using

# sudo /etc/init.d/apache2 status

and it is not running use

# sudo /etc/init.d/apache2 start

to start it. After that, open a browser and type,

http://localhost/cgi-bin/1.bsh

If everything is ok, we can see something like that:

 
We can pass some variables like this

http://localhost/cgi-bin/1.bsh?var1=3&var2=stdio&var3=aValue