如何在JSP中使用資源包?
<fmt:bundle>標籤會使指定的資源包可用於<fmt:message>標籤之間出現的全部<fmt:message>標籤。這樣,您無需為每個<fmt:message>標籤指定資源包。
例如,以下兩個<fmt:bundle>塊將產生相同的輸出:
<fmt:bundle basename = "com.tutorialspoint.Example"> <fmt:message key = "count.one"/> </fmt:bundle> <fmt:bundle basename = "com.tutorialspoint.Example" prefix = "count."> <fmt:message key = "title"/> </fmt:bundle>
屬性
<fmt:bundle>標籤具有以下屬性:
| 屬性 | 描述 | 必需 | 預設值 |
|---|---|---|---|
| basename | 指定要載入的資源包的基本名稱。 | 是 | 無 |
| Prefix (字首) | 附加到<fmt:message>子標籤中每個鍵名稱的值 | 否 | 無 |
示例
資源包包含特定於區域設定的物件。資源包包含**鍵/值**對。當您的程式需要特定於區域設定的資源時,您保留所有區域設定通用的所有鍵,但您可以擁有特定於區域設定的翻譯值。資源包有助於向區域設定提供特定內容。
Java資源包檔案包含一系列**鍵到字串的對映**。我們關注的方法涉及建立擴充套件**java.util.ListResourceBundle**類的已編譯Java類。您必須編譯這些類檔案並使它們可用於Web應用程式的類路徑。
讓我們定義一個預設資源包,如下所示:
package com.tutorialspoint;
import java.util.ListResourceBundle;
public class Example_En extends ListResourceBundle {
public Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
{"count.one", "One"},
{"count.two", "Two"},
{"count.three", "Three"},
};
}讓我們編譯上面的類**Example.class**並使其在Web應用程式的CLASSPATH中可用。現在,您可以使用以下JSTL標籤來顯示這三個數字,如下所示:
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/fmt" prefix = "fmt" %> <html> <head> <title>JSTL fmt:bundle Tag</title> </head> <body> <fmt:bundle basename = "com.tutorialspoint.Example" prefix = "count."> <fmt:message key = "one"/><br/> <fmt:message key = "two"/><br/> <fmt:message key = "three"/><br/> </fmt:bundle> </body> </html>
以上程式碼將生成以下結果:
One Two Three
嘗試在沒有字首的情況下使用以上示例,如下所示:
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %> <%@ taglib uri = "http://java.sun.com/jsp/jstl/fmt" prefix = "fmt" %> <html> <head> <title>JSTL fmt:bundle Tag</title> </head> <body> <fmt:bundle basename = "com.tutorialspoint.Example"> <fmt:message key = "count.one"/><br/> <fmt:message key = "count.two"/><br/> <fmt:message key = "count.three"/><br/> </fmt:bundle> </body> </html>
以上程式碼將生成以下結果:
One Two Three
廣告
資料結構
網路
關係型資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP