I'm now reading the chapter on Listeners for the 2nd time and still I'm not able to get what exactly are Listeners for?? Well the definition says that "Application event listeners are classes that implement one or more of the servlet event listener interfaces." What exectly they come to say??Anyone on this please.
Listeners are mainly used in swings. In event handling there are mainly two terms which needs attention 1.Listener 2.Event For every Listener there is event associated with it. For example in swing when we press a button a event is generated which is handled by Listener. you can think event as a message which is generated when specific action is performed and this message is handeled by a listener. So when web application is loaded a event known as ServletContextEvent is generated which is handled by ServletContextListener. Same way HttpSessionEvent is generated when a session is created and this event is handled by HttpSessionEvent.
If you know when you add an attribute and you know you need to use the attribute that you added, why not just do the work then? Why do you need a listener?
Let's say someone submits a form for a shopping cart, you have a doPost method and you handle them adding an item to their shopping cart (storing the stuff in the database or session data, whatever...) Then they move on to shopping and add more items, etc... Then they go to checkout. You have a servlet to handle checking the person out too... The checkout pull the session data, charges them checks them out... we're done.
At what point would there need to be a Listener to help with that application? Why does a class need to be sitting around waiting for another class to add a parameter or attribute??
Even I'm still not clear and looking for some more explanations. Michael's explanation was fairly good but I would be happy if I can get a more detailed explanation.
The concept is knows as "application lifecycle events", and there is a chapter on it in the servlet spec (e.g., chapter 10 in the Servlet 2.4 spec). That would be a good starting point for some research.
The point is basically separation of concerns. Event listeners are independent of any servlet code, and can be reused/triggered by events happening in multiple places. The developer doesn't need to worry about remembering to put the code in all the places where an event might be triggered - he just puts it into the listener once, and is done.
The analogy to GUI listeners would be that you don't want to check -every time the mouse was clicked- whether the click happened inside the area covered by a button, and then do whatever needs to happen upon a button click. You just want to specify what should happen if a button is clicked (in a listener), and then let the JVM worry about invoking the listener at appropriate times.