JavaData & JavaEasy Development with the JSP Standard Tag Library (JSTL)

Easy Development with the JSP Standard Tag Library (JSTL)

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

In this article, I will introduce you to interesting and flexible technology based on JSP, called JSTL. JSTL stands for Java Server Pages Standard Tag Library. Although JSP has already become very popular, it is not widely used in the development of easy, rapidly-done front-ends with SQL databases. Once you get to know JSTL, you will understand its advantages and will see numerous ways how it can be used in your everyday programmer’s life. I assume that you are familiar with HTML, the basics of SQL requests, and JSP; however, I will describe everything along the way.

JSTL is a standardized collection of tag libraries for supporting iterations and conditionals, XML documents parsing, internationalization, and database access using SQL. Originally, the JSTL specification was being developed by the JSR #52 under the Java Community Process program (JCP). “The JCP holds the responsibility for the development of Java technology.”—claims the official site. As an open, inclusive organization of active members and non-member public input, JCP primarily guides the development and approval of Java technical specifications. There are four basic tag libraries: core, XML, internationalization, and SQL support. As our goal is to quickly study opportunities for JSTL to work with SQL, in this article we shall consider only the basic functions of the libraries’ core and SQL.

This technology is simple and yet powerful enough to be a worthy competitor PHP and ColdFusion. It has the capability to really expand Java’s area of usage, not only for large, scalable Web applications, but also for simple “homepages.” This would allow you to create sites without ceremony integrating them with XML documents and linking them with databases. As I have already noted, its plus is its simplicity of use. It is necessary to remember that it is being constructed on JSP. JSTL will allow us to use the power of all Java technologies.

To begin with, let’s talk about how we will be able to run JSTL. JSTL builds on JSP technology; that’s why running it requires any JSP-compatible container. For this purpose, we can use the free JSP container called Tomcat (http://jakarta.apache.org/tomcat/index.html). An explanation of installing this product goes beyond this article. Needless to say, this software is very popular and there is a lot of documentation on this topic. I will assume that you have already installed and configured the container, so you will need to install an implementation of JSTL. It can be downloaded from its Web site at http://jakarta.apache.org/taglibs/doc/standard-doc/intro.html.

If you have difficulty understanding what such .JAR files are, it is possible that you are familiar with Java only superficially. I would advise you from the beginning to learn the basics of Web programming in Java; nevertheless, I shall describe the meaning of .JAR. JAR is an archive in which there are classes, all written and compiled in p-code, stored to facilitate their use and mobility. Thus, in JAR’s Connector/J, you will find classes for MySQL JDBC driver, and in JSTL’s you will find its branch of classes.

You do not really need to install it; you can just include the .JAR files from the JSTL package into your /WEB-INF/lib/ directory. But, hold on for a while — I will show you how to do that a bit later.

Because we will work with SQL databases, you need to have any one of them installed. There is a wide range of different databases, but in this article MySQL is used because for a few reasons. First of all, we are showing you how JSTL can be helpful for creating easy and fast applications in the area where PHP and MySQL dominate. Secondly, MySQL can be freely downloaded and has a JDBC driver for Java. In summary, to use our examples below, you need to download MySQL server (http://www.mysql.com/products/mysql/index.html), the MySQL Connector/J JDBC driver (http://www.mysql.com/products/connector-j/index.html), and MySQL Control Center (http://www.mysql.com/products/connector-j/index.html). These will let you work with your databases and administer them more easily. Once downloaded, you will need to install the server and control center. Again, your .JAR JDBC driver will need to be included into your /WEB-INF/lib/ directory.

Before creating code, you need to create and fill the database table. Again, the SQL database administration topic is too extensive and goes beyond this article, but I will give you a few recommendations. With the help of a visual administration tool, MySQL Control Center, you will be able to create a new test user, new test database, a table in it, and fill it with test data records. You will need to remember the settings that you create and use (such as login, password, database names, and so forth), because you will use them in your code.

You should now be ready to create your first real-world JSTL application. It will do the following things (the legendary “Hello World” that does nothing, just shows how to use functions):

  • The first screen will allow you to enter the database name, login, password to the database, and the table name.
  • The next screen will take all the data and will connect to the database, executing a SELECT request from the database’s table.

The following is the full code for this application. I’ll comment each line of code step-by-step. The code is really pretty easy, so I bet that you either will understand the structure of the program even without my explanation.

1: <!-- Hello.jsp -->
2: <html>
3: <head>
4:   <title>Hello</title>
5: </head>
6: <body bgcolor="#ffffff">
7: <h1>Please, enter all necessary information and click OK.</h1>
8: <form method="post" action="Continue.jsp">
9: <br>Your login to database:
     <input type="text" name="login" size="15">
10: <br>Your password to database: 
      <input type="password" name="password" size="15">
11: <br>Your database name:
      <input type="text" name="database" size="15">
12: <br>Your database table:
      <input type="text" name="table" size="15">
13: <br><br><input type="submit" name="submit" value=" OK ">
14: </form>
15: </body>
16: </html>

(Please note that numbers on the left to the text are just for your information. You do not need to type them!)

This is the first screen. Surprised? It’s plain HTML; you are right. Nothing more. No comments necessary, I guess. I’ve included this code fragment in the article because I want to show you how JSTL is easy to integrate in any HTML site that requires a few fast-added additional features. Let me show you the next piece of code, and you will find out at least what JSTL looks like.

1: <!-- Continue.jsp -->
2: <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
3: <@ taglib prefix="sql" uri="http://java.sun.com/jstl/sql" %>
4: <c:set var="h" value="localhost"/>
5: <c:set var="l" value="${param.login}"/>
6: <c:set var="p" value="${param.password}"/>
7: <c:set var="d" value="${param.database}"/>
8: <c:set var="t" value="${param.table}"/>
9: <html>
10: <head>
11:   <title>Continue</title>
12: </head>
13: <body bgcolor="#ffffff">
14: <sql:setDataSource driver="com.mysql.jdbc.Driver"
         url="jdbc:mysql://${l}/${d}?user=${u}&password=${p}"/>
15: <sql:query var="result">
16:   SELECT * FROM <c:out value="${t}"/>
17: </sql:query>
18: <c:forEach var="row" items="${result.rowsByIndex}">
19:   <c:out value="${row[0]}"/> <br>
20: </c:forEach>
21: </body>
22: </html>

(Please note that numbers on the left to the text are just for your information. You do not need to type them!)

And that is all! Looks good, doesn’t it? Now is the time to explain everything.

Line 1 is just an HTML comment.

Lines 2-3—these JSP tags are used for using external tag libraries, and to be more exact, to use core and SQL JSTL libraries. We set prefixes for them, so by using these prefixes we will access their functions.

Lines 4-8—as far as the first screen goes, Hello.jsp is passed to the second screen, Continue.jsp. We need to get a couple of different variables and parse them somehow. For that purpose, we are using ${param.YOUR_VAR} here. In line 4, <c:set sets var ${h} to value “localhost”, line 5 sets var ${l} to value of field “login” that you’ve entered on the first Hello.jsp screen, and so on.

Lines 9-13 are simple HTML tags that I used to create the HTML page header. Now, important functions are coming.

In line 14, we are trying to install a connection with a MySQL database via its driver, com.mysql.jdbc.Driver (MySQL Connector/J). url is the field where we specified all connection properties as database name, host name, login, and password. As you can understand, you can use any other JDBC driver to any other SQL database here. This supposedly will be the only string that needs to be changed to support other databases.

Lines 15-17—here we execute our SELECT query. Please notice that on line 16 we are also using another JSTL function, <c:out; it’s used only to output our table name. As far as you know, there are other commands in SQL; for example, INSERT, UPDATE, DELETE, and so forth. To execute these queries (that are not returning a value), you need to use the <sql:update JSTL function. It works the same way as <sql:query, but it doesn’t need var specified.

Lines 18-20—as far as we just executed the SELECT query above, we need to show our result. <c:forEach is an iteration function of JSTL that will set variable ${row} to value ${result.rowsByIndex} and, with the help of line 19, will show the first field of each row (please pay attention!) of your result. Depending on how many fields you have in your table, you can access any of them, just by specifying the field’s number.

Lines 21-22 are a plain HTML footer.

Even if you are not feeling enough power in your fingertips to create your own JSTL application, you should already mention how easy JSTL‘s functions are and how productive it could be. Just imagine how fast it will be to integrate a SQL-based news column and how easy integration will look into your existing Web site.

Perfect. Our code is ready and understandable. Even a non-programmer—for example, a designer—will be able to read it, understand, and maybe modify a bit, or at least change the page layout.

As mentioned in the very beginning, to make your JSTL code run you need to install .JARs from MySQL Connector/J and JSTL apart with your code. In the case of the Tomcat JSP container, you will need to create your directory where you will place all your files in the tree branch of Tomcat’s webapps/ directory, put your Hello.jsp and Continue.jsp, also create the WEB-INF/ directory, and put the web.xml file there:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
  PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
         "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app />

And then create the WEB-INF/lib/ subdirectory and put into it the next files:

  • jstl.jar
  • saxpath.jar
  • standard.jar
  • mysql-connector-java-3.0.9-stable-bin.jar (note, the name could vary, depending on your version of your Connector/J)

All this information is also provided with the JSTL and Tomcat manuals, and you will need to read it to understand what exactly is done and why. I am also including it here to help you with a quick start. Reload Tomcat and enjoy your stuff.

If you are using another JSP container, please read its manual guide.

To crown it all, I would like to mention that this article is only an introduction into JSTL technology — not a full guide. JSTL is full of different functions that will help you make your JSP development faster and easier. I recommend that you read more detailed documentation on JSTL‘s abilities and how it interacts with JavaBeans. Therefore, probably you will find that it is supposed to be your target development platform. Nevertheless, even with the knowledge from this article, you will be able to create simple front ends for your SQL database.

© Olexiy Prokhorenko, http://www.7dots.com/resume/
Co-author: Alexander Prohorenko

# # #

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories