开发者

How to generate multiple HTML items based on a properties file?

I have the following 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>

I am loading it as follows:

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.next开发者_如何转开发Element();
        loMap.put(key, loRB.getString(key));
    }

    return loMap ;
}

The returned map is set as HTTP request attribute.

I am generating the HTML in JSP as follows:

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

How can I do this dynamically in a loop? I have the total amount of records in total property of the properties file.


A Resource Bundle is already sort of a map from keys to values, except it has a fallback mechanism. Why do you copy its content to another map?

Just use the <fmt:message> tag: its goal is precisely to get a message from a resource bundle and to output it to the JSP writer. And it can be parameterized, of course :

<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>

This last snippet displaying "Welcome John!" if the value of the greeting key is "Welcome {0}!".

The tag can also store the value in a variable, and take an EL expression as parameter, so this snippet should work to implement your loop:

<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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜