Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Uses of the ServletContextListener class

 
Souvvik Basu
Ranch Hand
Posts: 96
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am a little confused about the exact reason why we need a ServletContextListener class in web applications. Is it because we can use it to convert context-parameters defined as strings in the DD into objects through that class (as given in Head First Servlets)? Or is it because we may need to do certain things when an application starts/shuts down on the server?

Also, can anyone kindly give me a few example cases where its useful/necessary to use a ServletContextListener class? Head First Servlets speaks of the situation where we can convert a Data Source name (defined as a string in DD) into a proper datasource reference. But I could not find any other uses. I tried searching the net for some examples, but nothing useful came up.

Thanks in advance for all your help.
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65228
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There could be any number of reasons to have such a listener depending upon the needs of the application. If you have something that needs to be done at application startup (not server startup), then this listener is the way to do it.

An example use that I've used: read a properties file containing customer-settable values and store the results as a Map in application context for easy reference by all components of the application.
 
Souvvik Basu
Ranch Hand
Posts: 96
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot for your help.
 
Souvvik Basu
Ranch Hand
Posts: 96
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you please also give me an example of what I should use the contextDestroyed() method for? Should it be used to like...clean up resources etc. being held by the application? Or to close any database connection?
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65228
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've never had a use for the destroyed listener. But yes, anything that needs to be done when the app is winding down can go there.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic