JSP Formatting JSTL

JSP Formatting JSTL

  • The JSP Standard Tag Library (JSTL) adds essential features to JSP that enable JSP programming without the need for embedded Java code.
  • It is a collection of standard JSP tags that perform several common tasks.
  • This frees us from having to develop custom tags for these tasks, or from using a mix of tags from several organizations to do our work.
  • The formatting JSTL provides support for internationalization which is to enable the formatting of data (dates, numbers, time) in different locales.
  • Before using the formatting JSTL, the following directive needs to be added to the JSP page:
  • <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

Here is a summary of all formatting JSTL tags

  • Tag Description
    bundle Loads a resource bundle.
    formatDate Formats date and time.
    formatNumber Formats a numeric value as a number, currency, or a percent
    message Outputs a localized string.
    param Supplies an argument to a containing message tag.
    parseDate Parses a string representation of date/time.
    parseNumber Parses a string representation of a number, currency, or a percent.
    requestEncoding Sets the request character encoding.
    setBundle Loads a resource bundle and stores it in a named variable.
    setLocale Stores the locale in a named variable.
    setTimeZone Stores the time zone in a named variable.
    timeZone Specifies the time zone for formatting or parsing date/time data

    You will find an example that includes several JSTL formatting tags here.

The following is a detail presentation of each formatting JSTL tag

  • bundle

    The <c:bundle> tag loads a resource bundle for the body of the tag. The body usually contains a nested <fmt:message> tag to display a localized message.
    The syntax is as follows:
    <fmt:bundle basename="resource bundle basename"
                [prefix="message key prefix"]>
                JSP body
    </fmt:bundle>
    Attribute(s):
    Attribute Required Description
    basename yes The basename of the resource bundle.
    prefix no The prefix to be applied to the message key for any nested <fmt:message> tags.
    Example:
    <fmt:bundle basename="mess.messages">
      <fmt:message key="key.welcome"/><br/>
      <fmt:message key="key.description"/>
    </fmt:bundle>
  • formatDate

    The <fmt:formatDate> action provides flexible, time zone–aware formatting of java.
    The syntax is as follows:
    <fmt:formatDate value="string representation"
                    [type="date|time|both"]
                    [dateStyle="formatting style"]
                    [timeStyle="formatting style"]
                    [pattern="formatting pattern"]
                    [timeZone="timezone"]
                    [var="variable name"]
                    [scope="page|request|session|application"] />

    The formatDate tag formats date and time data according to a specified style and pattern.

    <fmt:formatDate> tag attribute(s):
    Attribute Required Description
    value Yes The date/time to be formatted.
    type No (default=date) Specifies if the data to be formatted contains a date, time, or both.
    dateStyle No Formatting style used for dates. The valid style values are defined by the java.text.DateFormat class. (i.e., default, short, medium, long, and full). Valid only if the type attribute is date or both.
    timeStyle No Formatting style used for time values. The valid style values are defined by the java.text.DateFormat class (i.e., default, short, medium, long, and full). Valid only if the type attribute is time or both.
    pattern No Custom formatting pattern for dates and times. The patterns are specified by the java.text.SimpleDateFormat class. See table below.
    timeZone No Time zone to be used for the time information.
    var No Variable containing the parsed date/time value. This variable is of type java.util.Date
    scope No (default=page) Scope of the var variable. This optional attribute can be page, request, session, or application.
    Pattern letters, date/time component, presentation, and examples.:
    Letter Date or Time Component Presentation Examples
    G Era designator Text AD
    y Year Year 1996; 96
    Y Week year Year 2009; 09
    M Month in year Month July; Jul; 07
    w Week in year Number 27
    W Week in month Number 2
    D Day in year Number 189
    d Day in month Number 10
    F Day of week in month Number 2
    E Day name in week Text Tuesday; Tue
    u Day number of week (1 = Monday, ..., 7 = Sunday) Number 1
    a Am/pm marker Text PM
    H Hour in day (0-23) Number 0
    k Hour in day (1-24) Number 24
    K Hour in am/pm (0-11) Number 0
    h Hour in am/pm (1-12) Number 12
    m Minute in hour Number 30
    s Second in minute Number 55
    S Millisecond Number 978
    z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
    Z Time zone RFC 822 time zone -0800
    X Time zone ISO 8601 time zone -08; -0800; -08:00
    Example:
     <c:set var="today" value="<%=new java.util.Date()%>" />
     <p>Time: <fmt:formatDate type="time" value="${today}"  /></p>
     <p>Date: <fmt:formatDate type="date" value="${today}"  /></p>
     <p>Date & Time: <fmt:formatDate type="both" value="${today}" /></p> 
  • formatNumber

    The <fmt:formatNumber> tag is flexible and capable of formatting a numeric value in a locale-sensitive or custom format as a number, currency, or percent.
    The syntax is as follows:
    <fmt:formatNumber [value="numeric value"]
      [type="number|currency|percent"]
      [pattern="pattern"]
      [currencyCode="currency code"]
      [currencySymbol="currency symbol"]
      [groupingUsed="true|false"]
      [maxIntegerDigits="max integer digits"]
      [minIntegerDigits="min integer digits"]
      [maxFranctionDigits="max fractional digits"]
      [minFractionDigits="min fractional digits"]
      [var="variable name"]
      [scope="page|request|session|application"]>
      JSP body 
    </fmt:formatNumber>
    Attribute(s):
    Attribute Required Description
    value No The numeric value to be formatted.
    type No (default=number) Specifies if the numeric value is to be formatted as a number, currency, or a percent.
    pattern No Custom formatting pattern. The patterns are as specified by the java.text.DecimalFormat class. See table below.
    currencyCode No Currency codes as defined by the ISO 4217 standard. This is applicable only when the type attribute is currency.
    currencySymbol No This is applicable only when the type attribute is currency. It is used to override the defaults.
    groupingUsed No (default=true) Specifies if the output format contains any grouping separators. Will be commas, periods or spaces which depends on the local language.
    maxIntegerDigits No Maximum number of digits in the integer portion of the formatted output.
    minIntegerDigits No Minimum number of digits in the integer portion of the formatted output.
    maxFractionDigits No Maximum number of digits in the fractional portion of the formatted output.
    minFractionDigits No Minimum number of digits in the fractional portion of the formatted output.
    var No Variable that contains the formatted numeric value as a string.
    scope No (default=page) Scope of the var variable. This optional attribute can be page, request, session, or application.
    Custom pattern symbol, location, localized, and meaning:
    Symbol Location Localized Meaning
    0 Number Yes Digi
    # Number Yes Digit, zero shows as absent
    . Number Yes Decimal separator or monetary decimal separator
    - Number Yes Minus sign
    , Number Yes Grouping separator
    E Number Yes Separates mantissa and exponent in scientific notation. Need not be quoted in prefix or suffix.
    ; Subpattern boundary Yes Separates positive and negative subpatterns
    % Prefix or suffix Yes Multiply by 100 and show as percentage
    \u2030 Prefix or suffix Yes Multiply by 1000 and show as per mille value
    ¤ (\u00A4) Prefix or suffix No Currency sign, replaced by currency symbol. If doubled, replaced by international currency symbol. If present in a pattern, the monetary decimal separator is used instead of the decimal separator.
    ' Prefix or suffix No Used to quote special characters in a prefix or suffix, for example, "'#'#" formats 123 to "#123". To create a single quote itself, use two in a row: "# o''clock".
    Example:
    <c:set var="cost" value="14250.64500" />
    <p> Min. fraction digits 3: 
    <fmt:formatNumber type="number"  
                      minFractionDigits="3" value="${cost}" /></p>
    <p>Percent with max. integer digits 2: 
    <fmt:formatNumber type="percent"
                      maxIntegerDigits="2" value="${cost}"  /></p>
    <p>Using pattern: 
    <fmt:formatNumber type="number" 
                      pattern="#.###E0" value="${cost}"  /></p>
    <p>Using var and max. integer digits 3 : 
    <fmt:formatNumber type="number" maxIntegerDigits="3"  
                      value="${cost}" var="value" scope="page" />
    ${value}</p>
  • message

    The <fmt:message> tag displays a localized message. The body can contain a nested fmt:param tag to pass parameterized values to the message.
    The syntax is as follows:
    <fmt:message [key="message key"]
      [bundle="localization bundle where key is looked up"]
      [var="variable that stores localized message"]
      [scope="page|request|session|application"]>
      JSP body 
    </fmt:message>
    Attribute(s):
    Attribute Required Description
    key No The message key corresponding to the message.
    bundle No The localization context in which the message key is looked up.
    var No The variable that stores the localized message.
    scope No (default=page) Scope of the var variable. This is an optional attribute and can be page, request, session, or application.
    Example:
    <fmt:bundle basename="mess.messages">
      <fmt:message key="key.welcome"/><br/>
      <fmt:message key="key.description"/>
    </fmt:bundle>
  • param

    The <fmt:param> tag Supplies an argument to a containing message tag.
    The syntax is as follows:
    <fmt:param [value="argument value"] >
      JSP body 
    </fmt:param>
    Attribute(s):
    Attribute Required Description
    value No Value used for parametric replacement in the fmt:message tag.
    Example:
    <!--key.paramwelcome: {0} are welcome to JSTL formatting -->
    <fmt:setBundle basename="mess.messages" var="bundle" />
    <c:set var="user" value="You"/>
    <fmt:message key="key.paramwelcome" bundle="${bundle}">
      <fmt:param value="${user}" />
    </fmt:message>  
  • parseDate

    The <fmt:parseDate> tag parses string representations of date and time specified either via an attribute or in its body content.
    The syntax is as follows:
    <fmt:parseDate [value="string representation"]
      [type="date|time|both"]
      [dateStyle="formatting style"]
      [timeStyle="formatting style"]
      [pattern="formatting pattern"]
      [timeZone="timezone"]
      [parseLocale="locale"]
      [var="variable name"]
      [scope="page|request|session|application"]>
      JSP body
    </fmt:parseDate> 
    Attribute(s):
    Attribute Required Description
    value No (default=body content) The string to be parsed.
    type No (default=date) Specifies if the value is to be parsed; contains a date, time, or both.
    dateStyle No Formatting style used for dates. The valid style values are defined by the java.text.DateFormat class. (i.e., default, short, medium, long, and full). Valid only if the type attribute is date or both.
    timeStyle No Formatting style used for time values. The valid style values are defined by the java.text.DateFormat class (i.e., default, short, medium, long, and full). Valid only if the type attribute is time or both.
    pattern No Custom formatting pattern. The patterns are as specified by the java.text.DecimalFormat class. See table below.
    timeZone No Time zone to be used for the time information.
    parseLocale No Locale to be used for formatting date and time values.
    var No Variable that contains the parsed date/time value. This variable is of type java.util.Date.
    scope No (default=page) Scope of the var variable. This is an optional attribute and can be page, request, session, or application
    Custom pattern symbol, location, localized, and meaning:
    Symbol Location Localized Meaning
    0 Number Yes Digi
    # Number Yes Digit, zero shows as absent
    . Number Yes Decimal separator or monetary decimal separator
    - Number Yes Minus sign
    , Number Yes Grouping separator
    E Number Yes Separates mantissa and exponent in scientific notation. Need not be quoted in prefix or suffix.
    ; Subpattern boundary Yes Separates positive and negative subpatterns
    % Prefix or suffix Yes Multiply by 100 and show as percentage
    \u2030 Prefix or suffix Yes Multiply by 1000 and show as per mille value
    ¤ (\u00A4) Prefix or suffix No Currency sign, replaced by currency symbol. If doubled, replaced by international currency symbol. If present in a pattern, the monetary decimal separator is used instead of the decimal separator.
    ' Prefix or suffix No Used to quote special characters in a prefix or suffix, for example, "'#'#" formats 123 to "#123". To create a single quote itself, use two in a row: "# o''clock".
    Example:
    <c:set var="today" value="28-03-2017" />
    <p>Parsing date, ${today}, to: 
    <fmt:parseDate pattern="dd-MM-yyyy" var="thedate" value="${today}" />
    <fmt:formatDate pattern="${datepattern}" value="${thedate}" /></p>
  • parseNumber

    The <fmt:parseNumber> tag parses a string representation of a number, currency, or a percent specified either via an attribute or in its body content.
    The syntax is as follows:
    <fmt:parseNumber [value="string representation"]
      [type="number|currency|percent"]
      [pattern="pattern"]
      [parseLocale="locale"]
      [integerOnly="true|false"]
      [var="variable name"]
      [scope="page|request|session|application"]>
      JSP body content
    </fmt:parseNumber>
    Attribute(s):
    Attribute Required Description
    value No (default=body content) The string to be parsed.
    type No (default=number) Specifies whether the value is to be parsed as a number, currency, or a percent.
    pattern No Custom formatting pattern. The patterns are as specified by the java.text.DecimalFormat class. See table below.
    parseLocale No Locale to be used for parsing.
    integerOnly No (default=false) Specifies that only the integer part needs to be parsed.
    var No (default=print to page) Variable that contains the parsed numeric value.
    scope No (default=page) Scope of the var variable. This is an optional attribute and can be page, request, session, or application.
    Custom pattern symbol, location, localized, and meaning:
    Symbol Location Localized Meaning
    0 Number Yes Digi
    # Number Yes Digit, zero shows as absent
    . Number Yes Decimal separator or monetary decimal separator
    - Number Yes Minus sign
    , Number Yes Grouping separator
    E Number Yes Separates mantissa and exponent in scientific notation. Need not be quoted in prefix or suffix.
    ; Subpattern boundary Yes Separates positive and negative subpatterns
    % Prefix or suffix Yes Multiply by 100 and show as percentage
    \u2030 Prefix or suffix Yes Multiply by 1000 and show as per mille value
    ¤ (\u00A4) Prefix or suffix No Currency sign, replaced by currency symbol. If doubled, replaced by international currency symbol. If present in a pattern, the monetary decimal separator is used instead of the decimal separator.
    ' Prefix or suffix No Used to quote special characters in a prefix or suffix, for example, "'#'#" formats 123 to "#123". To create a single quote itself, use two in a row: "# o''clock".
    Example:
    <c:set var="budget" value="15022.770" />
    <fmt:parseNumber var="parsedNumber" type="number" value="${budget}" />
    <p>Parsed budget using value : <strong><c:out value="${parsedNumber}" /></strong></p>
    <fmt:parseNumber var="parsedNumber" integerOnly="true" type="number" >33022.660</fmt:parseNumber>
    <p>Parsed budget using body : <strong><c:out value="${parsedNumber}" /></strong></p>
  • requestEncoding

    The <fmt:requestEncoding> tag is used to specify the character encoding of the request an used to decode the incoming forms data entered by the user. Use this if the encoding used is different from the ISO-8859-1.
    The syntax is as follows:
    <fmt:requestEncoding [value="character encoding name"] />
    Attribute(s):
    Attribute Required Description
    value No The name of the character encoding for the request. Examples of request encodings include UTF-8, ISO-8859-1, and so on. A complete list of encoding codes can be found here.
    Example:
    <fmt:requestEncoding value="UTF-8"/>
  • setBundle

    The <fmt:setBundle> loads a resource bundle for a specified scope.
    The syntax is as follows:
    <fmt:setBundle basename="resource bundle basename"
    [var="Localization context variable"]
    [scope="page|request|session|application"] />
    Attribute(s):
    Attribute Required Description
    basename Yes The basename of the resource bundle.
    var No The name of the localization context variable.
    scope No (default=page) Scope of the var variable. This is an optional attribute and can be page, request, session, or application.
    Example:
    <fmt:setBundle basename = "mess.messages" var = "lang"/>
  • setLocale

    The <fmt:setLocale> tag sets the locale value in the locale configuration variable.
    The syntax is as follows:
    <fmt:setLocale value="Locale string"
    [variant="Vendor or browser specific variant"]
    [scope="page|request|session|application"]
    />
    Attribute(s):
    Attribute Required Description
    value Yes The name of the character encoding for the request. Examples of request encodings include UTF-8, ISO-8859-1, and so on. A complete list of encoding codes can be found here.
    variant No This is a vendor/browser-specific value. Examples of the variants are WIN (for Windows), MAC (for Macintosh), and POSIX (for POSIX).
    scope No (default=page) Scope of the variable specified in the var attribute. This can be page, request, session, or application.
    Example:
    <fmt:setLocale value = "es_ES"/>
  • setTimeZone

    The <fmt:setTimeZone> tag sets the time zone value in the time zone configuration variable for a specified scope.
    The syntax is as follows:
    <fmt:setTimeZone value="Time Zone string"
      [var="time zone variable"]
      [scope="page|request|session|application"]
      />
    Attribute(s):
    Attribute Required Description
    value Yes The name of the time zone. This can be specified as a custom time zone ID ("GMT+8") or as a time zone supported by Java ("America/Los_Angeles").
    var No Name of the time zone variable.
    scope No (default=page) Scope of the variable specified in the var attribute. This can be page, request, session, or application.
    Example:
    <fmt:setTimeZone value="GMT-2"/>
  • timeZone

    The <fmt:timeZone> tag specifies the time zone for any time formatting in its body content.
    The syntax is as follows:
    <fmt:timeZone value="time zone">
      JSP body 
    </fmt:timeZone>
    Attribute(s):
    Attribute Required Description
    value Yes The time zone value for the body content. This can be specified as a custom time zone ID ("GMT+8") or as a time zone supported by Java ("America/Los_Angeles").
    Example:
    <c:set var="today" value="<%=new java.util.Date()%>" />
    <fmt:timeZone value="GMT-6">
       <fmt:formatDate value="${today}" type="both" />
    </fmt:timeZone>

Example of using Formatting JSTL element.

In the example we use Netbeans IDE and Glassfish Server.

You can download this example here (needed tools can be found in the right menu on this page).

If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is FormattingJSTL).

In this example, we will add two files, header.jsp and footer.jsp.

  • It is customary to place all include files, which are used several times in the WEB-INF folder. Some would also like the include files should have the extension .jspf, but this is not a requirement.
    Here is the file we want to include at the top of all pages:
    <h1>JSTL Formatting demo</h1>
    <hr>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Header.jsp and folder should be WEB-INF).

    Here is the file we want to include at the bottom of all pages:
    <hr>
    Current date: <%= (new java.util.Date()).toString() %>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is Footer.jsp and folder should be WEB-INF).

We need a JSP file(s) to demonstrate the JSTL fomatting tags.

  • Here is the JSP file (ShowJSTL.jsp):
    <%@ page contentType="text/html" pageEncoding="UTF-8"  import="java.util.*" %>
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
    <!DOCTYPE html >
    <html>
      <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>JSTL Formatting Demo</title>
      </head>
      <body>
        <div style="width:500px; margin-left: 40px; border: 1px solid black; padding: 10px;">
        <c:import url="/WEB-INF/header.jsp" />
        <h2><fmt:bundle> Demo</h2>
        <h3>Without prefix:</h3>
        <fmt:bundle basename="mess.messages">
          <fmt:message key="key.welcome"/><br/>
          <fmt:message key="key.description"/>
        </fmt:bundle>
        <br/>
        <h3>With prefix:</h3>
        <fmt:bundle basename="mess.messages" prefix="key." >
          <fmt:message key="welcome"/><br/>
          <fmt:message key="description"/>
        </fmt:bundle>
        <h2><fmt:setBundle> Demo</h2>
        <fmt:setBundle basename="mess.messages" var="bundle" />
        <fmt:message key="key.welcome" bundle="${bundle}"/><br/>
        <c:set var="user" value="you"/>
        <fmt:message key="key.description" bundle="${bundle}" />
    
        <h2><fmt:formatNumber> Demo</h2>
        <c:set var="cost" value="14250.64500" />
        <p> Min. fraction digits 3: <strong><fmt:formatNumber type="number"  minFractionDigits="3" value="${cost}" /></strong> </p>
        <p><fmt:setLocale value="en_GB"/>
          United Kingdom currency: <strong><fmt:formatNumber type="currency" value="${cost}"   /></strong></p>
        <p><fmt:setLocale value="it_IT"/>
          Italy currency: <strong><fmt:formatNumber type="currency" value="${cost}" /></strong></p>
        <p><fmt:setLocale value="no_NO"/>
          Norway currency: <strong><fmt:formatNumber type="currency" value="${cost}" /></strong>
          <fmt:setLocale value="en_GB"/></p>
        <p>Percent with max. integer digits 2: <strong><fmt:formatNumber type="percent" maxIntegerDigits="2" value="${cost}"  /></strong></p>
        <p><c:set var="pattern" value="#.###E0" />
          Using pattern ${pattern}: <strong><fmt:formatNumber type="number" pattern="${pattern}" value="${cost}"  /></strong></p>
        <p>
          Using var and max. integer digits 3 : 
          <fmt:formatNumber type="number" maxIntegerDigits="3"  value="${cost}" var="value" scope="page" />
          <strong>${value}</strong></p>
    
        <h2><fmt:formatDate> Demo</h2>
        <c:set var="today" value="<%=new java.util.Date()%>" />
        <p>Time: <strong><fmt:formatDate type="time" value="${today}"  /></strong></p>
        <p>Date: <strong><fmt:formatDate type="date" value="${today}"  /></strong></p>
        <p>Date & Time: <strong><fmt:formatDate type="both" value="${today}" /></strong></p>    
        <p><c:set var="datepattern" value="dd.MMM yyyy" />
          Date (${datepattern}):
          <strong>
            <fmt:formatDate pattern="${datepattern}" value="${today}" />
          </strong></p>    
        <p><c:set var="timepattern" value="HH:mm:ss" />
          Time (${timepattern}):
          <strong>
            <fmt:formatDate pattern="${timepattern}" value="${today}" />
          </strong></p>     
        <p><c:set var="weekpattern" value="ww-yyyy" />
          Week of year (${weekpattern}):
          <strong>
            <fmt:formatDate pattern="${weekpattern}" value="${today}" />
          </strong></p>   
        <!--key.paramwelcome: {0} are welcome to JSTL formatting -->
        <h2><fmt:param> Demo</h2>
        <fmt:setBundle basename="mess.messages" var="bundle" />
        <c:set var="user" value="You"/>
        <fmt:message key="key.paramwelcome" bundle="${bundle}">
          <fmt:param value="${user}" />
        </fmt:message>   
        <br/>
        <c:set var="user" value="you"/>
        <fmt:message key="key.paramdescription" bundle="${bundle}" >
          <fmt:param value="${user}" />
        </fmt:message> 
    
        <h2><fmt:parseDate> Demo</h2>
        <c:set var="today" value="28-03-2017" />
        <p>Parsing date, ${today}, to: <fmt:parseDate pattern="dd-MM-yyyy" var="thedate" value="${today}" />
          <strong><fmt:formatDate pattern="${datepattern}" value="${thedate}" /></strong></p>   
        <p>Parsing date in body to: <fmt:parseDate pattern="dd-MM-yyyy" var="thedate">2-10-2016</fmt:parseDate>
          <strong><fmt:formatDate pattern="${datepattern}" value="${thedate}" /></strong></p>     
          <c:set var="currTime" value="12 23 40" />
        <p>Parsing time, ${currTime}, to: <fmt:parseDate pattern="HH mm ss" var="thetime" value="${currTime}" />
          <strong><fmt:formatDate pattern="${timepattern}" value="${thetime}" /></strong></p>  
    
        <h2><fmt:parseNumber> Demo</h2>
        <c:set var="myNumber" value="689.892" />
        <c:set var="pattern" value="###.###" />
        <fmt:parseNumber var="parsedNumber" type="number" value="${myNumber}" pattern="${pattern}"  />
        <p>My number is: <strong><c:out value="${parsedNumber}" /></strong></p>
        <fmt:parseNumber var="parsedNumber" type="number" value="${myNumber}" integerOnly="true" />
        <p>My number is (as integer): <strong><c:out value="${parsedNumber}" /></strong></p>
        <c:set var="budget" value="15022.770" />
        <fmt:parseNumber var="parsedNumber" type="number" value="${budget}" />
        <p>Parsed budget using value : <strong><c:out value="${parsedNumber}" /></strong></p>
        <fmt:parseNumber var="parsedNumber" integerOnly="true" type="number" >33022.660</fmt:parseNumber>
        <p>Parsed budget using body : <strong><c:out value="${parsedNumber}" /></strong></p>
    
        <h2><fmt:requestEncoding> Demo</h2>
        <fmt:requestEncoding value = "UTF-8" />
        <fmt:setBundle basename = "mess.messages" var = "lang"/>
        <strong><fmt:message key = "key.paramwelcome" bundle = "${lang}">
            <fmt:param value="${param.loginname}" />
          </fmt:message></strong><br/>
        <strong><fmt:message key = "key.paramdescription" bundle = "${lang}">
            <fmt:param value="${param.loginname}" />
          </fmt:message></strong><br/>  
    
        <h2><fmt:setBundle> Demo</h2>
        <p>Bundle basename is : <strong>mess.messages</strong></p>
        <fmt:setBundle basename = "mess.messages" var = "lang"/>
        <strong><fmt:message key = "key.namepassword" bundle = "${lang}">
            <fmt:param value="${param.loginname}" />
            <fmt:param value="${param.password}" />
          </fmt:message></strong><br/>
    
        <h2><fmt:setLocale> Demo</h2>
        <fmt:setLocale value = "es_ES"/>
        <fmt:setBundle basename = "mess.messages" var = "lang"/>
        <strong><fmt:message key = "key.paramwelcome" bundle = "${lang}">
            <fmt:param value="${param.loginname}" />
          </fmt:message></strong><br/>
        <strong><fmt:message key = "key.paramdescription" bundle = "${lang}">
            <fmt:param value="${param.loginname}" />
          </fmt:message></strong><br/>
          <fmt:setLocale value = "en"/>
          <fmt:setBundle basename = "mess.messages" var = "lang"/>
        <strong><fmt:message key = "key.paramwelcome" bundle = "${lang}">
            <fmt:param value="${param.loginname}" />
          </fmt:message></strong><br/>
        <strong><fmt:message key = "key.paramdescription" bundle = "${lang}">
            <fmt:param value="${param.loginname}" />
          </fmt:message></strong><br/>  
    
        <h2><fmt:setTimeZone> Demo</h2>
        <c:set var="today" value="<%=new java.util.Date()%>" />
    
        <p>Time now: <strong><fmt:formatDate type="time" value="${today}"  /></strong></p>
        <p>Time GMT-2: <strong> <fmt:setTimeZone value="GMT-6"/>
            <fmt:formatDate type="time" value="${today}"  /></strong>
        </p>  
        <!-- set back the default TimeZone -->
        <fmt:setTimeZone value="<%=Calendar.getInstance().getTimeZone()%>" />
    
        <h2><fmt:timeZone> Demo</h2>
        <c:set var="today" value="<%=new java.util.Date()%>" />
        <p>Time now: <strong><fmt:formatDate type="time" value="${today}"  /></strong></p>
        <p>Time GMT-2: 
          <strong><fmt:timeZone value="GMT-6">
              <fmt:formatDate type="time" value="${today}"  />
            </fmt:timeZone>
          </strong>
        </p>
        <c:import url="/WEB-INF/footer.jsp" />
    
    </div>
    
    
      </body>
    </html>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is ShowJSTL).

Startup jsp file.

  • Because the jsp file above expects a few request parameters, we start the application with another jsp file (index.jsp).
    Here is the main JSP file (index.jsp):
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
      <head>
        <title></title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
      </head>
      <body onload="document.getElementById('ShowJSTL').submit();">
        <form id="ShowJSTL" action="ShowJSTL.jsp"  method="POST">
          <fieldset >
            <input name="loginname" value="Obama" type="text" />
            <input name="password" value="amabo" type="password" />
          </fieldset>
        </form>
      </body>
    </html>

    For those who participate in the review: create a JSP file in Netbeans and replace generated code for the JSP with that shown above (the JSP file name is index).

Properties files.

  • Because the jsp files above uses properties we need to create properties files.
    Here is the properties file (mess.messages.properties):
    key.welcome=Welcome to JSTL formatting
    key.description=This provides an opportunity to learn JSTL
    key.paramwelcome={0} is welcome to JSTL formatting
    key.paramdescription=This provides {0} an opportunity to learn JSTL
    key.namepassword=Welcome {0}, your password is {1}.

    For those who participate in the review: create a Properties file in Netbeans and replace generated code for the JSP with that shown above (the properties file name is message).

    We need another properties file, mess.messages_es_ES, for the JSTL formatting setLocale demo.

    Here is the properties file (mess.messages_es_ES.properties):
    key.welcome=Bienvenido al formato JSTL
    key.description=Esto proporciona una oportunidad para aprender JSTL
    key.paramwelcome={0} es bienvenido al formato JSTL
    key.paramdescription=Esto proporciona a {0} una oportunidad de aprender JSTL

    For those who participate in the review: create a Properties file in Netbeans and replace generated code for the JSP with that shown above (the properties file name is message_es_ES).

Creating Deployment descriptor.

  • To run this JSP you have to deploy it to a web-server or a Application server. To deploy means to install the JSP with some instruction to a such server.
  • The instructions are mainly defined to be deployment descriptors. The standard part of the deployment descriptor should be in an XML-file with the name web.xml.

    You may need to create a Deployment descriptor file, web.xml in Netbeans.

  • The contents of the web.xml file should look like this:
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
     http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
      <servlet>
        <servlet-name>FormattingJSP</servlet-name>
        <jsp-file>/index.jsp</jsp-file>
      </servlet>
      <servlet-mapping>
        <servlet-name>FormattingJSP</servlet-name>
        <url-pattern>/FormattingJSP</url-pattern>
      </servlet-mapping>
      <session-config>
        <session-timeout>
          30
        </session-timeout>
      </session-config>
      <welcome-file-list>
        <welcome-file>FormattingJSP</welcome-file>
      </welcome-file-list>
    </web-app>
  • This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app. Every ting inside the last tag is to tell the server about our application, which in this case is a JSP file.
  • With a servlet tag we give the JSP file a servlet name, which is used in the servlet-mapping tag to specify a url for the JSP file.
  • In this way we can have many urls for the same JSP file.
  • If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
  • The welcome-file tag specifies the startup for our application, which in this case and our application is the welcome file with url FormattingJSP. Reorganize the welcome-file-list to what is shown above.

Creating Web-server Deployment descriptor.

  • The context-root (in example /FormattingJSTL) for the application will in most cases be specified by a server vendor deployment descriptor.

    For those who participate in the review: create a Glassfish deployment descriptor in Netbeans.

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, 
    Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN" 
    "http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd">
    <sun-web-app error-url="">
      <context-root>/FormattingJSTL</context-root>
      <class-loader delegate="true"/>
      <jsp-config>
        <property name="keepgenerated" value="true">
          <description>
            Keep a copy of the generated servlet class' java code.
          </description>
        </property>
      </jsp-config>
    </sun-web-app>

Run the application.

  • For those who participate in the review: right click the Web-project and select Run.
  • This results in that the application will be deployed to the server and started.
  • The browser will display:
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.