How to get all attributes names(nested or not) in Servlet Context and iterate if it's a map or list?

29,462

Here's code that will do what you want:

Enumeration<?> e = getServletContext().getAttributeNames();
while (e.hasMoreElements())
{
    String name = (String) e.nextElement();

    // Get the value of the attribute
    Object value = getServletContext().getAttribute(name);

    if (value instanceof Map) {
        for (Map.Entry<?, ?> entry : ((Map<?, ?>)value).entrySet()) {
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }
    } else if (value instanceof List) {
        for (Object element : (List)value) {
            System.out.println(element);
        }
    }
}

Notes:

  1. Always favour referring to the abstract interface over concrete implementations. In this case, check for List and Map (interfaces), rather than ArrayList and HashMap (specific implementations); consider what will happen if the context hands you a LinkedList rather than an ArrayList, or a Map that's not a HashMap - your code would (unnecessarily) explode
  2. Use while (condition) rather than for (;condition;) - it's just ugly
  3. If you know the types of your Collections, specify them. For example, web contexts usually give you a Map<String, Object>:

so the code could become

for (Map.Entry<String, Object> entry : ((Map<String, Object>)value).entrySet()) {
    String entryKey = entry.getKey();
    Object entryValue = entry.getValue();
}
Share:
29,462
hamahama
Author by

hamahama

Updated on June 14, 2020

Comments

  • hamahama
    hamahama about 4 years

    I've tried to get attributeNames of a ill-maintained context, then use those names with reflection.

    Here's some pseudo code for a rough idea. E.g. I have an ArrayList and a HashMap in the context.

    enum = getServletContext().getAttributeNames();
    for (; enum.hasMoreElements(); ) {
        String name = (String)enum.nextElement();
    
        // Get the value of the attribute
        Object value = getServletContext().getAttribute(name);
    
        if (value instanceof HashMap){
          HashMap hmap = (HashMap) value;
          //iterate and print key value pair here
        }else if(value instanceof ArrayList){
          //do arraylist iterate here and print
        }
    }
    
  • Bohemian
    Bohemian almost 5 years
    @PAA what's the exact code of yours that's causing the error?