The servlet context is also available when you implement the ServletContextListener. This makes it easy to load parameters such as connection string at start-up. You can define the listener class in web.xml that loads you ServletContextListener at startup of your web application.
Inside the web.xml file, add the <listener>and <context-param> tags. The <listener> specifies the class that is called at startup. The <context-param> tag defines context parameter that is available within your web application.
First, include the <listener>and <context-param> tags in the web.xml file:
<web-app> <!-- ... --> <listener> <listener-class>com.your.package.ServletContextClass</listener-class> </listener> <!-- Init parameters for db connection --> <context-param> <param-name>your_param</param-name> <param-value>your_param_value</param-value> </context-param> <!-- ... --> </web-app>
Now create the servlet context class as follows.
public class ServletContextClass implements ServletContextListener { public void contextInitialized(ServletContextEvent arg0) { //use the ServletContextEvent argument to access the //parameter from the context-param String my_param = arg0.getServletContext().getInitParameter("your_param"); }//end contextInitialized method @Override public void contextDestroyed(ServletContextEvent arg0) { }//end constextDestroyed method }
You can now choose which static variable to assign the parameter you have read. This allows you to read the parameter once at start-up, and reuse many time through the static variable that you assign it to.