You are on page 1of 94

08/29/2006

JSTL (JSP Standard


Tag Library)

In this session, we are going to learn about JSTL (JSP Standard Tag
Library). We learned about custom tags in the previous session and how
custom tags are used within a JSP based Web applications. JSTL is
basically a standard set of custom tags.

1
08/29/2006

Sang Shin
sang.shin@sun.com
www.javapassion.com
Java ™ Technology Evangelist
Sun Microsystems, Inc.
2

2
08/29/2006

Revision History
?
11/01/2003: version 1: created by Sang Shin
?
Things to do
– speaker notes need to be polished
– there are still some topics that are not covered yet

3
08/29/2006

Agenda
? What is and Why JSTL?
? JSTL Functional areas
– Core tags
– Database Access tags
– XML tags
? Quick review on XPath

– Internationalization and Text Formatting tags


– EL (Expression Language) functions tags

So what are we going to talk about in this session?

First, we will talk a little bit on what is and why you want to use JSTL? Then
we will go over the JSTL tags which are categorized into 5 functional areas as
mentioned above in the slide. As for XML tags, since understanding XPath
expression is important, we will spend some time going over important aspects
of XPath. At the end, we will also talk about JSTL roadmap.

4
08/29/2006

What is &
Why JSTL?

So let's talk about what is and why you want to use leverage with JSTL in
your Web application.

5
08/29/2006

What is JSTL?
? Standard set of tag libraries
? Encapsulates core functionality common to
many JSP applications
– iteration and conditionals
– XML
– database access
– internationalized formatting
? Likely to evolve to add more commonly
used tags in future versions

The JavaServer Pages Standard Tag Library (JSTL) is a standard set of


commonly used tag libraries.

That is, JSTL encapsulates core functionality common to many JSP


applications. For example, instead of iterating over lists using a scriptlet or
different iteration tags from numerous vendors, JSTL defines a standard set of
iteration tags.

JSTL has tags for common structural tasks such as iteration and conditionals,
tags for manipulating XML documents, internationalization tags, and tags for
accessing databases using SQL.

6
08/29/2006

Why JSTL?
? You don't have to write them yourself
? You learn and use a single standard set of
tag libraries that are already provided by
compliant Java EE platforms
? Vendors are likely to provide more
optimized implementation
? Portability of your applications are enabled

Even though it should obvious why you want to use JSTL, let's go over them
anyway. To your JSP application, JSTL is what standard Java library is to your
Java application.

First and foremost, you don't have to write them yourself. Instead, you learn
and use a single standard set of tag libraries that should be provided by all
compliant J2EE platforms. Furthermore, vendors are expected to provide more
optimized implementations for these tags than the ones you would write
yourself. And of course, portability of you JSP applications are also enabled.

7
08/29/2006

JSTL Tag Libraries


? Core (prefix: c)
– Variable support, Flow control, URL management
? XML (prefix: x)
– Core, Flow control, Transformation
? Internationalization (i18n) (prefix: fmt)
– Locale, Message formatting, Number and date
formatting
? Database (prefix: sql)
– SQL query and update
? Functions (prefix: fn)
– Collection length, String manipulation 8

So JSTL 1.1 have categorized the standard tags into 5 different functional
areas- core tags, XML tags, Internationalization and formatting tags, database
tags, and functions tags. Each tag category has its own prefix convention as
mentioned in the slide.

In the rest of this presentation, we will look into each of these tag categories.
By the way, in this presentation, we will use example JSP pages that are
provided in Java WSDP tutorial.

8
08/29/2006

Declaration of JSTL Tag Libraries


? Core
– <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
? XML
– <%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
? Internationalization (i18n)
– <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
? Database (SQL)
– <%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
? Functions
– <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

This slide shows “taglib” declarations of the JSTL tag libraries. Please note the
different values of “prefix” attribute and “uri” attribute for each tag library.

9
08/29/2006

Core Tags
(Core Actions)

10

Now let's look into core tags. By the way, the terms “tags” and “Actions”
are used interchangeably.

10
08/29/2006

Core Tags Types (page 1)


? Variable support
– <c:set>
– <c:remove>
? Conditional
– <c:if>
– <c:choose>
? <c:when>
?
<c:otherwise>
? Iteration
– <c:forEach>
– <c:forTokens>
11

Core tags themselves are categorized into several types - tags that are used for
setting and removing scoped variable, conditional tags such as <c:if>, iteration
tags such as <c:forEach>.

11
08/29/2006

Core Tags Types (page 2)


? URL management
– <c:import>
? <c:param>
– <c:redirect>
? <c:param>
– <c:url>
?
<c:param>
? General purpose
– <c:out>
– <c:catch>

12

The core tags also include tags that are used for URL management such as
URL rewriting. And then there are general purpose tags such as <c:out> and
<c:catch>. So let's go over each of these in a bit more detail.

12
08/29/2006

Variable Support, <c:set>


? Sets the value of an EL variable or the
property of an EL variable via “var” attribute
– in any of the JSP scopes via “scope” attribute
– page, request, session, application
? If the variable does not already exist, it gets
created and saved (in the scope object)
? Variable can be set in 2 different ways
– <c:set var="foo" scope="session" value="..."/>
? example: <c:set var="bookId" value="${param.BookID}"/>
– <c:set var="foo">value to be set</c:set>
13

The set tag sets the value of an EL variable or the property of an EL variable in
any of the JSP scopes (page, request, session, application). The name of the
variable is set via “var” attribute and the scope of the variable is set via “scope”
attribute.

If the variable does not already exist, it is created.

The JSP EL variable or property can be set either from attribute value:

<c:set var="foo" scope="session" value="..."/>

or from the body of the tag:

<c:set var="foo">
...
</c:set>

For example, the following sets a EL variable named bookId with the value of
the request parameter named BookID:

<c:set var="bookId" value="${param.BookID}"/> 13


08/29/2006

Example: <c:set> definition


quoted from ./elsupport/Set.jsp
<c:set var="customerTable" scope="application">
<table border="1">
<c:forEach var="customer" items="${customers}">
<tr>
<td>${customer.lastName}</td>
<td><c:out value="${customer.address}" default="no address
specified"/></td>
<td>
<c:out value="${customer.address}">
<font color="red">no address specified</font>
</c:out>
</td>
</tr> The content between <c:set> and /c:set
</c:forEach> is saved as ${customerTable}.
</table>
</c:set>
14

This JSP fragment shows the usage of <c:set> tag in which the body content of
the <c:set> is set as a value of scoped variable. This fragment is quoted from
in another JSP page.

In this example, a scoped variable named “customerTable” is set to the body


content between <c:set ..> and </c:set> tag. The scope is set to “application”
thus any JSP page in the same application can have access to it. Now let's see
how this “customerTabe” is used in the following slide.

14
08/29/2006

Example: How a predefined Variable


“customerTable” is used: ./elsupport/Set2.jsp

<h4>Using "customerTable" application scope attribute defined in


Set.jsp a first time</h4>
<c:out value="${customerTable}" escapeXml="false"/>

<h4>Using "customerTable" application scope attribute defined in


Set.jsp a second time</h4>
<c:out value="${customerTable}" escapeXml="false" />

15

This JSP fragment shows the usage of <c:out> tag displaying the value of a
scoped variable “customerTable” that was set via <c:set> tag in previous slide.

15
08/29/2006

Example: How a predefined Variable


“customerTable” is used: ./elsupport/Set2.jsp

16

This is the result. The “customerTable” scope variable contains the JSP
fragment that contains table definition and it gets displayed here.

16
08/29/2006

Variable Support <c:remove>


? Remove an EL variable
– <c:remove var="cart" scope="session"/>

17

To remove an EL variable, you use the remove tag. When the bookstore JSP
page bookreceipt.jsp is invoked, the shopping session is finished, so the cart
session attribute is removed as follows:

<c:remove var="cart" scope="session"/>

17
08/29/2006

Conditional Tags
? Flow control tags eliminate the need for
scriptlets
– Without conditional tags, a page author must
generally resort to using scriptlets in JSP page
? <c:if test=”..”>
– Conditional execution of its body according to
value of a test attribute
? <c:choose>
– Performs conditional block execution by the
embedded <c:when> and <c:otherwise> sub tags
– Works like if-then-else
18

In a vanilla JSP page, in order to execute flow control logic, a page author must
generally resort to using scriptlet. Flow control tags eliminate the need for
scriptlets.

The <c:if > tag allows the conditional execution of its body according to value
of a test attribute.

The <c:choose> tag performs conditional block execution by the embedded


<c:when> sub tags. It renders the body of the first <c:when> tag whose “test”
condition evaluates to true. If none of the test conditions of nested when tags
evaluate to true, then the body of an <c:otherwise> tag is evaluated, if present.
The <c:choose>, <c:when>, and <c:otherwise> tags can be used to construct an
if-then-else logic.

18
08/29/2006

Example: <c:if test=”...”>, ./conditionals/If.jsp


<c:forEach var="customer" items="${customers}">
<c:if test="${customer.address.country == 'USA'}">
${customer}<br>
</c:if>
</c:forEach>

Only the customers whose “address.country” property


value is “USA” are displayed through <c:forEach> loop.

19

This JSP fragment shows the usage of <c:if> tag. Here only the customers
whose “address.country” property value is “USA” are displayed through
<c:forEach> loop. By the way, in this example, the scoped variable
“customers” has been set when the application is loaded into the container.

19
08/29/2006

Example: <c:choose>, <c:when>


./conditionals/Choose.jsp
<c:forEach var="customer" items="${customers}">
<c:choose>
<c:when test="${customer.address.country == 'USA'}">
<font color="blue">
</c:when>
<c:when test="${customer.address.country == 'Canada'}">
<font color="red">
</c:when>
<c:otherwise>
<font color="green">
</c:otherwise>
</c:choose>
${customer}</font><br>
</c:forEach>

20

This slide shows JSP fragment in which <c:choose> tag and its sub tags
<c:when> and <c:otherwise> are used. Here the font color is set differently
depending on the value of “address.country” property of a customer.

20
08/29/2006

Iterator Tag: <c:forEach>


? Allows you to iterate over a collection of
objects
– items: represent the collection of objects
– var: current item
– varStatus: iteration status
– begin, end, step: range and interval
? Collection types
– java.util.Collection
– java.util.Map
?
value of var attribute should be of type
java.util.Map.Entry
21

Now let's see the iterator tag.

The <c:forEach> tag allows you to iterate over a collection of objects. You
specify the collection via the “items” attribute, and the current item is available
through a variable named by the “var” attribute.

You can also get the iteration status via “varStatus” attribute. The range and
interval can be also specified via “begin”, “end”, and”step” attributes.

A large number of collection types are supported by <c:forEach>, including all


implementations of java.util.Collection and java.util.Map. If the items attribute
is of type java.util.Map, then the current item will be of type
java.util.Map.Entry, which has the following properties:

* key - the key under which the item is stored in the underlying Map
* value - the value that corresponds to the key

21
08/29/2006

Example: <c:forEach>
quoted from ./iterators/Simple.jsp
<c:forEach var="customer" items="${customers}">
${customer}<br>
</c:forEach>

22

This example shows iteration of customers from scope variable “customers”.

22
08/29/2006

Example: <c:forEach>, Range


quoted from ./iterators/SimpleRange.jsp
<c:forEach var="i" begin="1" end="10">
${i} •
</c:forEach>

23

Another simple iteration example. Similar to the previous one, except that in
this case there is no collection to iterate over. The items attribute is optional in
the <c:forEach> tag. When it is not specified, the range attributes must be used
to iterate a specific number of times over the tag's body. In this example, we
simply iterate over the integer values specified by the range attributes.

23
08/29/2006

Example: <c:forEach>, Data types


quoted from ./iterators/DataTypes.jsp
<c:forEach var="i" items="${intArray} ">
<c:out value="${i}"/> •
</c:forEach>

<c:forEach var="string" items="${stringArray}">


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

<c:forEach var="item" items="${enumeration}" begin="2" end="10" step="2">


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

<c:forEach var="prop" items="${numberMap}" begin="1" end="5">


<c:out value="${prop.key}"/> = <c:out value="${prop.value}"/><br>
</c:forEach>

<c:forEach var="token" items="bleu,blanc,rouge" >


<c:out value="${token}"/><br>
</c:forEach>
24

The <c:forEach> tag supports a large number of data types for the collection of
objects to iterate over. In this example, we feature the following data types:
array of primitives, array of objects, Enumeration, Properties (Map), String
(Comma Separated Values).

24
08/29/2006

Example: <c:forEach>, Data types


quoted from ./iterators/DataTypes.jsp

25

This is the result of the previous page.

25
08/29/2006

Example: <c:forEach>, Iteration status


quoted from ./iterators/Status.jsp
<c:forEach var="customer" items="${customers}" varStatus="status">
<tr>
<td><c:out value="${status.index}"/></td>
<td><c:out value="${status.count}"/></td>
<td><c:out value="${status.current.lastName}"/></td>
<td><c:out value="${status.current.firstName}"/></td>
<td><c:out value="${status.first}"/></td>
<td><c:out value="${status.last}"/></td>
</tr>...
</c:forEach>
<c:forEach var="i" begin="100" end="200" step="5" varStatus="status">
<c:if test="${status.first}">
begin:<c:out value="${status.begin}">begin</c:out>
end:<c:out value="${status.end}">end</c:out>
step:<c:out value="${status.step}">step</c:out><br>
sequence:
</c:if> ...
</c:forEach>
26

The <c:iterator> tag exposes a wealth of information relative to the iteration


taking place. This example features some of that status information.

26
08/29/2006

Example: <c:forEach>, Iteration status


quoted from ./iterators/Status.jsp

27

This page shows the result of executing the JSP page shown in previous slide.

27
08/29/2006

Example: <c:forToken>
<c:forTokens var="token" items="one,two,three" delims=",">
<c:out value="${token}"/>
</c:forTokens>

28

This example features <c:out> used with default values using the default
attribute as well as the tag's body content.

28
08/29/2006

Example: <c:out>
quoted from /elsupport/Out.jsp
<table border="1">
<c:forEach var="customer" items="${customers}">
<tr>
<td><c:out value="${customer.lastName}"/></td>
<td><c:out value="${customer.phoneHome}" default="no
home phone specified"/></td>
<td>
<c:out value="${customer.phoneCell}" escapeXml="false">
<font color="red">no cell phone specified</font>
</c:out>
</td>
</tr>
</c:forEach>
</table>

29

This example features <c:out> used with default values using the default
attribute as well as the tag's body content.

29
08/29/2006

Example: <c:out>
quoted from /elsupport/Out.jsp

30

This page shows the result of executing JSP page shown in previous slide.

30
08/29/2006

URL Import: <c:import>


? More generic way to access URL-based
resources (than <jsp:include>)
– Absolute URL: for accessing resources outside of
Web application
– Relative URL: for accessing resources inside of
the same Web application
? More efficient (than <jsp:include>)
– No buffering
? <c:param> tag can be used to specify
parameters (like <jsp:param>)
31

The <jsp:include> element provides for the inclusion of static and dynamic
resources in the same context as the current page. However, <jsp:include>
cannot access resources that reside outside of the Web application and causes
unnecessary buffering when the resource included is used by another element.

In the example below, the transform element uses the content of the included
resource as the input of its transformation. The <jsp:include> element reads the
content of the response, writes it to the body content of the enclosing transform
element, which then re-reads the exact same content. It would be more efficient
if the transform element could access the input source directly and avoid the
buffering involved in the body content of the transform tag.

<acme:transform>
<jsp:include page="/exec/employeesList"/>
<acme:transform/>

The <c:import> tag is therefore the simple, generic way to access URL-based
resources whose content can then be included and or processed within the JSP
page.

31
08/29/2006

Example: <c:import> Absolute URL


quoted from /import/Absolute.jsp
<blockquote>
<ex:escapeHtml>
<c:import url="http://www.cnn.com/cnn.rss"/>
</ex:escapeHtml>
</blockquote>

32

This is JSP fragment which shows the usage of <c:import url=”..”> in which
absolute URL address is used. Here the contents of the file that is referenced
by the URL will be included.

32
08/29/2006

Example: <c:import> with <c:param>

<c:import url="header.jsp">
<c:param name="pageTitle" value="newInstance.com"/>
<c:param name="pageSlogan" value=" " />
</c:import>

33

This is JSP fragment which shows the usage of <c:import url=”..”> in which
absolute URL address is used. Here the contents of the file that is referenced
by the URL will be included.

33
08/29/2006

URL Rewriting: <c:url>


? Used for URL rewriting
– All the URL's that are returned from a JSP page
(to a browser) have session ID if Cookie is
disabled on the browser
? Can take param subtags for including
parameters in the returned URL

34

In Session Tracking session of basic “J2EE programming” course, we


discussed how an application must rewrite URLs to enable session tracking
whenever the client turns off cookies. You can use the <c:url> tag to “rewrite”
URLs that are being returned from a JSP page. The tag includes the session ID
in the URL only if cookies are disabled; otherwise, it returns the URL
unchanged. Note that this feature requires the URL to be relative. The url tag
takes param subtags for including parameters in the returned URL.

34
08/29/2006

Example: <c:url>
<table border="1" bgcolor="#dddddd">
<tr>
<td>"base", param=ABC</td>
<td>
<c:url value="base">
<c:param name="param" value="ABC"/>
</c:url>
</td>
</tr>
<tr>
<td>"base", param=123</td>
<td>
<c:url value="base">
<c:param name="param" value="123"/>
</c:url>
</td>
</tr> 35
<tr>

This is an example of <c:url> tag usage. This page will be displayed


differently depending on whether the client browser has disabled cookies or
not. So let's see how this works in the following two slides.

35
08/29/2006

Example: <c:url> - Cookie enabled


quoted from /import/Encode.jsp

36

This is the case where client's browser has cookies enabled. So the URL
rewriting will send URL without session ID information postfixed to each URL
that is returned to the client.

36
08/29/2006

Example: <c:url> - Cookie disabled

37

This is the case where client disabled cookies. Now you can see the URL that
is returned to the client has session ID attached.

37
08/29/2006

Redirection: <c:redirect>
? Sends an HTTP redirect to the client
? Takes <c:param> subtags for including
parameters in the returned URL

38

The redirect tag sends an HTTP redirect to the client. The redirect tag takes
param subtags for including parameters in the returned URL.

38
08/29/2006

<c:out>
? Evaluates an expression and outputs the
result of the evaluation to the current JspWriter
object
? If the result of the evaluation is a
java.io.Reader object, data is first read from
the Reader object and then written into the
current JspWriter object
– improved performance
? Syntax
– <c:out value="value" [escapeXml="{true|false}"]
[default="defaultValue"] />
– If escapeXml is true, escape character conversion 39

The out tag evaluates an expression and outputs the result of the evaluation to
the current JspWriter object. The syntax and attributes are

<c:out value="value" [escapeXml="{true|false}"]


[default="defaultValue"] />

If the result of the evaluation is a java.io.Reader object, data is first read from
the Reader object and then written into the current JspWriter object. The
special processing associated with Reader objects improves performance when
large amount of data must be read and then written to the response.

If escapeXml is true, the character conversions as following are applied. This


conversion will allow these characters which have special meaning under
XML to be displayed as characters.

Character Character Entity Code


< &lt;
> &gt;
& &amp;
' &#039;
" &#034; 39
08/29/2006

Example: <c:out>
quoted from /elsupport/Out.jsp
<table border="1">
<c:forEach var="customer" items="${customers}">
<tr>
<td><c:out value="${customer.lastName}"/></td>
<td><c:out value="${customer.phoneHome}" default="no
home phone specified"/></td>
<td>
<c:out value="${customer.phoneCell}" escapeXml="false">
<font color="red">no cell phone specified</font>
</c:out>
</td>
</tr>
</c:forEach>
</table>

40

This is an example of <c:out> tag. Here we are displaying customer's last


name, phone number, and cell phone number in a table format.

40
08/29/2006

Example: <c:out>
quoted from /elsupport/Out.jsp
<h4><c:out> with Reader object</h4>
<%
java.io.Reader reader1 = new java.io.StringReader("<foo>Text for
a Reader!</foo>");
pageContext.setAttribute("myReader1", reader1);
java.io.Reader reader2 = new java.io.StringReader("<foo>Text for
a Reader!</foo>");
pageContext.setAttribute("myReader2", reader2);
%>
Reader1 (escapeXml=true) : <c:out value="${myReader1}"/><br>
Reader2 (escapeXml=false): <c:out value="${myReader2}"
escapeXml="false"/><br>

41

This is an example of <c:out> tag usage in which the result of evaluation is


java.Io.Reader object. We are also showing the usage of escapeXML attribute.
The same content “<foo>Text for a Reader<foo>” is displayed with
escapeXML is set to true and then false.

41
08/29/2006

Example: <c:out>
quoted from /elsupport/Out.jsp

42

This is the result.

42
08/29/2006

Database Access Tags


(SQL Tags)

43

Now let's talk about SQL tags.

43
08/29/2006

RAD/Prototyping/Simple Apps

SQL
Database

.jsp

44

The JSTL SQL tags are designed for quick prototyping and simple
applications. For production applications, database operations are
normally encapsulated in JavaBeans components through MVC pattern as
shown in the following slide.

44
08/29/2006

MVC Architecture

Business Logic

Beans Dynamic Content SQL


Database

.jsp

45

So in production environment, the database access logic is typically


captured within JavaBeans which functions as a Model under MVC
architecture. This state of the JavaBeans is set by the Controller (Servlet)
and then is accessed by the JSP pages (View).

Again accessing database directly using SQL tags is NOT following this
MVC pattern, thus the reason why usage of SQL tags within JSP pages
are usually reserved for simple prototyping situations.

45
08/29/2006

SQL Tags

Query the database


<sql:query>

Easy access to
result set
Result
ResultSupport
Database

Update the database


.jsp
<sql:update>
<sql:transaction>

46

SQL tags that are supported include <sql:query> for querying and
<sql:update> for creating and updating database table

46
08/29/2006

DataSource
? All DB actions operate on a DataSource
? Different ways to access a DataSource
– Object provided by application logic
– Object provided by <sql:dataSource> action
<sql:dataSource var="dataSource"
driver="org.gjt.mm.mysql.Driver"
url="jdbc:..."/>
<sql:query dataSource="${dataSource}" .../>

47

The setDataSource tag is provided to allow you to set data source


information for the database. You can provide a JNDI name or
DriverManager parameters to set the data source information.

47
08/29/2006

Example: <sql:setDataSource>
for setting a table using PointBase
<sql:setDataSource
var="example"
driver="com.pointbase.jdbc.jdbcUniversalDriver"
url="jdbc:pointbase:server://localhost:1092/jstlsample;create=true"
/>

48

So using <sql:setDataSource> tag, you can set your JDBC driver and URL
of your database. Here in this example, you are setting these two for a
database table that is to be created in PointBase database server.

48
08/29/2006

Example: <sql:transaction> &


<sql:update> from /sql/QueryDirect.jsp
<sql:transaction dataSource="${example}">

<sql:update var="newTable">
create table mytable (
nameid int primary key,
name varchar(80)
)
</sql:update>

<sql:update var="updateCount">
INSERT INTO mytable VALUES (1,'Paul Oakenfold')
</sql:update>
<sql:update var="updateCount">
INSERT INTO mytable VALUES (2,'Timo Maas')
</sql:update>
...

<sql:query var="deejays">
SELECT * FROM mytable
</sql:query>

</sql:transaction> 49

This example shows the creation of a very simple database and then populating
the table. Then querying the database table and save the query result into a
scope variable “deejays”.

By the way, it is expected that you started the PointBase database server and
also DataSource has been set. Otherwise, you will experience HTTP 500 error
condition.

49
08/29/2006

Example: <sql:transaction> &


<sql:update> from /sql/QueryDirect.jsp

50

This is the execution result of the JSP page of the previous page.

50
08/29/2006

XML Tags

51

Now let's talk about XML tags.

51
08/29/2006

XML Tags
? Flow control
– <x:choose>, <x:when>, <x:if>, <x:otherwise>
? Iteration
– <x:forEach>
? General purpose
– <x:out>
– <x:set>
? Parsing and Transformation
– <x:parse>
– <x:transform> with <x:param> subtags
52

This slide shows XML tags. As you can see, XML tags has flow control,
iteration, and general purpose tags as in the Core tags. For parsing and
transformation, which are unique for XML tags, there are <x:parse> and
<x::transform> tags.

52
08/29/2006

XML Tags
? Used to access information stored in XML
document
? Access description is specified in XPath
expression as a value of select attribute
– <x:set var="d" select="$a//d"/>
– <x:out select="$d/e"/>
? Flow control, Iteration, General purpose
XML tags work similarly as corresponding
tags in Core tags

53

XML tags are used to access information stored in XML document. Now what
is unique about XML tags is that the access description is specified in XPath
expression as a value of “select” attribute as shown in the slide above. Except
that the access description is described in XPath expression, the flow control,
iteration, and general purpose tags work similarly as corresponding tags in
Core tags.

53
08/29/2006

Quick XPath
Review (Start)
54

Since understanding XPath is very important for understanding XML tags, let's
do a quick overview of XPath.

54
08/29/2006

Example XML Document


<?xml version="1.0" encoding="ISO-8859-1"?>
<games>
<country id="Luxembourg">
<athlete>
<name>Lux 1</name>
<sport>swimming</sport>
<age>23</age>
<gender>M</gender>
</athlete>
</country>
<country id="Denmark">
<athlete>
<name>Den 1</name>
<sport>cycling</sport>
<age>18</age>
<gender>F</gender>
</athlete>
<athlete>
<name>Den 2</name>
<sport>sailing</sport>
<age>27</age>
<gender>M</gender>
</athlete>
</country>
</games> 55

This slide shows an example XML document we are going to use in our
explanation of XPath. Please quickly glance over this XML document. This
example is from JWSDP.

55
08/29/2006

What is XPath?
? XPath is an Expression Language for
referencing particular parts of XML
document
? XPath expression uses a tree model to
represent a XML document
– XPath expression /games/country/athlete
evaluates to a node-set that contains all nodes
corresponding to the athletes of all countries in the
games XML document

56

So what is XPath? XPath is an expression language for referencing particular


parts of XML document. Now the XPath expression uses a very familiar tree
model to represent a XML document. For example, XPath expression /
games/country/athlete evaluates to a node-set that contains all nodes
corresponding to the “athletes” of all “country”'s of the “games” in a XML
document. Now please note that we use a term “node set” here. This is an
important concept you need to understand, so let's spend sometime on it.

56
08/29/2006

XPath Expression Result Data


Types: 4 Data Types
? Node set
– Type we will spend most time with
? Boolean
? Number
? String

57

XPath expression result data type can be in one of the 4 data types - node set,
boolean, number, and string. Among these, you will use the node set data type
the most. Now let's learn what a node set is in the following slide.

57
08/29/2006

Node Set, Location Path, Location


Step, Predicate
? A node-set is a collection of zero or more
nodes from XML document
? A note-set is a return type from location path
expression
? A location path expression is composed of
location steps
? A Location step can be qualified with a
predicate
– /games/country/athlete[sport=”sailing”]
– /games/country[@id=”Demark”]/athlete
58

As you might have guessed it, a node set is a collection of zero or more nodes
from an XML document.

A node-set is a return type from location path expression such as /


games/country. Each entry between the “/” (slash) is called “location step”. So
a “location expression” is composed of “location steps” delimited by “/”.

Each location step can be qualified with a predicate. For example, in the
location expression example, /games/country/athlete[sport=”sailing”], the
“athlete” location step is qualified with a predicate [sport=”sailing”], which
means athlete elements whose child element “sport” has a string value
“sailing”.

58
08/29/2006

Examples of Node Set


? /games/country/athlete
– all athlete elements which has country parent
element which in turn has games parent element
? /games/country[1]/athlete[2]
– the 2nd athlete element under 1st country element
? /games/country/athlete[sport=”sailing”]
– all athlete elements whose child element sport has
string-value sailing
? /games/country[@id=”Demark”]/athlete
– all athlete elements whose parent element country
has id attribute value Denmark
59

Now let's go over some more XPath expression examples. Here we have 4
examples. (please read the slide)

59
08/29/2006

Examples of Node Set


? /games/country/*
– all child elements under /games/country
? /games/country//sport
– all sport elements in a subtree that begins with
/games/country

60

(please read the slide)

60
08/29/2006

XPath Type Coercion (Conversion)


? XPath specification defines rules on how
node-set, boolean, number, string are to be
converted to each other
? Note-set is converted to
– boolean: true if note-set is not empty, false
otherwise
– string: the string value of the first node in the node-
set
?
the reason why <x:out select="$doc//sport"/> results in
“swimming”
– number: node-set is first coerced to a string, which
is then coerced to a number
61

Now let's talk about XPath type coercion. XPath specification defines rules on
how the 4 data types - node set, boolean, number, and string - can be converted
to each other. Since node-set is the most type you will convert to other types,
let's go over it.

When node-set is converted to boolean type, the resulting value is true if the
node set is not empty, false otherwise. If a node set is converted to a string, the
return value is the string value of the first node in the node set. As you will see
later on, this is the reason why <x:out select="$doc//sport"/> results in
“swimming”. (We will talk about this example again later on. So if you don't
understand this example, just move on.) When a node set is converted to a
number, basically the node set is converted to a string first, which is then
converted to a number.

Now when do these type coercion occur? It depends. The node-set to string
conversion occur when <x:out> tag is used. Node set to boolean type coercion
can occur when boolean function is used. (We have learn about these functions
in the next slide.)

61
08/29/2006

XPath Functions
? XPath expression can contain functions
? Example
– count(node-set): returns number of nodes in a
node-set
? count(/games/country) returns 2 since there are 2
country nodes in the node-set
– id(object): selects a node with the specified id
– last(): returns size of the current node-set
– string functions
?
string substring(/games/country, 1, 3)
– boolean functions
? boolean not(/games/country)
62

I briefly mentioned XPath functions in the previous slide. What is XPath


functions? These are functions that can be applied to XPath expressions. For
example, count(note-set) function returns the number of nodes in a node set.

Please note that there are string functions and boolean functions. These string
functions and boolean functions can take any one of the 4 data types - node set,
boolean, string, number -, hence the need for a rule of type conversion.

62
08/29/2006

Quick XPath
Review (End)
63

OK. This is the end of the quick review of XPath. I hope you get some idea
what XPath is. Now let's get back to XML tags.

63
08/29/2006

<x:parse>
? Parse XML document into a scoped
variable

64

<x:parse> tag is for parsing XML document into a scoped varilable.

64
08/29/2006

Example: <x:parse>
from /xml/Parse.jsp
<c:set var="xmlText">
<a>
<b>
<c>
foo
</c>
</b>
<d>
bar
</d>
</a>
</c:set>

<x:parse var="a" doc="${xmlText}" />

<x:out select="$a//c"/>
<x:out select="$a/a/d"/>
65

In this example which I quoted from ./xml/Parse.jsp of JWSDP, we are XML


data into a variable called “xmlTest”. This XML data is then parsed into a
variable called “a”.

Now $a//c returns a node set which contains all “c” elements while $a/a/d
returns a node set which contains all “d” elements which has a parent element
“a”. As we will learn later on, <x:out> tag returns string value of the node set,
which means the string value of the first node in the node set.

65
08/29/2006

Example: <x:parse>
from /xml/Parse.jsp

66

This slide shows the result of running the Parse.jsp page. As expected,
the <x:out select=”$a//c”> returns “foo” through the following logic:

(1) select=”$a//c” returns a node set which contains all the “c” elements in
this XML document. In this example, there is only one “c” element <c>
foo </c>.
(2) <x:out ..> then returns the string value of the node set. The string
value of a node set is the string value of the first node in the node set. In
this example, the first node (and the only node) is <c> foo</c> and the
string value is “foo”.

The <x:out select=”$a/a/d”> works in a similar way

(1) select=”$a/a/d” returns a node set which contains all the “d” elements
which has “a” as parent element. In this example, there is only one
element that fits this pattern.
(2) <x:out ..> then returns the string value of the node set. In this case, it is
“bar”.

66
08/29/2006

<x:out>
? Works like <c:out> tag
? <x:out> tag converts node-set type to a
String type
– the string value of the first node in the node-set
– The string value of an element is the
concatenation of all descendent text nodes, no
matter how deep
– Example element String value
<athlete>
<name>Lux 1</name> Lux 1
<sport>swimming</sport> swimming
<age>23</age> 23
<gender>M</gender> M
67
</athlete>

OK, we already talked about <x:out> tag. As mentioned before, <x:out> tag
works like <c:out> tag, again except the fact that the access description is in
the form of XPath expression.

<x:out> tag converts node set type to a string type. As mentioned a couple of
times already, when node set is converted to a string type, the resulting value is
the string value of the first node in the node set.

Now a string value of an element is the concatenation of all the child text nodes
no matter how deep it is. The example shown above illustrates this. The
<athlete> element has several child elements. And the string value of this
<athlete> element is the concatenation of all the texts of its child elements.

67
08/29/2006

Example: <x:out>
from /xml/Out.jsp
<tr>
<td>$doc//sport</td>
<td><pre><x:out select="$doc//sport"/></pre></td>
</tr>
<tr>
<td>$doc/games/country/*</td>
<td><pre><x:out select="$doc/games/country/*"/></pre></td>
</tr>
<tr>
<td>$doc//*</td>
<td><pre><x:out select="$doc//*"/></pre></td>
</tr>
<tr>
<td>$doc/games/country</td>
<td><pre><x:out select="$doc/games/country"/></pre></td>
</tr>

68

Now I would like to go over ./xml/Out.jsp example of the JWSDP. This contains
various <x:out ..> tag examples. This slide shows the first part of the Out.jsp page.

I am going to explain the first couple on this page. The first one is <x:out
select=$doc//sport”>. The XPath expression $doc//sport returns a node set that contains
all “sport” elements in this XML document. In this XML document, there are 4 “sport”
elements - <sport>swimming</sport>, <sport>wrestling</sport>,
<sport>cycling</sport>, <sport>sailing</sport>. Then <x:out ..> converts the node set
into a string type. According to the conversion rule, the string value of the first node in
the node set is returned. And that is what you will see in the following captured screen
of running Out.jsp page.

Same thing can be said for <x:out select=”$doc/games/country/*”/>. In this case, the
XPath expression returns a node set that contains all child elements under /
games/country, which means all 4 <athlete> elements. Again <x:out> converts this
node set into a string type. And the string value of the first node will be returned, thus
the result you will see in the next slide.

68
08/29/2006

Example: <x:out>
from /xml/Out.jsp

69

This is the results of the running the Out.jsp page. Please spend some time
going through the logic we have used in the previous slide for the remaining
<x:out> examples.

69
08/29/2006

Example: <x:out>
from /xml/Out.jsp
<tr>
<td>$doc/games/country[last()]</td>
<td><pre><x:out select="$doc/games/country[last()]"/></pre></td>
</tr>
<tr>
<td>$doc//@id</td>
<td><pre><x:out select="$doc//@id"/></pre></td>
</tr>
<tr>
<td>$doc//country[@id='Denmark']</td>
<td><pre><x:out select="$doc//country[@id='Denmark']"/></pre></td>
</tr>
</table>
</td>
</tr>

70

This is the latter part of Out.jsp which shows XPath expressions that has
predicates and addressing attributes.

70
08/29/2006

Example: <x:out>
from /xml/Out.jsp

71

This slide shows captured screen of running Out.jsp page of the previous page.

71
08/29/2006

Example: <x:out>
from /xml/Out.jsp

72

This slide shows the result of last <x:out> tag.

72
08/29/2006

Access to built-in scope


variables in XPath expression
? $foo
? $param:
? $header:
? $cookie:
? $initParam:
? $pageScope:
? $requestScope:
? $sessionScope:
? $applicationScope:
73

In addition to the standard XPath syntax, the JSTL XPath engine supports the
following scopes to access Web application data within an XPath expression:

* $foo
* $param:
* $header:
* $cookie:
* $initParam:
* $pageScope:
* $requestScope:
* $sessionScope:
* $applicationScope:

These scopes are defined in exactly the same way as their counterparts in the
JSP expression language discussed in Implicit Objects

73
08/29/2006

Example: Access to built-in


scope variables
? $sessionScope:profile
– The session-scoped EL variable named profile
? $initParam:mycom.productId
– The String value of the mycom.productId context
parameter

74

These are examples of XPath expressions in which scope variables are used.

74
08/29/2006

EL Functions

75

Now let's talk about EL functions. If you are familiar with Java string
functions, which I assume most of you are, then understanding EL
functions is easy. It is standard string functions you can use in JSP page.

75
08/29/2006

EL Functions in JSTL 1.1


?
<fn:length> Length of collection of string
? <fn:toUpperCase>, <fn:toLowerCase> Change the
capitalization of a string
? <fn:substring>, <fn:substringBefore>, <fn:substringAfter>
Get a subset of a string
?
<fn:trim> Trim a string
? <fn:replace> Replace characters in a string
?
<fn:indexOf>, <fn:startsWith>, <fn:endsWith contains>,
<fn:containsIgnoreCase> Check if a string contains
another string
?
<fn:split>, <fn:join> Split a string into an array,and join a
collection into a string
? <fn:escapeXml> Escape XML characters in the string
76

This slide shows the list of EL functions you can use.

76
08/29/2006

Example: EL Functions
<%-- truncate name to 30 chars and display it in uppercase --%>
${fn:toUpperCase(fn:substring(name, 0, 30))}

<%-- Display the text value prior to the first ’*’ character --%>
${fn:substringBefore(text, ’*’)}

<%-- Scoped variable "name" may contain whitespaces at the


beginning or end. Trim it first, otherwise we end up with +'s in the URL
--%>
<c:url var="myUrl" value="${base}/cust/${fn:trim(name)}"/>

<%-- Display the text in between brackets --%>


${fn:substring(text, fn:indexOf(text, ’(’)+1, fn:indexOf(text, ’)’))}

<%-- Display the name if it contains the search string --%>


<c:if test="${fn:containsIgnoreCase(name, searchString)}">
Found name: ${name}
</c:if>

<%-- Display the last 10 characters of the text value --%>


${fn:substring(text, fn:length(text)-10)}

<%-- Display text value with bullets instead of ’-’ --%>


${fn:replace(text, ’-’, ’&#149;’)} 77

This slide shows usage of EL functions.

77
08/29/2006

Internationalization (i18n)
&Text Formatting Tags

78

Now let's talk about internationalization and text formatting tags.

Internationalization is the process of preparing an application to support


more than one language and data format. Localization is the process of
adapting an internationalized application to support a specific region or
locale. Examples of locale-dependent information include messages and
user interface labels, character sets and encoding, and date and currency
formats. Although all client user interfaces should be internationalized and
localized, it is particularly important for Web applications because of the
global nature of the Web.

78
08/29/2006

I18N and Formatting Tags


? Setting locale
– <fmt:setLocale>
– <fmt:requestEncoding>
? Messaging
– <fmt:bundle>
– <fmt:message> with <fmt:param> subtag
– <fmt:setBundle>
? Number and Date formatting
– <fmt:formatNumber>, <fmt:parseNumber>
– <fmt:formatDate>, <fmt:parseDate>
– <fmt:setTimeZone>, <fmt:timeZone >
79

JSTL defines tags for: setting the locale for a page, creating locale-sensitive
messages, and formatting and parsing data elements such as numbers,
currencies, dates, and times in a locale-sensitive or customized manner.

This slide shows the I18N and formatting related tags that are supported by
JSTL.

79
08/29/2006

Quick I18N
Review (Start)
80

Let's quickly overview I18N concept here.

80
08/29/2006

How Locale Is Set in Web app

Worldwide Users Web Application

1. Request sensing
chinese, …
2. Application-based
prefs
preferred locales
session
login
spanish, … locales

81

This picture shows how locale preference can be set for a Web
application. There are two different approaches - one that is based on
client locale preference that is sent as part of HTTP request, the other
approach in which locale preference is determined by other factors such as
login name. Here we are mainly concerned about the first approach.

So in the first approach, a client browser is typically configured with a


particular language preference - we will call this locale preference. Once
it is set, this locale preference is sent to the server as part of HTTP
request.

A web application running on the server, when it receives the HTTP


request that contains locale preference information, can either honor it or
override it. In the servlet code, a Web application retrieves the client
locale preference via getLocale() method of HTTPServerRequest object.

81
08/29/2006

I18N Architecture: Option 1

Worldwide Users Web Application

1. One page per locale

JSP
ch <fmt:formatNumber>
<fmt:parseNumber>
controller
<fmt:formatDate>
<fmt:parseDate>
JSP
es

82

Messages and labels should be tailored according to the conventions of a


user's language and region. There are two approaches to providing
localized messages and labels in a Web application. We will take a look
at these two approaches here.

In the first approach, which you see on this slide, you provide a version of
the JSP page in each of the target locales and have a controller servlet
dispatch the request to the appropriate page depending on the requested
locale. This approach is useful if large amounts of data on a page or an
entire Web application need to be internationalized.

82
08/29/2006

I18N Architecture: Option 2

Worldwide Users Web Application

2. One page for all locales


Resource Bundles

ch es

JSP
<fmt:message key="...">

83

This is the 2nd approach. In this approach, you isolate any locale-sensitive
data on a page into resource bundles, and access the data so that the
corresponding translated message is fetched automatically and inserted
into the page. Thus, instead of creating strings directly in your code, you
create a resource bundle that contains translations and read the
translations from that bundle using the corresponding key. Using JSP
I18N tags allows you to take this approach.

83
08/29/2006

Quick I18N
Review (End)
84

This is the end of quick i18n review.

84
08/29/2006

Setting Locales

? <fmt:setLocale>
– Override client-specified locale for a page
? <fmt:requestEncoding>
– Set the request's character encoding, in order to be
able to correctly decode request parameter values
whose encoding is different from ISO-8859-1

85

The <fmt:setLocale> tag is used to override the client-specified locale for a


page. The <fmt:requestEncoding> tag is used to set the request's character
encoding, in order to be able to correctly decode request parameter values
whose encoding is different from ISO-8859-1.

85
08/29/2006

Messaging Tags

? <fmt:bundle>
– specify a resource bundle for a page
? <fmt:message key=”..”>
– used to output localized strings
– <fmt:param> subtag provides a single argument
(for parametric replacement) to the compound
message or pattern in its parent message tag

86

The <fmt:message> tag is used to output localized strings. The following tag
from bookcatalog.jsp

<h3><fmt:message key="Choose"/></h3>

is used to output a string inviting customers to choose a book from the catalog.

The param subtag provides a single argument (for parametric replacement) to


the compound message or pattern in its parent message tag. One param tag
must be specified for each variable in the compound message or pattern.
Parametric replacement takes place in the order of the param tags.

86
08/29/2006

Example:
quoted from ./fmt/GermanLocale.jsp
<fmt:setLocale value="de"/>
<fmt:bundle
basename="org.apache.taglibs.standard.examples.i18n.R
esources">
<fmt:message>
greetingMorning
</fmt:message>
</fmt:bundle>

87

In this example, locale is set to “de” which is locale for Germany. And bundle
is set. And then a German message whose key is “greetingMorning” is
displayed.

87
08/29/2006

Example: <fmt:setLocale>

http://localhost:8080/webapps-jstl/format/GermanLocale.jsp
88

This is the result.

88
08/29/2006

Formatting Tags

? <fmt:formatNumber>, <fmt:formatDate>
– used to output localized numbers and dates
? <fmt:parseNumber>, <fmt:parseDate>
– used to parse localized numbers and dates
? <fmt:setTimeZone>, <fmt:timeZone >
– used to set and get timezone

89

JSTL provides a set of tags for parsing and formatting locale-sensitive numbers
and dates.

The formatNumber tag is used to output localized numbers. The following tag
from bookshowcart.jsp

<fmt:formatNumber value="${book.price}" type="currency"/>

is used to display a localized price for a book. Note that since the price is
maintained in the database in dollars, the localization is somewhat simplistic,
because the formatNumber tag is unaware of exchange rates. The tag formats
currencies but does not convert them.

Analogous tags for formatting dates (formatDate), and parsing numbers and
dates (parseNumber, parseDate) are also available. The timeZone tag
establishes the time zone (specified via the value attribute) to be used by any
nested formatDate tags.

89
08/29/2006

Example:
quoted from ./format/FormatDateTime.jsp
<jsp:useBean id="now" class="java.util.Date" />
<fmt:setLocale value="en-US" />

<ul>
<li> Formatting current date as "GMT":<br>
<fmt:timeZone value="GMT">
<fmt:formatDate value="${now}" type="both" dateStyle="full" timeStyle="full"/>
</fmt:timeZone>

<li> Formatting current date as "GMT+1:00", and parsing


its date and time components:<br>
<fmt:timeZone value="GMT+1:00">
<fmt:formatDate value="${now}" type="both" dateStyle="full"
timeStyle="full" var="formatted"/>
<fmt:parseDate value="${formatted}" type="both" dateStyle="full"
timeStyle="full" timeZone="PST" var="parsedDateTime"/>
Parsed date: <fmt:formatDate value="${parsedDateTime}" type="date"
dateStyle="full"/><br>
Parsed time: <fmt:formatDate value="${parsedDateTime}" type="time"
timeStyle="full"/>
</fmt:timeZone> 90

This JSP fragment is quoted from FormatDataTime.jsp page of JWSDP


tutorial. We will see the result of the running this page one using en-us Locale
preference in the browser and the other resetting the browser Locale preference
to Korean and then rerun the same page.

90
08/29/2006

Example: using browser locale en-us


quoted from ./format/FormatDateTime.jsp

91

This is the result of running the page with default en-us Locale setting on my
netscape browser. As you can see, the format of date and time is en-us locale.

91
08/29/2006

Change Browser Locale preference to


Korean

92

Now I added Korean (ko) Locale and make it as my default Locale setting on
my Netscape browser.

92
08/29/2006

Example: using browser locale ko


quoted from ./format/FormatDateTime.jsp

93

After rerunning the same page, this is what I get. The date and time is now in
Korean Locale.

93
08/29/2006

Passion!

94

94

You might also like