Upload
lawrence-weaver
View
215
Download
0
Embed Size (px)
Citation preview
JSTL: The JavaServer Pages Standard Tag Library
Mark A. KolbSecurity Broadband, Austin, [email protected]
Prerequisites Servlet API JavaServer Pages
Basic syntaxImplementation via Servlet API
Using resource bundles for I18N XML
Related Sessions Kimberly Bobrow’s “Introduction to
JavaServer Pages (JSP)” Bryan Basham’s “Web Application
Development, A Case Study” Noel Bergman’s “A Visitor’s Guide to
Jakarta” Mark Kolb’s “Authoring JSP Custom
Tags”
What Is the JSTL? A poor acronym
J = JSP?There are actually four tag libraries in the
JSP Standard Tag Library Based on JSP 1.2/Servlet 2.3
What Is the JSTL? A collection of tag libraries
implementing common JSP functionalityCore functions
• Variables, I/O, conditionalization, iterationFormatting/I18n
• Message bundles, numbers, datesXML operations
• parsing, transformationsDatabase operations
• SQL
What Is the JSTL? An expression language for specifying
custom tag attribute valuesBased on ECMAScript and Xpath
Expression language is optionalEach of the four JSTL libraries has an EL
version and an RT version.• EL = JSTL expression language• RT = JSP request-time attribute values
What Is the JSTL? A set of Java classes
Interfaces and support classes for custom tag implementors• Provides for interoperability with JSTL tags
General-purpose tag library validators• JSTL 1.0 validators focus on enforcing coding
standards•ScriptFreeTLV - prohibit scripting elements•PermittedTaglibsTLV - restrict tag library
usage
Why JSTL? JSTL tags provide a standard
implementation for typical application functionalityReusabilityAvoid reinventing the wheel
Another mechanism for avoiding the use of JSP scripting elementsEL considerably simpler than JavaStrong emphasis on “variables”Two steps forward, one step back?
JSTL Expression Language Delimiters are “${” and “}” The EL can only be used for specifying
attribute values in JSTL tags<c:out value=”${user.firstName}”/>
Multiple expressions can be combined and mixed with static text (i.e., implicit string concatenation)<c:out value=”Hello ${user.firstName} ${user.lastName}!”/>
JSTL Expression Language Individual expressions are
combinations of identifiers, accessors, and operators
There are also identifiers for a set of JSTL implicit objectsNot the same as the JSP implicit objects
(with one exception)
EL Identifiers Identifiers are resolved against the four JSP
scopesUsing PageContext.findAttribute(name)Scopes are searched sequentially: page, request, session, application
Reserved identifiers for the 11 JSTL implicit objects:pageContext, pageScope, requestScope, sessionScope, applicationScope
param, paramValues, header, headerValuesinitParam, cookie
EL Accessors Properties of objects are accessed via
the “.” operatoruser.firstName represents the value of
the “firstName” property of the object referenced by the “user” identifier
EL Accessors Elements of a Map, List, or array are
accessed via the “[]” operatorFor a map associated with the identifier users, users[”frodo”] represents the value mapped to the ”frodo” key
For a list or array associated with the identifier track, track[4] represents the fifth element of the sequence
Elements can be referenced via identifiers, as in users[username] or track[index]
EL Accessors Actually, the “.” and “[]” operators are
interchangeableuser.firstName and user[”firstName”]
are equivalent expressions
EL Implicit Objects pageContext is identical to the JSP implicit object of
the same name Provides access to the other JSP implicit objects and their
properties${pageContext.request.queryString}
The “scope” implicit objects are maps for looking up scoped attributes pageScope, requestScope, sessionScope, and applicationScope
For example, ${sessionScope[”userProfile”]} retrieves the attribute named ”userProfile” from the user’s session, equivalent to
<%= session.getAttribute(”userProfile”)%>
EL Implicit Objects The param implicit object is a map for
looking up the value of a request parameter${param[”keyword”]} is equivalent to
<%= request.getParameter(”keyword”)%>
paramValues is also a map, which returns an array of strings containing all of the values associated with a request parameter${paramValues[”keyword”]} is equivalent to<%= request.getParameterValues(”keyword”)%>
EL Implicit Objects The header implicit object is a map for
looking up the value of a request header${header[”User-Agent”]} is equivalent to
<%= request.getHeader(”User-Agent”)%>
headerValues is also a map, which returns an array of strings containing all of the values associated with a request header${headerValues[”Accept”]} is equivalent to
<%= request.getHeaders(”Accept”)%>
EL Implicit Objects The initParam implicit object is a map
for looking up the value of a context initialization parameter
The cookie implicit object is a map for looking up a cookie from its name
EL Operators Arithmetic operators
+, -, *, / (or div), % (or mod)
Relational operators == (or eq), != (or ne), < (or lt), > (or gt), <= (or le), >=
(or ge) Can be applied to both numeric and string values
Logical operators && (or and), || (or or), ! (or not)
Empty operator empty expr indicates whether expr is null or an empty String, Map, List, or array.
EL Operators Logical operators will short-circuit
evaluationFor example, in ${expr1 && expr2}, expr2 will not be evaluated if expr1 has a value of false.
Parentheses can be used for grouping and will override operator precedence rulesFor example, ${a * (b + c)} overrides
the normal precedence of multiplication over addition
Core Library EL library
Dynamic attribute values specified using the JSTL expression language (i.e., ${ expr }) <%@ taglib uri=”http://java.sun.com/jstl/core”
prefix=”c”>
RT libraryDynamic attribute values specified using
the JSP expressions (i.e., <%= expr %>) <%@ taglib uri=”http://java.sun.com/jstl/core_rt”
prefix=”c_rt”>
Core Library Tags General-purpose actions
<c:out><c:set><c:remove><c:catch>
Conditional actions<c:if><c:choose>, <c:when>, <c:otherwise>
Core Library Tags Iteration actions
<c:forEach><c:forTokens>
URL actions<c:url>, <c:param><c:redirect>, <c:param><c:import>, <c:param>
<c:out> Tag <c:out value=”value”
default=”defaultValue”escapeXml=”bool”/>
Evaluates the value attribute and outputs the result as a string
Provides equivalent functionality to JSP expressions and the <jsp:getProperty> action
Prints the value of the default attribute if the value attribute evaluates to nullDefault result can also be specified via body
content
<c:out> Tag The escapeXml attribute determines
whether or not characters are converted to XML entities (defaults to true)
< <
> >
& &
’ '
” "
<c:set> Tag <c:set var=”varName”
value=”value”scope=”varScope”/>
Evaluates the value attribute and assigns the result to a scoped variable
Variable scope is either page (the default), request, session, or application
Variable value can also be specified via body content
<c:set> Tag <c:set target=”beanOrMap”
property=”propertyOrKey”value=”value”/>
Evaluates the value attribute and assigns the result to the specified JavaBeans property or map key In the former role, provides equivalent
functionality to the <jsp:setProperty> action
Property value can also be specified via body content
<c:remove> Tag<c:remove var=”varName”
scope=”varScope”/> Removes the named variable from the
indicated scope Variable scope is either page (the
default), request, session, or application
<c:catch> Tag <c:catch var=”varName”>
nested actions </c:catch>
Catches any exception thrown by the nested actionsCaught exception is assigned to the
(optional) named variable (with page scope)
If no exception is thrown, the variable is removed from page scope
<c:if> Tag<c:if test=”condition”
var=”varName”scope=”varScope”>
body content</c:if>
Conditionally processes the body content Body content can be omitted to just
perform the variable assignment, in which case the var attribute is no longer optional
<c:choose> Tag<c:choose>
<c:when test=”condition”>body content
</c:when>…<c:otherwise>
body content</c:otherwise>
</c:choose> Enables mutually exclusive conditionalization
<c:choose> Tag There must be at least one <c:when> action Only the first <c:when> whose test condition
evaluates to true will have its body content processed
There can be at most one <c:otherwise> action, and it must be the last action within the <c:choose> body
The <c:choose> body can contain only whitespace, <c:when> actions, and <c:choose> actions
ConditionalTagSupport Class
JSTL provides base class for custom tag implementors javax.servlet.jsp.jstl.core.ConditionalTagSupport
Utility class for implementing custom tags for conditionalizing contentCustom tag works like <c:if>, conditionalizing
body content and optionally exposing a scoped variable
This variable can then be referenced by the test attribute of subsequent <c:if> and <c:when> actions
<c:forEach> Tag <c:forEach var=”varName”
varStatus=”varStatusName”begin=”begin” end=”end”step=”step”>
body content</c:forEach>
Iteratively processes the body content for a fixed number of times, like a for statementFrom begin to end, by an optional step
<c:forEach> Tag <c:forEach var=”varName”
items=”collection” varStatus=”varStatusName”begin=”begin” end=”end”step=”step”>
body content</c:forEach>
Iteratively processes the body content for all of the items in a collectionOptionally bound by begin, end, and step
<c:forEach> Tag The items attribute supports all
standard J2SE collection typesjava.util.Collection, java.util.Mapjava.util.Iterator, java.util.EnumerationArrays, including arrays of primitivesString objects which use embedded comma
delimiters
<c:forEach> Tag The variable named by the var
attribute references the current item of the iterationPrimitives (from an array) are wrappedFor maps, the variable references an
instance of java.util.Map.Entry (inner class of Map)•Entry has two properties, key and value
This variable has nested visibility
<c:forEach> Tag The variable named by the varStatus
attribute references an instance of the LoopTagStatus class from the javax.servlet.jsp.jstl.core package Properties indicate the current iteration
status This variable has nested visibility
LoopTagStatus Class The LoopTagStatus properties are
defined by eight getter methodsgetCurrent() returns the current itemgetIndex() returns the current index
(0-based, initialized via the begin attribute)getCount() returns the current count
(1-based, independent of the begin attribute)isFirst(), isLast()getBegin(), getEnd(), getStep()
LoopTag Interface JSTL provides an interface and a
corresponding base class for custom tag implementors javax.servlet.jsp.jstl.core.LoopTag interface javax.servlet.jsp.jstl.core.LoopTagSupport class
Allows developers to leverage the functionality of <c:forEach> in their own custom tags
<c:forTokens> Tag <c:forTokens var=”varName”
items=”stringOfTokens”delims=”delimiters” varStatus=”varStatusName”begin=”begin” end=”end”step=”step”>
body content</c:forEach>
JSTL version of java.util.StringTokenizer Iteratively processes the body content for all of the
tokens in a String String is tokenized using the specified delimiters
<c:url> Tag <c:url value=”baseURL”
context=”context”var=”varName”scope=”varScope”/>
URL re-writingAppends session id (if appropriate)Prepends context to relative URLs (defaulting to
current context)
Request parameters can be specified via body content
<c:param> Tag <c:param name=”paramName”
value=”paramValue”/> Used to add request parameters to a URL Nested in the body content of a <c:url>, <c:redirect>, or <c:import> tag
The values of the name and value will be URL encoded when added to the URL
<c:redirect> Tag <c:redirect url=”baseURL”
context=”context”/> Sends an HTTP redirect response
Aborts processing of remainder of page Request parameters can be specified via body content
<c:import> Tag <c:import url=”baseURL”
context=”context”charEncoding=”encoding” var=”varName”scope=”varScope”/>
Fetches the content of a URL If a variable is specified, content is assigned to variable as a String
If no variable is specified, content is inserted into current page (like <jsp:include> action)
Request parameters can be specified via body content
<c:import> Tag <c:import url=”baseURL”
context=”context”charEncoding=”encoding” varReader=”readerName”>
body content </c:import>
Fetches the content of a URL URL content is exposed via a variable referencing a java.io.Reader
The varReader variable has nested scope
Request parameters cannot be specified via body content Can use <c:url> with var attribute to build URL with
request parameters, then pass variable to <c:import>
Formatting Library EL library
Dynamic attribute values specified using the JSTL expression language (i.e., ${ expr }) <%@ taglib uri=”http://java.sun.com/jstl/fmt”
prefix=”fmt”>
RT libraryDynamic attribute values specified using
the JSP expressions (i.e., <%= expr %>) <%@ taglib uri=”http://java.sun.com/jstl/fmt_rt”
prefix=”fmt_rt”>
Formatting Library Tags Internationalization actions
<fmt:message>, <fmt:param><fmt:bundle><fmt:setBundle><fmt:setLocale><fmt:requestEncoding>
Formatting Library Tags Data formatting actions
<fmt:formatNumber><fmt:parseNumber><fmt:formatDate><fmt:parseDate><fmt:timeZone><fmt:setTimeZone>
<fmt:message> Tag <fmt:message key=”messageKey”
bundle=”context”var=”varName”scope=”varScope”/>
Displays a message fetched from a resource bundle
The bundle attribute specifies an instance of javax.servlet.jsp.jstl.fmt.LocalizationContext
Message key can also be specified in body content
Message parameters can be specified via body content (after the key value, if present)
<fmt:param> Tag<fmt:param value=”messageParam”/>
Supplies a single value for parametric replacement within a message
Each parameter in a message requires a corresponding <fmt:param> tag
Nested within a <fmt:message> action
<fmt:bundle> Tag <fmt:bundle basename=”basename”
prefix=”prefix”> body content </fmt:bundle>
Specifies a localization context for nested formatting actions (e.g., <fmt:message>)
Required basename attribute identifies the resource bundle (subject to localization)
Optional prefix attribute specifies a prefix to be prepended to all message keys appearing in the body content
Other I18N Tags <fmt:setBundle> assigns a localization
context to a variable, or assigns the default localization context for a scope
<fmt:setLocale> sets the current locale across a JSP scope (overrides browser-based locale) JSTL also provides a configuration variable for
specifying a fallback locale <fmt:requestEncoding> set the character
encoding for a request so that request parameter values can be correctly decodedCompensates for browser misbehavior with
respect to the Content-Type header
<fmt:formatNumber> Tag <fmt:formatNumber value=”numericValue”
type=”type” pattern=”pattern”currencyCode=”code” currencySymbol=”symbol” groupingUsed=”bool”maxIntegerDigits=”maxIntDigits”
minIntegerDigits=”minIntDigits” maxFractionDigits=”maxFracDigits”
minFractionDigits=”minFracDigits” var=”varName” scope=”varScope”/>
Displays a formatted number, or assigns the formatted result to a variable
<fmt:formatNumber> Tag The value to be formatted can also be
specified via body content. Formatting type is either number, currency, or percentage
The pattern attribute takes precedence over the type attribute, and must follow the pattern conventions of the java.text.DecimalFormat class
Formatting is influenced by localization context
<fmt:formatDate> Tag <fmt:formatDate value=”numericValue”
type=”type” pattern=”pattern”dateStyle=”dateStyle” timeStyle=”timeStyle” timeZone=”timeZone”
var=”varName”scope=”varScope”/>
Displays a formatted date and/or time, or assigns the formatted result to a variable
<fmt:formatDate> Tag Formatting type is either time, date, or both Permitted values for the dateStyle and timeStyle attributes are default, short, medium, long, and full Values follow java.text.DateFormat conventions
The pattern attribute takes precedence over the type, dateStyle, and timeStyle attributes, and must follow the pattern conventions of the java.text.SimpleDateFormat class
Formatting is influenced by localization context
Parsing Tags <fmt:parseNumber> parses a String
into a numeric valueResulting value can be assigned to a
variable or output to page <fmt:parseDate> parses a String into
a numeric valueResulting value can be assigned to a
variable or output to page Both parsing tags are locale-sensitive
<fmt:timeZone> Tag<fmt:timeZone value=”timeZone”>
body content</fmt:timeZone>
Specifies the timezone in which to format or parse any nested <fmt:formatDate> or <fmt:parseDate> tags
The timezone value can be either a String identifying a timezone or an instance of java.util.TimeZone
<fmt:setTimeZone> assigns a time zone to a variable, or assigns the default time zone
<fmt:setTimeZone> Tag<fmt:setTimeZone value=”timeZone”
var=”varName”scope=”varScope”/>
Assigns a time zone to a variable, or assigns the default time zone for a scope
XML Library EL library
Dynamic attribute values specified using the JSTL expression language (i.e., ${ expr }) <%@ taglib uri=”http://java.sun.com/jstl/xml”
prefix=”x”>
RT libraryDynamic attribute values specified using
the JSP expressions (i.e., <%= expr %>) <%@ taglib uri=”http://java.sun.com/jstl/xml_rt”
prefix=”x_rt”>
XML Library Tags Core actions
<x:parse><x:out><x:set>
Flow control actions<x:if><x:choose>, <x:when>, <x:otherwise><x:forEach>
<x:parse> Tag <x:parse xml=”document”
systemId=”systemId” filter=”filter”
var=”varName”scope=”varScope”
varDom=”varDomName”scopeDom=”varDomScope”/>
Parses an XML document via a String or Reader specified via the xml attributeInteroperable with <c:import> action
<x:parse> Tag <x:parse systemId=”systemId”
filter=”filter” var=”varName”
scope=”varScope” varDom=”varDomName”
scopeDom=”varDomScope”> body content
</x:parse> Parses an XML document provided as
body content
<x:parse> Tag Result is stored in a variable
Variable specified by either var and optional scope, or by varDom and optional scopeDom
When var is used, the type of the result is implementation-specific
When varDom is used, the result will implement the org.w3c.dom.Document interface
The filter attribute can specify an instance of org.xml.sax.XMLFilter for filtering the XML document during parsing
<x:out> Tag <x:out select=”XPathExpression”
escapeXml=”bool”/>
Displays data from a parsed XML document
The select attribute employs a syntax based on XPath to identify the data to be displayedReferences variable created by <x:parse>
Analogous to <c:out> action
<x:set> Tag <x:set var=”varName”
select=”XPathExpression”scope=”varScope”/>
Assigns data from a parsed XML document
The select attribute employs a syntax based on XPath to identify the data to be displayedReferences variable created by <x:parse>
Analogous to <c:set> action
XML Flow Control Tags Three sets of flow control actions
<x:if><x:choose>, <x:when>, <x:otherwise><x:forEach>
Analogous to like-named JSTL core actionsConditionalization or iteration driven by
XPath expression values (select attribute), rather than EL or RT values
<x:transform> Tag <x:transform xslt=”stylesheet”
xmlSystemId=”systemId” xsltSystemId=”systemId”
result=”resultObject” var=”varName”
scope=”varScope”/> Transforms an XML document specified via
the xml attributeString, Reader, javax.xml.transform.Source, org.w3c.dom.Document, or implementation-specific class
Transformation parameters can be supplied via nested <x:param> actions
<x:transform> Tag <x:transform xml=”xmlDocument”
xslt=”stylesheet”xmlSystemId=”systemId”
xsltSystemId=”systemId” result=”resultObject”
var=”varName”scope=”varScope”>
body content</x:transform>
Transforms an XML document provided as body content, via a nested document, <c:import> , or <x:transform>
XML document can be followed by <x:param> actions for setting transformation parameters
<x:transform> Tag Stylesheet specified via the xslt attribute
String, Reader, or javax.xml.transform.Source
The result attribute specifies an instance of javax.xml.transform.Result for capturing the transformation result
If the var attribute is specified, the named variable will be assigned an instance of org.w3c.dom.Document representing the transformation result
If neither var nor result is specified, the transformation result is written to the JSP page.
<x:param> Tag <x:param name=”name” value=”value”/>
Supplies a value for the named transformation parameter
Parameter value can also be specified via body content
SQL Library EL library
Dynamic attribute values specified using the JSTL expression language (i.e., ${ expr }) <%@ taglib uri=”http://java.sun.com/jstl/sql”
prefix=”sql”>
RT libraryDynamic attribute values specified using
the JSP expressions (i.e., <%= expr %>) <%@ taglib uri=”http://java.sun.com/jstl/sql_rt”
prefix=”sql_rt”>
SQL Library Tags Database actions
<sql:query>, <sql:param>, <sql:dateParam>
<sql:update>, <sql:param>, <sql:dateParam>
<sql:transaction><sql:setDataSource>
Useful for debugging and quick one-offsHeinous violation of MVC design pattern:
DB code (i.e., raw SQL) doesn’t belong in the presentation layer!