Go From Zero to JSP 2.0 in No Time at All

ava technology has maintained a strong foothold in the Web development world since Java Servlets and JSP hit the scene more than 6 years ago. Java technologies are mature and particularly well adopted in the enterprise where they are used on a variety of large scale Web applications.

There are, of course, alternatives to using JSP, servlets, and Enterprise JavaBeans (EJB) to build Web applications. Simpler scripting languages such as PHP have achieved great success for many reasons, most notably that they have a short learning curve and wide availability for hosting. Then there is ASP and the .NET framework; these center around Microsoft operating systems and server software. If you run Windows, chances are you already have IIS running on your computer and you can very quickly write a simple ASP page that performs some action.

What You Need
General programming skills, some experience with Web programming in any language. Access to a database or installation of a local database and basic SQL knowledge. This article uses SQL Server 2000 but can be applied to any database.

All platforms/languages are similar in some ways and dissimilar in others, however Java is frequently perceived to be a more difficult introduction to Web programming. It is true that as platform freedom and flexibility increase, so does complexity. And thus, Java technologies are at least potentially more complicated than their counterparts. But this is slowly changing. JSP 2.0 has new ease-of-development features that increase the use of simple tags and decrease the amount of Java code you need to make high performance Web applications. And, happily, this means that a Java-based Web site is well within reach for almost any Web developer.

In this tutorial, I’ll show how to get a Java-based Web site up and running quickly, even if you have little or no Java experience. I’ll show you how to install the latest and greatest version of Apache Tomcat, do a quick overview of the new JSP 2.0 tag libraries (JSP Standard Tag Library or JSTL), and write a JSP page that will connect to and retrieve data from a database.

At the conclusion of this tutorial you will have created a database-driven dynamic Web page (see Figure 1) that will display results from a database table and allow you to insert new records using a form.

Figure 1. The Finished Product. At the conclusion of this tutorial you will have created this database-driven dynamic Web page.

Install the Java Runtime Environment and Tomcat 5.0.5
The first thing you need to do is download the Java 2 SDK and install it. As I write this the latest version is 1.4.2. Download the Windows installation from the SDK column under “Download J2SE 1.4.2.” Run the installer with all the defaults.

You’ll also need a JSP 2.0 compliant application server. Download Tomcat 5.0.5 and install the directory at the root of your drive. Call it C:Tomcat 5.0.

Start the server (Start -> All Programs -> Apache Tomcat 5 -> Start Tomcat). Then open a Web browser and browse to http://localhost:8080. You should see there, displayed in all its glory, the Tomcat 5.0 welcome page. If you want, you can take a few minutes to check out the example pages http://localhost:8080/jsp-examples/ and http://localhost:8080/servlets-examples/.

There are many folders under the C:Tomcat 5.0 directory, but right now we are only interested in the C:Tomcat 5.0webappsROOT folder. This will be our playground for the rest of this article.

Configure and Install Needed Libraries
Under the ROOT folder there are a few files and a folder called WEB-INF. WEB-INF is a part of all Java 2 Web applications and is not exposed to the Web user through a URL such as //localhost/:8080/WEB-INF. The WEB-INF folder holds the application configuration, the Java libraries required for your application, and any Java classes that you create.

Create a directory named lib in your WEB-INF folder (i.e. C:Tomcat 5.0webappsROOTWEB-INFlib). Copy the files standard.jar and jstl.jar from C:Tomcat 5.0webappsjsp-examplesWEB-INFlib and put them into your new lib directory. These are library components (.jar files) that will have to be available to your application to complete this tutorial.

Download the appropriate Java database drivers (also .jar files) and place them into the lib directory you just created. The example code uses a SQL Server database, so you will need the database drivers (.jar files) provided by Microsoft (click on “SQL Server 2000 Driver for JDBC”?Read our review of the driver). The executable for the SQL Server 200 Driver for JDBC installs .jar files and Help documentation onto your computer. You will need to copy the three .jar files from its install directory into your WEB-INF/lib directory.

Now you need to modify the application’s configuration file, named web.xml. Open the web.xml file (C:Tomcat 5.0webappsROOTWEB-INFweb.xml) and locate, toward the top, the opening XML tag . Replace this opening tag with:

   

Save and close the web.xml file, right click the Tomcat icon in the system tray, and select Shutdown. Then restart it again from your Start menu. You can make some changes without restarting, but restarting is generally a good way to confirm that your changes are loaded and in effect.

Now you have a platform onto which you can unleash your brilliant Java Powered mind!

JSP 2.0 and the JSTL
JSTL (the tag component of JSP 2.0) is a collection of “HTML type” tags that allow you to create dynamic Web pages by providing tools to process XML, connect to a database, control programming flow, and support internationalization and general formatting. The benefits of JSTL are simpler code and more friendly tags for you to program with. JSTL is broken down into four ‘tag libraries’:

  • Core?The “core” library provides actions for common programming logic, such as dynamically including or excluding text at request time, and looping over lists, such as database results.
  • XML?The “xml” library provides actions to parse, generate, and transform XML data.
  • Formatting?The “fmt” library provides actions for formatting and localizing Web dates and numbers.
  • Database Access?The “sql” library provides tags to connect to a database and perform queries and updates.

For the sample application in this article, you’ll need the standard “core” library as well as the “sql” library. You’ll start with an HTML template and then add the JSP tags to use these libraries. Create a file at C:Tomcat 5.0webappsROOT called zero2.jsp, and put the following HTML into it.

         Zero2JSP Music Collection                  

Zero2JSP Music Collection

Name Title Rating Genre

# Name Album Title Rating Genre
         

By adding the following lines (called taglib directives) to the top of your .jsp page you are telling Tomcat that you are going to use the core and sql sets of tags in your page.

   <%-- These two taglib DIRECTIVES define the       two tag libraries used on this page--%>   <%@ taglib prefix="c"       uri="http://java.sun.com/jstl/core_rt" %>   <%@ taglib prefix="sql"       uri="http://java.sun.com/jstl/sql_rt" %>

Query the Database and Display Results
Now you’ll use a ‘sql’ tag to make a connection to the database. The tag loads the database driver and creates a database connection. Place the following code toward the top of the page (above the tag is fine).

   <%-- sql:setDataSource will create a database       connection and its reference stored in the variable       mdb--%>   

Table 1 defines the parameters passed in the tag.

Table 1. The Tag.

Variable

Description

Var

The connection this tag creates will be referredto by this variable name.

Driver

This is the name of the JDBC driver class, in thiscase the SQL Server driver.

url

JDBC drivers require a URL to specify the name,location, and port number of the database.

User

The username needed to access the database.

Password

The password to access the database.

Now that you have a connection to the database, go get some data. Place the following tag just before the

tag in your .jsp page:

   <%-- Example of the sql:query tag --%>          select * from collection       order by name   

This tag executes a query against the database and returns the results you specify in the “var” attribute. It uses an expression?enclosed with ${?}?to retrieve the data from the data source.

Table 2 defines the parameters passed in the tag.

Table 2. The Tag.

Variable

Description

Var

The variable name in which the results of the query will be stored.

dataSource

The data source the query is being executed against. Notice that ${mdb}, the var name you gave in the tag, is in this field.

So far you have created a connection to a database and executed a query. Now you need to display the results. This is where the “core” library comes into play. You need to loop through the results of the query and display them in your HTML table.

Replace the entire table row

?that has nothing but  ?with the following code:

                  ${counter.count}         ${row.name}         ${row.title}         ${row.rating}         ${row.genre}         

The core tag is going to loop through the collection of rows held by the variable results. Everything between the beginning tag and the ending tag is repeated until each row of the query results are processed. The varStatus attribute allows you to designate a variable that will count the number of loops. You use this to count the records in your database (in our example, a music collection) and display them in the table. You get the query result data into the cells using expressions on the row variable. As seen above, the expression ${row.name} gets the data from the database table column “name” in the current row.

Table 3 defines the parameters passed in the tag.

Table 3. The Tag.

Variable

Description

Var

The name of the variable that will hold the current item in theloop

Items

This attribute contains a reference to any type of Java collection,array, or in this case a resultset

varStatus

Variable set here holds the status of the iteration

At this point, open a browser and run the zero2.jsp page. Unless you preloaded your database table the page will not be very exciting because your query will not have retrieved any rows. But you will have that HTML form at the top of the page and you can start adding your favorite albums to it.

Handling the

and Inserting Data
In this section you’ll use more of the logic control offered by the core library, as well as another sql library tag, to insert records into your database.

The HTML

already does a ‘get’ back to this same page. You want to insert data only when the user has actually entered some data to insert. If the form is blank when the page is requested there is no action to take. This is the perfect situation for the “core” tag. Our example application requires that the user fill out a name before it will insert a new record be inserted into the database. Place the following code toward the top of the .jsp page.

The test variable in the preceding code is the expression you are testing to determine if a certain action should occur. The process to display the HTML occurs between the starting and ending tags.

You can test any expression using the tag. The empty operator tests whether a collection or string is empty or null.

Table 4 shows a list of the available operators.
Table 4. Available Operators. Operators will evaluate to a “true” or “false” value.

Operator

Description

==

Equality

eq

Equality

!=

Inequality

ne

Inequality

<

Less than

lt

Less than

>

Greater than

gt

Greater than

<=

Less or equal to

le

Less or equal to

>=

Greater or equal to

ge

Greater or equal to

empty

Test for null and/or empty string

To complete the example, you need to retrieve data from the form but insert it into the table only if the user has filled out the form’s txtName parameter. The was completed so now you use the tag to insert the record. Insert the following code between the beginning and ending tags from the last step.

INSERT INTO collection VALUES    ('${param.txtName}',    '${param.txtTitle}',    '${param.txtRating}',    '${param.txtGenre}')

INSERTED ${updateCount} row into database

Table 5. The Tag. The table shows the attributes passed in the tag.

Attribute

Description

dataSource

Refers to the database connection on which you are performing the update.

var

The var in this attribute will count the effected rows.

Crossing the Finish Line
Run your .jsp page. You should be able to insert records using the form and immediately see them displayed in the table of query results. If you have seen similar examples using JSP to connect to a database prior to JSP 2.0 and the JSTL you would have noticed a lot more inline Java code and associated overhead to achieve the same result. What we have done here, in effect, is query a database and handle form processing using a small number of tags.

A couple of things worth noting: Remember that, unlike HTML and VBScript, Java and its tags and tag attributes are case-sensitive. For example, you will get an error if you use a ‘datasource’ attribute instead of a ‘dataSource’ attribute. Also, in any programming language, limiting the amount of code in the template pages is good practice. This makes the tags easier to work around and easier maintain, particularly for fledgling developers or those who are accustomed to HTML.

While the “sql” library is useful in most cases it is bad practice to include database code or complex business logic in your .jsp pages. In the Java world, accessing the database and performing business logic is better done in servlets, JavaBeans, and EJBs. Once you become familiar with JSP, I recommend learning more about Java servlets, and later a Model View Controller (MVC)-based framework. MVC Frameworks are a set of proven design patterns that help you create more maintainable applications by separating business logic and data access (model) from your templates (view) with requests being marshaled through a tier representing the controller. For a great out of the box framework check out Jakarta Struts.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: