JSP Standard Tag Library

Uploaded on

A gentle introduction to the JSP Standard Tag Library (JSTL)

A gentle introduction to the JSP Standard Tag Library (JSTL)

More in: Education , Technology
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads


Total Views
On Slideshare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide


  • 1. JSP Standard Tag LibraryIlio Catallo – Politecnico di Milanocatallo@elet.polimi.it
  • 2. Outline¤  Server-side web languages & JSP¤  JSP Standard Tag Library¤  Learning JSTL¤  Preliminaries¤  The core library¤  The formatting & internationalization library¤  The XML library¤  References2
  • 3. Server-side web languages &JavaServer Pages3
  • 4. Server-side web languages¤  Web browsers do not care on how the web server createdthe web page¤  Web browsers can correctly interpret only HTML markups¤  Therefore, all server-side web languages have the samegoal: to produce familiar web pages¤  A widely diverse array of technologies all have the samepurpose:¤  JavaServer Pages (JSP)¤  Active Server Pages (ASP)¤  PHP: Hypertext Preprocessor (PHP)4
  • 5. JavaServer Pages (JSP)¤  JavaServer Pages is a technology that helps Javadevelopers create dynamically generated web pages¤  A JSP page is a mix of plain old HTML tags and JSP scriptingelements¤  By using JSP pages:¤  HTML developers can prepare the static part of the page¤  Java developers can then complete the business-logicportionJSP Scripting Element<b> This page was accessed at <%= new Date() %></b>!5
  • 6. 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 lastmodified date of the JSP file against the class file¤  If the JSP has changed the container will rebuild the page allover again6
  • 7. JavaServer Pages tags¤  JSP scripting elements require that developers mix Javacode with HTML. This situation leads to:¤  non-maintainable applications¤  no opportunity for code reuse¤  An alternative to scripting elements is to use JSP tags¤  JSP tags can be used as if they were ordinary HTML tags¤  Each JSP tag is associated with a Java class¤  It’s sufficient to insert the same tag on another page to reusethe same code¤  If the code changes, all the pages are automatically updated7
  • 8. Plain JSP vs. JSP tagsPlain 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 behavioris automatically propagated to all JSP pages in which thetag is used8
  • 9. JSP Standard Tag LibraryWhat is JSTL?
  • 10. JSP Standard Tag Library¤  The JSP Standard Tag Library (JSTL) is a JSP tag library whichoffers 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¤  JSTL is composed by a standard set of tags, i.e., applicationswritten with JSTL can be deployed on any JSP containersupporting JSTL¤  JSTL is a specification, not an implementation¤  Apache Standard Taglibs is one of the most famousimplementation10
  • 11. JSTL tags (1/2)¤  JSTL divides its tags in four groups and makes themavailable as separate tag librariesJSTL tag library URI (Suggested)prefixCore library http://java.sun.com/jstl/core cFormatting &Internationalization(i18n)http://java.sun.com/jstl/fmt fmtXML processing http://java.sun.com/jstl/xml xDatabase (SQL) access http://java.sun.com/jstl/sql sql11
  • 12. JSTL tags (2/2)¤  Every tag library has a URI and a prefix associated with it¤  The prefix assigned to the tag library is not mandatory, but itis usually best to follow recommendation¤  JSTL tag libraries can be imported in the JSP page bymeans of the <%@ taglib %> directive¤  Directives are pseudo-tags that have special meaning to theJSP container<@ taglib %> for the JSTL core tag library*<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>!12*Please notice that JSTL 1.2’s URIs differ from the JSTL 1.1’s ones
  • 13. Learning JSTLPreliminaries
  • 14. JSP Scopes (1/2)¤  All variables in a Java web application have twocharacteristics:¤  A name that identifies the data¤  A scope that determines which parts of the web app canaccess the data¤  Scopes let you decide:¤  How long data stay around¤  How your data should be shared among different pages inyour web app14
  • 15. JSP Scopes (2/2)¤  Page scope: data can beaccessed only within thepage that created it¤  Request scope: data can beaccessed within the samerequest¤  Application scope: data canbe accessed from any pointin the web app¤  Session scope: data are tiedto a particular user,regardless of pages andrequestsPagescope RequestscopeSessionscopeApplicationscope15
  • 16. Expression Language¤  The JSTL Expression Language (EL) is a special purposeprogramming language for embedding expressions intoweb pages¤  The Expression Language is part of the JSP specification,although it does not directly depend on the JSPspecification itself¤  EL is available to other technologies, such as JavaServerFaces (JSF)16
  • 17. Expression Language:Expressions¤  The Expression Language is responsible for handling bothexpressions and literalsExample of literal in EL<c:out value="Hi there"/>!Example of expression in EL<c:out value="${1 + 2}"/>!¤  Expressions are always in the form ${expression}¤  When an expression appears, it gets evaluated by the EL17
  • 18. Expression Language:Scoped variables (1/2)¤  The major goal of the EL is to make data access easy¤  Data of interest can be store in a specific scope or in theHTTP request¤  To this end, the EL defines a set of implicit objectsObject ContentpageScope a Map of all page-scoped variablesrequestScope a Map of all request-scoped variablesapplicationScope a Map of all application-scoped variablessessionScope a Map of all session-scoped variables18
  • 19. Expression Language:Scoped variables (2/2)¤  the Scope objects are MapS: for each scoped-variable, itsname 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, application19
  • 20. Expression Language:Request parameters (1/2)¤  JSP pages use scoped variables to manage their owndata¤  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 requestparameters¤  The JSP page receiving data has to be specified has theaction end-point in the HTML <form> tag<form> tag<form method="post" action="formHandler.jsp">!20
  • 21. Expression Language:Request parameters (2/2)¤  Two ways of pointing to the request parameters:¤  ${param.varName} returns the String value of the varNameparameter (or null if it is not found)¤  ${paramValues.varName} returns the String[] containingall values of the varName parameter (or null if it is notfound)¤  paramValues is particularly useful if a request parameterhas multiple values (e.g., checkboxes)Displaying a request parameter<p>Your name is <c:out value="${param.username}"/>.</p>!21
  • 22. Expression Language:Accessing data (1/2)¤  Sometimes JSP pages need to manage scoped datacoming from the Java back-end¤  JSTL makes JavaBeans and other data types belongingto the Java Collections Framework extremely easy toaccess¤  Ordered collections (e.g., Lists) can be accessed bymeans of the subscript operator¤  Unordered collections (e.g., Maps) can be accessed by usingeither the subscript operator or the dot notation22
  • 23. Expression Language:Accessing data (2/2)Example of scoped data stored by the back-end (e.g., a servlet)public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {List l = new ArrayList<String>();l.add("foo");l.add("bar");l.add("smith");request.setAttribute("strings", l);}23Accessing back-end data from the JSP page<c:out value="${requestScope.strings[1]}" />
  • 24. Expression Language:Automatic type conversion¤  The page author is not responsible for convertingvariables into appropriate objects or primitives¤  JSTL defines a set of conversion rules calledcoercion rules¤  Conversions are done automatically by the implementation¤  Example: <c:out> will always print a String¤  If the scoped variable is not a String, JSTL will try to convertthe object automatically¤  If coercion is not possible, an exception will be thrown24
  • 25. Learning JSTLThe core tag library
  • 26. 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 farthe most used in any JSP page26
  • 27. Accessing and modifying data:<c:out>¤  The <c:out> tag lets you print out the results of anexpressionPrinting the value of a scoped variable<c:out value="${username}" default="Guest"/>!Attribute Description Required Defaultvalue the EL expression to compute Yes Nonedefault The expression to compute if value fails No Use bodyescapeXml Whether to escape characters (e.g., & as&amp;)No true27
  • 28. Accessing and modifying data:<c:set> (1/2)¤  The <c:set> tag lets you create scoped variablesSaving a scoped variable in the session scope<c:set var="four" scope="session" value="${3 + 1}"/>!Attribute Description Required Defaultvalue the EL expression to compute No Use bodyvar The name of the scoped variable to save Yes Nonescope the scope of the variable to save No page**possible values are: page, request, session and application28
  • 29. Accessing and modifying data:<c:set> (2/2)¤  JSP lets every tag have access to the output of its body¤  When tags appear inside another tag, the parent tagcollects the output from its body and then decides whatto do with itNested tags examples<c:set var="eight">!!<c:out value="${4 * 2}"/>!</c:set>!The page-scopedvariable eight is setto the result of<c:out> (8)29
  • 30. Accessing and modifying data:<c:remove>¤  The <c:remove> tag removes a variable from a givenscope30Attribute Description Required Defaultvar The name of the scoped variable to delete Yes Nonescope the scope of the variable to delete No AnyRemoving 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 scopesuntil it finds a variable named after the var attribute
  • 31. Making decisions: <c:if>¤  The <c:if> can be used in case of simple, mutualexclusive conditionsAttribute Description Required Defaulttest Condition to evaluate, if true process thebody; if false, ignore the bodyYes Nonevar the name of the attribute to expose the endresult of the test expressionYes Nonescope Scope of the variable in the var attribute No pagePrinting Dr. only if the the user has a doctorate<c:if test="${user.education == doctorate}">Dr.</c:if>!<c:out value="${user.name}"/>!31
  • 32. 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, mutualexclusive conditionsAttribute Description Required Defaulttest Condition to evaluate if no sibling<c:when> tag has already succeededYes NonePrinting 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>!32<c:when> tag attributes
  • 33. Making decisions: operatorsOperator 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 disjunctionBinary operatorsOperator Descriptionempty Check if avariable exists! (not) Logical negationUnary operators33
  • 34. Looping over data: <c:forEach>¤  The <c:forEach> tag lets you loop over nearly anysensible collection of items the EL returnsAttribute Description Required Defaultitems Collection over which to iterate No Nonevar Name of the variable to expose the currentitemNo NonePrinting each book title in the books collection<c:forEach items="${books}" var="book">!!<c:out value="${book.title}"/>!</c:forEach>!34
  • 35. Looping over data:<c:forTokens> (1/2)¤  The <c:forTokens> can be used to iterate over acollection of tokens (i.e., a set of discrete strings within alarger string)Attribute Description Required Defaultitems Input string over which to iterate Yes Nonedelims Delimiter characters that separate tokens Yes Nonevar Name of the attribute to expose the currenttokenNo None35
  • 36. Looping over data:<c:forTokens> (2/2)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=“,”>36
  • 37. Looping over data:Advanced iterationsLooping 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>37
  • 38. Looping over data:Loop status (1/2)¤  The varStatus attribute can be used to exposeinformation about the state of the iteration¤  varStatus=“s” defines a scoped variable that includesproperties for determining information about the currentloop38Property Type Descriptionindex number The index of the current item in thecollectioncount number The number of iterations executed so far,starting from 1first boolean Whether the current iteration is the firstlast boolean Whether the current iteration is the last
  • 39. Looping over data:Loop status (2/2)Highlighting the first four rows in the table<table>!<c:forEach var="book" items="${books}" varStatus="status"!! begin="0" end="9">!!<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>!39
  • 40. Error handling:<c:catch>¤  the <c:catch> tag ignores all the errors occurring in itsbody40Attribute Description Required Defaultvar Variable to store information about theerrorNo NoneMultiplying by 2 the favnumber request parameter, 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>
  • 41. Managing URLs:<c:url>, <c:param> (1/2)¤  the cooperating tags <c:url> and <c:param> let youconstruct a link that passes a request parameter to apage41Attribute Description Required Defaultvalue Base URL to construct Yes Nonevar Name of the attribute to store the final URL No Nonescope Scope of the attribute to store the final URL No pagecontext / followed by the name of a local webapplicationNo currentcontext<c:url> tag attributes
  • 42. Managing URLs:<c:url>, <c:param> (2/2)Query string construction starting from the base URL buy.jsp<a href="<c:url value="buy.jsp">!! <c:param name="stock" value="IBM"/>!! </c:url>">Buy IBMs stock</a>42Attribute Description Required Defaultname Parameter name Yes Nonevalue Parameter value No Usebody<c:param> tag attributes
  • 43. Managing URLs:Context-relative URLs¤  A single web server might run many different webapplications at the same time¤  Web applications are sometimes called contexts¤  URLs starting with / may have different meanings within thesame page¤  <a href="/outline.html"> is pointing to the root directory ofthe web server¤  <a href="<c:url value="/outline.html"/>"> is pointing tothe root of the web application¤  The <c:url> tag’s context attribute can be used to createa URL to a page in another web application in the sameweb server43
  • 44. Managing URLs:Why to use <c:url>¤  Two good reasons to use <c:url>:¤  Session preservation: in case the session mechanism is basedon URL rewriting rather than cookies, <c:url> takes care ofmaintaining the jsessionid parameter in the query string¤  Adjusting relative URLs: <c:url> makes sure that if a givenURL begins with /, it will be mapped to the root directory ofthe web application, instead of the root of the entire webserver44
  • 45. Managing URLs:<c:import>¤  The <c:import> tag is used to import the content of aURL-based resource¤  JSTL version of the standard JSP tag <jsp:include>45Attribute Description Required Defaulturl URL to retrieve and import into the page Yes Nonevar Name of the attribute to store the final URL No Nonescope Scope of the attribute to store the final URL No pagecontext / followed by the name of a local webapplicationNo currentcontextImporting the external page outline.html<c:import url="outline.html"/>!
  • 46. Learning JSTLThe formatting & internationalization tag library
  • 47. The formatting & i18n tag library:Overview (1/2)¤  If the web application targets different users in differentcountries, it is important to present appropriate informationaccording 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 theweb application.47
  • 48. The formatting & i18n tag library:Overview (2/2)¤  The formatting & internationalization tag library includestags 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 effortrequired to internationalize the web application48
  • 49. Reading and printing numbers:<fmt:parseNumber> (1/2)¤  The <fmt:parseNumber> tag lets you interpretcomplicated strings as numbers49Attribute Description Required Defaultvalue The string to parse as number No Usebodyvar Variable to store the formatted number No Nonetype How to parse the number (possible values:number, currency and percent)No numberscope Scope in which to store the formattednumberNo pageintegerOnly Whether to discard any fractional digits No falseparseLocale Locale to use instead of default No Local
  • 50. Reading and printing numbers:<fmt:parseNumber> (2/2)Parsing the request parameter favnumber as a number<fmt:parseNumber var="fav" value="${param.favnumber}"/>!50¤  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¤  The parseLocale attribute is useful when dealing with adata source from another country¤  In such a case you want to parse a number using the datasource’s locale
  • 51. Reading and printing numbers:<fmt:formatNumber> (1/2)¤  the <fmt:formatNumber> tag prints out a formattednumber accordingly to user’s locale51Attribute Description Required Defaultvalue The numeric value to format No Use bodytype Whether to print regular numbers,currencies or percentages (possible values:number, currency and percent)No numbervar Variable to store the formatted number No Nonescope Scope in which to store the formattednumberNo pagecurrencyCode Currency code as in ISO-4217 (e.g., USD) No NonegroupingUsed Whether to group digits, as in 1,234,567 No true
  • 52. Reading and printing numbers:<fmt:formatNumber> (2/2)The numeric value is formatted according to user’s locale<fmt:formatNumber type="currency" value="78.74901"/>52The 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
  • 53. Reading and printing dates:<fmt:parseDate> (1/2)¤  The <fmt:parseDate> tag reads a string coming from anexternal source (e.g., a database) and treats it as a date53Attribute Description Required Defaultvalue The date string to parse No Use bodytype How to parse the date (possible values:time, date, or both)No datevar Variable to store the formatted date (as anumber)No Nonescope Scope in which to store the parsed date No pageparseLocale Locale to use instead of the default No LocaltimeZone Time zone to apply to the parsed date No Local
  • 54. Reading and printing dates:<fmt:parseDate> (2/2)Parsing a valid date by aggregating three request parameters<fmt:parseDate var="date" parseLocale="en_US" !value="${param.month} ${param.day}, ${param.year}"/>!54¤  date is a scoped variable of type java.util.Date¤  The value attribute must point to a string representing avalid date in the specified locale¤  To force JSTL to parse the string using the U.S. English locale’srules, rather than the browser’s current locale, theparseLocale attribute is set to en_US
  • 55. Reading and printing dates:<fmt:formatDate> (1/3)¤  the <fmt:formatDate> tag prints out formatted datesand times accordingly to the user’s locale55Attribute Description Required Defaultvalue Date to print Yes Nonetype Whether to print dates, times or both(possible value: date, time and both)No datevar Variable to store the formatted number No Nonescope Scope in which to store the formattednumberNo pagetimeZone Time zone to use when formatting the date No Local
  • 56. Reading and printing dates:<fmt:formatDate> (2/3)¤  Please notice that the value attribute must point to avariable of type java.util.Date¤  The standard JSP tag <jsp:useBean> can be used tocreate scoped variable of a specific class¤  If not specified, the default scope is page56Creating a page-scoped variable of type java.util.Date<jsp:useBean id="now" class="java.util.Date" />!Printing out the current date and time<fmt:formatDate value="${now}" type="both"/>!
  • 57. Reading and printing dates:<fmt:formatDate> (3/3)¤  A time zone is a region on Earth that has a uniform standardtime for legal, commercial, and social purposes¤  Example: Greenwich Mean Time¤  By default, the <fmt:formatDate> tag does its best to figureout a sensible time zone¤  If no time zone is specified, the page will use the time zone ofthe JSP container¤  The timeZone attribute accepts a number of different kindsof identifiers for time zones¤  Example: EST for Eastern Time, CST for Central Time, and PST forPacific Time57
  • 58. Working with different languages:Resource bundles¤  Every message that may be displayed in the application is stored ina separate file, called the resource bundle¤  A resource bundle maps a generic key (e.g., welcome), to a singletranslated value (e.g., Hello)¤  The web app can be localized by a adding resource bundle foreach supported locale¤  The same set of keys is associated with different, locale-specificmessages¤  Example: in the resource bundle for the Italian locale, the welcome keycan be associated with Ciao¤  We will refer to the set of localized resource bundles for the sameweb app as to the resource bundle family for the web app58
  • 59. Working with different languages:<fmt:setBundle>¤  The <fmt:setBundle>* tag defines the default resourcebundle family for a given scope59Attribute Description Required Defaultbasename Name of the resource bundle family to use Yes Nonevar Variable to store the bundle in use No Nonescope Scope in which to store the bundle in use No pageSpecifying the basename for the resource bundle family<fmt:setBundle basename=”resources.application" />!*See also <fmt:bundle> for locally defining the resource bundlefamily
  • 60. Working with different languages:<fmt:message>¤  The <fmt:message> tag accepts a key and looks up itstranslated value in a resource bundle60Attribute Description Required Defaultkey Internationalized key to use No Use bodybundle scoped variable containing a specificresource bundle to use in place of thedefault oneNo Localvar Variable to store the localized message No Nonescope Scope in which to store the localizedmessageNo pagePrinting out the value for the welcome key in the current locale<fmt:message key="welcome"/>!
  • 61. Working with different languages:<fmt:param>¤  The <fmt:param> lets you instantiate a parametricmessage¤  Example of parametric message: welcome=Hi, {0}61Attribute Description Required Defaultvalue Parameter to add No Use bodyWelcoming the user with his/her name<fmt:message key="welcome">!<fmt:param value="${user.name}" />!</fmt:message>!
  • 62. Learning JSTLThe XML tag library
  • 63. The XML tag library:Overview (1/2)¤  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 XMLdocument¤  Looping over parts of an XML document63
  • 64. The XML tag library:Overview (2/2)¤  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 forselecting nodes from an XML document64
  • 65. The XML Path Language:Document representation42 CHAPTER 7Selecting XML fragments7.2 XPath’s basic syntaxFigure 7.1The tree structure of a sample HTMLdocument. When an element like<h1> occurs inside <body>, youcan think of it as a child of that<body> element.¤  In XPath, each XML document isrepresented as a tree¤  Each element in the tree can beuniquely identified by a path,e.g., /html/body/p/b¤  Any descendent of an elementcan be searched through the treeby using two adjacentbackslashes, e.g., //b65
  • 66. The XML Path Language:Predicates (1/2)¤  XPath lets you identify elementsusing attributes¤  Example: the preferred customerscan be identified by the followingXPath expression¤  //customer[@status=“preferred”]¤  XPath expressions involving the []operator are called predicates66customer.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>
  • 67. The XML Path Language:Predicates (2/2)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 filterelements by the order in which theyappear¤  Example: The second customer canbe retrieved by using the followingXPath expression:¤  /customers/customer[2]¤  Please notice that in XPath numericpredicates start with 167
  • 68. The XML Path Language:Variables (1/2)¤  XPath supports variables, which are evaluated andreplaced with their actual values¤  Variable in XPath are qualified names, introduced with adollar sign ($)¤  XML defines a qualified name as a tag name with anamespace prefix attached to it, e.g., <periodic:table>68
  • 69. The XML Path Language:Variables (2/2)¤  For each JSTL’s implicit object there exists acorrespondent XML’s namespace¤  Example: $requestScope:varName refers to the scoped-variable ${requestScope.varName}¤  Just as in JSTL, if no namespace is specified, the followingorder is used:¤  page, request, session, application69
  • 70. Parsing XML documents: <x:parse>¤  The <x:parse> tag lets you acquire and parse an XMLdocument70Attribute Description Required Defaultxml The raw XML text to parse No Use bodyvar Variable to store the parsed document Yes Nonescope Scope in which to store the parseddocumentNo pageAcquiring and parsing the XML document mydocument.xml<c:import var="raw" url="/mydocument.xml"/> !<x:parse xml=”${raw}" var="doc"/>!
  • 71. Printing parts of XML documents:<x:out> (1/2)¤  The <x:out> tag evaluates and prints out the string valueof an XPath expression71Attribute Description Required Defaultselect XPath expression Yes Nonescope Variable to store the parsed document Yes NoneescapeXml Whether to escape characters (e.g., & as&amp;)No true¤  Please remember that the select attribute points to anXPath expression, not an EL expression¤  Expressions are in the form expression rather than${expression}
  • 72. Printing parts of XML documents:<x:out> (2/2)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"/>!72¤  The XPath expression causes the<x:out> tag to retrieve all nodesnamed <c>¤  The tag prints out the text C becausethat is the string value of the only <c>node present in the XML snippet
  • 73. Printing parts of XML documents:<x:set> (1/2)¤  the <x:set> tag stores the result of an XPath expressionin a variable73Attribute Description Required Defaultselect XPath expression Yes Nonevar Variable to store the result of the XPathexpressionYes Nonescope Scope in which to store the result of theXPath expressionNo page
  • 74. Printing parts of XML documents:<x:set> (2/2)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"/>!74¤  ${b} contains a subset of the originaldocument¤  <x:set> may be useful when part ofthe data needs to be shared in thesessionPart of thedocument selected
  • 75. Making decisions: <x:if> (1/2)¤  The <x:if> tag lets you make a decision based on theinformation contained in an XML document75Attribute Description Required Defaultselect XPath expression to evaluate, if true processthe body; if false, ignore the bodyYes Nonevar the name of the attribute to expose the endresult of the test expressionYes Nonescope Scope of the variable in the var attribute No page
  • 76. Making decisions: <x:if> (2/2)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 repeat customers<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>!76¤  The greeting is shown only if the userhas placed at least one order in thepast¤  In the example, we suppose theexistence of a page-scoped variablenamed customerId
  • 77. Making decisions: <x:choose>,<x:when>, <x:otherwise> (1/2)¤  The three cooperating tags <x:choose>, <x:when> and<x:otherwise> can be used for evaluating XML-basedconditions77Attribute Description Required Defaultselect XPath expression to evaluate if no sibling<x:when> tag has already succeededYes None<x:when> tag attributes
  • 78. Making decisions: <x:choose>,<x:when>, <x:otherwise> (2/2)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>!78
  • 79. Looping over a document:<x:forEach> (1/3)¤  The <x:forEach> tag lets you iterate over an XMLdocument79Attribute Description Required Defaultselect XPath expression over whose result to iterate Yes Nonevar Name of the variable to expose the currentnodeNo None
  • 80. Looping over a document:<x:forEach> (2/3)¤  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 ofcurrent directory in a file system¤  During an <x:forEach> loop, the current node in theiteration becomes the context node¤  Therefore, each XPath expression defined inside the<x:forEach> tag’s body will use the current node as thecontext node80
  • 81. Looping over a document:<x:forEach> (3/3)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>!81¤  The $doc//customer matcheseach <customer> tag in thedocument¤  Within each loop, the <name> tagis printed out under the contextnode
  • 82. Topics not covered¤  Implicit objects other than scopes (e.g., cookie)¤  XML transformation tags¤  The SQL tag library82
  • 83. References¤  JSTL In Action, S. Bayern , Manning Publications Co.¤  JSTL: Practical Guide for JSP Programmers, S. Spielman,Morgan Kaufmann Publishers¤  Unified Expression Language, Wikipedia, The FreeEncyclopediahttp://en.wikipedia.org/w/index.php?title=Unified_Expression_Language&oldid=533174739¤  Time zone, Wikipedia, The Free Encyclopediahttp://en.wikipedia.org/w/index.php?title=Time_zone&oldid=53884441583