Download presentation
Presentation is loading. Please wait.
Published byLawrence Weaver Modified over 9 years ago
1
JSTL: The JavaServer Pages Standard Tag Library Mark A. Kolb Security Broadband, Austin, TX mak@taglib.com
2
Prerequisites Servlet API JavaServer Pages Basic syntax Implementation via Servlet API Using resource bundles for I18N XML
3
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”
4
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
5
What Is the JSTL? A collection of tag libraries implementing common JSP functionality Core functions Variables, I/O, conditionalization, iteration Formatting/I18n Message bundles, numbers, dates XML operations parsing, transformations Database operations SQL
6
What Is the JSTL? An expression language for specifying custom tag attribute values Based on ECMAScript and Xpath Expression language is optional Each of the four JSTL libraries has an EL version and an RT version. EL = JSTL expression language RT = JSP request-time attribute values
7
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
8
Why JSTL? JSTL tags provide a standard implementation for typical application functionality Reusability Avoid reinventing the wheel Another mechanism for avoiding the use of JSP scripting elements EL considerably simpler than Java Strong emphasis on “variables” Two steps forward, one step back?
9
JSTL Expression Language Delimiters are “ ${ ” and “ } ” The EL can only be used for specifying attribute values in JSTL tags Multiple expressions can be combined and mixed with static text (i.e., implicit string concatenation)
10
JSTL Expression Language Individual expressions are combinations of identifiers, accessors, and operators There are also identifiers for a set of JSTL implicit objects Not the same as the JSP implicit objects (with one exception)
11
EL Identifiers Identifiers are resolved against the four JSP scopes Using 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, headerValues initParam, cookie
12
EL Accessors Properties of objects are accessed via the “.” operator user.firstName represents the value of the “firstName” property of the object referenced by the “user” identifier
13
EL Accessors Elements of a Map, List, or array are accessed via the “[]” operator For 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]
14
EL Accessors Actually, the “.” and “[]” operators are interchangeable user.firstName and user[”firstName”] are equivalent expressions
15
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
16
EL Implicit Objects The param implicit object is a map for looking up the value of a request parameter ${param[”keyword”]} is equivalent to 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
17
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 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
18
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
19
EL Operators Arithmetic operators +, -, *, / (or div ), % (or mod ) Relational operators == (or eq ), != (or ne ), (or gt ), = (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.
20
EL Operators Logical operators will short-circuit evaluation For 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 rules For example, ${a * (b + c)} overrides the normal precedence of multiplication over addition
21
Core Library EL library Dynamic attribute values specified using the JSTL expression language (i.e., ${ expr } ) RT library Dynamic attribute values specified using the JSP expressions (i.e., )
22
Core Library Tags General-purpose actions Conditional actions ,,
23
Core Library Tags Iteration actions URL actions ,
24
Tag Evaluates the value attribute and outputs the result as a string Provides equivalent functionality to JSP expressions and the action Prints the value of the default attribute if the value attribute evaluates to null Default result can also be specified via body content
25
Tag The escapeXml attribute determines whether or not characters are converted to XML entities (defaults to true ) << >> && ’' ”"
26
Tag 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
27
Tag 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 action Property value can also be specified via body content
28
Tag Removes the named variable from the indicated scope Variable scope is either page (the default), request, session, or application
29
Tag nested actions Catches any exception thrown by the nested actions Caught exception is assigned to the (optional) named variable (with page scope) If no exception is thrown, the variable is removed from page scope
30
Tag body content 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
31
Tag body content … body content Enables mutually exclusive conditionalization
32
Tag There must be at least one action Only the first whose test condition evaluates to true will have its body content processed There can be at most one action, and it must be the last action within the body The body can contain only whitespace, actions, and actions
33
ConditionalTagSupport Class JSTL provides base class for custom tag implementors javax.servlet.jsp.jstl.core.ConditionalTagSupport Utility class for implementing custom tags for conditionalizing content Custom tag works like, conditionalizing body content and optionally exposing a scoped variable This variable can then be referenced by the test attribute of subsequent and actions
34
Tag body content Iteratively processes the body content for a fixed number of times, like a for statement From begin to end, by an optional step
35
Tag body content Iteratively processes the body content for all of the items in a collection Optionally bound by begin, end, and step
36
Tag The items attribute supports all standard J2SE collection types java.util.Collection, java.util.Map java.util.Iterator, java.util.Enumeration Arrays, including arrays of primitives String objects which use embedded comma delimiters
37
Tag The variable named by the var attribute references the current item of the iteration Primitives (from an array) are wrapped For 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
38
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
39
LoopTagStatus Class The LoopTagStatus properties are defined by eight getter methods getCurrent() returns the current item getIndex() 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()
40
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 in their own custom tags
41
Tag body content 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
42
Tag URL re-writing Appends session id (if appropriate) Prepends context to relative URLs (defaulting to current context) Request parameters can be specified via body content
43
Tag Used to add request parameters to a URL Nested in the body content of a,, or tag The values of the name and value will be URL encoded when added to the URL
44
Tag Sends an HTTP redirect response Aborts processing of remainder of page Request parameters can be specified via body content
45
Tag 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 action) Request parameters can be specified via body content
46
Tag body content 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 with var attribute to build URL with request parameters, then pass variable to
47
Formatting Library EL library Dynamic attribute values specified using the JSTL expression language (i.e., ${ expr } ) RT library Dynamic attribute values specified using the JSP expressions (i.e., )
48
Formatting Library Tags Internationalization actions ,
49
Formatting Library Tags Data formatting actions
50
Tag 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)
51
Tag Supplies a single value for parametric replacement within a message Each parameter in a message requires a corresponding tag Nested within a action
52
Tag body content Specifies a localization context for nested formatting actions (e.g., ) 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
53
Other I18N Tags assigns a localization context to a variable, or assigns the default localization context for a scope sets the current locale across a JSP scope (overrides browser-based locale) JSTL also provides a configuration variable for specifying a fallback locale set the character encoding for a request so that request parameter values can be correctly decoded Compensates for browser misbehavior with respect to the Content-Type header
54
Tag Displays a formatted number, or assigns the formatted result to a variable
55
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
56
Tag Displays a formatted date and/or time, or assigns the formatted result to a variable
57
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
58
Parsing Tags parses a String into a numeric value Resulting value can be assigned to a variable or output to page parses a String into a numeric value Resulting value can be assigned to a variable or output to page Both parsing tags are locale-sensitive
59
Tag body content Specifies the timezone in which to format or parse any nested or tags The timezone value can be either a String identifying a timezone or an instance of java.util.TimeZone assigns a time zone to a variable, or assigns the default time zone
60
Tag Assigns a time zone to a variable, or assigns the default time zone for a scope
61
XML Library EL library Dynamic attribute values specified using the JSTL expression language (i.e., ${ expr } ) RT library Dynamic attribute values specified using the JSP expressions (i.e., )
62
XML Library Tags Core actions Flow control actions ,,
63
XML Library Tags Transform actions ,
64
Tag Parses an XML document via a String or Reader specified via the xml attribute Interoperable with action
65
Tag body content Parses an XML document provided as body content
66
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
67
Tag Displays data from a parsed XML document The select attribute employs a syntax based on XPath to identify the data to be displayed References variable created by Analogous to action
68
Tag Assigns data from a parsed XML document The select attribute employs a syntax based on XPath to identify the data to be displayed References variable created by Analogous to action
69
XML Flow Control Tags Three sets of flow control actions ,, Analogous to like-named JSTL core actions Conditionalization or iteration driven by XPath expression values ( select attribute), rather than EL or RT values
70
Tag Transforms an XML document specified via the xml attribute String, Reader, javax.xml.transform.Source, org.w3c.dom.Document, or implementation-specific class Transformation parameters can be supplied via nested actions
71
Tag body content Transforms an XML document provided as body content, via a nested document,, or XML document can be followed by actions for setting transformation parameters
72
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.
73
Tag Supplies a value for the named transformation parameter Parameter value can also be specified via body content
74
SQL Library EL library Dynamic attribute values specified using the JSTL expression language (i.e., ${ expr } ) RT library Dynamic attribute values specified using the JSP expressions (i.e., )
75
SQL Library Tags Database actions ,, Useful for debugging and quick one-offs Heinous violation of MVC design pattern: DB code (i.e., raw SQL) doesn’t belong in the presentation layer!
76
JSTL Resources URLs JSP home page http://java.sun.com/products/jsp Reference implementation http://jakarta.apache.org/taglibs/index.html Books “JSTL in Action” by Shawn Bayern “Core JSTL” by David Geary “JSTL: JSP Standard Tag Library Kick Start” by Jeff Heaton
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.