Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

getServletContext from a ServletContextAttribute Listener

 
Anibal Smith
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic