JSTL quickly : very different useful concepts

Accessing Application Data

You can access application data either as a property of an object, using the dot (.) operator, or a named array element using the bracket[‘name’] operator.

The JSTL expression ${data} represents the scoped variable named data. You can retrieve properties from collections using either the dot (.) or bracket ([]) operator:

  • The dot (.) operator is used to retrieve a named property. For example, the expression ${customer.name} indicates the name property of thecustomer scoped variable.
  • The bracket operator ([]) can be used to retrieve a named property, as in ${customer[“name”]}. The bracket operator can also be used as${customers[0]} to refer to the first item in the customers collection.

The expression language unifies the treatment of dot (.) and bracket ([]) operators. Therefore, ${customer.name} is equivalent to${customer[“name”]}. As you can see, all EL expressions must be enclosed between ${ and }.

The EL evaluates an identifier by looking up its value as an attribute using PageContext.findAttribute(String). If the attribute is not found,null is returned.

Operators

The EL supports arithmetic, relational, and logical operators to handle the most common data manipulations. In addition, a special operator for testing if an object is empty is provided. The operators are shown in Table 1. You can use the empty operator to determine whether a collection or a string is empty or null. For example, ${empty param.name} will be true only if the request parameter named param is not present. The emptyoperator can be combined with the ! operator, as in the expression ${!empty param.name}, which evaluates to true if the request parameter named param is present.

Table 1: Expression language operators

Operator

Description

+ Addition
Subtraction
* Multiplication
/ or div Division
% or mod Modulus (Remainder)
== or<eq< code=””></eq<> Equality
!= or != Inequality
< or lt Less than
> or gt Greater than
<= or le Less than or equal to
>= or ge Greater than or equal to
&& or and Logical AND
|| or or Logical OR
! or not Boolean complement
empty Check for empty value

Implicit Objects

In addition to operators, the EL defines implicit objects to support access to application data that is of interest to page authors. The implicit objects defined by the EL are shown in Table 2. An example of how to use some of these implicit objects is provided later.

Table 2: Implicit objects provided by the expression language

Implicit Object

Content

applicationScope A collection of scoped variables from page scope
cookie A collection of all cookies
header HTTP request headers as strings
headerValues HTTP request headers as collections of strings
initParam A collection of all application parameter names
pageContext The javax.servlet.jspPageContext object for the current page
pageScope A collection of all page scope objects
param A collection of all request parameters as strings
paramValues All request parameters as collections of strings
requestScope A collection of all request scope objects
sessionScope A collection of all session scope objects

Twin Tag Libraries

For JSTL to support both the scripting and expression-language worlds, its designers came up with the concept of twin tag libraries. In other words, the JSTL tag library comes in two flavors that differ only in the way they support the use of runtime expressions for attribute values.

One library supports the request time expression values, and another supports the expression language. It is expected that most people will end up using the expression language (since it will be part of the JavaServer Pages 1.3 specification), but some may still prefer to use JSTL with scripting runtime (RT) expression values. The URIs of the RT-based tag libraries simply have the “_rt” suffix appended.

Table 3 lists each expression language-based tag library, with its recommended tag prefix and default URI, and Table 4 lists each runtime-based tag library with its recommended tag prefix and default URI.

Table 3: EL-based tag libraries

Functional Area

URI

Prefix

Core http://java.sun.com/jstl/core c
XML Processing http://java.sun.com/jstl/xml x
Internationalization http://java.sun.com/jstl/fmt fmt
Database Access http://java.sun.com/jstl/sql sql

 

Table 4: Runtime-based tag libraries

Functional Area

URI

Prefix

Core http://java.sun.com/jstl/core_rt c_rt
XML Processing http://java.sun.com/jstl/xml_rt x_rt
Internationalization http://java.sun.com/jstl/fmt_rt fmt_rt
Database Access http://java.sun.com/jstl/sql_rt sql_rt

Now, to use an EL-based JSTL library, you must declare the library using a taglib directive, similar to declaring a regular custom tag library:

<@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core”&gt;

Similarly, to use a runtime-based JSTL tag library, you must declare the library using a taglib directive:

<@ taglib prefix=”c_rt” uri=”http://java.sun.com/jstl/core_rt”&gt;

Once this is declared, you can use tags from that library with: <c:aTag>.

The Core Tag Library

The core tag library supports actions, including: output, manipulation of scoped variables, conditional logic, loops, URL manipulation, and error handling.

General Purpose Tags

Here are the general purpose tags for writing data, saving data to memory, deleting data, and handling errors:<c:out>, <c:set>, <c:remove>, and <c:catch>.

You can use <c:out> to write data, as in the following example:

The name of your city is: <c:out value=”${customer.city}” default=”unknown”/>

The <c:out> tag supports default values for cases where the EL expression is null. In this example, the value “unknown” will be displayed if the property city is not accessible.

Use <c:set> to set the value of a JSP scoped attribute as follows:

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

The <c:remove> tag is used to explicitly remove a scoped variable. For example:

<c:remove var=”cache” scope=”application/>

The <c:catch> tag allows page authors to recover gracefully from error conditions that they can control. See the next setion for an example.

Conditional Actions

The JSTL conditional actions support simple conditional execution (using <c:if>) and mutually exclusive conditional execution (using<c:choose>, <c:when>, and <c:otherwise>).

The <c:if> tag allows you to conditionally include a piece of the page, depending on runtime information. For example, the following snippet of code checks if a customer is based in Canada:

<c:if test=”${customer.country == ‘Canada’}”>

This customer is based in Canada.

</c:if>s

Here is another example that demonstrates the use of <c:if> with <c:catch>:

<c:catch var=”exception”>

<!– execution we can recover from. –>

</c:catch>

<c:if test=”${exception != null}”>

Processing could not be performed. Here is why….

</c:if>

 

You can achieve the equivalent of an if/then/else statement with <c:choose>, <c:when>, and <c:otherwise>, as follows:

<c:choose>

<c:when test=”${customer.country == ‘UK’}”>

UK has mild winters.

</c:when>

<c:when test=”${customer.country == ‘Canada’}”>

Canada has wild winters.

</c:when>

<c:when test=”$customer.country == ‘UAE’}”>

UAE has hot winters and good gold.

</c:when>

<c:otherwise>

Country is unknown.

</c:otherwise>

</c:choose>

 

Iteration Actions

Iterating over a collection of objects is a common task in JSP pages. The following snippet of code uses <c:forEach> to iterate over a list of customers:

<c:forEach var=”customer” items=”${customers}”>

Customer: <c:out value=”${customer}”/>

</c:forEach>

The <c:forEach> tag allows iteration over a subset of the collection items. The begin and end indices can be specified for this, along withsteps. Here is a simple example:

<c:forEach var=”k” begin=”1″ end”100″>

<c:out value=”${i % 2 == 0}”/>

</c:forEach>

As a more complete example, consider the following snippet of code, which prints all header parameters:

<%@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core&#8221; %>

 

<html>

<head>

<title>JSTL Implicit Objects</title>

</head>

<body bgcolor=”#FFFFCC”>

<h3>Header info:</h3>

 

<c:forEach var=”head” items=”${headerValues}”>

param: <c:out value=”${head.key}”/><br>

values:

<c:forEach var=”val” items=”${head.value}”>

<c:out value=”${val}”/>

</c:forEach>

<p>

</c:forEach>

 

</body>

</html>

 

If you are, however, interested in a specific header (the User-Agent for example), you can retrieve that information using the following syntax:${header[‘User-Agent’]}.

URL Actions

The <jsp:include> action, in the JSP specification, provides for the inclusion of static and dynamic resources located in the same context as the current page. This action is widely used, but it doesn’t allow page authors to include resources that are available remotely.

The JSTL provides a comprehensive set of actions for URL-related tasks. For example, you can use the <c:import> action to import local and remote resources. Here are some examples:

<c:import url=”./copyright.html”/>

<c:import url=”http://www.somewhere.com/hello.xml”/&gt;

You can use the <c:url> action to take care of all URL rewriting tasks. It can be combined with the <c:param> action, which transparently encodes query-string parameters. Consider the following example, which rewrites and encodes a URL for user registration:

<c:url value=”http://www.somewhere.com/customers/register&#8221; var=”registrationURL”>

<c:param name=”name” value=”${param.name}”/>

<c:param name=”country” value=”${param.country}”/>

</c:url>

<a href='<c:out value=”${registrationURL}”/>’>Customer Registration>/a>

 

Finally, <c:redirect> (to support HTTP redirect) completes the list of URL-related actions. Here is an example:

<c:redirect url=”https://www.somewhere.com/register”>

XML Tags

XML is becoming increasingly important to page authors, and the JSTL provides XML actions that address the basic needs of those developers. The XML actions can be divided into core, control flow, and transformation actions. The XML core actions are similar to those provided in the core actions discussed above, and include <x:out>, <x:set>, and <x:parse>. The main difference between the core actions discussed above and the XML core actions is that XML actions support XPath expressions, while the core actions do not. As a matter of fact, the XML actions are basedon XPath expressions. If you’re unfamiliar with XPath, it’s a language for defining parts of an XML document; XPath uses path expressions to identify nodes in an XML document.

The XML control flow actions are the same as the core actions discussed above. They include: <x:if>, <x:choose>, <x:when>, <x:otherwise>, and <x:forEach>. The main difference is that you use the select attribute to specify XPath expressions. Here is an example:

<x:forEach select=”$output/portfolio/stock”>

<x:out select=”price”/>

</x:forEach>

Now, let’s look at a set of examples that demonstrate the tags discussed so far. In Code Sample 1, xml-ex1.jsp uses the core and XML tag libraries to process an XML document. In this example, the XML document is embedded within the page and the <x:parse> tag is used to parse the document. Then, an XPath expression is used to select items from the document.

Code Sample 1: xml-ex1.jsp

<%@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core&#8221; %>

<%@ taglib prefix=”x” uri=”http://java.sun.com/jstl/xml&#8221; %>

 

<html>

<head>

<title>JSTL Support for XML</title>

</head>

<body bgcolor=”#FFFFCC”>

<h3>Books Info:</h3>

 

<c:set var=”xmltext”>

<books>

<book>

<title>Book Title A</title>

<author>A. B. C.</author>

<price>17.95</price>

</book>

<book>

<title>Book Title B</title>

<author>X. Y. Z.</author>

<price>24.99</price>

</book>

</books>

 

</c:set>

 

<x:parse xml=”${xmltext}” var=”output”/>

<b>The title of the first book is</b>:

<x:out select=”$output/books/book[1]/title”/>

<br>

<b>The price of the second book</b>:

<x:out select=”$output/books/book[2]/price”/>

</body>

</html>

 

If you request xml-ex1.jsp, you’ll see something like Figure 1.

Figure 1: JSTL support for XML

In the above example, the XML text is included within the JSP page. In a real application, however, the XML document would be hosted on a local or remote web server. You can import a remote resource by using the <c:import> tag. Consider the XML document shown in Code Sample 2, which is located at http://www.javacourses.com/stocks.xml.

Note: If you’d like to see how JSP pages can be used (and the amount of code involved) in processing stocks.xml, take a look atWeb Application Development with JSP pages and XML.

Code Sample 2: stocks.xml

<?xml version=”1.0″ encoding=”UTF-8″?>

<portfolio>

<stock>

<symbol>SUNW</symbol>

<name>Sun Microsystems</name>

<price>17.1</price>

</stock>

<stock>

<symbol>AOL</symbol>

<name>America Online</name>

<price>51.05</price>

</stock>

<stock>

<symbol>IBM</symbol>

<name>International Business Machines</name>

<price>116.10</price>

</stock>

<stock>

<symbol>MOT</symbol>

<name>Motorola</name>

<price>15.20</price>

</stock>

</portfolio>

 

This document can be imported using the following snippet of code:

<c:import url=”http://www.javacourses.com/stocks.xml&#8221; var=”xmldoc”/>

XML Conditional Logic

The conditional logic in the XML tag library is the same as the one in the core tag library. As an example, the following snippet of code parses an XML document, then selects (using an XPath expression) the stock with the symbol SUNW.

<x:parse xml=”${xmldoc}” var=”output”/>

<x:if select=”$output/portfolio/stock[symbol = ‘SUNW’]”>

You still have Microsystems Stocks!

</x:if>

if/then/else

You can implement an if/then/else clause using the <x:choose> action, which selects one among a number of possible alternatives. It consists of a sequence of <x:when> elements, followed by an optional <x:otherwise>. Each <x:when> element has a single attribute, select, that specifies an XPath expression. When a <x:choose> element is processed, each of the <x:when> elements has its expressions evaluated in turn. Only the body of the first <x:when> element (whose result is true) is rendered. If none of the test conditions of nested tags evaluates to true, the body of the <x:otherwise> tag is evaluated, if present.

Here is an example:

<x:parse xml=”${xmldoc}” var=”output”/>

 

<x:choose>

<x:when select=”$output/portfolio/stock[price > ’70’]”>

You still have stocks worth over $70.

</x:when>

<x:otherwise>

You have no stocks worth over $70.

</x:otherwise>

</x:choose>

 

Iteration

The <x:forEach> action evaluates the given XPath expression, and iterates over the result. The example shown in Code Sample 3, xml-ex2.jsp, shows how to print stock information from an XML document.

Code Sample 3: xml-ex2.jsp

<%@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core&#8221; %>

<%@ taglib prefix=”x” uri=”http://java.sun.com/jstl/xml&#8221; %>

 

<html>

<head>

<title>JSTL Support for XML</title>

</head>

<body bgcolor=”#FFFFCC”>

<h3>Portfolio</h3>

 

<c:import url=”http://www.javacourses.com/stocks.xml&#8221; var=”xmldoc”/>

<x:parse xml=”${xmldoc}” var=”output”/>

 

<p>

 

<table border=”2″ width=”50%”>

<tr>

<th>Stock Symbol</th>

<th>Company Name</th>

<th>Price</th>

</tr>

<tr>

 

<x:forEach select=”$output/portfolio/stock” var=”item”>

<td><x:out select=”symbol”/></td>

<td><x:out select=”name”/></td>

<td><x:out select=”price”/></td></tr>

</x:forEach>

</table>

 

</body>

</html>

 

When you request this page, you will see something similar to Figure 2.

Figure 2: Importing and parsing an XML document, then iterating over its nodes

Transforming XML

Many web applications use XSLT stylesheets to transform XML within JSP pages, and the JSTL supports this. The XML document to be transformed, as well as the XSLT stylesheet to be used, can be retrieved from a relative, absolute, or remote URL. The result of the transformation is written to the page. As an example, the stocks.xml document shown in Code Sample 2 (which is located at a remote web server) is transformed using the XSLT stylesheet (stocks.xsl) shown in Code Sample 4 but fetched from a local web server:

Code Sample 4: stocks.xsl

<?xml version=”1.0″?>

<xsl:stylesheet xmlns:xsl=

http://www.w3.org/1999/XSL/Transform&#8221; version=”1.0″>

 

<xsl:output method=”html” indent=”yes”/>

 

<xsl:template match=”/”>

<html>

<body>

<xsl:apply-templates/>

</body>

</html>

</xsl:template>

 

<xsl:template match=”portfolio”>

<table border=”2″ width=”50%”>

<xsl:for-each select=”stock”>

<tr>

<td>

<i><xsl:value-of select=”symbol”/></i>

</td>

<td>

<xsl:value-of select=”name”/>

</td>

<td>

<xsl:value-of select=”price”/>

</td>

</tr>

</xsl:for-each>

</table>

</xsl:template>

</xsl:stylesheet>

 

The following example, xml-ex3.jsp (shown in Code Sample 5) demonstrates how to transform an XML document located on a remote web server using the stocks.xsl stylesheet shown in Code Sample 4.

Code Sample 5: xml-ex3.jsp

<%@ taglib prefix=”c” uri=”http://java.sun.com/jstl/core&#8221; %>

<%@ taglib prefix=”x” uri=”http://java.sun.com/jstl/xml&#8221; %>

 

<html>

<head>

<title>JSTL: Importing XML Document</title>

</head>

<body bgcolor=”#FFFFCC”>

<h3>Transforming stocks.xml into HTML using stocks.xsl</h3>

 

<c:import url=”http://www.javacourses.com/stocks.xml&#8221; var=”xmldocument”/>

<c:import url=”./stocks.xsl” var=”xslt”/>

<x:transform xml=”${xmldocument}” xslt=”${xslt}”/>

 

</body>

</html>

 

When you load xml-ex3.jsp, you should see something in the browser similar to Figure 3.

Figure 3: Transforming an XML document using an XSLT stylesheet

 

Advertisements

About rajkirpal

i am a software engineer. and i have decent knowledge about java technologies like ANDROID, Servlet, Jsp, Struts, Hibernet, Spring, J2ME, Java Script, Ajax, JQuery, CSS. Further i am Preparing Easy understandable materials/documents upon the same java technologies and developing project in core java , advanced java and j2me , ANDROID as per the requirements Also designing the web sites and logos Thank You.
This entry was posted in JSTL. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s