Professional Documents
Culture Documents
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
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
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
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
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 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
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
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.
The JSP EL variable or property can be set either from attribute value:
<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:
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.
14
08/29/2006
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
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
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:
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.
18
08/29/2006
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
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
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.
* 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
22
08/29/2006
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
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
25
25
08/29/2006
26
08/29/2006
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
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
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
<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
34
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>
35
08/29/2006
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
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
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.
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
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
41
08/29/2006
Example: <c:out>
quoted from /elsupport/Out.jsp
42
42
08/29/2006
43
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
.jsp
45
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
Easy access to
result set
Result
ResultSupport
Database
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
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
<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
50
This is the execution result of the JSP page of the previous page.
50
08/29/2006
XML Tags
51
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
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
56
08/29/2006
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
As you might have guessed it, a node set is a collection of zero or more nodes
from an XML document.
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
Now let's go over some more XPath expression examples. Here we have 4
examples. (please read the slide)
59
08/29/2006
60
60
08/29/2006
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
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
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:out select="$a//c"/>
<x:out select="$a/a/d"/>
65
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”.
(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
72
08/29/2006
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
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
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, ’*’)}
77
08/29/2006
Internationalization (i18n)
&Text Formatting Tags
78
78
08/29/2006
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
80
08/29/2006
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.
81
08/29/2006
JSP
ch <fmt:formatNumber>
<fmt:parseNumber>
controller
<fmt:formatDate>
<fmt:parseDate>
JSP
es
82
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
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
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
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.
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
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
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>
90
08/29/2006
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
92
Now I added Korean (ko) Locale and make it as my default Locale setting on
my Netscape browser.
92
08/29/2006
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