WEBSITE

Java EE 6 with GlassFish 3 Application Server : Core JSTL tag library

9/18/2012 7:06:43 PM
Core JSTL tags perform tasks such as writing output to the browser, conditional display of segments in a page, and iterating through collections. Much of what the core JSTL tags do can be accomplished with scriptlets. However, the page is much easier to read and therefore more maintainable if core JSTL tags are used instead of scriptlets.

The following example shows a JSP using some of the most common JSTL core tags:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="java.util.ArrayList"%>
<html>
<%
ArrayList<String> nameList = new ArrayList<String>(4);
nameList.add("David");
nameList.add("Raymond");
nameList.add("Beth");
nameList.add("Joyce");
request.setAttribute("nameList", nameList);
%>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Core Tag Demo</title>
</head>
<body>
<c:set var="name" scope="page" value="${param.name}"></c:set>
<c:out value="Hello"></c:out>
<c:choose>
<c:when test="${!empty name}">
<c:out value="${name}"></c:out>
</c:when>
<c:otherwise>
<c:out value="stranger"></c:out>
<br />
<c:out value="Need a name? Here are a few options:" />
<br />
<ul>
<c:forEach var="nameOption" items="${requestScope.nameList}">
<li /><c:out value="${nameOption}"></c:out>
</c:forEach>
</ul>
</c:otherwise>
</c:choose>
<c:remove var="name" scope="page" />
</body>
</html>


					  

In a nutshell, this example looks for a request parameter called name. If it finds it, it displays the message "Hello ${name}" in the browser (${name} is actually replaced with the value of the parameter). If the parameter is not found, it prints the message "Hello stranger" and gets a little smart with the user, suggesting a few names. This can be seen in the following screenshot:

The page employs the taglib directive to declare that it uses the JSTL core tag library. Although any prefix can be used for this library, using the prefix c is standard practice.

Before doing anything with JSTL, the page has a scriptlet that initializes an instance of java.util.ArrayList with some strings containing names and attaches ArrayList to the request (this would typically be done in a servlet or some other class, not in the JSP itself; it was done this way in the example for simplicity).

The first JSTL tag used in the page is the<c:set> tag. This tag sets the result of the expression defined in its variable attribute and stores it in a variable in the specified scope. The name of the variable is defined in the tag's var attribute. The scope of the variable is defined in the tag's scope attribute; if no scope is specified, the page scope is used by default. The expression to be evaluated is defined in the tag's value attribute.

Page scope is always the default

A number of JSTL tags contain a var attribute to define a variable in a scope specified by a scope attribute. In all cases, if no scope is specified, the page scope is used by default.


In the previous example, the expression is looking for the value of a request parameter with a name of "name". param is an implicit variable that resolves to a map using request parameter names as keys and request parameter values as values. This implicit variable is equivalent to calling the getParameterMap() method on the request. The value after the dot (name in the previous example) corresponds to the key we want to get from the parameter map (which in turn corresponds to the request parameter name).

The next core JSTL tag we see in the example is the<c:out> tag. This tag simply displays in the browser the value of the expression defined in its value attribute. In this particular case, the expression defined in the value attribute is a constant, therefore it is displayed verbatim in the browser output.

Next, we see the<c:choose> tag. This tag allows us to perform if/then/else like conditions in the page. The<c:choose> tag must contain one or more<c:when> tags and optionally a<c:otherwise> tag. The<c:when> tag contains a test attribute that must contain a Boolean expression. Once the expression in one of the<c:when> tags nested in a<c:choose> tag evaluates to true, the body of the tag is executed and the test attribute of other<c:when> tags nested inside the same<c:choose> tag is not evaluated.

The next new tag we see in the example is the<c:otherwise> tag. The body of this optional tag is executed if none of the expressions in any<c:when> tag evaluates to true. In the example, the body of the tag is executed when no request parameter with a name of "name" exists in the request, or if the value of the parameter is an empty String.

In the previous example, the<c:when> tag contains a ! operator that negates a Boolean expression, just like in Java. The tag also contains an empty operator; this operator checks to see if a String is null or has a length of zero. The test attribute of the<c:when> tag can have several logical and/or relational operators that can be combined to build more complex expressions. All relational operators that can be used in the test attribute (or any other Unified Expression Language expression, for that matter) are listed in the following table:

Relational operator Description
== or eq Equals: evaluates to true if the expression on the left of the operator equals the expression on the right of the operator.
> or gt Greater than: evaluates to true if the expression on the left of the operator is greater than the expression on the right of the operator.
< or lt Less than: evaluates to true if the expression on the left of the operator is less than the expression on the right of the operator.
>= or ge Greater than or equal: evaluates to true if the expression on the left of the operator is greater than or equal to the expression on the right of the operator.
<= or le Less than or equal: evaluates to true if the expression on the left of the operator is less than or equal to the expression on the right of the operator.
!= or ne Not equal: evaluates to true if the expression on the left of the operator is not equal to the expression on the right of the operator.

All of these symbolic operators work the same way as their equivalent Java operators, therefore, their use should be natural to any Java developer. In addition to allowing us to use the symbolic operators in the Unified Expression Language, all symbolic operators have a textual equivalent. These textual equivalents are used if we need our page to be valid XML, as using the symbolic operators typically results in an invalid XML markup.

In addition to relational operators, logical operators can also be used in Unified Expression Language expressions. Valid logical operators are listed in the following table:

Logical operator Description
&& or and And: evaluates to true if both the expression on the left of the operator and the one on the right of the operator are true.
|| or or Or: evaluates to true if either the expression on the left of the operator or the one on the right of the operator is true (or both).
! or not Not: negates the expression on the right of the operator. If the expression evaluates to true, this operator makes it evaluate to false, and vice versa.
empty Empty: evaluates to true if the value to the right of the operator is null or empty. The value to the right of the operator must be a String or a Collection.
E1?E2:E3 Conditional expression: if E1 is true, evaluates to E2; otherwise, it evaluates to E3.

Just like with relational operators, logical operators work the same way as their Java equivalents. All of them, except the ternary operator and empty, have a symbolic and textual variant.

The Unified Expression Language also contains arithmetic operators. These are listed in the following table:

Arithmetic operator Description
+ Addition: adds the values on the left and right of the operator.
- (binary) Subtraction: subtracts the value on the right of the operator from the value on the left of the operator.
* Multiplication: multiplies the values on the left and right of the operator
/ or div Division: divides the values on the left (dividend) and right (divisor) of the operator.
% or mod Modulo: divides the values on the left (dividend) and right (divisor) of the operator and returns the remainder.
- (unary) Minus: multiplies the value to the right of the operator by -1.

All arithmetic operators must be used with numerical values.

After our brief discussion of the Unified Expression Language operators, we can now get back to discussing the example. The next new tag we see in the example is the<c:forEach> tag. This tag iterates through a Collection, array, or Map. In the example, it iterates through an instance of java.util.ArrayList attached to the request in the scriptlet defined earlier in the page. The var attribute of the<c:forEach> tag defines a variable to be used to access the current element in the collection. This variable is only visible inside the body of the tag. The items attribute of the<c:forEach> tag indicates the array, collection, or map to iterate through. The<c:forEach> tag has additional attributes that are not shown in the example: the begin attribute indicates the index of the first item to iterate from and the end attribute indicates the last item to iterate to. If the begin attribute is not set, iteration begins at the first item in the Collection, array, or Map. If the end attribute is not set, iteration ends at the last element of the Collection, array, or Map. An additional attribute of the<c:forEach> tag is the step attribute. It indicates the increment from one index to the next and defaults to 1. In addition to iterating through a Collection, array, or Map, the<c:forEach> tag can be used to execute its body a number of times. To use the<c:forEach> tag this way, its items attribute is omitted and its begin and end attributes are required.

The next new tag we see in the example is the<c:remove> tag. This tag is used to remove a variable attached to the scope specified in its scope attribute. If no scope is specified, the<c:remove> tag uses a default scope of page.

There are some additional core JSTL tags not shown in the example. These remaining tags are explained next.

The<c:if> tag is similar to the<c:when> tag; its body is executed if the expression defined by its test attribute is true. The<c:if> tag has two optional attributes: a var attribute that defines the name of a Boolean variable storing the results of the tag's test attribute, and a scope attribute defining the scope of the var attribute. The<c:if> tag should not be nested in a<c:choose> tag. Unlike the<c:when> tag, the expression defined in the test attribute of multiple<c:if> tags is evaluated, regardless of whether a previous<c:if> expression resolved to true or not.

The<c:forTokens> tag iterates over a delimiter separated string. The<c:forTokens> tag has two required attributes: items and delims. The items attribute value must be an expression resolving to a String or a String constant. The value of the delims attribute must be an expression or a String constant indicating the characters to be used as delimiters. Each individual character in the delims attribute will be used as a delimiter for the value of the item, similar to the way the java.util.StringTokenizer class works. Additionally, the<c:forTokens> tag has a var attribute that works essentially the same way as the var attribute of the<c:forEach> tag. That is, it defines a name for the current item in its items attribute, allowing it to be accessed in the body of the<c:forTokens> tag.

The<c:import> tag is similar to<jsp:include>. It includes the contents of a relative or absolute URL into the rendered JSP. Optionally, this tag can store the contents of the included URL in a String or in an instance of java.io.Reader. The<c:import> tag has one required attribute called url; the value of this attribute is a String expression containing the URL to be imported. If we wish to store the contents of the included URL in a String, then the var attribute must be used. The value of this attribute is the name of the String that will hold the contents of the included URL. If we wish to include the contents of the included URL in an instance of java.io.Reader, then the varReader attribute must be used. The value of this attribute is the name of the variable that will hold the contents of the included URL. The<c:import> tag has an optional scope attribute that defines the scope of the variable defined by the var or varReader attributes. If this attribute is not used, the var or varReader variable will have a default scope of page.

The<c:redirect> tag redirects the browser to the URL specified in its url attribute. It is equivalent to calling the sendRedirect() method of an instance of javax.servlet.http.HttpServletResponse.

The<c:url> tag constructs a URL from the value of its url attribute and stores it in a String whose name is defined in the tag's var attribute. The default scope of the variable defined by the var attribute is page. This can be changed by using the tag's scope attribute.

It is possible to pass parameters to the URL defined in the url attribute of the<c:import>, <c:redirect>, or<c:url> tags. This is done by using the<c:param> tag. This tag must be nested inside one of the mentioned three tags. The<c:param> tag has two attributes: a required name attribute defining the parameter name and a value attribute defining the parameter value.

The last core JSTL tag is the<c:catch> tag. This tag catches any java.lang.Throwable thrown inside its body.

java.lang.Throwable is the parent class of java.lang.Exception and java.lang.Error. Therefore, any Exception or Error thrown inside the body of the<c:catch> tag is also caught.


If a Throwable is thrown inside the body of the<c:catch> tag, control goes to the line immediately following the closing</c:catch> tag. Any lines inside the body of the<c:catch> tag, that were processed before the Throwable is thrown, are processed. The<c:catch> tag has a single optional attribute named var. This attribute defines a variable to hold the Throwable that was thrown inside the body of the<c:catch> tag. This variable always has a scope of page.

The following table lists all of the JSTL core tag libraries:

Tag Description Example
<c:catch> Catches any Exception, Error, or Throwable thrown inside its body. <c:catch var="e">

<c:out value="1/0"/>

<c:if test="e!=null">

<c:out value= "e.message"/>

</c:if>

</c:catch>
<c:choose> Used to wrap the<c:when> and (optionally)<c:otherwise> tags. The body of the first<c:when> tag containing a test expression that evaluates to true is executed. If none of the<c:when> tags contain a test expression that evaluates to true, then the body of the<c:otherwise> tag is executed. <c:choose>

<c:when test="empty o">

<c:out value="o is empty"/>

</c:when>

<c:otherwise>

<c:out value="o is not empty"/>

</c:otherwise>

</c:choose>
<c:forEach> Iterates over an array, Collection, or Map. <c:forEach items="${session.array OrCollection}" var="item">

<c:out value="item" = ${item}><br/>

</c:forEach>
<c:if> Its body gets executed if the test expression evaluates to true. <c:if test="${a>b}">

<c:out value="a is greater than b"/>

</c:if>
<c:import> Imports content from the URL indicated in the url attribute into the rendered page. <c:import url="http://foo.com/ somePage.jsp">

<c:param name="someName" value="some val"/>

</c:import>
<c:out> Outputs the value of the value expression. <c:out value="> is the greater than symbol" escapeXml="true"/>
<c:otherwise> Its body gets executed if none of the test expressions in the<c:when> tags nested in the same<c:choose> tag evaluate to true. See example for<c:choose>
<c:param> Sets a parameter for a URL defined in the<c:url> or<c:import> tag. See example for<c:import>
<c:redirect> Redirects to the specified URL. <c:redirect url="http://ensode.net"/>
<c:remove> Removes a variable from the page scope or the specified scope. <c:remove var="varName" scope="session"/>
<c:set> Sets a variable in the page scope or the specified scope. <c:set var="varName" value="foo" scope="session"/>
<c:url> Creates a URL variable. <c:url value="http://foo.com" var="fooUrl"/>
<c:when> Its body gets executed when its test expression evaluates to true. See example for<c:choose>
Other  
 
Top 10
Review : Sigma 24mm f/1.4 DG HSM Art
Review : Canon EF11-24mm f/4L USM
Review : Creative Sound Blaster Roar 2
Review : Philips Fidelio M2L
Review : Alienware 17 - Dell's Alienware laptops
Review Smartwatch : Wellograph
Review : Xiaomi Redmi 2
Extending LINQ to Objects : Writing a Single Element Operator (part 2) - Building the RandomElement Operator
Extending LINQ to Objects : Writing a Single Element Operator (part 1) - Building Our Own Last Operator
3 Tips for Maintaining Your Cell Phone Battery (part 2) - Discharge Smart, Use Smart
REVIEW
- First look: Apple Watch

- 3 Tips for Maintaining Your Cell Phone Battery (part 1)

- 3 Tips for Maintaining Your Cell Phone Battery (part 2)
VIDEO TUTORIAL
- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 1)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 2)

- How to create your first Swimlane Diagram or Cross-Functional Flowchart Diagram by using Microsoft Visio 2010 (Part 3)
Popular Tags
Microsoft Access Microsoft Excel Microsoft OneNote Microsoft PowerPoint Microsoft Project Microsoft Visio Microsoft Word Active Directory Biztalk Exchange Server Microsoft LynC Server Microsoft Dynamic Sharepoint Sql Server Windows Server 2008 Windows Server 2012 Windows 7 Windows 8 Adobe Indesign Adobe Flash Professional Dreamweaver Adobe Illustrator Adobe After Effects Adobe Photoshop Adobe Fireworks Adobe Flash Catalyst Corel Painter X CorelDRAW X5 CorelDraw 10 QuarkXPress 8 windows Phone 7 windows Phone 8
Visit movie_stars's profile on Pinterest.