<fmt:setLocale> 标签


<fmt:setLocale>标签用来将给定的区域存储在locale配置变量中。

属性

<fmt:setLocale>标签有如下属性:

属性描述是否必要默认值
value指定ISO-639 语言码和ISO-3166 国家码en_US
variant特定浏览器变体
scopeLocale配置变量的作用域Page

程序示例

资源束包含区域特定对象。资源束包含键值对。当您的程序需要区域特定资源时,可以将所有的关键词对所有的locale共享,但是也可以为locale指定转换后的值。资源束可以帮助提供指定给locale的内容。

一个Java资源束文件包含一系列的键值对。我们所关注的方法涉及到创建继承自java.util.ListResourceBundle 类的已编译Java类。您必须编译这些类然后放在您的Web应用程序的CLASSPATH中。

让我们来定义一个默认的资源束:

  1. package com.tutorialspoint;
  2.  
  3. import java.util.ListResourceBundle;
  4.  
  5. public class Example_En extends ListResourceBundle {
  6.   public Object[][] getContents() {
  7.     return contents;
  8.   }
  9.   static final Object[][] contents = {
  10.   {"count.one", "One"},
  11.   {"count.two", "Two"},
  12.   {"count.three", "Three"},
  13.   };
  14. }

现在,再定义一个资源束,用于Spanish Locale:

  1. package com.tutorialspoint;
  2.  
  3. import java.util.ListResourceBundle;
  4.  
  5. public class Example_es_ES extends ListResourceBundle {
  6.   public Object[][] getContents() {
  7.     return contents;
  8.   }
  9.   static final Object[][] contents = {
  10.   {"count.one", "Uno"},
  11.   {"count.two", "Dos"},
  12.   {"count.three", "Tres"},
  13.   };
  14. }

编译以上文件至Examble.class和Examble_es_ES.class中,然后将它们放在Web应用程序的CLASSPATH中。现在可以使用JSTL标签来显示这三个数字,就像这样:

  1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  2. <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
  3. <html>
  4. <head>
  5. <title>JSTL fmt:setLocale Tag</title>
  6. </head>
  7. <body>
  8.  
  9. <fmt:bundle basename="com.tutorialspoint.Example">
  10.    <fmt:message key="count.one"/><br/>
  11.    <fmt:message key="count.two"/><br/>
  12.    <fmt:message key="count.three"/><br/>
  13. </fmt:bundle>
  14.  
  15. <!-- Change the Locale -->
  16. <fmt:setLocale value="es_ES"/>
  17. <fmt:bundle basename="com.tutorialspoint.Example">
  18.    <fmt:message key="count.one"/><br/>
  19.    <fmt:message key="count.two"/><br/>
  20.    <fmt:message key="count.three"/><br/>
  21. </fmt:bundle>
  22.  
  23. </body>
  24. </html>

运行结果如下:

  1. One 
  2. Two 
  3. Three
  4. Uno
  5. Dos
  6. Tres

查看<fmt:bundle>和<setBundle>来获取更多信息。