2. Outline
¤ Server-side Web languages
¤ JSP Standard Tag Library
¤ Learning JSTL
¤ Expression language
¤ The core library
¤ The formatting & internationalization library
¤ The XML library
¤ References
2
4. Server-side Web languages
¤ Web browsers do not care on how the Web server
created the Web page
¤ Web browsers can correctly interpret only HTML markups
4
5. Server-side Web languages
¤ Therefore, all server-side Web languages have the same
goal: to produce familiar Web pages
5
6. Server-side Web languages
¤ A widely diverse array of technologies all have the same
purpose:
¤ JavaServer Pages (JSP)
¤ Active Server Pages (ASP)
¤ PHP: Hypertext Preprocessor (PHP)
6
7. JavaServer Pages
¤ JavaServer Pages (JSP) is a technology that helps Java
developers create dynamically generated Web pages
¤ A JSP page is a mix of plain old HTML tags and JSP
scripting elements
JSP Scripting Element
<b> This page was accessed at <%= new Date() %></b>
7
8. JavaServer Pages
¤ By using JSP pages:
¤ HTML developers can prepare the static part of the page
¤ Java developers can then complete the business-logic
portion
8
JSP Scripting Element
<b> This page was accessed at <%= new Date() %></b>
9. JavaServer Pages lifecycle
¤ When a client requests a JSP page, the JSP container
(e.g., Tomcat)
¤ translates the page into a Java servlet;
¤ compiles the source into a Java class file.
¤ At runtime, the JSP container can also check the last
modified date of the JSP file against the class file
¤ If the JSP has changed the container will rebuild the page all
over again
9
10. JavaServer Pages tags
¤ JSP scripting elements require that developers mix Java
code with HTML. This situation leads to:
¤ Non-maintainable applications
¤ No opportunity for code reuse
10
11. JavaServer Pages tags
¤ An alternative to scripting elements is to use JSP tags
¤ JSP tags can be used as if they were ordinary HTML tags
11
<table>
<c:forEach var="book" items="${books}" varStatus="status”>
<tr>
<td><c:out value="${book.title}"/></td>
</tr>
</c:forEach>
</table>
12. JavaServer Pages tags
¤ Each JSP tag is associated with a Java class
¤ It is sufficient to insert the same tag into another page to
reuse the same code
¤ If the code changes, all the pages are automatically
updated
12
13. Plain JSP vs. JSP tags
Plain JSP
<%= ((User) session.getAttribute("user")).getLastName() %>
JSP tag (JSTL library)
<c:out value="${sessionScope.user.lastName}"/>
¤ The JSP tag is more readable than the JSP scriptlet
¤ If the semantic of the JSP tag changes, the new behavior
is automatically propagated to all JSP pages in which the
tag is used
13
15. JSP Standard Tag Library
¤ The JSP Standard Tag Library (JSTL) is a JSP tag library
which offers tags to:
¤ Control the flow in the JSP page
¤ Date/number formatting and internationalization
¤ Parse XML snippets inside the JSP page
¤ Declaratively execute SQL queries
15
16. JSP Standard Tag Library
¤ JSTL is composed by a standard set of tags
¤ Applications written with JSTL can be deployed on any JSP
container supporting JSTL
¤ JSTL is a specification, not an implementation
¤ Apache Standard Taglibs is one of the most famous
implementation
16
17. JSTL tags
¤ JSTL divides its tags in four groups and makes them
available as separate tag libraries
JSTL tag library URI (Suggeste
d) prefix
Core library http://java.sun.com/jsp/jstl/core c
Formatting &
Internationalization
(i18n)
http://java.sun.com/jsp/jstl/fmt fmt
XML processing http://java.sun.com/jsp/jstl/xml x
Database (SQL)
access
http://java.sun.com/jsp/jstl/sql sql
17
18. JSTL tags
¤ JSTL tag libraries can be imported in the JSP page by
means of the <%@ taglib %> directive
¤ Directives are pseudo-tags that have special meaning to
the JSP container
<@ taglib %> for the JSTL core tag library*
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
18
*Please notice that JSTL 1.2’s URIs differ from the JSTL 1.1’s ones
19. JSTL tags
¤ Every tag library has a URI and a prefix associated with it
¤ The prefix assigned to the tag library is not mandatory, but it
is usually best to follow recommendation
19
*Please notice that JSTL 1.2’s URIs differ from the JSTL 1.1’s ones
<@ taglib %> for the JSTL core tag library*
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
21. Expression Language
¤ The JSTL Expression Language (EL) is a special purpose
programming language for embedding expressions into
Web pages
¤ The Expression Language is part of the JSP specification,
although it does not directly depend on the JSP
specification itself
¤ EL is available to other technologies, such as JavaServer
Faces (JSF)
21
22. Expression Language:
Expressions
¤ Expressions are always in the form ${expression}
¤ When an expression appears, it gets evaluated by the EL
22
Example of expression in EL
<c:out value="${1 + 2}"/>
24. Expression Language:
Automatic type conversion
¤ The page author is not responsible for converting
variables into appropriate objects or primitives
¤ JSTL defines a set of conversion rules called
coercion rules
¤ Conversions are done automatically by the implementation
24
25. Expression Language:
Automatic type conversion
¤ Example: <c:out> will always print a String
¤ If the scoped variable is not a String, JSTL will try to convert
the object automatically
¤ If coercion is not possible, an exception will be thrown
25
26. Expression Language:
Accessing data
¤ The major goal of the EL is to make data access easy
¤ Namely, EL makes extremely easy to access:
¤ JavaBeans
¤ Data types belonging to the Collections API
26
27. Expression Language:
Accessing data
¤ With respect to the Collections API:
¤ Ordered collections (e.g., Lists) can be accessed by
means of the subscript operator
¤ Unordered collections (e.g., Maps) can be accessed by using
either the subscript operator or dot notation
27
28. Accessing ordered collections
¤ Example: if we assume the existence of a names variable
of type List<String>, we can access its second
element as
28
<c:out value="${names[1]}" />
29. Accessing unordered collections
¤ Example: if we assume the existence of a grade variable
of type Map<String, Integer>, we can access a given
element as
29
<c:out value="${grade[“738340”]}" />
30. Expression Language:
Sources of data
¤ In a Java Web app, data of interest can be available
¤ As scoped variables coming from the Java back-end
¤ As HTTP requestparameters, when receiving input from the
outside world
30
31. JSP Scopes
¤ All variables in a Java Web application have two
characteristics:
¤ A name that identifies the data
¤ A scope that determines which parts of the Web app can
access the data
¤ Scopes let you decide:
¤ How long data stay around
¤ How your data should be shared among different pages in
your Web app
31
32. JSP Scopes
¤ Page scope: data can be
accessed only within the
page that created it
¤ Request scope: data can be
accessed within the same
request
¤ Application scope: data
can be accessed from any
point in the web app
¤ Session scope: data are tied
to a particular user,
regardless of pages and
requests
Page
scope Request
scope
Session
scope
Application
scope
32
33. Expression Language:
Scoped variables
Request-scoped data from the back-end (e.g., a servlet)
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
List<String> names = new ArrayList<String>();
names.add("foo");
names.add("bar");
names.add("smith");
request.setAttribute(”names", names);
// the source code continues
}
33
34. Expression Language:
Scoped variables
Request-scoped data from the back-end (e.g., Spring’s controller)
@RequestMapping(“/names”)
public String getNames(Model model) {
List<String> names = new ArrayList<String>();
names.add("foo");
names.add("bar");
names.add("smith");
model.addAttribute(”names", names);
return ...
}
34
35. Expression Language:
Scoped variables
¤ The Expression language defines a set of implicit objects
Object Content
pageScope a Map of all page-scoped variables
requestScope a Map of all request-scoped variables
applicationScope a Map of all application-scoped variables
sessionScope a Map of all session-scoped variables
35
36. Expression Language:
Scoped variables
¤ the Scope objects are Maps
¤ For each scoped-variable, its name is mapped to its value
¤ Two possible ways to access Scope objects:
¤ Dot notation: ${sessionScope.shoppingCart}
¤ Subscript operator: ${sessionScope[“shoppingCart”]}
¤ When no scope is specified for the variable of interest,
the EL will search all the JSP scopes following the order:
¤ page, request, session, application
36
37. Expression Language:
Scoped variables
Request-scoped data from the back-end (e.g., a servlet)
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
List<String> names = new ArrayList<String>();
names.add("foo");
names.add("bar");
names.add("smith");
request.setAttribute(”names", names);
// the source code continues
}
37
Accessing back-end data from the JSP page
<c:out value="${requestScope.names[1]}" />
38. Expression Language:
Request parameters
¤ JSP pages use scoped variables to manage their own
data
¤ JSP pages can also receive input from the outside world,
e.g., from a user entering information into an HTML form
¤ This information is made available through the request
parameters
38
39. Expression Language:
Request parameters
¤ The JSP page receiving data has to be specified has the
action end-point in the HTML <form> tag
39
<form> tag
<form method="post" action="formHandler.jsp">
40. Expression Language:
Request parameters
¤ Two ways of pointing to the request parameters:
¤ ${param.varName} returns the String value of the varName
parameter (or null if it is not found)
¤ ${paramValues.varName} returns the String[] containing
all values of the varName parameter (or null if it is not
found)
¤ paramValues is particularly useful if a request parameter
has multiple values (e.g., checkboxes)
40
43. The core library:
Overview
¤ The core tag library includes tags for the following uses:
¤ Accessing and modifying data in memory
¤ Making decisions
¤ Looping over data
¤ Error handling
¤ Managing URLs
¤ The set of tags available in the core tag library is by far
the most used in any JSP page
43
44. Accessing and modifying data:
<c:out>
¤ The <c:out> tag lets you print out the results of an
expression
Printing the value of a scoped variable
<c:out value="${username}" default="Guest"/>
Attribute Description Required Default
value the EL expression to compute Yes None
default The expression to compute if value fails No Use body
escapeXml Whether to escape characters (e.g., & as
&)
No true
44
45. Accessing and modifying data:
<c:set>
¤ The <c:set> tag lets you create scoped variables
Saving a scoped variable in the session scope
<c:set var="four" scope="session" value="${3 + 1}"/>
Attribute Description Required Default
value the EL expression to compute No Use body
var The name of the scoped variable to save Yes None
scope the scope of the variable to save No page*
*possible values are: page, request, session and application
45
46. Accessing and modifying data:
<c:set>
¤ JSP lets every tag have access to the output of its body
¤ When tags appear inside another tag, the outer tag
collects the output from the inner tag and then decides
what to do with it
Nested tags examples
<c:set var="eight">
<c:out value="${4 * 2}"/>
</c:set>
The page-scoped
variable eight is set
to the result of
<c:out> (8)
46
47. Accessing and modifying data:
<c:remove>
¤ The <c:remove> tag removes a variable from a given
scope
47
Attribute Description Required Default
var The name of the scoped variable to delete Yes None
scope the scope of the variable to delete No Any
Removing the variable cart from the session scope
<c:remove var="cart" scope="session"/>
¤ If no scope is specified, the tag will look in all the scopes
until it finds a variable named after the var attribute
48. Making decisions: <c:if>
¤ The <c:if> can be used in case of simple, mutual
exclusive conditions
Attribute Description Required Default
test Condition to evaluate, if true process the
body; if false, ignore the body
Yes None
var the name of the attribute to expose the end
result of the test expression
Yes None
scope Scope of the variable in the var attribute No page
Printing Dr. only if the the user has a doctorate
<c:if test="${user.education == 'doctorate'}">Dr.</c:if>
<c:out value="${user.name}"/>
48
49. Making decisions: <c:choose>,
<c:when>, <c:otherwise>
¤ the three cooperating tags <c:choose>, <c:when> and
<c:otherwise> can be used in case of complex, mutual
exclusive conditions
Attribute Description Required Default
test Condition to evaluate if no sibling
<c:when> tag has already succeeded
Yes None
Printing one error out of two possible ones
<c:choose>
<c:when test="${error1}"> <li>Error 1 has occurred.</li> </c:when>
<c:when test="${error2}"> <li>Error 2 has occurred.</li> </c:when>
<c:otherwise> <li> No error </li> </c:otherwise>
</c:choose>
49
<c:when> tag attributes
50. Making decisions: operators
Operator Description
== (eq) Equals
!= (ne) Not equals
< (lt) Less than
> (gt) Greater than
<= (le) Less than or equal to
>= (ge) Greater than or equal to
&& (and) Logical conjunction
|| (or) Logical disjunction
Binary operators
Operator Description
empty Check if a
variable exists
! (not) Logical negation
Unary operators
50
51. Looping over data: <c:forEach>
¤ The <c:forEach> tag lets you loop over nearly any
sensible collection of items the EL returns
Attribute Description Required Default
items Collection over which to iterate No None
var Name of the variable to expose the current
item
No None
Printing each book title in the books collection
<c:forEach items="${books}" var="book">
<c:out value="${book.title}"/>
</c:forEach>
51
52. Looping over data:
Loop status
¤ The varStatus attribute can be used to expose
information about the state of the iteration
¤ varStatus=“s” defines a scoped variable s that includes
properties for determining information about the current
loop
52
Property Type Description
index number The index of the current item in the
collection
count number The number of iterations executed so far,
starting from 1
first boolean Whether the current iteration is the first
last boolean Whether the current iteration is the last
53. Looping over data:
Loop status
Highlighting the first four rows in the table
<table>
<c:forEach var="book" items="${books}" varStatus="status”>
<tr>
<c:choose>
<c:when test="${status.count < 4}">
<td bgcolor="#FFFF00“><c:out value="${book.title}"/></td>
</c:when>
<c:otherwise>
<td><c:out value="${book.title}"/></td>
</c:otherwise>
</c:choose>
</tr>
</c:forEach>
</table>
53
54. Looping over data:
<c:forTokens>
¤ The <c:forTokens> can be used to iterate over a
collection of tokens
¤ We define tokens as a set of discrete strings within a larger
string
Attribute Description Required Default
items Input string over which to iterate Yes None
delims Delimiter characters that separate tokens Yes None
var Name of the attribute to expose the current
token
No None
54
55. Looping over data:
<c:forTokens>
Printing out each email address
<c:forTokens items="foo@gmail.com,bar@gmail.com,smith@gmail.com"
delims="," var="email">
<c:out value="${email}" />
</c:forTokens>
¤ The items attribute can also refer to an expression, e.g.,
items=“${emailAddresses}”
¤ Multiple delimiters can be specified, e.g., delims=“:,;”
¤ Also <c:forEach> supports simple string tokenization
¤ <c:forEach items=“a,b,c”> is equivalent to
<c:forTokens items=“a,b,c,” delims=“,”>
55
56. Looping over data:
Advanced iterations
Looping over part of a collection
<c:forTokens items="a,b,c,d,e,f" delims=","
var="letter" begin="2" end="4">
<c:out value="${letter}"/>
</c:forTokens>
Looping over numbers
<c:forEach begin="2" end="10" step="2" var="current">
<c:out value="${current}"/>
</c:forEach>
56
57. Error handling:
<c:catch>
¤ the <c:catch> tag ignores all the errors occurring in its
body
57
Attribute Description Required Default
var Variable to store information about the
error
No None
Multiplying by 2 the favnumber requestparameter, error if NaN
<c:catch var="parsingError">
<c:set var="number" value="${param.favnumber}" />
<c:out value="${number*2}" />
</c:catch>
<c:if test="${not empty parsingError}">
<c:out value="the parameter you specified is not a number" />
</c:if>
58. Managing URLs:
<c:url>, <c:param>
¤ the cooperating tags <c:url> and <c:param> let you
construct a link that passes a request parameter to a
page
58
Attribute Description Required Default
value Base URL to construct Yes None
var Name of the attribute to store the final URL No None
scope Scope of the attribute to store the final URL No page
context / followed by the name of a local web
application
No current
context
<c:url> tag attributes
59. Managing URLs:
<c:url>, <c:param>
Query string construction starting from the base URL /stocks
<a href="<c:url value=”/stocks">
<c:param name=”company" value="IBM"/>
</c:url>”>IBM's stock</a>
59
Attribute Description Required Default
name Parameter name Yes None
value Parameter value No Use
body
<c:param> tag attributes
60. Managing URLs:
Context-relative URLs
¤ A single web server might run many different web
applications at the same time
¤ Web applications are sometimes called contexts
¤ URLs starting with / may have different meanings within the
same page
¤ <a href="/outline.html"> is pointing to the root directory of
the web server
¤ <a href="<c:url value="/outline.html"/>"> is pointing to
the root of the web application
¤ The <c:url> tag’s context attribute can be used to create
a URL to a page in another web application in the same
web server
60
61. Managing URLs:
Why to use <c:url>
¤ Two good reasons to use <c:url>:
¤ Session preservation: in case the session mechanism is based
on URL rewriting rather than cookies, <c:url> takes care of
maintaining the jsessionid parameter in the query string
¤ Adjusting relative URLs: <c:url> makes sure that if a given
URL begins with /, it will be mapped to the root directory of
the web application, instead of the root of the entire web
server
61
62. Managing URLs:
<c:import>
¤ The <c:import> tag is used to import the content of a
URL-based resource
¤ JSTL version of the standard JSP tag <jsp:include>
62
Attribute Description Required Default
url URL to retrieve and import into the page Yes None
var Name of the attribute to store the final URL No None
scope Scope of the attribute to store the final URL No page
context / followed by the name of a local web
application
No current
context
Importing the external page outline.html
<c:import url="outline.html"/>
64. The formatting & i18n tag library:
Overview
¤ If the web application targets different users in different
countries, it is important to present appropriate information
according to user’s locale
¤ Example: The string “7/2/1947” means
¤ July 2, 1947 in the United States
¤ February 7, 1947 in Europe
¤ JSTL’s formatting and internationalization support aims at
¤ correctly formatting number and dates;
¤ translating in different languages words and sentences in
the web application.
64
65. The formatting & i18n tag library:
Overview
¤ The formatting & internationalization tag library includes
tags for the following uses:
¤ Reading and printing numbers
¤ Reading and printing dates
¤ Helping your application work with more than one language
¤ The objective is to reduce as much as possible the effort
required to internationalize the web application
65
66. Reading and printing numbers:
<fmt:parseNumber>
¤ The <fmt:parseNumber> tag lets you interpret
complicated strings as numbers
¤ Example: the string “50,000” can be interpret as
¤ 50000 if the user’s locale is set to United States
¤ 50.00 if the user’s locale is set to Europe
66
67. Reading and printing numbers:
<fmt:parseNumber>
¤ The <fmt:parseNumber> tag lets you interpret
complicated strings as numbers
67
Attribute Description Required Default
value The string to parse as number No Use
body
var Variable to store the formatted number No None
type How to parse the number (possible values:
number, currency and percent)
No number
scope Scope in which to store the formatted
number
No page
integerOnly Whether to discard any fractional digits No false
parseLocale Locale to use instead of default No Local
68. Reading and printing numbers:
<fmt:parseNumber>
Parsing the request parameter favnumber as a number
<fmt:parseNumber var="fav" value="${param.favnumber}"/>
68
¤ Where:
¤ The input is the string param.favnumber
¤ The output is a number that is stored in the scoped variable
fav
69. Reading and printing numbers:
<fmt:parseNumber>
¤ Remember: the parseLocale attribute is useful when
dealing with a data source from another country
¤ In such a case you want to parse a number using the data
source’s locale
69
70. Reading and printing dates:
<fmt:parseDate>
¤ The <fmt:parseDate> tag reads a string coming from an
external source (e.g., a database) and treats it as a date
¤ Example: The string “7/2/1947” means
¤ July 2, 1947 in the United States
¤ February 7, 1947 in Europe
70
71. Reading and printing dates:
<fmt:parseDate>
¤ The <fmt:parseDate> tag reads a string coming from an
external source (e.g., a database) and treats it as a date
71
Attribute Description Required Default
value The date string to parse No Use body
type How to parse the date (possible values:
time, date, or both)
No date
var Variable to store the formatted date (as a
number)
No None
scope Scope in which to store the parsed date No page
parseLocale Locale to use instead of the default No Local
timeZone Time zone to apply to the parsed date No Local
72. Reading and printing dates:
<fmt:parseDate>
Parsing a valid date by aggregating three request parameters
<fmt:parseDate var="date" parseLocale="en_US"
value="${param.month} ${param.day}, ${param.year}"/>
72
¤ Where:
¤ date is a scoped variable of type java.util.Date
¤ The value attribute must point to a string representing a
valid date in the specified locale
¤ To force the usage of the U.S. English locale (instead of
the browser’s locale) the parseLocale attribute is set to
en_US
73. Reading and printing numbers:
<fmt:formatNumber>
¤ the <fmt:formatNumber> tag prints out a formatted
number accordingly to user’s locale
73
Attribute Description Required Default
value The numeric value to format No Use
body
type Whether to print regular numbers,
currencies or percentages (possible values:
number, currency and percent)
No number
var Variable to store the formatted number No None
scope Scope in which to store the formatted
number
No page
currencyCode Currency code as in ISO-4217 (e.g., USD) No None
groupingUsed Whether to group digits, as in 1,234,567 No true
74. Reading and printing numbers:
<fmt:formatNumber>
The numeric value is formatted according to user’s locale
<fmt:formatNumber type="currency" value="78.74901"/>
74
The numeric value is formatted as US Dollars
<fmt:formatNumber type="currency" currencyCode="USD”
value="78.74901"/>
¤ In the first example, the numeric value is displayed as*
¤ $78.75 in the United States
¤ €78,75 in Europe
¤ In the second example, the numeric value is displayed as
$78.75 regardless user’s locale
*Please set the charset ISO for the JSP page to ISO-8859-15
75. Reading and printing dates:
<fmt:formatDate>
¤ the <fmt:formatDate> tag prints out formatted dates
and times accordingly to the user’s locale
75
Attribute Description Required Default
value Date to print Yes None
type Whether to print dates, times or both
(possible value: date, time and both)
No date
var Variable to store the formatted number No None
scope Scope in which to store the formatted
number
No page
timeZone Time zone to use when formatting the date No Local
76. Reading and printing dates:
<fmt:formatDate>
¤ Please notice that the value attribute must point to a
variable of type java.util.Date
¤ The standard JSP tag <jsp:useBean> can be used to
create scoped variable of a specific class
¤ If not specified, the default scope is page
76
Creating a page-scoped variable of type java.util.Date
<jsp:useBean id="now" class="java.util.Date" />
Printing out the currentdate and time
<fmt:formatDate value="${now}" type="both"/>
77. Reading and printing dates:
<fmt:formatDate>
¤ A time zone is a region on Earth that has a uniform standard
time for legal, commercial, and social purposes
¤ Example: Greenwich Mean Time
¤ By default, the <fmt:formatDate> tag does its best to figure
out a sensible time zone
¤ If no time zone is specified, the page will use the time zone of
the JSP container
¤ The timeZone attribute accepts a number of different kinds
of identifiers for time zones
¤ Example: EST for Eastern Time, CST for Central Time, and PST for
Pacific Time
77
78. Working with different languages:
Resource bundles
¤ Every message that may be displayed in the application is stored in
a separate file, called the resource bundle
¤ A resource bundle maps a generic key (e.g., welcome), to a single
translated value (e.g., Hello)
¤ The web app can be localized by a adding resource bundle for
each supported locale
¤ The same set of keys is associated with different, locale-specific
messages
¤ Example: in the resource bundle for the Italian locale, the welcome key
can be associated with Ciao
¤ We will refer to the set of localized resource bundles for the same
web app as to the resource bundle family for the web app
78
79. Working with different languages:
<fmt:setBundle>
¤ The <fmt:setBundle>* tag defines the default resource
bundle family for a given scope
79
Attribute Description Required Default
basename Name of the resource bundle family to use Yes None
var Variable to store the bundle in use No None
scope Scope in which to store the bundle in use No page
Specifying the basename for the resource bundle family
<fmt:setBundle basename=”resources.application" />
*See also <fmt:bundle>for locally defining the resource bundle
family
80. Working with different languages:
<fmt:message>
¤ The <fmt:message> tag accepts a key and looks up its
translated value in a resource bundle
80
Attribute Description Required Default
key Internationalized key to use No Use body
bundle scoped variable containing a specific
resource bundle to use in place of the
default one
No Local
var Variable to store the localized message No None
scope Scope in which to store the localized
message
No page
Printing out the value for the welcome key in the currentlocale
<fmt:message key="welcome"/>
81. Working with different languages:
<fmt:param>
¤ The <fmt:param> lets you instantiate a parametric
message
¤ Example: welcome=Hi, {0}
81
Attribute Description Required Default
value Parameter to add No Use body
Welcoming the user with his/her name
<fmt:message key="welcome">
<fmt:param value="${user.name}" />
</fmt:message>
83. The XML tag library:
Overview
¤ The XML tag library includes tags for the following uses:
¤ Parsing XML documents
¤ Printing parts of XML documents
¤ Making decisions based on the contents of an XML
document
¤ Looping over parts of an XML document
83
84. The XML tag library:
Overview
¤ The JSTL’s XML library parallels the core library
¤ As the core library, the XML tag library supports flow control,
saving and printing data
¤ The major difference is that:
¤ the core library uses the EL to work with regular variables
¤ the XML library uses XPath to manipulate XML documents
¤ The XML Path Language (XPath) is a query language for
selecting nodes from an XML document
84
85. The XML Path Language:
Document representation42 CHAPTER 7
Selecting XML fragments
7.2 XPath’s basic syntax
Figure 7.1
The tree structure of a sample HTML
document. When an element like
<h1> occurs inside <body>, you
can think of it as a child of that
<body> element.
¤ In XPath, each XML document is
represented as a tree
¤ Each element in the tree can be
uniquely identified by a path, e.g.,
/html/body/p/b
¤ Any descendent of an element
can be searched through the tree
by using two adjacent
backslashes, e.g., //b
85
86. The XML Path Language:
Predicates
¤ XPath lets you identify elements
using attributes
¤ Example: the preferred customers
can be identified by the following
XPath expression
¤ //customer[@status=“preferred”]
¤ XPath expressions involving the []
operator are called predicates
86
customer.xml
<customers>
<customer id="555" status="regular">
<name>Jim Heinz</name>
</customer>
<customer id="556" status="preferred">
<name>Roberto del Monte</name>
</customer>
<customer id="557" status="preferred">
<name>Richard Hunt</name>
</customer>
</customers>
87. The XML Path Language:
Predicates
customer.xml
<customers>
<customer id="555" status="regular">
<name>Jim Heinz</name>
</customer>
<customer id="556" status="preferred">
<name>Roberto del Monte</name>
</customer>
<customer id="557" status="preferred">
<name>Richard Hunt</name>
</customer>
</customers>
¤ Predicates can also be used to filter
elements by the order in which they
appear
¤ Example: The second customer can
be retrieved by using the following
XPath expression:
¤ /customers/customer[2]
¤ Please notice that in XPath numeric
predicates start with 1
87
88. The XML Path Language:
Variables
¤ XPath supports variables, which are evaluated and
replaced with their actual values
¤ Variable in XPath are qualified names, introduced with a
dollar sign ($)
¤ XML defines a qualified name as a tag name with a
namespace prefix attached to it, e.g., <periodic:table>
88
89. The XML Path Language:
Variables
¤ For each JSTL’s implicit object there exists a
correspondent XML’s namespace
¤ Example: $requestScope:varName refers to the scoped-
variable ${requestScope.varName}
¤ Just as in JSTL, if no namespace is specified, the following
order is used:
¤ page, request, session, application
89
90. Parsing XML documents: <x:parse>
¤ The <x:parse> tag lets you acquire and parse an XML
document
90
Attribute Description Required Default
xml The raw XML text to parse No Use body
var Variable to store the parsed document Yes None
scope Scope in which to store the parsed
document
No page
Acquiring and parsing the XML documentmydocument.xml
<c:import var="raw" url="/mydocument.xml"/>
<x:parse xml=”${raw}" var="doc"/>
91. Printing parts of XML documents:
<x:out>
¤ The <x:out> tag evaluates and prints out the string value
of an XPath expression
91
Attribute Description Required Default
select XPath expression Yes None
scope Variable to store the parsed document Yes None
escapeXml Whether to escape characters (e.g., & as
&)
No true
¤ Please remember that the select attribute points to an
XPath expression, not an EL expression
¤ Expressions are in the form expression rather than
${expression}
92. Printing parts of XML documents:
<x:out>
simple.xml
<a>
<b>
<c>C</c>
</b>
<d>
<e>E</e>
</d>
</a>
Printing out the string value of <c>
<c:import var="raw" url="/simple.xml"/>
<x:parse xml=”${raw}" var=”simple"/>
<x:out select="$simple//c"/>
92
¤ The XPath expression causes the
<x:out> tag to retrieve all nodes
named <c>
¤ The tag prints out the text C because
that is the string value of the only <c>
node present in the XML snippet
93. Printing parts of XML documents:
<x:set>
¤ the <x:set> tag stores the result of an XPath expression
in a variable
93
Attribute Description Required Default
select XPath expression Yes None
var Variable to store the result of the XPath
expression
Yes None
scope Scope in which to store the result of the
XPath expression
No page
94. Printing parts of XML documents:
<x:set>
simple.xml
<a>
<b>
<c>C</c>
</b>
<d>
<e>E</e>
</d>
</a>
store the sub-tree with root in <b>
<c:import var="raw" url="/simple.xml"/>
<x:parse xml=”${raw}" var=”simple"/>
<x:set var="b" select="$simple/a/b"/>
94
¤ ${b} contains a subset of the original
document
¤ <x:set> may be useful when part of
the data needs to be shared in the
sessionPart of the
document selected
95. Making decisions: <x:if>
¤ The <x:if> tag lets you make a decision based on the
information contained in an XML document
95
Attribute Description Required Default
select XPath expression to evaluate, if true process
the body; if false, ignore the body
Yes None
var the name of the attribute to expose the end
result of the test expression
Yes None
scope Scope of the variable in the var attribute No page
96. Making decisions: <x:if>
customers.xml
<customers>
<customer id="525">
<name>Jim Heinz</name>
<order>20005</order>
<order>20127</order>
</customer>
<customer id="526">
<name>Roberto del Monte</name>
</customer>
</customers>
Printing a greeting for repeatcustomers
<c:import var="raw" url="/customer.xml"/>
<x:parse xml=”${raw}" var=”doc"/>
<x:if select="$doc/customers/
customer[@id=$customerId]/order">
Thank you for letting us sell you something
</x:if>
96
¤ The greeting is shown only if the user
has placed at least one order in the
past
¤ In the example, we suppose the
existence of a page-scoped variable
named customerId
97. Making decisions: <x:choose>,
<x:when>, <x:otherwise>
¤ The three cooperating tags <x:choose>, <x:when> and
<x:otherwise> can be used for evaluating XML-based
conditions
97
Attribute Description Required Default
select XPath expression to evaluate if no sibling
<x:when> tag has already succeeded
Yes None
<x:when> tag attributes
98. Making decisions: <x:choose>,
<x:when>, <x:otherwise>
customer.xml
<customers>
<customer id="555" status="regular">
<name>Jim Heinz</name>
</customer>
<customer id="556" status="preferred">
<name>Roberto del Monte</name>
</customer>
<customer id="557" status="preferred">
<name>Richard Hunt</name>
</customer>
</customers>
Qualifying users by status
<x:choose>
<x:when select="$doc//customer[@id=$customerId]/
@status='regular'">
Normal
</x:when>
<x:when select="$doc//customer[@id=$customerId]/
@status='preferred'">
Important
</x:when>
<x:otherwise>
Unknown
</x:otherwise>
</x:choose>
98
99. Looping over a document:
<x:forEach>
¤ The <x:forEach> tag lets you iterate over an XML
document
99
Attribute Description Required Default
select XPath expression over whose result to iterate Yes None
var Name of the variable to expose the current
node
No None
100. Looping over a document:
<x:forEach>
¤ If an XPath expression does not define an explicit root,
the expression will be evaluated w.r.t. the context node
¤ The concept of context node is similar to the the concept of
current directory in a file system
¤ During an <x:forEach> loop, the current node in the
iteration becomes the context node
¤ Therefore, each XPath expression defined inside the
<x:forEach> tag’s body will use the current node as the
context node
100
101. Looping over a document:
<x:forEach>
customer.xml
<customers>
<customer id="555" status="regular">
<name>Jim Heinz</name>
</customer>
<customer id="556" status="preferred">
<name>Roberto del Monte</name>
</customer>
<customer id="557" status="preferred">
<name>Richard Hunt</name>
</customer>
</customers>
Printing out the customers’ name
<x:forEach select="$doc//customer">
<p><x:out select="name"/></p>
</x:forEach>
101
¤ The $doc//customer matches
each <customer> tag in the
document
¤ Within each loop, the <name> tag
is printed out under the context
node
103. References
¤ S. Bayern, JSTL In Action, Manning Publications Co.
¤ S. Spielman, JSTL: Practical Guide for JSP Programmers,
Morgan Kaufmann Publishers
¤ Wikipedia, Unified Expression
Languagehttp://en.wikipedia.org/w/index.php?title=Unified
_Expression_Language&oldid=533174739
¤ Wikipedia, Time
zonehttp://en.wikipedia.org/w/index.php?title=Time_zone&
oldid=538844415
103
104. Topics not covered
¤ Implicit objects other than scopes (e.g., cookie)
¤ XML transformation tags
¤ The SQL tag library
104
105. Expression Language:
Scoped variables
¤ The major goal of the EL is to make data access easy
¤ Data of interest can be store in a specific scope or in the
HTTP request
¤ To this end, the EL defines a set of implicit objects
Object Content
pageScope a Map of all page-scoped variables
requestScope a Map of all request-scoped variables
applicationScope a Map of all application-scoped variables
sessionScope a Map of all session-scoped variables
105
106. Expression Language:
Accessing data
¤ Sometimes JSP pages need to manage scoped data
coming from the Java back-end
¤ JSTL makes JavaBeans and other data types belonging
to the Java Collections API extremely easy to access
¤ Ordered collections (e.g., Lists) can be accessed by
means of the subscript operator
¤ Unordered collections (e.g., Maps) can be accessed by using
either the subscript operator or dot notation
106