Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Apr 19, 2005

Initializing Application Attributes During Context Initialization

Many applications require some of their attributes to be initialized much before the application is made available to the user or before it can process a request.

Suppose you've got an application with a new version that needs to be present across the application—but it needs to be initialized beforehand. The approach outlined in this tip eliminates the process of retrieving that value from the datastore (or permanent storage location) every time such an initialization is required.

The ServletContextListener interface from the javax.servlet package can perform this operation for you.

First, you need to register the class that implements this interface as a listener element in the web.xml. Then, you implement the methods contextInitialized(ServletContextEvent sce) and contextDestroyed(ServletContextEvent sce) as required.

The class that implements this interface receives notification when the context is initialized, as well as when it gets destroyed.

Here's a sample code fragment:


public class InitializeData implements ServletContextListener {
   public void contextInitialized(ServletContextEvent event) {
      ServletContext context = event.getServletContext();
      setInitialAttribute(context,"app.version",value); 
      // value can be either from a properties file or from a datasource    
      // or any-other source
   }

   public void contextDestroyed(ServletContextEvent event){
      //code that needs to be done when the context is destroyed.
      //can be like destroying the thread or closing resources etc.
   }

   private void setInitialAttribute(ServletContext context,
      String initParamName,String initialValue) {
         context.setAttribute(initParamName, initialValue);
   }

   //other methods can also come in
}
The attribute that is set can be retrieved across the application using the getServletContext().getAttribute("app.version") and used appropriately.
MS Sridhar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap