ServletContext.getAttribute()

Hey everyone,

I'm working on the web components cert and while doing one of the programming exercises, I came across a ClassCastException error on the code below (bold is the line causing the issue):

ServletContext context = getServletContext();

Enumeration contextNames = context.getAttributeNames();

while(contextNames.hasMoreElements())

{

String name = (String)contextNames.nextElement();

String value = (String)context.getAttribute(name);

out.println("Context attribute name: " + name + "Value: " + value);

}

Thanks in advance!

[606 byte] By [Jolly_Rogera] at [2007-11-27 11:13:20]
# 1

I should have added that I thought getAttribute() was suppose to return an Object. The exact error message is java.lang.ClassCastException: java.lang.String, but I could have swore it said java.io.File before. Like it was returning a File object.

Jolly_Rogera at 2007-7-29 14:00:16 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2

Dear Jolly to be honest with you, that when i was preparing my web developer certificate i faced many problems like that. what i used to do is that i make sure that the attributes saved are Strings, or defined objects (Customer, Student, etc, ....)..

this is what i used to do and here are some lines of what i used to do..

Customer cust = new Customer();

session.setAttribute("customerBean", cust);

and later when i want to get this attribute:

Customer newCust = (Customer)session.getAttribute("customerBean");

so to conclude, making sure of the type while setting and using the same cast while obtaining it will avoid you a trouble of ClassCastException...

hope it helps..(^_^);

QussayNajjara at 2007-7-29 14:00:16 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...