Our tour of the Java Servlet Specification is almost finished. So far we have covered Servlets, Filters, and the Servlet Context. Now we will look the last major Servlet feature - Listeners.
If you’ve spent enough time writing Java, chances are you have encountered the listener concept before. They wait for some event to occur, at which point they will trigger and perform some action. In general, listeners can be made to listen for any sort of event, but if we want to use the Servlet-specific listener classes provided by the API, we are limited to only a predetermined set of events. When you consider that the purpose of a Servlet is to simply process requests and responses, these events are really all you need.
The Servlet API provides several types of Listeners in the form of Java Interfaces. We aren’t going to cover all of the Listeners in this post, instead focusing on the most commonly used ones. The first is ServletContextListener
, which listens for two events - when the Servlet Context is created, and when it is destroyed. The next interface is ServletRequestListener
, which also listens to two events - when an incoming request is created, and when it is destroyed.