JSTL 格式化標籤庫 (uri="https://java.sun.com/jsp/jstl/fmt") 提供國際化 (I18N) 支援,依客戶端 Locale 自動格式化數字、日期、貨幣、百分比,並管理訊息資源檔實現多語系。本文詳細解析 11 個標籤的語法、屬性與實戰模式。
<%@ taglib prefix="fmt" uri="https://java.sun.com/jsp/jstl/fmt" %>
| 分類 | 標籤 | 功能 |
|---|---|---|
| 數字/日期格式化 | formatNumber | 數字/貨幣/百分比格式化輸出 |
| formatDate | 日期時間格式化輸出 | |
| parseNumber | 字串解析為數字 | |
| parseDate | 字串解析為日期 | |
| timeZone | 指定時區範圍 | |
| setTimeZone | 設定預設時區 | |
| 訊息資源 | bundle | 載入 ResourceBundle 至範圍 |
| message | 輸出國際化訊息 (支援參數) | |
| setBundle | 設定預設 Bundle | |
| 國際化設定 | setLocale | 設定頁面/範圍 Locale |
| requestEncoding | 設定請求字符編碼 |
<fmt:formatNumber> - 數字/貨幣/百分比格式化<fmt:formatNumber value="${price}" type="currency" currencyCode="TWD" currencySymbol="$"
groupingUsed="true" maxFractionDigits="2" minFractionDigits="2" var="formattedPrice" />
type 屬性:`number` (預設)、`currency` (依 Locale 顯示貨幣符號)、`percent` (乘 100 加 %)。
pattern 屬性:自訂格式模式 (如 `#,##0.00`),優先於 type。
<fmt:formatDate> - 日期時間格式化<fmt:formatDate value="${order.time}" type="both" dateStyle="full" timeStyle="short"
pattern="yyyy-MM-dd HH:mm:ss" timeZone="GMT+8" var="formattedDate" />
`type`:`date`、`time`、`both` (預設)。`dateStyle/timeStyle`:`default`、`short`、`medium`、`long`、`full`。`pattern` 直接指定 `SimpleDateFormat` 模式。
<fmt:parseNumber> / <fmt:parseDate> - 字串解析<fmt:parseNumber var="parsedNum" type="currency" value="${param.price}" />
<fmt:parseDate var="parsedDate" pattern="yyyy-MM-dd" value="${param.birth}" />
解析失敗會拋出異常,建議搭配 `
<fmt:bundle> / <fmt:setBundle> / <fmt:message> - 訊息資源<!-- 載入基礎名稱 com.app.messages 的 .properties 檔 (依 Locale 自動選擇 _zh_TW.properties 等) -->
<fmt:bundle basename="com.app.messages">
<fmt:message key="welcome" />
<fmt:message key="hello.user">
<fmt:param value="${user.name}" /> <!-- 參數替換 {0} -->
</fmt:message>
</fmt:bundle>
<!-- 全域設定預設 Bundle -->
<fmt:setBundle basename="com.app.messages" scope="application" />
<fmt:setLocale> / <fmt:requestEncoding> - Locale 與編碼控制<fmt:setLocale value="zh_TW" scope="session" /> <!-- 強制繁體中文 -->
<fmt:requestEncoding value="UTF-8" /> <!-- 設定請求解碼編碼 -->
messages_en_US.properties 等。JSTL 格式化標籤庫讓 JSP 輕鬆實現企業級國際化需求,無需手寫 Locale 判斷與格式化代碼,是多語系 Web 應用的標準利器。