Permanent servlet in java

Satyapriyanayak
Posted by Satyapriyanayak under Others category on | Points: 40 | Views : 476
Permanent servlet : - Such types of servlet get instantiated on start of the server. The instance of this servlet remains on the server till the server runs. Whenever the server shutdowns then instance of this servlet gets destroyed and before to it destroy () method execute. Life span of 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 doGet(),doPost() or service() method executes. Such types of servlets can be used to perform task on start of server or on stop of server. The servlet can be created by using 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>

Comments or Responses

Login to post response