如何在JSP中設定locale以識別所需的資源包?
<fmt:setLocale>標籤用於將給定的區域設定儲存在區域設定配置變數中。
屬性
<fmt:setLocale>標籤具有以下屬性:
| 屬性 | 描述 | 必需 | 預設值 |
|---|---|---|---|
| 值 | 指定一個兩部分程式碼,表示ISO-639語言程式碼和ISO-3166國家程式碼。 | 是 | en_US |
| variant | 瀏覽器特定的變體 | 否 | 無 |
| scope | 區域設定配置變數的作用域 | 否 | 頁面 |
示例
資源包包含特定於區域設定的物件。資源包包含鍵值對。當您的程式需要特定於區域設定的資源時,您可以保留所有區域設定通用的所有鍵,但您可以擁有特定於區域設定的翻譯值。資源包有助於提供特定於區域設定的內容。
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"},
};
}現在讓我們再定義一個資源包,我們將用於西班牙語區域設定:
package com.tutorialspoint;
import java.util.ListResourceBundle;
public class Example_es_ES extends ListResourceBundle {
public Object[][] getContents() {
return contents;
}
static final Object[][] contents = {
{"count.one", "Uno"},
{"count.two", "Dos"},
{"count.three", "Tres"},
};
}讓我們編譯上面的類Example.class和Example_es_ES.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:setLocale 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> <!-- Change the Locale --> <fmt:setLocale value = "es_ES"/> <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 Uno Dos Tres
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP