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

Listener question

 
JPraveen Kumar
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a listener class implemets multiple listener interfaces like ServletContextAttributeListener, HttpSessionAttributeListener then is the same instance used when the different events are triggered or is it a new instance for each event?

Also how can I refer to the instance of the listener object from my servlet code or from other listener code.

Thanks JPraveen.
 
Mikalai Zaikin
Ranch Hand
Posts: 3364
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Even if listener class implements multiple interfaces, only one instance is created by servlet container and it is used for several types of events.

You can not refer to listener directly (and invoke methods), its life cycle is under control of servlet container, you can only call methods on listener by providing specific events which listener is listening.

regards,
MZ


P.S. Note, since listener is created by servlet container, it must have default (no arguments) public constructor.
 
Omar Dziri
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Event listeners are instantiated even before the initialization of the servletContext. The web container creates a single instance for each listener class declared in the web.xml file. If the same listener is declared twice in web.xml, two instances are created and so on.
Different events can be triggered to the same listener instance if it implements the appropriate interfaces.
A listener that implements only HttpSessionBindingListener is not required to be declared in web.xml.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic