Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Go From Zero to JSP 2.0 in No Time at All : Page 3

Java Server Pages 2.0 promises to make it easier for beginners and non-programmers to code highly functional, dynamic Web sites. Learn to use JSP 2.0 to connect to a database and display dynamic results on your very own web page using new features such as the expression language.

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.0\webapps\ROOT called zero2.jsp, and put the following HTML into it.

<HTML> <HEAD> <TITLE>Zero2JSP Music Collection</TITLE> </HEAD> <!-- say NO to Times New Roman examples! --> <BODY style="font-family: Arial, Helvetica, sans-serif;"> <h2>Zero2JSP Music Collection</h2> <form action="zero2.jsp" name="frmInsert" id="frmInsert"> Name <input type="text" name="txtName" size="10" maxlength="20" value=""> Title<input type="text" name="txtTitle" size="10" maxlength="20" value=""> Rating<input type="text" name="txtRating" size="10" maxlength="20" value=""> Genre<input type="text" name="txtGenre" size="10" maxlength="20" value=""> <p> <input type="submit" value="Insert"><input type="Reset"> </form> <table border=2 cellpadding=2> <tr> <th>#</th> <th>Name</th> <th>Album Title</th> <th>Rating</th> <th>Genre</th> </tr> <tr> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> <td>&nbsp;</td> </tr> </table> </BODY> </HTML>

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 <sql:setDataSource> tag loads the database driver and creates a database connection. Place the following code toward the top of the page (above the <body> tag is fine).

<%-- sql:setDataSource will create a database connection and its reference stored in the variable mdb--%> <sql:setDataSource var="mdb" driver="com.microsoft.jdbc.sqlserver.SQLServerDriver" url="jdbc:microsoft:sqlserver://" user="dbuser" password="secret" />

Table 1 defines the parameters passed in the <sql:setDataSource> tag.

Table 1. The <sql:setDataSource> Tag.




The connection this tag creates will be referred to by this variable name.


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


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


The username needed to access the database.


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 <table> tag in your .jsp page:

<%-- Example of the sql:query tag --%> <sql:query var="results" dataSource="${mdb}"> select * from collection order by name </sql:query>

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 <sql:query> tag.

Table 2. The <sql:query> Tag.




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


The data source the query is being executed against. Notice that  ${mdb}, the var name you gave in the <sql:setDataSource> 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 <tr>—that has nothing but &nbsp;—with the following code:

<c:forEach var="row" items="${results.rows}" varStatus="counter" > <tr> <td>${counter.count}</td> <td>${row.name}</td> <td>${row.title}</td> <td>${row.rating}</td> <td>${row.genre}</td> </tr> </c:forEach>

The core tag <c:forEach/> is going to loop through the collection of rows held by the variable results. Everything between the beginning <c:forEach> tag and the ending </c:forEach> 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 <c:forEach> tag.

Table 3. The <c:forEach> Tag.




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


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


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.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date