aspose file tools*
The moose likes Servlets and the fly likes getServletContext from a ServletContextAttribute Listener Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "getServletContext from a ServletContextAttribute Listener" Watch "getServletContext from a ServletContextAttribute Listener" New topic
Author

getServletContext from a ServletContextAttribute Listener

Anibal Smith
Greenhorn

Joined: Mar 23, 2006
Posts: 6
Hi, i have a class that extends from HttpServlet and implements ServletContextAttributeListener, all work great, when a context attribute is removed the attributeRemoved method is called, my problem is when calling the getSevletContext method from there i get a null pointer exception. Is it posible to access the servlet context from the attributeRemoved method?.
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

This is a bad idea. While you can do this, it encourages you to make mistakes like the one you have made. The two are not the same, and you should consider making them two separate classes to reflect this.

The problem in this case is that the servlet and servlet contexts have different lifecycles, when you want to access one, the other is not valid. You could possibly add a bunch of code to manage the peculiarities in the behaviour but it wouldn't change the fact that these are two different things and you shouldn't try to combine them.

Dave
Anibal Smith
Greenhorn

Joined: Mar 23, 2006
Posts: 6
ok, thanks Dave, i resolved my problem, i will try to explain why i did that and how i resolved it.
I have to access a context attribute called user (ArrayList) from the a class that implements HttpSessionAttributeListener, i thought i need to extends the HttpServlet class to be able to access a context attribute but i realized that i can access it through event.getSession().getServletContext().getAttribute("user") where event is the HttpSessionBindingEvent. So i don't have the need anymore to extends from HttpServlet.
What do you think about this.
Sorry about my english.
David O'Meara
Rancher

Joined: Mar 06, 2001
Posts: 13459

Don't worry about your English, it's fine.

Getting the context and hence the context value via this code looks like a much better idea. Drop us a line and tell us how you go!

...and welcome to the Ranch!
Anibal Smith
Greenhorn

Joined: Mar 23, 2006
Posts: 6
To clarify a litte bit more fore people who are just beging, like me, this is the code of the listener i wrote to test it:

[ March 23, 2006: Message edited by: Anibal Smith ]
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: getServletContext from a ServletContextAttribute Listener