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
}
}
If there's any chance a parameter could have more than one value, you should use the getParameterValues( ) method instead. This method returns all the values of the named parameter as an array of String objects or null if the parameter was not specified.
HttpSession interface. Servlets can set and get information about the session in this HttpSession object, which must be of application-level scope. A servlet uses the getSession() method of an HttpServletRequest object to retrieve or create an HttpSession object for the user.
An attribute in servlet is an object that can be set, get or removed from one of the following scopes: request scope. session scope. application scope.
The doGet() method in servlets is used to process the HTTP GET requests. So, basically, the HTTP GET method should be used to get the data from the server to the browser. Although in some requests, the GET method is used to send data from the browser to the server also.
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:
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) explodewhile (condition)
rather than for (;condition;)
- it's just uglyMap<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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With