9-Feb-05 (Created: 9-Feb-05) | More in 'CS-Java'

Writing an initialization servlet

why

These days j2ee applications can be developed with out necessarily resorting to writing servlets. On the easiest of the paths one can use just JSPs to write their applications. Or if one were to use servlet controllers then also one rarely needs to write a servlet. Nevertheles even in those cases you have no servlets of your own other than what the frameworks provide, you may want to make sure certain parts of your application is initialized prior to accepting any requests from the clients. The following sample code will give you everything you need to do this quickly.

Minimum code for a startup servlet


package com.mycomp.servlet;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

public class MyAppInitServlet extends HttpServlet
{
	public void init(ServletConfig config) throws ServletException
	{
		//Your initialization code goes here
	}
}

Register your servlet in the web.xml


<servlet>
  <servlet-name>MyAppInitServlet</servlet-name>
  <servlet-class>com.mycomp.servlet.MyAppInitServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
/servlet>

Please note that the order of the above entries inside servlet are important to some app servers that perform dtd validation. For example the load on startup should come after the servlet class, so on and so forth.