Advertisment

Write Your Own JSP Script

author-image
PCQ Bureau
New Update

A part of Java 2, Enterprise Edition, JSP (JavaServer Pages) is a handy tool for server-side scripting. It offers ease of use for creating dynamic Web pages, and like all members of the Java family, gives you the benefit of platform independence. If you’re a Web designer or developer, you must try your hand on this one. 

Advertisment

Last month, we had begun a series on JSP programming with our article on Tomcat (See Tomcat on Linux, page 105, PCQuest April 2001). There, we saw how to set up Tomcat both as a standalone and an add-on module for Apache Web server and executed some JSP pages that come with Tomcat. Continuing where we left off, this time we’ll write our own JSP script, install it on Tomcat, and execute it in a Web browser. In a separate article in this issue, we’ll take you through customizing Tomcat (see page 158 in this issue). We assume that you’re familiar with Java, because writing JSP scripts is nothing but familiarizing yourself with some simple JSP tags.

JSP tags

A JSP page can contain JSP as well as HTML tags. HTML contents are displayed as they are, but Tomcat parses the content within JSP tags and displays it. For writing JSP content you can use all the Java data types, language constructs (loops, conditions), and most Java classes. The only thing we need to learn is to segregate a Java program between appropriate JSP tags. The declaration–variable and methods–must be done within Declaration tags (<%! …. %>); expressions which are to be evaluated and displayed must be written within a pair of Expression tags (<%= ……%>); and other statements, conditions, loops, etc, must be embedded within Scriplet tags (<% …. %>). Let’s take a few examples to understand these.

Advertisment

Declaration tags

In programming, we declare and subsequently use a number of variables. In case of a Java program, we declare these variables within a class; while in case of

JSPs, we use declaration tags for this. Suppose we want to declare three variables:

intA, doubleB, and stringC of the type int, double, and String respectively. This is done



in JSP as:

<%!



int intA;


double doubleB;


String stringC = “My name is Shekhar”;


%>


Advertisment

Note that the last declaration is also an initialization where the String variable (or object) is initialized to the value of “My name is Shekhar”. So we can also initialize variables in declaration tags. Methods (functions) must also be declared within declaration tags. For example:

<%!



int getIntA( )


{


return intA;


}


%>



The method getIntA( ) when called from a scriplet tag (see below) will return the value of the integer variable

intA.

Advertisment

Expression tags

Suppose we want to display the value of the String variable stringC on a Web page. This can be done using the expression tags:

<%= stringC %>

Advertisment

Whatever is between the expression tags is converted into a string and displayed on the Web page. So the value of

stringC, “My name is Shekhar” will be displayed on the Web page. We can also place arithmetic expressions within tags, like:

<%= intA + doubleB %>

If we initialize intA and doubleB with values 12 and 16.75, the arithmetic expression will be evaluated and the result, 28.75, displayed. 

Advertisment

Scriplet tag

Everything else goes within the scriplet tags. All the Java code containing if-else conditions, loops (like for, while), switch, calling user-defined or Java class methods is written within these tags. We can declare variables, but not methods, within these tags. For example, suppose we want to add intA to doubleB 100 times and if the result is greater than 1,000 we want to display

stringC, the scriplet tag can be used to code this program.

<%



int intA = 30;


double doubleB = 50.56;


String stringC = “Now doubleB is greater than 1000”;


for (int i = 0; i < 100 ; i++ )


doubleB = doubleB +intA;


if (doubleB > 1000)


{


%>


<%= stringC %>


<%


}


%>










Advertisment

We have declared the variables intA, doubleB and stringC within the scriplet tag. After intA is added to doubleB a 100 times, we check using an ‘if’ condition whether doubleB is greater than 1,000. If it is, then the value of stringC is displayed. As said before, we use the expression tag to display it. Hence, we close the scriplet tag. We have also added an HTML bold tag (…..) to the expression tag. So, if doubleB is greater than 1,000, we’ll get a Web page with the display in bold as below:

The value of stringC = Now doubleB is greater than 1000

Finally we again start the scriplet tag to close the ‘if’ block using the closing brackets ‘}’.

Converting a Java application into JSP

Armed with the above information, we’ll now convert a Java application program called JavaApplication into a JSP called

jspprogram. Both of them connect to a MySQL database on Linux called Products and display the product information–product ID, product name, and price. 

To execute the Java application as well as JSP, you need some prerequisites. You’ll need to set up the JDK for Linux found on our last month’s CD, as described in the article Tomcat on Linux. MySQL for Linux was given on the PCQuest January 2001 CD and the instructions to set it up can be found in the article Publish your Database on the Web (page 72) of the same issue. Now, we must create the database named Products. Login as root and issue the following:

mysqladmin create products —p

When prompted for the password, enter the password that you’ve set up for

MySQL. Now we create a table named ‘info’ and populate it with some information of computer products. To ease this process, we’ve written all the SQL commands in a file called mysql_script.txt found in

/cdrom/sorc_cod/jsp directory in this month’s CD. Change to this directory and issue the following:

mysql -p < mysql_script.txt

The next task is to set up JDBC (Java DataBase Connectivity) so that our Java program and JSP can communicate with the MySQL database. Copy the file named mm.mysql.jdbc-1.2c.tar.gz from

cdrom/linux/mysql-jdbc to, say, /opt directory and issue the following 

command:

tar -zxvf mm.mysql.jdbc-1.2c.tar.gz

This will create a directory named mm.mysql.jdbc-1.2c under /opt. Copy the file named mysql_comp.jar found in this directory to

/usr/java/jdk1.3.0_02/lib directory. The mysql_comp.jar file constitutes the JDBC drivers for

MySQL. Now you must include the path to mysql_comp.jar file in the CLASSPATH environment variable. This is done as:

export CLASSPATH=/usr/java/jdk1.3.0_02/lib/mysql_comp.jar:.

Append this line to a Linux startup file, like profile in /etc directory, so that the settings persist on subsequent reboots. 

We are now ready to run our Java application. Copy the file JavaApplication.java from

/cdrom/sorc_cod/ jsp to /opt directory. Open the file in a text editor and change the value of the variable ‘password’, which in our case is

pcq, to the password you used to connect to MySQL. Compile and run the program as:

/usr/java/jdk1.3.0_02/bin/javac JavaApplication.java



/usr/java/jdk1.3.0_02/bin/java JavaApplication

If everything was set up right, you’ll be able to see information on your computer. The corresponding

JSP, which does the same work, can be found in the file named jspprogram.jsp in the

sorc_cod/jsp directory of this month’s CD. Let’s analyze the difference between the code of the JavaApplication and

jspprogram. You can refer to the source code on the CD to follow this better.

Our JSP starts with HTML tags. The first noteworthy difference is how the variables username and password are declared within the JSP declaration tags <%!…%>. Next we encounter scriplet tags <% …. %>. The four statements here load the MySQL JDBC drivers; establish a connection using the database name Products, and the username and password; and issue the SQL query ‘select * from info’. Since we don’t use an import statement in JSPs to import packages–like import

java.sql.*; in JavaApplication–we must refer to the classes Connection, Statement, ResultSet along with their package names–java.sql.Connection,

java.sql. Statement, and java.sql.ResultSet respectively. Now we’ve queried the Database and have the result of the query in the ResultSet object; so, we are ready to display the data. 

Unlike a Java application where the output goes to the console or command line using System.out method, the output of a JSP goes to a Web page. So we can format the output using HTML elements like tables. After closing the scriplet tag, we begin constructing an HTML table. Next we start a While loop in a scriplet tag to iterate through the query result contained in the ResultSet Object. We display each row and column of the retrieved data from the database using the

and tags respectively. Note the use of expression tags to display the data contained in the ResultSet object.

After the expression tags, we again start the scriplet tag which contains the closing brackets–}–of the While loop and the Try block. We also catch any exception or error, if occurred, within these tags. As you may see, the only uncomfortable thing about JSP is that you have to frequently hop among the JSP tags, without forgetting to close one before starting the other.

To run the JSP, copy the file jspprogram.jsp to webapps/examples/jsp directory under the tomcat directory. Do remember to change the variable ‘password’ to the password you used to connect to

MySQL. Stop and restart Tomcat so that it becomes aware of the new CLASSPATH (that we had defined above):

/opt/tomcat/bin/shutdown.sh



/opt/tomcat/bin/startup.sh

Now key in the following URL in Netscape:






http://localhost/examples/jsp/jspprogram.jsp

If you have not configured Tomcat to work with Apache, you must use the port number (8080) in the URL as:






http://localhost:8080/examples/jsp/jspprogram.jsp

Next month, we’ll see how JSPs can be used to retrieve HTML Form data and store it in a database using

JavaBeans.

Shekhar Govindarajan

Advertisment