如何根据属性文件生成多个HTML项?

时间:2011-10-15 16:02:00

标签: java jstl properties-file

我有以下属性文件:

title = Welcome to Home Page
total = 5
gallery1 = images/gallery/cs.png
text1 =  <b>Counter Strike</b><br />
gallery2 = images/gallery/css.png
text2 =  <b>Counter Strike Source Servers Available</b>
gallery3 = images/gallery/cs.png
text3 =  <b>Counter Strike</b>
gallery4 = images/gallery/cs.png
text4 =  <b>Counter Strike</b>
gallery5 = images/gallery/cs.png
text5 =  <b>Counter Strike</b>

我按如下方式加载:

public static HashMap<String, String> getPropertyMap(String asPropBundle) throws ApplicationException {
    HashMap<String, String> loMap = new HashMap<String, String>();
    ResourceBundle loRB = (ResourceBundle) moHMProp.get(asPropBundle) ;

    if (loRB == null) {
        throw new ApplicationException("No property bundle loaded with name: " + asPropBundle);
    }

    Enumeration<String> loKeyEnum = loRB.getKeys();

    while (loKeyEnum.hasMoreElements()) {
        String key = (String) loKeyEnum.nextElement();
        loMap.put(key, loRB.getString(key));
    }

    return loMap ;
}

返回的地图设置为HTTP请求属性。

我在JSP中生成HTML如下:

<li class="s3sliderImage">
    <img src="${map.gallery1}" />
    <span>${map.text1}</span>
</li>
.
.
.
<li class="s3sliderImage">
    <img src="${map.gallery2}" />
    <span>${map.text2}</span>
</li>

如何在循环中动态执行此操作?我在属性文件的total属性中有总记录数。

1 个答案:

答案 0 :(得分:2)

资源包已经是从键到值的映射,除了它具有回退机制。为什么要将其内容复制到另一个地图?

只需使用<fmt:message>标记:其目标正是从资源包中获取消息并将其输出到JSP编写器。它当然可以参数化:

<fmt:setBundle basename="the.base.name.of.your.Bundle"/>
<fmt:message key="text2"/>
<img src="<fmt:message key="gallery2"/>" />

<fmt:message key="greeting">
  <fmt:param value="${user.firstName}"/>
</fmt:message>

最后一段显示“欢迎约翰!”的片段。如果问候键的值是“欢迎{0}!”。

标记还可以将值存储在变量中,并将EL表达式作为参数,因此该片段应该可以实现循环:

<fmt:message var="total" key="total"/>
<c:forEach begin="1" end="${total}" varStatus="loopStatus">
    <li class="s3sliderImage">
        <img src="<fmt:message key="gallery${loopStatus.index}"/>" />
        <span><fmt:message key="text${loopStatus.index}"/></span>
    </li>
</c:forEach>