[ Team LiB ] Previous Section Next Section

The Format Tag Library

Java's text formatting and internationalization APIs are useful in making Web sites for users in many countries. You may need to display times, dates, and numbers in a different format, or you may need to display messages in different languages, depending on a browser's language preferences. JSTL includes a number of text formatting and internationalization tags that provide easy access to the underlying Java APIs.

Internationalization Tags

The internationalization (I18N) tags let you specify a particular locale, which controls the formatting of data. You can also access resource bundles, which contain language-specific items.

Who Wants to Type That Much?

graphics/bytheway_icon.gif

You might have seen "internationalization" abbreviated as I18N. The abbreviation is a clever acknowledgment of the fact that there are 18 letters between the I and the N in internationalization.


The <fmt:setLocale> Tag

The <fmt:setLocale> tag sets the locale used for performing any locale-specific operations. The value attribute specifies the locale and may be either an expression that evaluates to a java.util.Locale object or a string of the form "LL" or "LL-ccc" where LL is a two-letter language code and ccc is an optional country code (for example, EN, EN-us, EN-gb, DE-at). You can also specify a scope for the locale setting. A scope of session means that the locale setting remains active for the entire scope of this session, but it doesn't affect other sessions. A scope of application would set the locale for the entire application. By using a session scope, you avoid the trouble of setting the locale every time you process a new request.

By default, the I18N and formatting tags determine the locale based on the browser's preferences.

The <fmt:bundle> Tag

The <fmt:bundle> tag specifies a resource bundle to use for any messages enclosed within the <fmt:bundle> tag. The basename attribute specifies a fully qualified resource bundle name, without the locale-specific suffix. A resource bundle name uses the same form as a classname. If the resource bundle is a properties file, don't include .properties at the end. As you'll see in a moment, the <fmt:bundle> tag is used when you format messages with the <fmt:message> tag.

A resource bundle may contain a number of items, each associated with a key value. If the key values are long and share a common prefix, you can use the prefix attribute to specify the prefix in the <fmt:bundle> tag. For example, suppose several messages all begin with the key com.wutka.i18n.msg. Rather than using the long key name, you specify prefix="com.wutka.i18n.msg.", and then in your <fmt:message> tags you just supply the part of the key that comes after the common prefix.

The <fmt:setBundle> Tag

The <fmt:setBundle> tag locates a resource bundle and assigns it to a variable for later use. As with the <fmt:bundle> tag, the basename attribute specifies the name of the resource bundle. The var attribute specifies the name of the variable in which to store the bundle, and the optional scope attribute specifies the scope of the variable (page being the default).

The <fmt:message> Tag

The <fmt:message> tag retrieves a message from a resource bundle and optionally uses the java.util.MessageFormat class to format the message. The key attribute specifies the message key. If the <fmt:message> tag occurs within a <fmt:bundle> tag, the key is appended to the bundle's prefix, if there is one. If the <fmt:message> tag occurs outside of a <fmt:bundle> tag, the bundle attribute must be present and must be an expression that evaluates to a LocalizationContext object (most often, a variable initialized with the <fmt:setBundle> tag).

Rather than specify a key with the key attribute, you can put the key in the body of the <fmt:message> tag. For example, the following two tags are equivalent:


<fmt:message key="greeting"/>
<fmt:message>greeting</fmt:message>

By default, the <fmt:message> writes its output to the JSP's writer. You can also store the formatted message in a variable by specifying the variable name in a var attribute. If you store the message in a variable, <fmt:message> doesn't write the message to the JSP's writer. You can also specify a scope for the variable with the scope attribute.

The MessageFormat class can perform parameter substitution, and the <fmt:message> tag enables you to pass parameters with the <fmt:param> tag. There are two ways to specify a parameter with the <fmt:param>. You can specify the value in the value attribute or specify the value in the content of the <fmt:param> tag. For example, the following two tags are equivalent:


<fmt:param value="destination"/>
<fmt:param>destination</fmt:param>

The following tag formats a message with several parameters:


<fmt:message key="shipment">
   <param value="${shipDate}"/>
   <param value="${shipmentStatus}"/>
</fmt:message>

Listing 22.9 shows the JSTL version of the ResourceBundle.jsp page. It uses the <jsp:bundle> tag to load a resource bundle and the <jsp:message> tag to retrieve messages from the bundle.

Listing 22.9 Source Code for ResourceBundleJSTL.jsp
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
<fmt:bundle basename="TestResourceProps">
<html>
<body>
<h1><fmt:message key="greetHeading"/></h1>
<p>
<fmt:message key="welcomeText"/>:
<p>
<form action="your_form_handler_here" method="post">

<fmt:message key="namePrompt"/>
<input type="text" name="name"><br>

<fmt:message key="agePrompt"/>
<input type="text" name="age"><br>

<fmt:message key="placePrompt"/>
<input type="text" name="place"><br>

<p>
<input type="submit" value="<fmt:message key='submitButtonText'/>">
</form>
</body>
</html>
</fmt:bundle>
The <fmt:requestEncoding> Tag

The <fmt:requestEncoding> tag specifies the encoding for the request object. Many browsers don't specify a content encoding in the HTTP header, so you often need to set the encoding yourself. By default, the <fmt:requestEncoding> tag uses the current locale to determine the request encoding. You can also specify a particular encoding with the value attribute.

Formatting Tags

The formatting tags provide access to many of the formatting objects in the java.text package. The formatting tags focus on formatting and parsing dates, numbers, percentages, and currency values.

The <fmt:timeZone> Tag

The <fmt:timeZone> tag specifies the time zone to be used by any tags contained within it (similar to the way <fmt:bundle> specifies a resource bundle to use). The <fmt:timeZone> can't determine the browser's time zone; you must always supply some kind of time zone value via the value attribute. The value attribute can be any of the time zones supported by the java.util.TimeZone class, such as America/New_York, Asia/Calcutta, or GMT-8.

The <fmt:setTimeZone> Tag

The <fmt:setTimeZone> tag stores a time zone in a variable and uses the time zone as the default time zone depending on the scope of the variable. As with the <fmt:timeZone> tag, the value attribute specifies the time zone name. The var attribute specifies the variable name (if the variable name is omitted, the time zone is stored in the default time zone variable). You can also specify a scope, which can apply to either the named variable or the default time zone variable. For example, if you specify a session scope and omit the variable name, you set the default time zone for only the current session. If you specify an application scope and omit the variable name, you specify the default time zone for the entire application.

The <fmt:formatNumber> Tag

The <fmt:formatNumber> tag formats numbers as integers, decimals, percentages, and currencies. You can specify the number to format either with an EL expression in the value attribute or as the tag's body content. The type attribute specifies the kind of formatting to perform: number, currency, or percent. The default formatting type is number. By default, the <fmt:formatNumber> tag writes the formatted number to the JSP's writer. Instead of writing the number to the JSP's writer, you can store the formatted number in a variable by supplying a variable name in the var attribute and an optional scope in the scope attribute.

The <fmt:formatNumber> tag has several attributes related to formatting, as shown in Table 22.1.

Table 22.1. Attributes Supported by <fmt:formatNumber>

Attribute

Description

pattern

A custom pattern for decimal numbers, as defined by the java.text.DecimalFormat class.

currencyCode

The currency code to use (only if type=currency).

currencySymbol

The currency symbol to use (only if type=currency).

groupingUsed

If true, numbers may contain grouping characters (for example, 1000 appears as 1,000 for English locales). If false, no grouping is performed. This setting is true by default.

maxIntegerDigits

The maximum number of digits to show in the integer portion of a number.

minIntegerDigits

The minimum number of digits to show in the integer portion of a number.

maxFractionDigits

The maximum number of digits to show in the fraction portion of a number.

minFractionDigits

The minimum number of digits to show in the fraction portion of a number.

To write out a decimal number with two digits to the right of the decimal point, and up to six digits to the left, use the following tag:


<fmt:formatNumber value="3.1415926536" maxFractionDigits="2"
    maxIntegerDigits="6"/>

When specifying a number pattern, there are a number of characters that may appear in the pattern. These characters are shown in Table 22.2.

Table 22.2. Allowable Number Pattern Characters

Character

Meaning

0

Represents a single digit, displaying leading zeros.

#

Represents a single digit with a blank or blanks for leading zeros.

.

Represents a decimal or monetary separator (decimal point in English locales, translates to a comma in locales such as DE [German].

-

Indicates where to display the minus sign for negative numbers.

,

Represents a grouping separator.

E

Represents the separator between the mantissa and exponent in scientific notation.

;

Separates the patterns for a positive and negative number (you can specify these separately).

%

Represents the percent symbol; causes the result to be multiplied by 100 and displayed as a percent.

\u2030

Represents the per-mille symbol; causes the result to be multiplied by 1000 and displayed as a per-mille.

\u00a4

Represents a currency symbol; causes the monetary separator to be used instead of decimal separator, if different.

'

Causes the next character to be interpreted as a simple character, similar to the way \works in Java strings. To represent a single quote, use two of them (''). The sequence '0 represents a 0 instead of any digit, for example.

The <fmt:parseNumber> Tag

The <fmt:parseNumber> tag converts a string to a numeric value, including percentages and currencies. It can parse a value specified by the value attribute or parse the body content of the <fmt:parseNumber> tag.

You can store the parsed number in a variable by specifying a var attribute and an optional scope attribute. If you don't store the parsed value in a variable, the <fmt:parseNumber> tag writes the parsed value to the JSP's writer.

The type attribute specifies the kind of value to parse: number, percent, or currency. The default type is number. The <fmt:parseNumber> tag uses the default locale, although you can specify an alternate locale with the parseLocale attribute, which must be an EL expression that evaluates to a java.util.Locale object. To parse only integer values (that is, no decimal numbers), specify integerOnly="true". Finally, to parse a number using a custom pattern, specify the pattern with the pattern attribute. The custom pattern for <fmt:parseNumber> is the same as the pattern in <fmt:formatNumber> and is described by Table 22.2.

The <fmt:formatDate> Tag

The <fmt:formatDate> tag formats a date value specified either by the value attribute or by the body content of the tag itself. By default, the <fmt:formatDate> tag writes the formatted date to the JSP's writer, but you can instead store the value in a string variable named by the var attribute and optional scope attribute.

The <fmt:formatDate> tag can format both times and dates. The type attribute specifies what kind of value you want to format: time, date, or both. You can also specify the general type of a date or time with the dateStyle and timeStyle attributes. The possible styles are default, short, medium, long, and full. You can also specify a custom format with the pattern attribute. Table 22.3 shows the pattern characters for a custom pattern.

Table 22.3. Valid Date Pattern Characters

Character

Description

G

The era (A.D., B.C., and so on)

y

The year (yy for two-digit years, yyyy for four digits)

M

The month (MM for numeric month, MMM or longer for month names or abbreviations)

w

The week of the year (ww for two digits)

W

The week of the month

D

The day of the year (DDD for three digits)

d

The day of the month (dd for two digits)

F

The numeric day of the week

E

The text day of the week (EEEE or longer for full name)

a

AMa.m./PMp.m. indicator

H

Hour of the day (0–23)

k

Hour of the day (1–24)

K

Hour in a.m./p.m. (0–11)

h

Hour in a.m./p.m. (1–12)

m

Minutes in hour

s

Seconds in minute

S

Milliseconds in second

z

Full time zone name

Z

RFC 822 time zone (for example, 0500)

The <fmt:parseDate> Tag

The <fmt:parseDate> tag parses a date specified by either the value attribute or the tag's body content and stores the result in a variable named by the var attribute (with optional scope). If no variable is specified, the tag writes its output to the JSP's writer.

The <fmt:parseDate> tag supports all the attributes in the <fmt:formatDate> tag and also supports a parseLocale attribute that specifies the locale of the time being parsed. The value of the attribute should be an EL expression that evaluates to a java.util.Locale object.

    [ Team LiB ] Previous Section Next Section