首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> JSP 程式設計 >> 關於JSP

JSTL 格式化標籤庫 (fmt:) 完整指南:數字、日期、國際化與訊息資源

     編輯:關於JSP

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" /> <!-- 設定請求解碼編碼 -->

實戰多語系架構

  1. 建立訊息檔:`messages.properties` (預設)、`messages_zh_TW.properties`、messages_en_US.properties 等。
  2. 配置 `` (通常在 Filter 或首頁)。
  3. 頁面使用 `` 輸出,參數用 ``。
  4. 用戶切換語言時:``。
  5. 瀏覽器 `Accept-Language` 標頭會被 `` 自動解析選擇對應資源檔。

關鍵提示

  • 格式化標籤 `var` 存結果時,輸出型別為 `String`,不可直接參與數學運算。
  • 貨幣格式化依賴 JDK 內建 `Currency`/`NumberFormat`,確保 JDK 版本支援目標貨幣代碼。
  • 時區處理:`` 包裹區塊,或 `` 全域設定。
  • 資源檔編碼:Java 9+ 支援 UTF-8 `.properties`,舊版需用 `native2ascii` 轉 Unicode 轉義。

JSTL 格式化標籤庫讓 JSP 輕鬆實現企業級國際化需求,無需手寫 Locale 判斷與格式化代碼,是多語系 Web 應用的標準利器。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved