Caffeinated
Caffeinated

Reputation: 12484

What is the purpose of a listener class in a large project

I'm confused about what listener classes do. For example, in this project there is a listener class referenced as so:

<listener>
    <listener-class>com.sun.javaee.blueprints.petstore.model.CatalogFacade</listener-class> 
</listener>

Is it as the name implies, just listening for actions to do?

Upvotes: 8

Views: 24996

Answers (4)

shelley
shelley

Reputation: 7324

I'd suggest reviewing the chapter on "Application Lifecycle Events" from the Servlet specification.

Depending on which version you're using, here are the corresponding chapters and links to the docs:

Listeners are used to be notified of events to web applications, including state changes in the ServletContext, HttpSession, and ServletRequest objects. By implementing predefined listener interfaces (javax.servlet.ServletContextListener, javax.servlet.http.HttpSessionListener, javax.servlet.ServletRequestListener, etc.), the servlet container will notify you of certain events that are happening in your application. They have a lot of potential uses, such as performing one-time application setup and shutdown tasks, intercepting requests to perform logging, tracking HTTP session use, etc.

Upvotes: 4

MaDa
MaDa

Reputation: 10762

More generally, a listener is the observer/subscriber side in the observer pattern. The server/framework side provides you with a means to be notified of some event and therefore give you a chance to do your actions.

And it not necessarily must be "a large project". Listeners come handy even in the smaller ones :).

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240898

Yes exactly they are listening for some action todo, for example if its contextloaderlistener then it will listen to context loading event and there are many stuff that we can do at such event so these are made for that

Upvotes: 2

P&#229;l Brattberg
P&#229;l Brattberg

Reputation: 4698

Listener Classes get notified on selected events, such as starting up the application or creating a new Session.

Listener Classes :

These are simple Java classes which implement one of the two following interfaces :

  • javax.servlet.ServletContextListener
  • javax.servlet.http.HttpSessionListener

If you want your class to listen for application startup and shutdown events then implement ServletContextListener interface. If you want your class to listen for session creation and invalidation events then implement HttpSessionListener interface.

Source

Upvotes: 7

Related Questions