2

I'm trying to iterate through a set of keys in a properties file, so that only the "message.pX" is output.

a.property=foo
message.p1=a
message.p2=b
message.p3=c
some.other.property=bar

I don't know how many properties with the prefix (message.p) will be in the file, so I want to display any that are present. I've already got a bean class using ResourceBundle that handles it and pulls in the correct bundle for the locale, but is there a standard tag like <fmt:message> that can handle this?

Matt Solnit
  • 32,152
  • 8
  • 53
  • 57
David
  • 1,887
  • 2
  • 13
  • 14

2 Answers2

1
Properties properties = new Properties();
        try {
            properties.load(new FileInputStream("filename.properties"));
        } catch (IOException e) {
        }

        Enumeration e = properties.propertyNames();

        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();
            //Edited answer
            if(key.indexOf("message.p") != -1 ){
               System.out.println(key + " , " + properties.getProperty(key));
               //Add key and value to a list
            }
            //Edited answer

        }

I suggest you to do this inside a Servlet or a Java class and store the properties list in a java.lang.List object such as an ArrayList or LinkedList then send the result to the jsp. Avoid doing this inside the jsp.

Enrique
  • 9,920
  • 7
  • 47
  • 59
  • I edited my question- I should have made it clearer, that I wasn't iterating through the entire file, but just a subset of the keys. – David Mar 19 '10 at 05:33
  • Ok I have edited the answer to filer the message.p_ messages. – Enrique Mar 19 '10 at 05:55
1

There is no standard way to handle this. As you apparently already have the full control over the resourcebundle creation, your best bet is to introduce a new keyword/convention, such as a key ending with .list:

<c:forEach items="${bundle['message.p.list']}" var="p">
    <p>${p}</p>
</c:forEach>

..and create a custom ResourceBundle wherein you override handleGetObject() to return the desired values as a List<String>, something like:

protected Object handleGetObject(String key) {
    if (key.endsWith(".list")) {
        String listkey = key.substring(0, key.length() - 5);
        List<String> list = new ArrayList<String>();
        for (int i = 1; containsKey(listkey + i); i++) {
            list.add(String.valueOf(getObject(listkey + i)));
        }
        if (!list.isEmpty()) {
            return list;
        }
    }
    return getObject(key);
}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • except for having to use java5 and not having containsKey available, this is much better than what I had come up with. – David Mar 19 '10 at 16:15