How to get all attribute names (nested or not) in the servlet context and repeat if it is a map or list?

I tried to get the name attributes of a poorly supported context, and then use these names with reflection.

Here is some pseudo code for a rough idea. For instance. I have an ArrayList and HashMap in 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 } } 
+4
source share
1 answer

Here is the 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:

  • Always prefer to refer to an abstract interface over specific implementations. In this case, check List and Map (interfaces), not ArrayList and HashMap (specific implementations); consider what happens if the context passes you a LinkedList , not an ArrayList or Map , not a HashMap - your code (without need) will explode
  • Use while (condition) , not for (;condition;) - it's just ugly
  • If you know the types of your Collections, list them. For example, web contexts usually provide you with Map<String, Object> :

so the code can become

 for (Map.Entry<String, Object> entry : ((Map<String, Object>)value).entrySet()) { String entryKey = entry.getKey(); Object entryValue = entry.getValue(); } 
+8
source

All Articles