Permanent servlet:
This type of servlet gets instantiated on the start of the server. The instance of
this servlet remains on the server till the server stops running. Whenever the server
shutdowns then instance of this servlet gets destroyed, after running its it destroy() method. The life span of the servlet is same as the life span of the server.
Such type of servlet is independent of users appearance. If any user come to
access this servlet then the doGet(),doPost() or service() method executes. Such
types of servlets can be used to perform tasks on the start of a server or on the stop of a server. The servlet can be created by using a generic or http servlet. During
deployment of this servlet a tag must be used as <load-on-startup>
Web.xml settings
<servlet>
<servlet-name>The name of servlet</servlet-name>
<servlet-class>The class of servlet</servlet-class>
<load-on-startup>This contains a number of specifying order of execution between
permanent servlet</load-on-startup>
</servlet>
<servlet>
Ex: - A permanent servlet to write tomcat's starting time and shut down time
into a file
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class write_log extends HttpServlet
{
public void init()
{
GregorianCalendar gc=new GregorianCalendar();
String str=""+gc.get(Calendar.HOUR);
str=str+":"+gc.get(Calendar.MINUTE);
str=str+":"+gc.get(Calendar.SECOND);
try
{
FileWriter fw=new FileWriter("d:/permanentserv/time123.txt",true);
fw.write("\n starts ->"+str);
System.out.println("data written to File...");
fw.close();
}
catch(Exception e){}
}
public void destroy()
{
GregorianCalendar gc=new GregorianCalendar();
String str=""+gc.get(Calendar.HOUR);
str=str+":"+gc.get(Calendar.MINUTE);
str=str+":"+gc.get(Calendar.SECOND);
try
{
FileWriter fw=new FileWriter("d:/permanentserv/time123.txt",true);
fw.write("\n sutting down ->"+str);
fw.close();
}
catch(Exception e){}
}
}
Web.xml settings
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<servlet>
<servlet-name>wl</servlet-name>
<servlet-class>write_log</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
</web-app>
Storing and Compiling
Please follow the below link
http://www.c-sharpcorner.com/UploadFile/satyapriyanayak/8515/