<fmt:bundle> 标签

约 2110 字 更新于 2026-11-18 5iyo.com

<fmt:bundle> 标签

<fmt:bundle>标签将指定的资源束对出现在<fmt:bundle>标签中的<fmt:message>标签可用。这可以使您省去为每个<fmt:message>标签指定资源束的很多步骤。

举例来说,下面的两个<fmt:bundle>块将产生同样的输出:


<fmt:bundle basename="com.runoob.Example">

    <fmt:message key="count.one"/>

</fmt:bundle>



<fmt:bundle basename="com.runoob.Example" prefix="count.">

    <fmt:message key="title"/>

</fmt:bundle>

语法格式

<fmt:bundle baseName="<string>" prefix="<string>"/>

属性

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

属性 描述 是否必要 默认值
basename 指定被载入的资源束的基础名称 是 无
prefix 指定<fmt:message>标签key属性的前缀 否 无


程序示例

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

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

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


package com.runoob;



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来显示这三个数字了,就像这样:


<%@ 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:bundle 标签</title>

</head>

<body>



<fmt:bundle basename="com.runoob.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

将其改为无prefix属性:


<%@ 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:bundle 标签</title>

</head>

<body>



<fmt:bundle basename="com.runoob.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

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