SlideShare ist ein Scribd-Unternehmen logo
1 von 13
Downloaden Sie, um offline zu lesen
Object                      Description                          Operator                          Description


         JSTL Quick Reference                                   headerValues         Map of request header name to a String
                                                                                     array of values
                                                                                                                                     ! (not)              True if operand is false; false, otherwise.

                 Copyright 2003 Bill Siggelkow
                                                                cookie               Map of cookie name to a Cookie object           Other Operators
                                                                initParam            Map of context initialization parameter              Operator                          Description
                                                                                     name to a String parameter value (set in
                 Expressions (EL)                                                    web.xml)                                        empty                True if the operand is null, an empty String,
                                                                                                                                                          empty array, empty Map, or empty List; false,
                                                                                                                                                          otherwise.
                                                                Arithmetic Operators
In Attribute Values                                                                                                                  ()                   Paranthesis for changing operator
• <a:tag value="${expr}"/>                                          Operator                        Description                                           precedence.
• <a:tag value="me${expr} ${expr}"/>
                                                                +                 Addition
                                                                                                                                     EL Functions (JSTL 1.1)
Bean Property Access                                            -                 Subtraction                                         Note: All functions treat null Strings as empty Strings.
bean.name
bean["name"]                                                    *                 Multiplication                                     <%@ taglib prefix="fn"
                                                                                                                                       uri="http://java.sun.com/jstl/functions" %>

Indexed Property Access                                         / (div)           Division
                                                                                                                                     Usage: ${fn:function(arg0, ...)}
bean.property[index]                                            % (mod)           Remainder (modulus)

Map Property Access                                                                                                                  <p>We offer ${fn:length(flavorSet)} ice cream
                                                                                                                                     flavors.</p>
bean.property["key"]                                            Relational Operators
                                                                    Operator                        Description
Implicit Objects (maps)                                                                                                                        Function                         Description

     Object                       Description                   == (eq)           Equality
                                                                                                                                     fn:contains                  Returns true if substring is contained
                                                                                                                                                                  in string; false, otherwise.
pageContext       JSP Page Context object                       != (ne)           Inequality                                         (string, substring) :
                                                                                                                                     boolean
pageScope         Page-scoped variables (valid only on a        < (lt)            Less than
                  given JSP page)                                                                                                    fn:containsIgnoreCase Returns true if substring is contained
                                                                > (gt)            Greater than                                                             in string regardless of case; false,
                                                                                                                                     (string, substring) : otherwise.
requestScope      Request-scoped variables (valid for a given                                                                        boolean
                  request)                                      <= (le)           Less than or equal to
                                                                                                                                     fn:endsWith                  Returns true if string ends with the
sessionScope      Session-scoped variables (valid for the       >= (ge)           Greater than or equal to                                                        specified suffix; false, otherwise.
                  user's session)                                                                                                    (string, suffix) :
                                                                <= (le)           Less than or equal to                              boolean
applicationScope Application-scoped variables (valid for a
                  given application context)                                                                                         fn:escapeXml                 Escapes characters (e.g changing “<”
                                                                                                                                                                  to “&lt;”) that could be interpreted as
                                                                Logical Operators                                                    (string) : String            XML (including HTML) markup.
param             Map of request parameter name to a String         Operator                        Description
                  parameter value
                                                                                                                                     fn:indexOf                   Returns an integer representing the 0-
                                                                && (and)          True if both operands are true; false,                                          based index within string of the first
paramValues       Map of request parameter name to a String                                                                          (string, substring) : int    occurrence of substring. If substring is
                                                                                  otherwise.
                  array of parameter values                                                                                                                       empty, 0 is returned.
                                                                || (or)           True if either or both operands are true; false,
header            Map of request header name to a header
                                                                                  otherwise.
                  String value
Function                       Description                                                                                  <c:remove var="dogAge" scope="page"/>
                                                                                         Core Tag Library
fn:join                    Joins all elements of the string array
                           into a single string. Separator                                                                              Attribute           Description            Rqd   Default
(string[], separator) :    separates each element in the
String                     resulting string. If separator is an      <%@ taglib prefix="c"                                            var           Name of variable to delete     Yes   None
                           empty string, the elements are joined       uri="http://java.sun.com/jstl/core" %>
                           without a separator.                                                                                       scope         Scope of variable              No    All
                                                                     General-Purpose Actions                                                                                             scopes
fn:length                  If a collection or array is passed, the
                           size of the collection or array is
                                                                     Actions for rendering data, creating and
(collection or string) :                                             modifying scoped variables, and catching                         <c:catch> - traps all exceptions or errors from the
                           returned; If a string is passed, the
int                        number of characters in the string is     exceptions.                                                      enclosed body.
                           returned.
                                                                                                                                      <c:catch var="err">
                                                                     <c:out> - renders data to the page                                 <c:import value="http://java.sun.com"/>
fn:replace               Replaces in inputString, every
                                                                                                                                      </c:catch>
                         occurrence of beforeString with             <h2>Welcome, <c:out value="${user.name}"                         <c:if test="${not empty err}">
(inputString,            afterString. An empty string is
beforeSubstring,                                                     default="Guest"/></h2>                                             Could not connect to Java web site.
                         returned if either inputString or                                                                            </c:if>
afterSubstring) : String beforeString is empty. If afterString is
                         empty, all occurences of the
                         beforeString are removed.                      Attribute               Description           Rqd   Default
                                                                                                                                        Attribute           Description            Rqd   Default
fn:split                   Splits string into a string array using   value             Data to output                 Yes   None
                                                                                                                                      var           Name of variable to hold the   No    None
                           the given set of delimiter characters.
(string, delimiters) :                                               default           Fallback data to output if     No    Body                    thrown exception, if any.
                           The delimiter characters are not
String[]                                                                               value is empty                                               Variable will be of type
                           included in any returned tokens.
                                                                                                                                                    java.lang.Throwable.
fn:startsWith              Returns true if string starts with the    escapeXml         true      to escape special    No    true
                           specified prefix; false, otherwise.                         characters
(string, prefix) :         Returns true if prefix is empty.                                                                           Conditional Actions
boolean                                                                                                                               Actions for processing markup based on logical
                                                                                                                                      conditions.
fn:substring               Returns a subset of string using the
                           zero-based indices – inclusive of the     <c:set> - saves data to a scoped variable
(string, beginIndex,       begin index, but exclusive of the end                                                                      <c:if> - processes the body if test is true
endIndex) : String         index.                                    <c:set var="dogAge" value="${age div 7}"/>
                                                                     You are <c:out value="${dogAge}"/> in dog                        <c:if test="${user.age ge 40}">
fn:substringAfter          Returns the subset of string following    years.                                                             You are over the hill.
                           the given substring.                                                                                       </c:if>
(string, substring) :
String                                                                  Attribute               Description           Rqd   Default
                                                                                                                                        Attribute           Description            Rqd   Default
fn:substringBefore         Returns the subset of string that         value             Data to save                   No    Body
                           procedes the given substring.                                                                              test          Condition to evaluate          Yes   None
(string, substring) :
String                                                               target            Name of variable to modify     No    None
                                                                                                                                      var           Name of variable to store      No    None
fn:toLowerCase             Converts all characters of a string to    property          Property of target to modify   No    None                    test condition's result
                           lowercase.
(string) : String                                                                                                                     scope         Scope of variable              No    page
                                                                     var               Name of variable to store      No    None
                                                                                       data
fn:toUpperCase             Converts all characters of a string to
                           uppercase.
(string) : String                                                    scope             Scope of variable              No    page
                                                                                                                                      <c:choose> - multiple conditions – processes the
fn:trim                    Removes whitespace from both ends
                                                                                                                                      body of the first enclosed when tag where the test
                           of a string.                                                                                               condition is true. If none match then the body of the
(string) : String                                                    <c:remove> - deletes a scoped variable
                                                                                                                                      otherwise tag (if present) is processed.
                                                                                                                                      <c:choose>
<c:when test="${a boolean expr}">                                 Attribute             Description                  Rqd      Default     Attribute               Description               Rqd    Default
      // do something
  </c:when>
                                                                  varStatus       Name of variable to hold the          No      None       var               Name of variable to hold      No         None
   <c:when test="${another boolean expr}">                                        loop status with the following                                             the current token. This
    // do something else                                                          properties:                                                                variable has only nested
  </c:when>                                                                                                                                                  visibility.
  <c:otherwise>                                                                   •   index – position of the
    // do this when nothing else is true                                              current item                                         items             String of tokens to loop      Yes        None
  </c:otherwise>                                                                                                                                             over.
</c:choose>                                                                       •   count – number of times
                                                                                      through the loop (starting
                                                                                      with 1)                                              delims            Set of characters that        Yes        None
The choose tag accepts no attributes and can only                                                                                                            separate the tokens (e.g.
contain when tag(s) and an optional otherwise tag.                                •   first – boolean                                                        delims=”,;” will tokenize a
                                                                                      indicator if this is the first                                         string separated by
                                                                                      iteration                                                              commas or semi-colons).
<c:when> - processes the body if test is true and no
other previous <c:when> tags evaluated to true.                                   •   last – boolean indicator
                                                                                      if this is the last iteration
                                                                                                                                           URL Related Actions
   Attribute            Description             Rqd   Default
                                                                                                                                           Actions for importing content from URLs, building
test           Condition to evaluate            Yes   None
                                                                                                                                           URLs, and redirecting.
                                                                  <c:forEach> - repeats the nested body content
                                                                  over a collection or for a fixed number of times.                        <c:import> - imports the content of a URL-based
                                                                                                                                           resource. Action may include nested <c:param>
<c:otherwise> - processes the body if no other                    <c:forEach items="${user.languages}"
                                                                                                                                           tags to specify the query string (unless the
previous <c:when> condition matched. This tag                                  var="lang" varStatus="status">
                                                                    <c:if test="${status.first}">                                          varReader attribute is specified).
accepts no attributes and, if present, must be the last               You speak these languages:<br><ul>
tag in the <c:choose> body.                                         </c:if>                                                                <c:import url="includes/header.jsp">
                                                                    <li><c:out value="${lang}"/></li>                                        <c:param name="title">Hello World</c:param>
Iterator Actions                                                    <c:if test="${status.last}"></ul></c:if>                               </c:import>
Actions that loop over collections, for a fixed number            </c:forEach>
of times, or over a set of string tokens. These
actions share the following attributes for iterating over                                                                                        Attribute             Description               Rqd      Default
                                                                    Attribute            Description               Rqd       Default
a subset of elements.
                                                                                                                                           url                URL of the resource to             Yes     None
                                                                  var            Name of variable to hold          No        None                             import.
   Attribute            Description             Rqd   Default                    the current item. This
                                                                                 variable has only nested
                                                                                 visibility.                                               context            Name of the context                No      Current
begin          Zero-based index of first item   No    0                                                                                                       (beginning with a /) of some               context
               to process, inclusive.                                                                                                                         other local web application to
                                                                  items          Collection, iterator, map, or No            None                             import the resource from.
                                                                                 array to loop over.
end            Zero-based index of last item    No    Last item
               to process, inclusive.                                                                                                      var                Name of the variable to hold       No      None
                                                                                                                                                              the imported content as a
step           Process every stepth element No        1           <c:forTokens> - repeats the nested body                                                     String.
               (e.g 2 = every second                              content for each token of a delimited string.
               element).                                                                                                                   scope              Scope of the var variable          No      page
                                                                  <c:set var="users">Fred,Joe,Mary<c:set>
                                                                  <c:forTokens var="name" items="${users}"                                 varReader          Name of the variable to hold       No      None
                                                                               delims=",">                                                                    the imported content as a
                                                                    <c:out value="${name}"/><br/>                                                             Reader. This variable has
                                                                  </c:forTokens>                                                                              only nested visibility so that
                                                                                                                                                              the reader will always be
                                                                                                                                                              closed.
                                                                    Attribute            Description               Rqd       Default
<c:url> - builds a URL with the proper rewriting rules        <c:redirect> - sends the client a response to
applied (only relative URLs are rewritten). Action            redirect to the specified URL. This action will
                                                              abort processing of the current page. Action may
                                                                                                                                            Formatting Tag Library
may include nested <c:param> tags to specify
the query string.                                             include nested <c:param> tags to specify the
                                                              query string.                                                    <%@ taglib prefix="fmt"
<c:url="editProfile.do" var="profileLnk">
                                                                                                                                 uri="http://java.sun.com/jstl/fmt" %>
  <c:param name="id" value="${user.id}"/>                     <c:if test="${empty user}">
</c:url>                                                        <c:redirect url="login.do"/>
<a href='<c:out value="${profileLnk}"/>'>                     </c:if>                                                          Internationalization (I18N) Actions
  Edit Profile
</a>
                                                                                                                               Actions that establish localization (l10n) contexts,
                                                                                                                               specify resource bundles, and format messages.
                                                                    Attribute           Description            Rqd   Default

   Attribute           Description            Rqd   Default   url               URL of the resource to         Yes   None
                                                                                                                               <fmt:setLocale> - Sets the default locale for the
                                                                                redirect to.                                   specified scope. This will override the browser-
value          URL to be processed.           Yes   None                                                                       based locale.
                                                              context           Name of the context            No    Current
context        Name of the context            No    Current                     (beginning with a /) of some         context   <fmt:setLocale scope="session"
               (beginning with a /) of some         context                     other local web application.                                  value="fr_CA">
               other local web application.

var            Name of the variable to hold   No    None                                                                        Attribute              Description             Rqd   Default
               the URL as a String.                           <c:param> - adds request parameters to a URL.
                                                              This action can only be nested within                             value        String representation of a        Yes   None
scope          Scope of the var variable      No    page      <c:import>, <c:url>, or                                                        locale (e.g. en_US) or an
                                                                                                                                             actual java.util.Locale object.
                                                              <c:redirect>.
                                                                                                                                variant      Locale variant (as a String) to No      None
                                                                    Attribute           Description            Rqd   Default                 specify in conjunction with the
                                                                                                                                             locale (language and country).
                                                              name              Name of the query string       Yes   None
                                                                                parameter.                                      scope        Scope to set the default locale No      page
                                                                                                                                             for.
                                                              value             Value of the parameter. If not No    Body
                                                                                specified, value is taken from
                                                                                the tag body.
                                                                                                                               <fmt:bundle> - Sets the localization context, based
                                                                                                                               on the specified resource bundle, to be used within
                                                                                                                               the body content of this tag.
                                                                                                                               <fmt:bundle basename="resources"
                                                                                                                                           prefix="label.">
                                                                                                                                 <fmt:message key="userId"/>
                                                                                                                               <fmt:bundle>


                                                                                                                                Attribute              Description             Rqd   Default

                                                                                                                                basename Fully-qualified name of the     Yes         None
                                                                                                                                         base bundle without a file type
                                                                                                                                         (such as “.properties”).

                                                                                                                                prefix       String prefix to be prepended No        None
                                                                                                                                             to the value of the message
                                                                                                                                             key. Note that the prefix
                                                                                                                                             must include all characters –
                                                                                                                                             a separator character (e.g. “.”)
                                                                                                                                             is not assumed.
<fmt:message key="fieldRequired">
<fmt:setBundle> - Creates and stores in a scoped                         <fmt:param value="User ID"/>
                                                                       </fmt:message>                                                   <fmt:setTimeZone> - Sets the specified time zone
variable, a localization context based on the specified
                                                                                                                                        in a named scoped variable or using the default time
resource bundle.
                                                                                                                                        zone name if var is not specified.
<fmt:setBundle                                                          Attribute             Description             Rqd    Default
     basename="ApplicationResources”                                                                                                    <fmt:setTimeZone var="mtnTime"
          var="strutsMessages"                                                                                                               value="America/Denver"/>
                                                                       value        Value used for parametric         No     Body       Mountain Time: <fmt:formatDate
        scope="application"/>
                                                                                    message format substitution.                          type="time" timeStyle="short"
                                                                                                                                          value="${now}" timeZone="${mtnTime}"/>
      Attribute                Description            Rqd    Default

basename              Fully-qualified name of the     Yes   None       <fmt:requestEncoding> - Instructs JSTL to use
                                                                                                                                         Attribute              Description          Rq    Default
                      base bundle without a file type                  a specific character encoding (see                                                                            d
                      (such as “.properties”).                         http://www.iana.org/assignments/character-sets)
                                                                       to decode request parameters. Omitting a value                   value        String representation of a time Yes None
var                   Name of the variable to hold   No     Default    indicates to use automatic detection of the proper                            zone (such as
                      the localization context.             l10n
                                                            context
                                                                       encoding.                                                                     “America/New_York”, “GMT-
                                                                                                                                                     5”, or “EST”) or an actual
                                                            (see                                                                                     java.util.TimeZone object.
                                                            “Configu   <fmt:requestEncoding key="ISO-8859-1"/>
                                                            ration”)
                                                                                                                                        var          Name of the variable to store   No   Default
                                                                        Attribute             Description             Rqd    Default                 the time zone.                       time zone
scope                 Scope of the var variable      No     page                                                                                                                          (see
                                                                                                                                                                                          “Configur
                                                                       value        Character encoding (e.g. “UTF-    No    Automatic                                                     ation”)
                                                                                    8”) to use.
<fmt:message> - Looks up a localized message in a
resource bundle. This tag can contain nested                                                                                            scope        Scope of the var variable       No   page
<fmt:param> tags to specify message format                             Formatting Actions
substitution values. The resultant message is printed                  Actions that format and parse numbers,
or stored in a scoped variable.                                        currencies, percentages, dates and times.                        <fmt:formatNumber> - Formats a number,
<fmt:message key="title"
                                                                                                                                        currency, or percentage in a locale-sensitive manner.
     bundle="${strutsResources}"/>                                     <fmt:timeZone> - Sets the specified time zone                    The formatted value is printed or stored in a scoped
                                                                       to be applied to the nested body content. The                    variable.
                                                                       following example demonstrates that the time
 Attribute                  Description              Rqd    Default                                                                     <fmt:formatNumber type="currency"
                                                                       zone by this action has only nested visibility.                       value="3.977">
key               Message key to be looked up.       No     Body       <jsp:useBean id="now"
                                                                            class="java.util.Date"/>
                                                                       <fmt:timeZone                                                          Attribute            Description       Rqd Default
bundle            Localization context (set by prio No      Default
                  configuration, <fmt:bundle>, or           l10n            value="America/Los_Angeles">
                  <fmt:setBundle>, which specifies          context      Pacific Time:<fmt:formatDate                                   value               Numeric value to         No    Body
                  the resource bundle the message                        type="time" timeStyle="short"                                                      format.
                  key is to be looked up in.                             value="${now}"/>
                                                                       </fmt:timeZone>
                                                                                                                                        type                Specifies the type of    No    number
                                                                       <br/>
var               Variable to hold the message.      No                Local Time:<fmt:formatDate type="time"                                               value. Valid values are:
                                                                              timeStyle="short" value="${now}"/>
                                                                                                                                                            •    number
scope             Scope of the var variable.         No     page
                                                                                                                                                            •    currency
                                                                        Attribute             Description             Rqd    Default                        •    percentage

<fmt:param> - Supplies a parameter for message                                                                                          pattern             Custom formatting        No    None
                                                                       value        String representation of a time   Yes   None                            pattern (overrides other
format substitution in a containing <fmt:message>                                                                                                           formatting options
                                                                                    zone (such as
tag. Parameters are substituted in sequential order.                                “America/New_York”, “GMT-5”,                                            including type – see
                                                                                    or “EST”) or an actual                                                  java.text.DecimalFormat
                                                                                    java.util.TimeZone object.                                              )
Attribute          Description            Rqd Default           Attribute              Description           Rqd   Default    Attribute               Description                 Rqd   Default

currencyCode       Currency code (ISO        No      Based     value                  Value to parse.              No    Body      timeStyle     Predefined formatting style for a    No      default
                   4217) used for                    on                                                                                          time (ignored if type=”date”) -- see
                   formatting currencies.            default   type                   Specifies the type of        No    number                  java.text.DateFormat.
                   Such as “USD” (US                 locale                           value. Valid values are:
                   dollars) or “EUR” (euro).                                                                                                     Valid values are:
                                                                                      •   number                                                 • default (2:51:16 PM)
currencySymbol     Currency symbol used         No   Based                            •   currency                                               • short (2:51 PM)
                   when formatting                   on                               •   percentage                                             • medium (2:51:16 PM)
                   currencies. Such as               default                                                                                     • long (2:51:16 PM EDT)
                   “$” for US dollars, or “F”        locale    pattern                Custom parsing pattern       No    None
                   for Francs.                                                        (overrides type – see                                      • full (2:51:16 PM EDT)
                                                                                      java.text.DecimalFormat)                     pattern       Custom formatting style (overrides No        None
groupingUsed       Specifies if grouping        No   true                                                                                        type, dateStyle, and
                   separators will be used                     parseLocale            String representation of a   No    Default                 timeStyle) – see
                   (for example –                                                     locale (e.g. en_US) or an          locale                  java.text.SimpleDateFormat.
                   formatting “23890” as                                              actual java.util.Locale
                   “23,890”).                                                         object used for parsing.                     timeZone      String representation of a time        No    Default
                                                                                                                                                 zone or an actual                            time
maxIntegerDigits Maximum number of              No   None      integerOnly            Specifies if only the        No    false                   java.util.TimeZone object.                   zone
                 digits to print in the                                               integer portion of the
                 integer part of the                                                  value should be parsed.
                 number.
                                                               var                    Variable to store the        No    None      <fmt:formatDate> - Formats a date and/or time in a
minIntegerDigits   Minimum number of            No   None                             formatted number.                            locale-sensitive manner. The formatted value is
                   digits to print in the
                   integer part of the
                                                                                                                                   printed or stored in a scoped variable.
                                                               scope                  Scope of the var variable    No    page
                   number.
                                                                                                                                   <fmt:formatDate value="${now}"
                                                                                                                                         pattern="yy-MMM-dd"/>
maxFractionDigit Maximum number of              No   None
s                digits to print in the                        Formatting Dates
                 fractional part of the
                                                                                                                                     Attribute             Description             Rqd Default
                 number.                                       Dates are formatted and parsed using the
                                                               <fmt:formatDate> and <fmt:parseDate>
minFractionDigit   Minimum number of            No   None                                                                          value           Date value to format. Value     No    None
                                                               actions which share the following common                                            must be a java.util.Date
s                  digits to print in the
                   fractional part of the                      attributes.                                                                         object.
                   number.
                                                                Attribute                 Description              Rqd   Default   var             Variable to store the           No    None
var                Variable to store the        No   None                                                                                          formatted number.
                   formatted number.                           type          Specifies the type of value. Valid    No    date
                                                                             values are:                                           scope           Scope of the var variable       No    page
scope              Scope of the var             No   page
                                                                             •    time (time only)
                   variable
                                                                             •    date (date only)
                                                                             •    both (date and time)                             <fmt:parseDate> - Parses a string representing a
                                                               dateStyle     Predefined formatting style for a    No     default   date and/or time in a locale-sensitive manner. The
<fmt:parseNumber> - Parses a String representing                             date (ignored if type=”time”) -- see                  parsed value is printed or stored in a scoped
a number, currency, or percentage in a locale-                               java.text.DateFormat.                                 variable.
sensitive manner. The parsed value is printed or                             Valid values are:
stored in a scoped variable.                                                 • default (Jul 19, 2003)
                                                                                                                                   <fmt:parseDate var="bday"
                                                                                                                                        pattern="MM/dd/yy"
<fmt:parseNumber var="num" type="number"
                                                                             • short (7/19/03)                                            value="05/10/63"/>
     pattern="#,###" value="2,447"/>                                         • medium (Jul 19, 2003)                               <fmt:formatDate value="${bday}"
<c:out value="${num}"/>                                                      • long (July 19, 2003)                                     dateStyle="full"/>
                                                                             • full (Saturday, July 19,
                                                                                 2003)
Attribute            Description              Rqd Default                                                                            Attribute              Description             Rqd   Default
                                                                                   SQL Tag Library
value         Date/time string to parse.       No   None                                                                             scope         Scope of the variable var.        No    page

parseLocale   String representation of a       No   Default
                                                              <%@ taglib prefix="sql"
              locale (e.g. en_US) or an             locale
                                                                uri="http://java.sun.com/jstl/sql" %>
              actual java.util.Locale object                                                                                         <sql:update> - Performs a database insert, update,
              used for parsing.                                                                                                      delete or other statement (such as a DDL statement)
                                                              The SQL tag library provides actions to perform                        that does not return any results. This action may
var           Variable to store the parsed     No   None      transactional database queries and updates and                         include body content containing the actual update
              value as a java.util.Date.                      easily access query results.                                           string as well as <sql:param> tags for parameter
scope         Scope of the var variable        No   page                                                                             substitution. Like <sql:query>, the <sql:param>
                                                              <sql:query> - Performs a database query (e.g.                          tags must occur after the sql statement if it is
                                                              select statement). The query should be expected                        contained in the <sql:update> tag body.
                                                              to return a ResultSet. This action may include
                                                              body content containing the actual query string as                     <sql:update var="updateCount">
                                                              well as <sql:param> and <sql:dateParam>                                  UPDATE users SET first_name="William" WHERE
                                                              tags for parameter substitution. If the body                               first_name = "Bill"
                                                              contains the SQL query, it must appear before                          </sql:update>
                                                                                                                                     <c:out value="${updateCount} rows updated."/>
                                                              any nested parameter tags.
                                                              <sql:query var="users">
                                                                                                                                       Attribute               Description           Rqd    Default
                                                                SELECT * FROM users WHERE
                                                                  last_name = "Burdell"
                                                              </sql:query>                                                           sql             SQL statement to execute.       No    Body
                                                              <c:forEach var="user"items="${users.rows}">
                                                                <c:out value="${users.user_name}"/><br/>                             dataSource      Database connection to use.     No    Default
                                                              </c:forEach>                                                                           A javax.sql.DataSource                data
                                                                                                                                                     object, or a String                   source
                                                                                                                                                     representing a JNDI resource
                                                                Attribute               Description                Rqd    Default                    or the parameters for
                                                                                                                                                     java.sql.DriverManager. If
                                                              sql            SQL query to execute.                 No    Body                        specified, this action cannot
                                                                                                                                                     be nested in
                                                                                                                                                     <sql:transaction>.
                                                              dataSource Database connection to use. A No                Default
                                                                         javax.sql.DataSource object, or a               data
                                                                         String representing a JNDI                                  var             Name of the variable to store No      None
                                                                                                                         source
                                                                         resource or the parameters for                                              the query results as a
                                                                         java.sql.DriverManager. If                                                  java.lang.Integer object (e.g.
                                                                         specified, this action cannot be                                            SQL update statements return
                                                                         nested in <sql:transaction>.                                                the number of rows affected).


                                                              maxRows        Maximum number of rows to             No    Default     scope           Scope of the variable var.      No    page
                                                                             return in the result. If not                maxRows
                                                                             specified or set to -1, no limit is         (see
                                                                             enforced.                                   “Configur
                                                                                                                         ation”)     <sql:transaction> - Establishes a database
                                                                                                                                     transaction for <sql:query> and <sql:update>
                                                              startRow       Returned results include rows         No    0           tags contained in this tag's body. That is, all SQL
                                                                             starting at this index. The first                       actions contained in the body of this tag will be
                                                                             row is row 0.
                                                                                                                                     treated as a single atomic transaction. The
                                                              var            Name of the variable to store the Yes       None
                                                                                                                                     transaction will be committed only if all statements
                                                                             query results. Returned rows are                        succeed. If any of the contained SQL actions cause
                                                                             accessible via the rows property                        an exception, the transaction will be rolled back.
                                                                             of this object.
                                                                                                                                     Note: this action will reinstate the prior “auto commit”
                                                                                                                                     setting after completion.
<sql:transaction>                                                Attribute           Description           Rqd    Default           Attribute           Description           Rqd    Default
  <sql:update sql="DELETE users WHERE
       user_name='bsiggelkow'"/>                               user           Database user's username No        None             value         Value of the parameter.       Yes   None
  <sql:update sql="INSERT INTO users                                                                                                            Must be a java.util.Date
   VALUES ('billsigg','Bill','Siggy')"/>                                                                                                        object.
</sql:transaction>                                             password       Database user's password     No    None

                                                               var            Name of the variable to      No    Default          type          Indicates how the database    No    timestamp
                                                                              hold the data source.              data                           should interpret the value.
  Attribute           Description            Rqd    Default
                                                                                                                 source                         Valid values are:
                                                                                                                 name
dataSource    Database connection to      No        Default                                                      (see
                                                                                                                                                • date
              use. A                                data                                                         “Configur                      • time
              javax.sql.DataSource                  source                                                       ation”)                        • timestamp
              object, or a String                   (see
              representing a JNDI                   “Configu
              resource or the parameters            ration”)   scope          Scope of the variable var.   No    page
              for java.sql.DriverManager.
                                                               <sql:param> - Substitutes parameters into SQL
isolation     Transaction isolation level.   No     Databas    prepared statement placeholders (“?”). This
              Valid values are:
                                                    e 's       action can only be nested within
                                                    default
              • read_committed                                 <sql:query> or <sql:update> tags.
              • read_uncommitted                               If the enclosing tag specifies the SQL in the body,
              • repeatable_read                                any <sql:param> tags must appear after the SQL.
              • serializable                                   Parameters are substituted in sequential order.
                                                               <c:set var="firstName">Bill</c:set>
                                                               <sql:query var="users">
<sql:setDataSource> - Creates and stores in a                    SELECT user_name, last_name
scoped variable an SQL data source. This tag                     FROM users WHERE first_name = ?
cannot have a body. Either the dataSource or url                 <sql:param value="${firstName}"/>
                                                               </sql:query>
attribute must be specified.
<sql:setDataSource var="testDB"
                                                                  Attribute             Description              Rqd    Default
     url="jdbc:mysql://localhost/test,
          com.mysql.jdbc.Driver"/>
<sql:query var="users"                                         value           Value of the parameter. If not No        Body
    dataSource="${testDB}">                                                    specified, value is taken from
  SELECT * FROM users                                                          the tag body.
</sql:query>

                                                               <sql:dateParam> - Substitutes time, date, or
  Attribute          Description             Rqd   Default     timestamp parameters into SQL prepared
                                                               statement placeholders. This action can only be
dataSource    Database connection to     No        None
              use or create. A                                 nested within <sql:query> or
              javax.sql.DataSource                             <sql:update> tags. Parameters are
              object, or a String
              representing a JNDI
                                                               substituted in sequential order.
              resource or the parameters
              for                                              <fmt:parseDate var="ww2End"
              java.sql.DriverManager.                               pattern="yyyy-MM-dd"
                                                                    value="1945-09-02"/>
                                                               <sql:query var="postWarBabies">
driver        Name of the JDBC driver        No    None             SELECT user_name FROM user_profile
              class.                                                  WHERE birth_date > ?
                                                                 <sql:dateParam value="${ww2End}"
url           URL for the JDBC               No    None               type="date"/>
              database connection.                             </sql:query>
scope="page"/>
                                                                                                                                          Function                       Description
                  XML Tag Library                          <%-- Find the user with matching ID --%>
                                                           <x:set var="user"                                                      contains              Returns true if string1 contains string2;
                                                           select="$doc//users/user[@id=$pageScope:user                                                 false, otherwise. Non-string arguments are
                                                           Id]"/>                                                                 (string1, string2):   converted to strings as if by the string()
<%@ taglib prefix="x"                                                                                                                                   function.
                                                           <%-- Say Hi to the user --%>                                           boolean
  uri="http://java.sun.com/jstl/xml" %>
                                                           Hi <x:out select="$user/first-name"/> !
                                                                                                                                  count                 Returns the number of nodes in the node
The XML tag library supports parsing of XML                                                                                                             set.
documents, selection of XML fragments, conditional         XPath Abbreviated Syntax                                               (node-set):
and iterative processing based on XML content, and                                                                                number
                                                                Abbr.       XPath Axis                   Example
XSLT transformations.
                                                           //             descendant        $doc//first-name                      floor                 Returns the greatest integer less than or
A common pattern for using the XML tags is as                                                                                     (number or
                                                                                                                                                        equal to number or object (as converted as
follows:                                                                                                                                                if by the number() function).
                                                           .              self              $doc/users/user/.                     object):
1. Use <x:parse> to parse XML into a scoped
                                                                                                                                  number
    variable. The XML can come from the body               ..             parent            $doc//[first-
    literally, from the body via <c:import>, or from the                                    name='George']/../last-
                                                                                                                                  last():               Returns the number of nodes in the context
                                                                                            name
    value attribute which may refer to any XML                                                                                                          node.
    source.                                                                                                                       number
                                                           @              attribute         $doc//user[@id="997"]/firs
    <x:parse var="varName" ...>                                                             t-name
                                                                                                                                  local-name            Returns the part of the element name after
                                                                                                                                                        the colon (:) when namespaces are used. If
2. Use the scoped variable from <x:parse> to specify                      child             $doc/users/user[last-                 (node-set):           node set is not specified the function is
   the XML document to use in XPath expressions.           (blank)
                                                                                            name='Burdell']
                                                                                                                                  string                applied to the context node.
   <x:out select="$varName/XPath
   expression"/>                                           *              (matches any      $doc//*[local-                        name                  Returns the qualified element name, that is,
                                                                          namespace)        name()='users']/user                                        prefix:local-name, when namespaces are
                                                                                                                                  (node-set):
Using JSTL Data as XPath Variables                                                                                                                      used. If node set is not specified the
Scoped variables can be used in XPath expressions                                                                                 string                function is applied to the context node.
($implicitObject:variableName) similar to how they
                                                           Useful XPath Functions                                                 namespace-uri         Returns the uri of the namespace of the
are used in EL (${implicitObject.variableName}). If
                                                           Following are some useful XPath functions that                                               given node set. If node set is not specified
the implicit object is omitted, scopes will be searched                                                                           (node-set):
                                                           can be used in XPath expressions. This list does                                             the function is applied to the context node.
in standard order. Note that the “.” and “[]”              not include all XPath functions – just those                           string
notations cannot be used for accessing bean                deemed particularly useful when using the JSTL
properties.                                                XML tags.                                                              not                   Returns the logical inversion of the supplied
                                                                                                                                                        argument. That is, if the argument is true,
                                                                                                                                  (boolean or
The following example demonstrates the above                                                                                      object):
                                                                                                                                                        false is returned; if argument is false, true is
techniques.                                                      Function                          Description                                          returned.
                                                                                                                                  boolean
                                                           ceiling                 Returns the smallest integer greater than or
<%-- Create the XML --%>                                                           equal to number or object (as converted as
<x:parse var="doc">                                        (number or                                                             number                Converts object (or the current node if
                                                                                   if by the number() function).                                        object is not specifed) to a number. True is
  <users>                                                  object):                                                               (object):
    <user id="997">                                                                                                                                     converted to 1, and false to 0. If the number
      <first-name>George</first-name>                      number                                                                 number                cannot be converted NaN is returned.
      <last-name>Burdell</last-name>
    </user>                                                concat                  Concatenates the arguments in order from
    <user id="998">                                                                                                               position():           Returns the position of the current node in
                                                                                   left to right. Non-string arguments are                              the current context node set. The first
      <first-name>Joseph</first-name>                      (string1, string 2,     converted to strings as if by the string()     number
      <last-name>Blough</last-name>                        ...):                                                                                        position is 1.
                                                                                   function.
    </user>
  </users>                                                 string
</x:parse>

<%-- Define a variable holding user ID --%>
<c:set var="userId" value="${user.id}"
Function                         Description                            <title>feed title</title>                                    expression as a string.
                                                                              <link>source url</link>
                                                                              <description>feed desc</description>                         RSS Channel:
round                 Returns the closest integer to number or                                                                             <x:out select="$news//channel/title"/>
                                                                              <item>
                      object (as converted as if by the number()
(number or                                                                      <title>article title</title>
                      function). If two integers are equally close,
object):                                                                        <link>article url</link>
                      the value closer to positive infinity is
                                                                                <description>article
number                chosen. (e.g. round(3.5) returns 4, round(-                                                                            Attribute           Description             Rqd   Default
                                                                          desc</description>
                      3.5) returns -3).
                                                                              </item>
                                                                              <item>                                                       select        XPath expression.               Yes   None
starts-with           Returns true if string1 starts with string2;              <title>article title</title>
                      false, otherwise.                                         <link>article url</link>
(string1,string2):                                                                                                                         escapeXml     true      to escape special     No    true
                                                                                <description>article
boolean                                                                   desc</description>                                                             characters
                                                                              </item>
                                                                            </channel>
string                Converts the object, or the current node if         </rss>
                      object is not specifed, to a string.
(object):             Generally, this function will output the body                                                                        <x:set> - Saves the result of the select XPath
string                of the elements (e.g. string(<a>b</a>)              <x:parse> - Parses XML content, provided by the                  expression to a scoped variable. Returned value
                      returns “b”).                                                                                                        may be a node set (XML fragment), boolean, string,
                                                                          value attribute or the tags body, into a scoped
                                                                          variable(s). This variable can then be used for                  or number.
string-length         Number of characters in the string. If object
                      is not a string it is first converted to a string   subsequent processing by other XML tags.
(object):                                                                                                                                  <x:set select="$news//channel/item"
                      as if by the string() function.                                                                                                var="newsItems"/>
                                                                          <c:import var="rss"
number                                                                    url="http://servlet.java.sun.com/syndication
                                                                          /rss_java_highlights-PARTNER-20.xml"/>
substring             Returns a substring of string starting at           <x:parse var="news" xml="${rss}"/>
                      index and continuing for length characters.                                                                            Attribute           Description             Rqd   Default
(string, index,       The first character is position 1, not
length):              position 0 as in Java and JavaScript.                                                                                select        XPath expression.               No    None
string                                                                     Attribute             Description               Rqd   Default
                                                                                                                                           var           Name of variable to store       No    None
substring-after       Returns the substring in string1 following the      doc          (JSTL 1.1) Text of the document     No    Body                    results. The variable type is
                      first of occurrence of string2 in string1.                       to a parse as a String or Reader.                                 equal to whatever is returned
(string1, string2):                                                                                                                                      by the select expression.
string                                                                    xml          (JSTL 1.0 – deprecated in 1.1)      No    Body
                                                                                       Same as doc attribute.                                            •   Boolean –
substring-before      Returns the substring in string1 preceding                                                                                             java.lang.Boolean
                      the first of occurrence of string2 in string1.      systemId     URI of the original document,       No    None
(string1, string2):                                                                                                                                      •   Number –
string                                                                                 used for entity resolution.                                           java.lang.Number

                                                                          filter       XML filter to apply. Value should   No    None                    •   Node or node set –
sum                   Converts each node in the set to a number,
                                                                                       be of type org.xml.sax.XMLFilter.                                     implementation-
                      as if by the number() function, adds up the
(node-set):                                                                                                                                                  dependent type
                      numbers and returns the sum.
number                                                                    var          Name of the variable to store the   Yes   None
                                                                                       results – may be an                                 scope         Scope of variable var.          No    page
                                                                                       implementation-specific object.

General XML Actions                                                       scope        Scope of the variable var.          No    page      Flow Control Actions
Actions for parsing XML, outputting to the page, and
                                                                          varDom       Name of the variable to store the   Yes   None      Actions for processing markup based on logical and
selecting XML fragments. The examples that follow                                      result – stored as a DOM object.                    iterative conditions.
demonstrate use of the XML tags for processing Rich
Site Summary (RSS) feeds. RSS has more or less                            scopeDom Scope to store variable varDOM          No    page
the following format:                                                              in.
                                                                                                                                           <x:if> - Processes the body if select XPath evaluates
                                                                                                                                           to true (following the rules of the boolean() XPath
<?xml version="1.0"?>                                                                                                                      function).
<rss version="0.91">
  <channel>                                                               <x:out> - Prints the result of the XPath                         <x:if select=
"$news//item[contains(description,'Linux')]">                 <x:choose> -- Processes the body of the first                       Attribute         Description          Rqd Default
 Linux is in the news today!                                  enclosed <x:when> tag where the select XPath
</x:if>
                                                              expression evaluates to true. If none match then              var               Name of variable to hold   No    None
                                                              the body of the <x:otherwise> tag (if present)                                  the current item. This
                                                                                                                                              variable has only nested
  Attribute            Description            Rqd   Default   is processed.                                                                   visibility.

select        Test condition as an XPath      Yes   None      <x:choose>
                                                                <x:when select="$news//item">                               Transformation Actions
              expression. Body content is
              processed if the condition is                        We've got news :)
                                                               </x:when>                                                    JSTL provides an <x:transform> tag for
              true.
                                                                <x:otherwise>                                               performing XSLT transformations. The <x:param>
var           Name of variable to store test No     None
                                                                  No news today :(                                          tag can be nested in the <x:transform> tag to set
                                                                </x:otherwise>
              condition's result                              </x:choose>                                                   a parameter that is used in the stylesheet.

scope         Scope of variable               No    page
                                                                                                                            <x:transform> - Conducts an XSLT transformation
                                                              The choose tag accepts no attributes and can                  on source XML. The source XML is provided by the
                                                              only contain <x:when> tag(s) and an optional                  doc attribute or the body of the tag. The XSL
                                                              <x:otherwise> tag.                                            stylesheet is specified by the xslt attribute. While in
                                                                                                                            most cases, the stylesheet will be set up by back-end
                                                              <x:when> - Represents an alternative in an                    code – it is possible to define the stylesheet inline
                                                              <x:choose> tag. Processes the body if the                     and make it available with <c:set> as in the
                                                              select expression evaluates to true and no other              following example:
                                                              previous <x:when> tags in the <x:choose>
                                                              matched.
                                                                                                                            <c:set var="xsl">
                                                                                                                              <?xml version="1.0" encoding="UTF-8"?>
                                                                Attribute            Description            Rqd   Default     <xsl:stylesheet version="1.0"
                                                                                                                            xmlns:xsl="http://www.w3.org/1999/XSL/Transform
                                                              select          Test condition as an XPath    Yes   None      ">
                                                                              expression.                                       <xsl:template match="item">
                                                                                                                                  <li>
                                                                                                                                    <xsl:value-of select="title"/>
                                                                                                                                  </li>
                                                                                                                                </xsl:template>
                                                              <x:otherwise> - Processes the body if no other                    <xsl:template match="/">
                                                              previous <x:when> condition in the                                  <ol>
                                                              <x:choose> matched. This tag accepts no                              <xsl:apply-templates
                                                                                                                                        select="//item"/>
                                                              attributes and, if present, must be the last tag in                 </ol>
                                                              <x:choose> body.                                                  </xsl:template>
                                                                                                                              </xsl:stylesheet>
                                                              <x:forEach> - Repeats the nested body content                 </c:set>
                                                              over a node set determined by an XPath                        <x:transform xml="${news}"
                                                              expression, setting the context node to each                              xslt="${xsl}"/>
                                                              element in the iteration.
                                                              <x:forEach select="$news//item">                                    Attribute           Description             Rqd   Default
                                                                <a href='<x:out select="link"/>'>
                                                                <x:out select="title"/></a><br/>
                                                              </x:forEach>                                                  doc                (JSTL 1.1) Source XML        No      Body
                                                                                                                                               document for the
                                                                                                                                               transformation. Value can
                                                                                                                                               be a String, Reader,
                                                                  Attribute            Description           Rqd Default                       javax.xml.transform.Source
                                                                                                                                               , org.w3c.dom.Document,
                                                              select             Name of variable to hold   No    None                         or any value exported
                                                                                 the current item. This                                        <x:parse> or <x:set>. If the
                                                                                 variable has only nested                                      value comes from <x:set> it
                                                                                 visibility.                                                   cannot be a partial
                                                                                                                                               document.
JSTLQuick Reference
JSTLQuick Reference

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskellnebuta
 
Math for Bus. and Eco. Chapter 3
Math for Bus. and Eco. Chapter 3Math for Bus. and Eco. Chapter 3
Math for Bus. and Eco. Chapter 3Mong Mara
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Oop07 6
Oop07 6Oop07 6
Oop07 6schwaa
 
08 advanced techniques
08 advanced techniques08 advanced techniques
08 advanced techniquesgoodhackers
 
Testing JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and ChaiTesting JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and ChaiMark
 
User defined functions
User defined functionsUser defined functions
User defined functionsshubham_jangid
 
C# Basics Quick Reference Sheet
C# Basics Quick Reference SheetC# Basics Quick Reference Sheet
C# Basics Quick Reference SheetFrescatiStory
 
Testing Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with JasmineTesting Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with JasmineMark
 
jQuery Visual Cheat Sheet (by WOORK)_1
jQuery Visual Cheat Sheet (by WOORK)_1jQuery Visual Cheat Sheet (by WOORK)_1
jQuery Visual Cheat Sheet (by WOORK)_1brecke
 
Dart function - Recursive functions
Dart function - Recursive functionsDart function - Recursive functions
Dart function - Recursive functionsKoAungThuOo1
 

Was ist angesagt? (16)

Ruby On Rails Cheat Sheet
Ruby On Rails Cheat SheetRuby On Rails Cheat Sheet
Ruby On Rails Cheat Sheet
 
Introduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in HaskellIntroduction to ad-3.4, an automatic differentiation library in Haskell
Introduction to ad-3.4, an automatic differentiation library in Haskell
 
Math for Bus. and Eco. Chapter 3
Math for Bus. and Eco. Chapter 3Math for Bus. and Eco. Chapter 3
Math for Bus. and Eco. Chapter 3
 
Chtp407
Chtp407Chtp407
Chtp407
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Oop07 6
Oop07 6Oop07 6
Oop07 6
 
08 advanced techniques
08 advanced techniques08 advanced techniques
08 advanced techniques
 
TraitとMoose::Role
TraitとMoose::RoleTraitとMoose::Role
TraitとMoose::Role
 
Testing JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and ChaiTesting JavaScript/CoffeeScript with Mocha and Chai
Testing JavaScript/CoffeeScript with Mocha and Chai
 
Real Work Scalaz
Real Work ScalazReal Work Scalaz
Real Work Scalaz
 
User defined functions
User defined functionsUser defined functions
User defined functions
 
Rails 3 Internals
Rails 3 InternalsRails 3 Internals
Rails 3 Internals
 
C# Basics Quick Reference Sheet
C# Basics Quick Reference SheetC# Basics Quick Reference Sheet
C# Basics Quick Reference Sheet
 
Testing Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with JasmineTesting Rich Client Side Apps with Jasmine
Testing Rich Client Side Apps with Jasmine
 
jQuery Visual Cheat Sheet (by WOORK)_1
jQuery Visual Cheat Sheet (by WOORK)_1jQuery Visual Cheat Sheet (by WOORK)_1
jQuery Visual Cheat Sheet (by WOORK)_1
 
Dart function - Recursive functions
Dart function - Recursive functionsDart function - Recursive functions
Dart function - Recursive functions
 

Andere mochten auch

Jdom how it works & how it opened the java process
Jdom how it works & how it opened the java processJdom how it works & how it opened the java process
Jdom how it works & how it opened the java processHicham QAISSI
 
International Business Isbn-9780273766957 - Points-counterpoints
International Business Isbn-9780273766957 - Points-counterpointsInternational Business Isbn-9780273766957 - Points-counterpoints
International Business Isbn-9780273766957 - Points-counterpointsHicham QAISSI
 
Grammars for Generative Art - Lectures @ Sofia University #2
Grammars for Generative Art - Lectures @ Sofia University #2Grammars for Generative Art - Lectures @ Sofia University #2
Grammars for Generative Art - Lectures @ Sofia University #2stelf
 
Grammars for Generative Art - Lectures @ Sofia University #5
Grammars for Generative Art - Lectures @ Sofia University #5Grammars for Generative Art - Lectures @ Sofia University #5
Grammars for Generative Art - Lectures @ Sofia University #5stelf
 
Grammars for Generative Art - Lectures @ Sofia University #8
Grammars for Generative Art - Lectures @ Sofia University #8Grammars for Generative Art - Lectures @ Sofia University #8
Grammars for Generative Art - Lectures @ Sofia University #8stelf
 
Grammars for Generative Art - Lectures @ Sofia University #0
Grammars for Generative Art - Lectures @ Sofia University #0Grammars for Generative Art - Lectures @ Sofia University #0
Grammars for Generative Art - Lectures @ Sofia University #0stelf
 
Grammars for Generative Art - Lectures @ Sofia University #1
Grammars for Generative Art - Lectures @ Sofia University #1Grammars for Generative Art - Lectures @ Sofia University #1
Grammars for Generative Art - Lectures @ Sofia University #1stelf
 
Grammars for Generative Art - Lectures @ Sofia University #9
Grammars for Generative Art - Lectures @ Sofia University #9Grammars for Generative Art - Lectures @ Sofia University #9
Grammars for Generative Art - Lectures @ Sofia University #9stelf
 
Grammars for Generative Art - Lectures @ Sofia University #6
Grammars for Generative Art - Lectures @ Sofia University #6Grammars for Generative Art - Lectures @ Sofia University #6
Grammars for Generative Art - Lectures @ Sofia University #6stelf
 
SAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginnersSAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginnersHicham QAISSI
 
Grammars for Generative Art - Lectures @ Sofia University #3
Grammars for Generative Art - Lectures @ Sofia University #3Grammars for Generative Art - Lectures @ Sofia University #3
Grammars for Generative Art - Lectures @ Sofia University #3stelf
 
YAPC::EU 2014 :: Lighting Talk :: Perl @ Sofia University
YAPC::EU 2014 :: Lighting Talk :: Perl @ Sofia UniversityYAPC::EU 2014 :: Lighting Talk :: Perl @ Sofia University
YAPC::EU 2014 :: Lighting Talk :: Perl @ Sofia Universitystelf
 
The Beauty of Night
The Beauty of NightThe Beauty of Night
The Beauty of Nightlotusflowah
 

Andere mochten auch (18)

PeaCe
PeaCePeaCe
PeaCe
 
Jdom how it works & how it opened the java process
Jdom how it works & how it opened the java processJdom how it works & how it opened the java process
Jdom how it works & how it opened the java process
 
JDOM makes xml easy
JDOM makes xml easyJDOM makes xml easy
JDOM makes xml easy
 
International Business Isbn-9780273766957 - Points-counterpoints
International Business Isbn-9780273766957 - Points-counterpointsInternational Business Isbn-9780273766957 - Points-counterpoints
International Business Isbn-9780273766957 - Points-counterpoints
 
Grammars for Generative Art - Lectures @ Sofia University #2
Grammars for Generative Art - Lectures @ Sofia University #2Grammars for Generative Art - Lectures @ Sofia University #2
Grammars for Generative Art - Lectures @ Sofia University #2
 
Bavaria Brewery
Bavaria BreweryBavaria Brewery
Bavaria Brewery
 
Grammars for Generative Art - Lectures @ Sofia University #5
Grammars for Generative Art - Lectures @ Sofia University #5Grammars for Generative Art - Lectures @ Sofia University #5
Grammars for Generative Art - Lectures @ Sofia University #5
 
Grammars for Generative Art - Lectures @ Sofia University #8
Grammars for Generative Art - Lectures @ Sofia University #8Grammars for Generative Art - Lectures @ Sofia University #8
Grammars for Generative Art - Lectures @ Sofia University #8
 
Grammars for Generative Art - Lectures @ Sofia University #0
Grammars for Generative Art - Lectures @ Sofia University #0Grammars for Generative Art - Lectures @ Sofia University #0
Grammars for Generative Art - Lectures @ Sofia University #0
 
Grammars for Generative Art - Lectures @ Sofia University #1
Grammars for Generative Art - Lectures @ Sofia University #1Grammars for Generative Art - Lectures @ Sofia University #1
Grammars for Generative Art - Lectures @ Sofia University #1
 
Grammars for Generative Art - Lectures @ Sofia University #9
Grammars for Generative Art - Lectures @ Sofia University #9Grammars for Generative Art - Lectures @ Sofia University #9
Grammars for Generative Art - Lectures @ Sofia University #9
 
Grammars for Generative Art - Lectures @ Sofia University #6
Grammars for Generative Art - Lectures @ Sofia University #6Grammars for Generative Art - Lectures @ Sofia University #6
Grammars for Generative Art - Lectures @ Sofia University #6
 
SAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginnersSAX, DOM & JDOM parsers for beginners
SAX, DOM & JDOM parsers for beginners
 
Grammars for Generative Art - Lectures @ Sofia University #3
Grammars for Generative Art - Lectures @ Sofia University #3Grammars for Generative Art - Lectures @ Sofia University #3
Grammars for Generative Art - Lectures @ Sofia University #3
 
YAPC::EU 2014 :: Lighting Talk :: Perl @ Sofia University
YAPC::EU 2014 :: Lighting Talk :: Perl @ Sofia UniversityYAPC::EU 2014 :: Lighting Talk :: Perl @ Sofia University
YAPC::EU 2014 :: Lighting Talk :: Perl @ Sofia University
 
We Win En 2 0
We Win En 2 0We Win En 2 0
We Win En 2 0
 
Cognates and false cognates copia
Cognates and false cognates   copiaCognates and false cognates   copia
Cognates and false cognates copia
 
The Beauty of Night
The Beauty of NightThe Beauty of Night
The Beauty of Night
 

Ähnlich wie JSTLQuick Reference

javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1brecke
 
Jquery 1.3 cheatsheet_v1
Jquery 1.3 cheatsheet_v1Jquery 1.3 cheatsheet_v1
Jquery 1.3 cheatsheet_v1Sultan Khan
 
Jquery 13 cheatsheet_v1
Jquery 13 cheatsheet_v1Jquery 13 cheatsheet_v1
Jquery 13 cheatsheet_v1ilesh raval
 
Xsl Tand X Path Quick Reference
Xsl Tand X Path Quick ReferenceXsl Tand X Path Quick Reference
Xsl Tand X Path Quick ReferenceLiquidHub
 
Object Oriented Programming in js
Object Oriented Programming in jsObject Oriented Programming in js
Object Oriented Programming in jsthreepointone
 
Code craftsmanship saturdays second session
Code craftsmanship saturdays second sessionCode craftsmanship saturdays second session
Code craftsmanship saturdays second sessionJean Marcel Belmont
 

Ähnlich wie JSTLQuick Reference (8)

javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1javascript-cheat-sheet-v1_1
javascript-cheat-sheet-v1_1
 
Jquery 1.3 cheatsheet_v1
Jquery 1.3 cheatsheet_v1Jquery 1.3 cheatsheet_v1
Jquery 1.3 cheatsheet_v1
 
Jquery 13 cheatsheet_v1
Jquery 13 cheatsheet_v1Jquery 13 cheatsheet_v1
Jquery 13 cheatsheet_v1
 
Xsl Tand X Path Quick Reference
Xsl Tand X Path Quick ReferenceXsl Tand X Path Quick Reference
Xsl Tand X Path Quick Reference
 
Object Oriented Programming in js
Object Oriented Programming in jsObject Oriented Programming in js
Object Oriented Programming in js
 
Code craftsmanship saturdays second session
Code craftsmanship saturdays second sessionCode craftsmanship saturdays second session
Code craftsmanship saturdays second session
 
Jquery.cheatsheet.1.4
Jquery.cheatsheet.1.4Jquery.cheatsheet.1.4
Jquery.cheatsheet.1.4
 
Meet scala
Meet scalaMeet scala
Meet scala
 

Kürzlich hochgeladen

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????blackmambaettijean
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 

Kürzlich hochgeladen (20)

The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
What is Artificial Intelligence?????????
What is Artificial Intelligence?????????What is Artificial Intelligence?????????
What is Artificial Intelligence?????????
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 

JSTLQuick Reference

  • 1. Object Description Operator Description JSTL Quick Reference headerValues Map of request header name to a String array of values ! (not) True if operand is false; false, otherwise. Copyright 2003 Bill Siggelkow cookie Map of cookie name to a Cookie object Other Operators initParam Map of context initialization parameter Operator Description name to a String parameter value (set in Expressions (EL) web.xml) empty True if the operand is null, an empty String, empty array, empty Map, or empty List; false, otherwise. Arithmetic Operators In Attribute Values () Paranthesis for changing operator • <a:tag value="${expr}"/> Operator Description precedence. • <a:tag value="me${expr} ${expr}"/> + Addition EL Functions (JSTL 1.1) Bean Property Access - Subtraction Note: All functions treat null Strings as empty Strings. bean.name bean["name"] * Multiplication <%@ taglib prefix="fn" uri="http://java.sun.com/jstl/functions" %> Indexed Property Access / (div) Division Usage: ${fn:function(arg0, ...)} bean.property[index] % (mod) Remainder (modulus) Map Property Access <p>We offer ${fn:length(flavorSet)} ice cream flavors.</p> bean.property["key"] Relational Operators Operator Description Implicit Objects (maps) Function Description Object Description == (eq) Equality fn:contains Returns true if substring is contained in string; false, otherwise. pageContext JSP Page Context object != (ne) Inequality (string, substring) : boolean pageScope Page-scoped variables (valid only on a < (lt) Less than given JSP page) fn:containsIgnoreCase Returns true if substring is contained > (gt) Greater than in string regardless of case; false, (string, substring) : otherwise. requestScope Request-scoped variables (valid for a given boolean request) <= (le) Less than or equal to fn:endsWith Returns true if string ends with the sessionScope Session-scoped variables (valid for the >= (ge) Greater than or equal to specified suffix; false, otherwise. user's session) (string, suffix) : <= (le) Less than or equal to boolean applicationScope Application-scoped variables (valid for a given application context) fn:escapeXml Escapes characters (e.g changing “<” to “&lt;”) that could be interpreted as Logical Operators (string) : String XML (including HTML) markup. param Map of request parameter name to a String Operator Description parameter value fn:indexOf Returns an integer representing the 0- && (and) True if both operands are true; false, based index within string of the first paramValues Map of request parameter name to a String (string, substring) : int occurrence of substring. If substring is otherwise. array of parameter values empty, 0 is returned. || (or) True if either or both operands are true; false, header Map of request header name to a header otherwise. String value
  • 2. Function Description <c:remove var="dogAge" scope="page"/> Core Tag Library fn:join Joins all elements of the string array into a single string. Separator Attribute Description Rqd Default (string[], separator) : separates each element in the String resulting string. If separator is an <%@ taglib prefix="c" var Name of variable to delete Yes None empty string, the elements are joined uri="http://java.sun.com/jstl/core" %> without a separator. scope Scope of variable No All General-Purpose Actions scopes fn:length If a collection or array is passed, the size of the collection or array is Actions for rendering data, creating and (collection or string) : modifying scoped variables, and catching <c:catch> - traps all exceptions or errors from the returned; If a string is passed, the int number of characters in the string is exceptions. enclosed body. returned. <c:catch var="err"> <c:out> - renders data to the page <c:import value="http://java.sun.com"/> fn:replace Replaces in inputString, every </c:catch> occurrence of beforeString with <h2>Welcome, <c:out value="${user.name}" <c:if test="${not empty err}"> (inputString, afterString. An empty string is beforeSubstring, default="Guest"/></h2> Could not connect to Java web site. returned if either inputString or </c:if> afterSubstring) : String beforeString is empty. If afterString is empty, all occurences of the beforeString are removed. Attribute Description Rqd Default Attribute Description Rqd Default fn:split Splits string into a string array using value Data to output Yes None var Name of variable to hold the No None the given set of delimiter characters. (string, delimiters) : default Fallback data to output if No Body thrown exception, if any. The delimiter characters are not String[] value is empty Variable will be of type included in any returned tokens. java.lang.Throwable. fn:startsWith Returns true if string starts with the escapeXml true to escape special No true specified prefix; false, otherwise. characters (string, prefix) : Returns true if prefix is empty. Conditional Actions boolean Actions for processing markup based on logical conditions. fn:substring Returns a subset of string using the zero-based indices – inclusive of the <c:set> - saves data to a scoped variable (string, beginIndex, begin index, but exclusive of the end <c:if> - processes the body if test is true endIndex) : String index. <c:set var="dogAge" value="${age div 7}"/> You are <c:out value="${dogAge}"/> in dog <c:if test="${user.age ge 40}"> fn:substringAfter Returns the subset of string following years. You are over the hill. the given substring. </c:if> (string, substring) : String Attribute Description Rqd Default Attribute Description Rqd Default fn:substringBefore Returns the subset of string that value Data to save No Body procedes the given substring. test Condition to evaluate Yes None (string, substring) : String target Name of variable to modify No None var Name of variable to store No None fn:toLowerCase Converts all characters of a string to property Property of target to modify No None test condition's result lowercase. (string) : String scope Scope of variable No page var Name of variable to store No None data fn:toUpperCase Converts all characters of a string to uppercase. (string) : String scope Scope of variable No page <c:choose> - multiple conditions – processes the fn:trim Removes whitespace from both ends body of the first enclosed when tag where the test of a string. condition is true. If none match then the body of the (string) : String <c:remove> - deletes a scoped variable otherwise tag (if present) is processed. <c:choose>
  • 3. <c:when test="${a boolean expr}"> Attribute Description Rqd Default Attribute Description Rqd Default // do something </c:when> varStatus Name of variable to hold the No None var Name of variable to hold No None <c:when test="${another boolean expr}"> loop status with the following the current token. This // do something else properties: variable has only nested </c:when> visibility. <c:otherwise> • index – position of the // do this when nothing else is true current item items String of tokens to loop Yes None </c:otherwise> over. </c:choose> • count – number of times through the loop (starting with 1) delims Set of characters that Yes None The choose tag accepts no attributes and can only separate the tokens (e.g. contain when tag(s) and an optional otherwise tag. • first – boolean delims=”,;” will tokenize a indicator if this is the first string separated by iteration commas or semi-colons). <c:when> - processes the body if test is true and no other previous <c:when> tags evaluated to true. • last – boolean indicator if this is the last iteration URL Related Actions Attribute Description Rqd Default Actions for importing content from URLs, building test Condition to evaluate Yes None URLs, and redirecting. <c:forEach> - repeats the nested body content over a collection or for a fixed number of times. <c:import> - imports the content of a URL-based resource. Action may include nested <c:param> <c:otherwise> - processes the body if no other <c:forEach items="${user.languages}" tags to specify the query string (unless the previous <c:when> condition matched. This tag var="lang" varStatus="status"> <c:if test="${status.first}"> varReader attribute is specified). accepts no attributes and, if present, must be the last You speak these languages:<br><ul> tag in the <c:choose> body. </c:if> <c:import url="includes/header.jsp"> <li><c:out value="${lang}"/></li> <c:param name="title">Hello World</c:param> Iterator Actions <c:if test="${status.last}"></ul></c:if> </c:import> Actions that loop over collections, for a fixed number </c:forEach> of times, or over a set of string tokens. These actions share the following attributes for iterating over Attribute Description Rqd Default Attribute Description Rqd Default a subset of elements. url URL of the resource to Yes None var Name of variable to hold No None import. Attribute Description Rqd Default the current item. This variable has only nested visibility. context Name of the context No Current begin Zero-based index of first item No 0 (beginning with a /) of some context to process, inclusive. other local web application to items Collection, iterator, map, or No None import the resource from. array to loop over. end Zero-based index of last item No Last item to process, inclusive. var Name of the variable to hold No None the imported content as a step Process every stepth element No 1 <c:forTokens> - repeats the nested body String. (e.g 2 = every second content for each token of a delimited string. element). scope Scope of the var variable No page <c:set var="users">Fred,Joe,Mary<c:set> <c:forTokens var="name" items="${users}" varReader Name of the variable to hold No None delims=","> the imported content as a <c:out value="${name}"/><br/> Reader. This variable has </c:forTokens> only nested visibility so that the reader will always be closed. Attribute Description Rqd Default
  • 4. <c:url> - builds a URL with the proper rewriting rules <c:redirect> - sends the client a response to applied (only relative URLs are rewritten). Action redirect to the specified URL. This action will abort processing of the current page. Action may Formatting Tag Library may include nested <c:param> tags to specify the query string. include nested <c:param> tags to specify the query string. <%@ taglib prefix="fmt" <c:url="editProfile.do" var="profileLnk"> uri="http://java.sun.com/jstl/fmt" %> <c:param name="id" value="${user.id}"/> <c:if test="${empty user}"> </c:url> <c:redirect url="login.do"/> <a href='<c:out value="${profileLnk}"/>'> </c:if> Internationalization (I18N) Actions Edit Profile </a> Actions that establish localization (l10n) contexts, specify resource bundles, and format messages. Attribute Description Rqd Default Attribute Description Rqd Default url URL of the resource to Yes None <fmt:setLocale> - Sets the default locale for the redirect to. specified scope. This will override the browser- value URL to be processed. Yes None based locale. context Name of the context No Current context Name of the context No Current (beginning with a /) of some context <fmt:setLocale scope="session" (beginning with a /) of some context other local web application. value="fr_CA"> other local web application. var Name of the variable to hold No None Attribute Description Rqd Default the URL as a String. <c:param> - adds request parameters to a URL. This action can only be nested within value String representation of a Yes None scope Scope of the var variable No page <c:import>, <c:url>, or locale (e.g. en_US) or an actual java.util.Locale object. <c:redirect>. variant Locale variant (as a String) to No None Attribute Description Rqd Default specify in conjunction with the locale (language and country). name Name of the query string Yes None parameter. scope Scope to set the default locale No page for. value Value of the parameter. If not No Body specified, value is taken from the tag body. <fmt:bundle> - Sets the localization context, based on the specified resource bundle, to be used within the body content of this tag. <fmt:bundle basename="resources" prefix="label."> <fmt:message key="userId"/> <fmt:bundle> Attribute Description Rqd Default basename Fully-qualified name of the Yes None base bundle without a file type (such as “.properties”). prefix String prefix to be prepended No None to the value of the message key. Note that the prefix must include all characters – a separator character (e.g. “.”) is not assumed.
  • 5. <fmt:message key="fieldRequired"> <fmt:setBundle> - Creates and stores in a scoped <fmt:param value="User ID"/> </fmt:message> <fmt:setTimeZone> - Sets the specified time zone variable, a localization context based on the specified in a named scoped variable or using the default time resource bundle. zone name if var is not specified. <fmt:setBundle Attribute Description Rqd Default basename="ApplicationResources” <fmt:setTimeZone var="mtnTime" var="strutsMessages" value="America/Denver"/> value Value used for parametric No Body Mountain Time: <fmt:formatDate scope="application"/> message format substitution. type="time" timeStyle="short" value="${now}" timeZone="${mtnTime}"/> Attribute Description Rqd Default basename Fully-qualified name of the Yes None <fmt:requestEncoding> - Instructs JSTL to use Attribute Description Rq Default base bundle without a file type a specific character encoding (see d (such as “.properties”). http://www.iana.org/assignments/character-sets) to decode request parameters. Omitting a value value String representation of a time Yes None var Name of the variable to hold No Default indicates to use automatic detection of the proper zone (such as the localization context. l10n context encoding. “America/New_York”, “GMT- 5”, or “EST”) or an actual (see java.util.TimeZone object. “Configu <fmt:requestEncoding key="ISO-8859-1"/> ration”) var Name of the variable to store No Default Attribute Description Rqd Default the time zone. time zone scope Scope of the var variable No page (see “Configur value Character encoding (e.g. “UTF- No Automatic ation”) 8”) to use. <fmt:message> - Looks up a localized message in a resource bundle. This tag can contain nested scope Scope of the var variable No page <fmt:param> tags to specify message format Formatting Actions substitution values. The resultant message is printed Actions that format and parse numbers, or stored in a scoped variable. currencies, percentages, dates and times. <fmt:formatNumber> - Formats a number, <fmt:message key="title" currency, or percentage in a locale-sensitive manner. bundle="${strutsResources}"/> <fmt:timeZone> - Sets the specified time zone The formatted value is printed or stored in a scoped to be applied to the nested body content. The variable. following example demonstrates that the time Attribute Description Rqd Default <fmt:formatNumber type="currency" zone by this action has only nested visibility. value="3.977"> key Message key to be looked up. No Body <jsp:useBean id="now" class="java.util.Date"/> <fmt:timeZone Attribute Description Rqd Default bundle Localization context (set by prio No Default configuration, <fmt:bundle>, or l10n value="America/Los_Angeles"> <fmt:setBundle>, which specifies context Pacific Time:<fmt:formatDate value Numeric value to No Body the resource bundle the message type="time" timeStyle="short" format. key is to be looked up in. value="${now}"/> </fmt:timeZone> type Specifies the type of No number <br/> var Variable to hold the message. No Local Time:<fmt:formatDate type="time" value. Valid values are: timeStyle="short" value="${now}"/> • number scope Scope of the var variable. No page • currency Attribute Description Rqd Default • percentage <fmt:param> - Supplies a parameter for message pattern Custom formatting No None value String representation of a time Yes None pattern (overrides other format substitution in a containing <fmt:message> formatting options zone (such as tag. Parameters are substituted in sequential order. “America/New_York”, “GMT-5”, including type – see or “EST”) or an actual java.text.DecimalFormat java.util.TimeZone object. )
  • 6. Attribute Description Rqd Default Attribute Description Rqd Default Attribute Description Rqd Default currencyCode Currency code (ISO No Based value Value to parse. No Body timeStyle Predefined formatting style for a No default 4217) used for on time (ignored if type=”date”) -- see formatting currencies. default type Specifies the type of No number java.text.DateFormat. Such as “USD” (US locale value. Valid values are: dollars) or “EUR” (euro). Valid values are: • number • default (2:51:16 PM) currencySymbol Currency symbol used No Based • currency • short (2:51 PM) when formatting on • percentage • medium (2:51:16 PM) currencies. Such as default • long (2:51:16 PM EDT) “$” for US dollars, or “F” locale pattern Custom parsing pattern No None for Francs. (overrides type – see • full (2:51:16 PM EDT) java.text.DecimalFormat) pattern Custom formatting style (overrides No None groupingUsed Specifies if grouping No true type, dateStyle, and separators will be used parseLocale String representation of a No Default timeStyle) – see (for example – locale (e.g. en_US) or an locale java.text.SimpleDateFormat. formatting “23890” as actual java.util.Locale “23,890”). object used for parsing. timeZone String representation of a time No Default zone or an actual time maxIntegerDigits Maximum number of No None integerOnly Specifies if only the No false java.util.TimeZone object. zone digits to print in the integer portion of the integer part of the value should be parsed. number. var Variable to store the No None <fmt:formatDate> - Formats a date and/or time in a minIntegerDigits Minimum number of No None formatted number. locale-sensitive manner. The formatted value is digits to print in the integer part of the printed or stored in a scoped variable. scope Scope of the var variable No page number. <fmt:formatDate value="${now}" pattern="yy-MMM-dd"/> maxFractionDigit Maximum number of No None s digits to print in the Formatting Dates fractional part of the Attribute Description Rqd Default number. Dates are formatted and parsed using the <fmt:formatDate> and <fmt:parseDate> minFractionDigit Minimum number of No None value Date value to format. Value No None actions which share the following common must be a java.util.Date s digits to print in the fractional part of the attributes. object. number. Attribute Description Rqd Default var Variable to store the No None var Variable to store the No None formatted number. formatted number. type Specifies the type of value. Valid No date values are: scope Scope of the var variable No page scope Scope of the var No page • time (time only) variable • date (date only) • both (date and time) <fmt:parseDate> - Parses a string representing a dateStyle Predefined formatting style for a No default date and/or time in a locale-sensitive manner. The <fmt:parseNumber> - Parses a String representing date (ignored if type=”time”) -- see parsed value is printed or stored in a scoped a number, currency, or percentage in a locale- java.text.DateFormat. variable. sensitive manner. The parsed value is printed or Valid values are: stored in a scoped variable. • default (Jul 19, 2003) <fmt:parseDate var="bday" pattern="MM/dd/yy" <fmt:parseNumber var="num" type="number" • short (7/19/03) value="05/10/63"/> pattern="#,###" value="2,447"/> • medium (Jul 19, 2003) <fmt:formatDate value="${bday}" <c:out value="${num}"/> • long (July 19, 2003) dateStyle="full"/> • full (Saturday, July 19, 2003)
  • 7. Attribute Description Rqd Default Attribute Description Rqd Default SQL Tag Library value Date/time string to parse. No None scope Scope of the variable var. No page parseLocale String representation of a No Default <%@ taglib prefix="sql" locale (e.g. en_US) or an locale uri="http://java.sun.com/jstl/sql" %> actual java.util.Locale object <sql:update> - Performs a database insert, update, used for parsing. delete or other statement (such as a DDL statement) The SQL tag library provides actions to perform that does not return any results. This action may var Variable to store the parsed No None transactional database queries and updates and include body content containing the actual update value as a java.util.Date. easily access query results. string as well as <sql:param> tags for parameter scope Scope of the var variable No page substitution. Like <sql:query>, the <sql:param> <sql:query> - Performs a database query (e.g. tags must occur after the sql statement if it is select statement). The query should be expected contained in the <sql:update> tag body. to return a ResultSet. This action may include body content containing the actual query string as <sql:update var="updateCount"> well as <sql:param> and <sql:dateParam> UPDATE users SET first_name="William" WHERE tags for parameter substitution. If the body first_name = "Bill" contains the SQL query, it must appear before </sql:update> <c:out value="${updateCount} rows updated."/> any nested parameter tags. <sql:query var="users"> Attribute Description Rqd Default SELECT * FROM users WHERE last_name = "Burdell" </sql:query> sql SQL statement to execute. No Body <c:forEach var="user"items="${users.rows}"> <c:out value="${users.user_name}"/><br/> dataSource Database connection to use. No Default </c:forEach> A javax.sql.DataSource data object, or a String source representing a JNDI resource Attribute Description Rqd Default or the parameters for java.sql.DriverManager. If sql SQL query to execute. No Body specified, this action cannot be nested in <sql:transaction>. dataSource Database connection to use. A No Default javax.sql.DataSource object, or a data String representing a JNDI var Name of the variable to store No None source resource or the parameters for the query results as a java.sql.DriverManager. If java.lang.Integer object (e.g. specified, this action cannot be SQL update statements return nested in <sql:transaction>. the number of rows affected). maxRows Maximum number of rows to No Default scope Scope of the variable var. No page return in the result. If not maxRows specified or set to -1, no limit is (see enforced. “Configur ation”) <sql:transaction> - Establishes a database transaction for <sql:query> and <sql:update> startRow Returned results include rows No 0 tags contained in this tag's body. That is, all SQL starting at this index. The first actions contained in the body of this tag will be row is row 0. treated as a single atomic transaction. The var Name of the variable to store the Yes None transaction will be committed only if all statements query results. Returned rows are succeed. If any of the contained SQL actions cause accessible via the rows property an exception, the transaction will be rolled back. of this object. Note: this action will reinstate the prior “auto commit” setting after completion.
  • 8. <sql:transaction> Attribute Description Rqd Default Attribute Description Rqd Default <sql:update sql="DELETE users WHERE user_name='bsiggelkow'"/> user Database user's username No None value Value of the parameter. Yes None <sql:update sql="INSERT INTO users Must be a java.util.Date VALUES ('billsigg','Bill','Siggy')"/> object. </sql:transaction> password Database user's password No None var Name of the variable to No Default type Indicates how the database No timestamp hold the data source. data should interpret the value. Attribute Description Rqd Default source Valid values are: name dataSource Database connection to No Default (see • date use. A data “Configur • time javax.sql.DataSource source ation”) • timestamp object, or a String (see representing a JNDI “Configu resource or the parameters ration”) scope Scope of the variable var. No page for java.sql.DriverManager. <sql:param> - Substitutes parameters into SQL isolation Transaction isolation level. No Databas prepared statement placeholders (“?”). This Valid values are: e 's action can only be nested within default • read_committed <sql:query> or <sql:update> tags. • read_uncommitted If the enclosing tag specifies the SQL in the body, • repeatable_read any <sql:param> tags must appear after the SQL. • serializable Parameters are substituted in sequential order. <c:set var="firstName">Bill</c:set> <sql:query var="users"> <sql:setDataSource> - Creates and stores in a SELECT user_name, last_name scoped variable an SQL data source. This tag FROM users WHERE first_name = ? cannot have a body. Either the dataSource or url <sql:param value="${firstName}"/> </sql:query> attribute must be specified. <sql:setDataSource var="testDB" Attribute Description Rqd Default url="jdbc:mysql://localhost/test, com.mysql.jdbc.Driver"/> <sql:query var="users" value Value of the parameter. If not No Body dataSource="${testDB}"> specified, value is taken from SELECT * FROM users the tag body. </sql:query> <sql:dateParam> - Substitutes time, date, or Attribute Description Rqd Default timestamp parameters into SQL prepared statement placeholders. This action can only be dataSource Database connection to No None use or create. A nested within <sql:query> or javax.sql.DataSource <sql:update> tags. Parameters are object, or a String representing a JNDI substituted in sequential order. resource or the parameters for <fmt:parseDate var="ww2End" java.sql.DriverManager. pattern="yyyy-MM-dd" value="1945-09-02"/> <sql:query var="postWarBabies"> driver Name of the JDBC driver No None SELECT user_name FROM user_profile class. WHERE birth_date > ? <sql:dateParam value="${ww2End}" url URL for the JDBC No None type="date"/> database connection. </sql:query>
  • 9. scope="page"/> Function Description XML Tag Library <%-- Find the user with matching ID --%> <x:set var="user" contains Returns true if string1 contains string2; select="$doc//users/user[@id=$pageScope:user false, otherwise. Non-string arguments are Id]"/> (string1, string2): converted to strings as if by the string() <%@ taglib prefix="x" function. <%-- Say Hi to the user --%> boolean uri="http://java.sun.com/jstl/xml" %> Hi <x:out select="$user/first-name"/> ! count Returns the number of nodes in the node The XML tag library supports parsing of XML set. documents, selection of XML fragments, conditional XPath Abbreviated Syntax (node-set): and iterative processing based on XML content, and number Abbr. XPath Axis Example XSLT transformations. // descendant $doc//first-name floor Returns the greatest integer less than or A common pattern for using the XML tags is as (number or equal to number or object (as converted as follows: if by the number() function). . self $doc/users/user/. object): 1. Use <x:parse> to parse XML into a scoped number variable. The XML can come from the body .. parent $doc//[first- literally, from the body via <c:import>, or from the name='George']/../last- last(): Returns the number of nodes in the context name value attribute which may refer to any XML node. source. number @ attribute $doc//user[@id="997"]/firs <x:parse var="varName" ...> t-name local-name Returns the part of the element name after the colon (:) when namespaces are used. If 2. Use the scoped variable from <x:parse> to specify child $doc/users/user[last- (node-set): node set is not specified the function is the XML document to use in XPath expressions. (blank) name='Burdell'] string applied to the context node. <x:out select="$varName/XPath expression"/> * (matches any $doc//*[local- name Returns the qualified element name, that is, namespace) name()='users']/user prefix:local-name, when namespaces are (node-set): Using JSTL Data as XPath Variables used. If node set is not specified the Scoped variables can be used in XPath expressions string function is applied to the context node. ($implicitObject:variableName) similar to how they Useful XPath Functions namespace-uri Returns the uri of the namespace of the are used in EL (${implicitObject.variableName}). If Following are some useful XPath functions that given node set. If node set is not specified the implicit object is omitted, scopes will be searched (node-set): can be used in XPath expressions. This list does the function is applied to the context node. in standard order. Note that the “.” and “[]” not include all XPath functions – just those string notations cannot be used for accessing bean deemed particularly useful when using the JSTL properties. XML tags. not Returns the logical inversion of the supplied argument. That is, if the argument is true, (boolean or The following example demonstrates the above object): false is returned; if argument is false, true is techniques. Function Description returned. boolean ceiling Returns the smallest integer greater than or <%-- Create the XML --%> equal to number or object (as converted as <x:parse var="doc"> (number or number Converts object (or the current node if if by the number() function). object is not specifed) to a number. True is <users> object): (object): <user id="997"> converted to 1, and false to 0. If the number <first-name>George</first-name> number number cannot be converted NaN is returned. <last-name>Burdell</last-name> </user> concat Concatenates the arguments in order from <user id="998"> position(): Returns the position of the current node in left to right. Non-string arguments are the current context node set. The first <first-name>Joseph</first-name> (string1, string 2, converted to strings as if by the string() number <last-name>Blough</last-name> ...): position is 1. function. </user> </users> string </x:parse> <%-- Define a variable holding user ID --%> <c:set var="userId" value="${user.id}"
  • 10. Function Description <title>feed title</title> expression as a string. <link>source url</link> <description>feed desc</description> RSS Channel: round Returns the closest integer to number or <x:out select="$news//channel/title"/> <item> object (as converted as if by the number() (number or <title>article title</title> function). If two integers are equally close, object): <link>article url</link> the value closer to positive infinity is <description>article number chosen. (e.g. round(3.5) returns 4, round(- Attribute Description Rqd Default desc</description> 3.5) returns -3). </item> <item> select XPath expression. Yes None starts-with Returns true if string1 starts with string2; <title>article title</title> false, otherwise. <link>article url</link> (string1,string2): escapeXml true to escape special No true <description>article boolean desc</description> characters </item> </channel> string Converts the object, or the current node if </rss> object is not specifed, to a string. (object): Generally, this function will output the body <x:set> - Saves the result of the select XPath string of the elements (e.g. string(<a>b</a>) <x:parse> - Parses XML content, provided by the expression to a scoped variable. Returned value returns “b”). may be a node set (XML fragment), boolean, string, value attribute or the tags body, into a scoped variable(s). This variable can then be used for or number. string-length Number of characters in the string. If object is not a string it is first converted to a string subsequent processing by other XML tags. (object): <x:set select="$news//channel/item" as if by the string() function. var="newsItems"/> <c:import var="rss" number url="http://servlet.java.sun.com/syndication /rss_java_highlights-PARTNER-20.xml"/> substring Returns a substring of string starting at <x:parse var="news" xml="${rss}"/> index and continuing for length characters. Attribute Description Rqd Default (string, index, The first character is position 1, not length): position 0 as in Java and JavaScript. select XPath expression. No None string Attribute Description Rqd Default var Name of variable to store No None substring-after Returns the substring in string1 following the doc (JSTL 1.1) Text of the document No Body results. The variable type is first of occurrence of string2 in string1. to a parse as a String or Reader. equal to whatever is returned (string1, string2): by the select expression. string xml (JSTL 1.0 – deprecated in 1.1) No Body Same as doc attribute. • Boolean – substring-before Returns the substring in string1 preceding java.lang.Boolean the first of occurrence of string2 in string1. systemId URI of the original document, No None (string1, string2): • Number – string used for entity resolution. java.lang.Number filter XML filter to apply. Value should No None • Node or node set – sum Converts each node in the set to a number, be of type org.xml.sax.XMLFilter. implementation- as if by the number() function, adds up the (node-set): dependent type numbers and returns the sum. number var Name of the variable to store the Yes None results – may be an scope Scope of variable var. No page implementation-specific object. General XML Actions scope Scope of the variable var. No page Flow Control Actions Actions for parsing XML, outputting to the page, and varDom Name of the variable to store the Yes None Actions for processing markup based on logical and selecting XML fragments. The examples that follow result – stored as a DOM object. iterative conditions. demonstrate use of the XML tags for processing Rich Site Summary (RSS) feeds. RSS has more or less scopeDom Scope to store variable varDOM No page the following format: in. <x:if> - Processes the body if select XPath evaluates to true (following the rules of the boolean() XPath <?xml version="1.0"?> function). <rss version="0.91"> <channel> <x:out> - Prints the result of the XPath <x:if select=
  • 11. "$news//item[contains(description,'Linux')]"> <x:choose> -- Processes the body of the first Attribute Description Rqd Default Linux is in the news today! enclosed <x:when> tag where the select XPath </x:if> expression evaluates to true. If none match then var Name of variable to hold No None the body of the <x:otherwise> tag (if present) the current item. This variable has only nested Attribute Description Rqd Default is processed. visibility. select Test condition as an XPath Yes None <x:choose> <x:when select="$news//item"> Transformation Actions expression. Body content is processed if the condition is We've got news :) </x:when> JSTL provides an <x:transform> tag for true. <x:otherwise> performing XSLT transformations. The <x:param> var Name of variable to store test No None No news today :( tag can be nested in the <x:transform> tag to set </x:otherwise> condition's result </x:choose> a parameter that is used in the stylesheet. scope Scope of variable No page <x:transform> - Conducts an XSLT transformation The choose tag accepts no attributes and can on source XML. The source XML is provided by the only contain <x:when> tag(s) and an optional doc attribute or the body of the tag. The XSL <x:otherwise> tag. stylesheet is specified by the xslt attribute. While in most cases, the stylesheet will be set up by back-end <x:when> - Represents an alternative in an code – it is possible to define the stylesheet inline <x:choose> tag. Processes the body if the and make it available with <c:set> as in the select expression evaluates to true and no other following example: previous <x:when> tags in the <x:choose> matched. <c:set var="xsl"> <?xml version="1.0" encoding="UTF-8"?> Attribute Description Rqd Default <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform select Test condition as an XPath Yes None "> expression. <xsl:template match="item"> <li> <xsl:value-of select="title"/> </li> </xsl:template> <x:otherwise> - Processes the body if no other <xsl:template match="/"> previous <x:when> condition in the <ol> <x:choose> matched. This tag accepts no <xsl:apply-templates select="//item"/> attributes and, if present, must be the last tag in </ol> <x:choose> body. </xsl:template> </xsl:stylesheet> <x:forEach> - Repeats the nested body content </c:set> over a node set determined by an XPath <x:transform xml="${news}" expression, setting the context node to each xslt="${xsl}"/> element in the iteration. <x:forEach select="$news//item"> Attribute Description Rqd Default <a href='<x:out select="link"/>'> <x:out select="title"/></a><br/> </x:forEach> doc (JSTL 1.1) Source XML No Body document for the transformation. Value can be a String, Reader, Attribute Description Rqd Default javax.xml.transform.Source , org.w3c.dom.Document, select Name of variable to hold No None or any value exported the current item. This <x:parse> or <x:set>. If the variable has only nested value comes from <x:set> it visibility. cannot be a partial document.