how do I iterate through multiple properties in jsp

后端 未结 2 1313

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         


        
相关标签:
2条回答
  • 2021-01-22 09:28

    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);
    }
    
    0 讨论(0)
  • 2021-01-22 09:34
    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.

    0 讨论(0)
提交回复
热议问题