I am trying to write a code to see a ContextListener class in action. I have a jsp, where clicking on a button will take me to a servlet. That servlet will retrieve a context attribute object and print it using out.println(). Also, the DD defines a context-param which is taken by the listener class and that parameter is used in the contextInitialised() method to convert into an object which is then stuck into the ServletContext object as an attribute (the same attribute which is later retrieved by the servlet)
However, at the end of it all, what the servlet prints is null instead of the attribute. Can you please point out where I am going wrong?
Here are the revelant codes :
The Listener class
The ColorClass.java class
I am doing this in Netbeans (incase that matters), and I am doing a 'Clean and Build' followed by a 'Run'. When I run, and click on the button in the jsp, the output I get is
you got null!!!
I have pasted only parts of the DD and jsp. There are other servlets from the same jsp that are working fine, so I guess the rest of the DD and jsp must be correct.
So there are a few places where the code could be breaking:
1) The ServletContextListener is simply not running: Have you verified it actually ran? If so, how did you do it?
2) Errors in the web.xml: Did you spell everything right? Do you have all the files in the proper directories? Can you show your application structure?
Souvvik Basu wrote:This should set an attribute 'colour' ...
No. It will set a scoped variable (attribute) with the key "red". How do you figure that the key will be "colour" when you are passing the value "red" to the setAttribute() method?
Joined: Apr 05, 2010
I verified that the listener class is running. I have been using netbeans, and I used the debugging feature and put breakpoints in different places. That is how I got to know that
in MyOwnListener.java is setting the variable colour to "red"...as expected.
And as far as the directory structure/web.xml etc is concerned, I think it should be correct, as its netbeans which is maintaining the structure. The web.xml I have already given...that is what I am using.
It has already been ascertained that the listener is executing.
2) Errors in the web.xml:
The problem is in the code (or rather the OP's understanding of the code). Not in the web.xml.
Joined: Apr 05, 2010
Thanks for your help. If I have understood correctly, the signature for the method is setAttribute(String name,Object value). Here 'name' is the name of the attribute and 'value' is the value for the attribute. Is that correct? Accordingly, what I have done is....bound the value of clrcls to an attribute named colour...isnt it?