JavaData & JavaUsing JSTL to Enhance JSP Functionality

Using JSTL to Enhance JSP Functionality

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

JSTL stands for JavaServer Pages Standard Tag Library; it provides a set of core Web page functionality that can perform many of the basic tasks, such as conditional and iterations of structural elements, manipulating XML documents, and support for internationalization tags to more sophisticated processing of SQL elements. JSP is better known for scriplets, yet it is highly discouraged since the inception of JSTL and EL (Expression Language). The reason is that scriplet element within JSP violates many of the basic principles of good engineering practices. The article delves into some of the key aspects of JSTL that highlight the convenience of using it over scriplets.

Problems of Using Scripting Elements in JSP

Look into some of the problems that arise due to the scripting elements (those written within <% … %>). There are just too many. Let’s get a quick overview of a few of them and the rest you can infer very easily.

  • Reusability: The scriplets embedded within JSP cannot be reused. As a result, using features of object-oriented technology, such as inheritance, composition, and association is utterly inapplicable. Also, there is no way to make a scriplet abstract. The side effect is repetition of the same code in multiple places, a highly unacceptable practise in object-oriented programming.
  • Debugging: This is one of the dark areas. Try debugging a JSP page with sprinkled scriplets ornamentally strewn across some of the unimportant corners of the HTML tags. I mean, if you haven’t come across such as file, let me tell you it’s very easy to create one, at least in JSP. Debug it. Now the hard part; do not bang your head. Any exception thrown in halfway tthrough the code gives a blank page, an empty scroll to create your own meaning out of it.
  • Maintainability: Well, something that is averse to reusability with horrendous debug ability, it’s out of the question. Cluttered, mangled, and duplicated codes are hardly maintainable.

However, a few simple scriplets within JSP is a mark of convenience but still business logic written within JSP scriplets is a strict no-no, not because it cannot be written but because it is a bad omen (difficult to maintain). The code convention from JSP 1.2 Specification recommends the use of the JSP Standard Tag Library in Web application. It would help reduce the need for JSP scriptlets in JSP pages. Pages that use JSTL are, in general, easier to read and maintain. Refer to Code Convention for JSP Technologies…. Apart from JSTL, there are other ways to overcome some of the aforesaid problems such as using Java bean components for writing business logic,and so forth. But, let’s forego those details and stick to what JSTL has to offer.

Overview of JSTL

JSTL tags can be grouped into five categories. Each of them can be used for a specific purpose. For example:

  • Core tagsare used for general purpose programming in a JSP page such as displaying string elements, conditional statements, iteration, and redirecting to a new URL. The syntax to include the core library is:
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
  • Formatting tagsare particularly useful for internationalization, apart from formatting text, date, time and numbers. The syntax to include the library is:
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
  • SQL tagscan be used for all CRUD operations when dealing with relational databases. The syntax to include the library is:
    <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
  • XML tagsare useful for manipulating XML documents such as parsing and transforming XML data. The syntax to include the library is:
    <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
  • JSTL functionsprovide numerous tags for string processing. The syntax to include the library is:
    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

Refer to the API documentaion for JSTL 1.1 library for more information on tag details of each category.

A Simple CRUD Application in JSTL

The example demonstrates how JSTL can be used to write a simple CRUD application without even writing a single scriplet element in the JSP page. Note that this program is a workable but rudimentary implementation. Data validation and error handling is omitted for brevity. The eye candy CSS part is also not given in the following code section for the same reason.

JSTL1
Figure 1: The program in execution

The program uses a MySQL database at the back-end. The SQL code to create the table is as follows.

CREATE DATABASE testdb1;
USE testdb1;
CREATE TABLE address_book
( id INT PRIMARY KEY,
   fname VARCHAR(30),
   lname VARCHAR(30),
   phone VARCHAR(30),
   email VARCHAR(30)
);

Page Workflow

JSTL2
Figure 2: The page’s workflow chart

index.jsp

<%--
   Document   : index
   Created on : 29 Dec, 2015, 7:48:45 PM
   Author     : mano
--%>

<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html;
         charset=UTF-8">
      <link href="style.css" rel="stylesheet" type="text/css"/>
      <title>Home Page</title>
   </head>
   <body>
      <sql:setDataSource var="dbSource" driver="com.mysql.jdbc.Driver"
                         url="jdbc:mysql://localhost/testdb1"
                         user="root" password="pass123"/>
      <sql:query dataSource="${dbSource}" var="dbResult">
         SELECT * FROM address_book;
      </sql:query>

      <div id="myform">
         <form action="insert.jsp" method="post">
            <h1>New Address</h1>
            <p class="mystyle">Add new address details</p>
            <label>ID <span>Insert numeric id</span> </label>
            <input type="text" name="id"/>
            <label>First Name <span>Enter first name of
               the person</span> </label>
            <input type="text" name="fname"/>
            <label>Last Name <span>Enter Last name of
               the person</span> </label>
            <input type="text" name="lname"/>
            <label>
               Phone <span>Enter phone number</span>
            </label>
            <input type="text" name="phone"/>
            <label>
               Email <span>Enter email address</span>
            </label>
            <input type="text" name="email"/>
            <input type="submit" value="Add New"/>
         </form>
      </div>

      <br/>
      <font color="blue">
         <c:if test="${not empty param.msg}">
            <c:out value="${param.msg}" />
         </c:if>
      </font>
      <br/>
      <form>
         <div class="CSSTableGenerator" >
            <table>
               <tr>
                  <td>ID</td>
                  <td>First Name</td>
                  <td>Last Name</td>
                  <td>Phone</td>
                  <td>Email</td>
                  <td colspan="2"></td>
               </tr>
               <c:forEach var="row" items="${dbResult.rows}">
                  <tr>
                     <td><c:out value="${row.id}"/></td>
                     <td><c:out value="${row.fname}"/></td>
                     <td><c:out value="${row.lname}"/></td>
                     <td><c:out value="${row.phone}"/></td>
                     <td><c:out value="${row.email}"/></td>
                     <td>
                        <a href="updateForm.jsp?id=<c:out
                           value="${row.id}"/>">Update</a>
                     </td>
                     <td><a href="delete.jsp?id=<c:out
                        value="${row.id}"/>">Delete</a></td>
                  </tr>
               </c:forEach>
            </table>
         </div>
      </form>
      <br/>
   </body>
</html>

insert.jsp

<%--
   Document   : insert
   Created on : 29 Dec, 2015, 8:15:47 PM
   Author     : mano
--%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html;
         charset=UTF-8">
      <title>JSP Page</title>
   </head>
   <body>

      <sql:setDataSource var="dbSource"
                         driver="com.mysql.jdbc.Driver"
                         url="jdbc:mysql://localhost/testdb1"
                         user="root" password="pass123"/>


      <sql:update dataSource="${dbSource}" var="dbResult">
         INSERT INTO address_book(id, fname, lname, phone, email)
            VALUES (?,?,?,?,?);
         <sql:param value="${param.id}" />
         <sql:param value="${param.fname}" />
         <sql:param value="${param.lname}" />
         <sql:param value="${param.phone}" />
         <sql:param value="${param.email}" />
      </sql:update>
      <c:if test="${dbResult>=1}">
         <c:redirect url="index.jsp" >
            <c:param name="msg" value="1 record inserted" />
         </c:redirect>
      </c:if>
   </body>
</html>

updateForm.jsp

<%--
   Document   : insertForm
   Created on : 29 Dec, 2015, 8:36:06 PM
   Author     : mano
--%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html;
         charset=UTF-8">
      <link href="style.css" rel="stylesheet" type="text/css"/>
      <title>Insert form Page</title>
   </head>
   <body>
      <sql:setDataSource var="dbSource" driver="com.mysql.jdbc.Driver"
                         url="jdbc:mysql://localhost/testdb1"
                         user="root" password="pass123"/>

      <sql:query dataSource="${dbSource}" var="dbResult">
         SELECT * from address_book where id=?;
         <sql:param value="${param.id}" />
      </sql:query>


      <div id="myform">
         <form action="update.jsp" method="post">
            <h1>Update Address</h1>
            <p class="mystyle">
               Update Address ID <c:out value="${param.id}"/>
            </p>
            <c:forEach var="row" items="${dbResult.rows}">
               <input type="hidden" value="${row.id}" name="id"/>
               <label
                  >First Name <span>Enter first name of the person</span>
               </label>
               <input type="text" value="${row.fname}" name="fname"/>
               <label>
                  Last Name <span>Enter Last name of the person</span>
               </label>
               <input type="text" value="${row.lname}" name="lname"/>
               <label>Phone <span>Enter phone number</span> </label>
               <input type="text" value="${row.phone}" name="phone"/>
               <label>Email <span>Enter email address</span> </label>
               <input type="text" value="${row.email}" name="email"/>
               <input type="submit" value="Update"/>
            </c:forEach>
         </form>
      </div>
   </body>
</html>

update.jsp

<%--
   Document   : update
   Created on : 29 Dec, 2015, 9:52:26 PM
   Author     : mano
--%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html;
         charset=UTF-8">
      <title>JSP Page</title>
   </head>
   <body>
      <sql:setDataSource var="dbSource" driver="com.mysql.jdbc.Driver"
                         url="jdbc:mysql://localhost/testdb1"
                         user="root" password="pass123"/>

      <sql:update dataSource="${dbSource}" var="dbResult">
         UPDATE address_book SET fname=?, lname=?, phone=?,
            email=? WHERE id=?;
         <sql:param value="${param.fname}" />
         <sql:param value="${param.lname}" />
         <sql:param value="${param.phone}" />
         <sql:param value="${param.email}" />
         <sql:param value="${param.id}" />
      </sql:update>

      <c:if test="${dbResult>=1}">
         <c:redirect url="index.jsp" >
            <c:param name="msg" value="1 record updated" />
         </c:redirect>
      </c:if>
   </body>
</html>

delete.jsp

<%--
   Document   : delete
   Created on : 29 Dec, 2015, 10:08:06 PM
   Author     : mano
--%>
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html;
         charset=UTF-8">
      <title>JSP Page</title>
   </head>
   <body>
      <sql:setDataSource var="dbSource" driver="com.mysql.jdbc.Driver"
                         url="jdbc:mysql://localhost/testdb1"
                         user="root" password="pass123"/>
      <sql:update dataSource="${dbSource}" var="dbResult">
         DELETE FROM address_book WHERE id=${param.id};
      </sql:update>
      <c:if test="${dbResult>=1}">
         <c:redirect url="index.jsp" >
            <c:param name="msg" value="1 record deleted." />
         </c:redirect>
      </c:if>
   </body>
</html>

Conclusion

By using JSTL, we can conveniently overcome the disadvantage of scripting elements in a JSP page. The code becomes simple and more readable. JSTL, however, cannot replace the flexibility of scripting. But, as a rule of thumb, a programmer should refrain from writing scriplets, especially in situations when other techniques such as JSTL suffice their needs.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories