Latest web development tutorials

<fmt:setLocale> 標籤

JSP 標準標籤庫 JSP標準標籤庫

<fmt:setLocale>標籤用來將給定的區域存儲在locale配置變量中。

語法格式

<fmt:setLocale value="<string>" variant="<string>" scope="<string>"/>

屬性

<fmt:setLocale>標籤有如下屬性:

屬性 描述 是否必要 默認值
value 指定ISO-639 語言碼和ISO-3166 國家碼 en_US
variant 特定瀏覽器變體
scope Locale配置變量的作用域 Page


程序示例

資源束包含區域特定對象。 資源束包含鍵值對。 當您的程序需要區域特定資源時,可以將所有的關鍵詞對所有的locale共享,但是也可以為locale指定轉換後的值。 資源束可以幫助提供指定給locale的內容。

一個Java資源束文件包含一系列的鍵值對。 我們所關注的方法涉及到創建繼承自java.util.ListResourceBundle 類的已編譯Java類。 您必須編譯這些類然後放在您的Web應用程序的CLASSPATH中。

讓我們來定義一個默認的資源束:

package com.w3big;

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"},
  };
}

現在,再定義一個資源束,用於Spanish Locale:

package com.w3big;

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"},
  };
}

編譯以上文件至Examble.class和Examble_es_ES.class中,然後將它們放在Web應用程序的CLASSPATH中。 現在可以使用JSTL標籤來顯示這三個數字,就像這樣:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ 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 标签</title>
</head>
<body>

<fmt:bundle basename="com.w3big.Example">
   <fmt:message key="count.one"/><br/>
   <fmt:message key="count.two"/><br/>
   <fmt:message key="count.three"/><br/>
</fmt:bundle>

<!-- 修改地区-->
<fmt:setLocale value="es_ES"/>
<fmt:bundle basename="com.w3big.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

查看<fmt:bundle><setBundle>來獲取更多信息。


JSP 標準標籤庫 JSP標準標籤庫