Monday, 17 September 2012

JavaServer Pages Standard Tag Library (JSTL)

In my earlier post on JSP Custom Tags, we created our own tags. Similarly in the past, most JSP authors came across wide range of custom functionality  and created custom tags for some general purpose functionality (so that these can be reused for all future products).

JSTL is a collection of such custom tag libraries that implement general-purpose functionality common to Web applications, including iteration, manipulation of XML, database access and many more. The main  purpose for developing JSTL is “scriptlet free JSP”.

JSTL itself is actually composed of four separate tag libraries:
  1. Core: contains tags for conditions, control flow and to access variables etc.
  2. XML manipulation: contains tags for XML parsing and processing.
  3. SQL: contains tags for accessing and working with database.
  4. Internationalization and formatting: contains tags to support locale messages, text, numbers and date formation.
Moreover, there are 2 versions available of JSTL libraries:

1) EL version - Using this version of libraries, we can specify attribute values of JSTL tags using EL. For using this in JSP, we have to provide below URIs and prefix in taglib directive:

                     Core - http://java.sun.com/jsp/jstl/core - Prefix: c
                      SQL - http://java.sun.com/jsp/jstl/sql   - Prefix: sql
  Internationalization - http://java.sun.com/jsp/jstl/fmt  - Prefix: fmt
                 /Format
                      XML - http://java.sun.com/jsp/jstl/xml  - Prefix: x


2) Request Time VersionUsing this version of libraries, we cannot use EL and can only specify attribute values of JSTL tags using JSP expressions (<%=expression%>). For using this in JSP, we just have to append '_rt' to URI as well as to the prefix.
For example, for using core tags, we have to specify below URI and prefix:

                     Core - http://java.sun.com/jsp/jstl/core_rt - Prefix: c_rt

Core Tags
==========================
Tags available in this library come are used for doing most of the things in our JSPs such as:
-   Manipulation of scoped variables
-   Output
-   Conditional logic
-   loops
-   URL manipulation
-   Handling errors.

Below are some of the tags:

c:set

Provides a tag based mechanism for creating and setting scope based variables. Its syntax is as follows:

<c:set var=“name” scope = “scope” value = “expression” />

where, var attribute - name of the scoped variable
scope attribute - which scope (page|request|session|application) the variable resides in (default - page)
value attribute - value to be bound to the variable.
If the specified variable already exists, it will simply be assigned the indicated value. If not, a new scoped variable is created and initialized to that value.

c:out

This tag simply displays the value of an expression, rather than storing it.

<c:out value = “expression” default = “expression” />

This tag evaluates the expression specified by its value attribute, and then prints the result.
If the optional default attribute is specified, the c:out action will print its (default) value if the value attribute's expression evaluates either to null or an empty String.
For example, if request parameter num evaluates to null or an empty string then default value “0” would be displayed:

<c:out value = “${param.num}” default = “0” />

This above code is equivalent to following scriptlet:

<%
String no = request.getParameter(“num”);
if (no == null || no.equals(“”)) {
System.out.println(0);
}else{
Out.println(no);
}
%>

c:remove

The c:remove action is used to delete a scoped variable, and takes two attributes. The var attribute names the variable to be removed, and the optional scope attribute indicates the scope from which it should be removed. For example if variable 'name' is required to be removed from request scope, then c:remove tag will look like:

<c:remove var = “email” scope = “request” />

c:forEach

We have to use iteration to fetch and display collections of data, mostly in the form of sequence of rows in tables. JSTL action for implementing iterative content is c:forEach tag. This tag supports two different styles of iteration:

1) Iteration over an Integer range:
To iterate over a range of integers, syntax of the c:forEach tag will look like:

<c:forEach var=“name” begin=“expression” end=“expression” step=“expression” >
Body Content
</c:forEach>

The begin and end attributes should be either constant integer values or expressions evaluating to integer values. They specify the initial value and final value for the iteration, respectively.
The step attribute specifies the amount to be added to the index after each iteration. If the step attribute is omitted, the step size defaults to 1.
For example to generate squares corresponding to range of integer values, the c:forEach tag will be used as:

<c:forEach var=“x” begin=“0” end=“10” step=“2” >
   <c:out value=“${x * x}” />
</c:forEach>

Output:  4 16 36 64 100

2) Iteration over a Collection:
When iterating over the members of a collection and arrays etc, one additional attribute of the c:forEach tag is used: the 'items' attribute. Now the c:forEach tag will look like this:

<c:forEach var=“name” items=“expression” >
Body Content
</c:forEach>

The value of the items attribute should be the collection/array over whose members the iteration is to occur, and is typically specified using an EL expression.
For example, to iterate over a String array using java code, we would write in JSP:

<%
for(int i=0; i<messages.length; i++) {
String msg = messages[i];
%>
<%= msg %>
<%
} // end for
%>

In a much simpler way, using c:forEach tag we can write:

<c:forEach var=“msg” items=“${messages}” >
   <c:out value= “${msg}” />
</c:forEach>

c:if

This tag is used to conditionally process the body content. It simply evaluates a single test expression and then processes its body content only if that expression evaluates to true. If not, the tag's body content is ignored. The syntax for writing c:if tag is:

<c:if test= “expression” >
Body Content
</c:if>

For example, to display a message “These are equal” if two strings 'str1' & 'str2' are equal, the c:if tag is used as:

<c:if test= “${str1 == str2}” >
   <h2> Theses are equal </h2>
</c:if>

c:choose

c:choose tag is used in cases in which mutually exclusively test are required to determine what content should be displayed. The syntax is shown below:

<c:choose>
   <c:when test= “expression” >
      Body content
   </c:when>
   ……………
   <c:otherwise >
      Body content
   </c:otherwise>
</c:choose>

Each condition to be tested is represented by a corresponding <c:when> tag.  If none of the <c:when> tests return true, then the body content of the <c:otherwise> tag will be processed.
The example code given below illustrates the usage of c:choose tag in which two strings  'str1' &  'str2' are compared and appropriate messages are displayed:

<c:choose>
   <c:when test= “str1 == str2” >
      <h2> These are equal</h2>
   </c:when>
   <c:when test= “str1 <= str2” >
      <h2> str1 is less than str2</h2>
   </c:when>
   <c:otherwise >
      <h2> Don’t know the result </h2>
   </c:otherwise>
</c:choose>








No comments:

Post a Comment