Permanent servlet in Java

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
  1. <servlet>  
  2. <servlet-name>The name of servlet</servlet-name>  
  3. <servlet-class>The class of servlet</servlet-class>  
  4. <load-on-startup>This contains a number of specifying order of execution between permanent servlet</load-on-startup>  
  5. </servlet>  
  6. <servlet>  
Ex: - A permanent servlet to write tomcat's starting time and shut downtime into a file
  1. import javax.servlet.*;  
  2. import javax.servlet.http.*;  
  3. import java.io.*;  
  4. import java.util.*;  
  5. public class write_log extends HttpServlet   
  6. {  
  7.  public void init()   
  8.  {  
  9.   GregorianCalendar gc = new GregorianCalendar();  
  10.   String str = "" + gc.get(Calendar.HOUR);  
  11.   str = str + ":" + gc.get(Calendar.MINUTE);  
  12.   str = str + ":" + gc.get(Calendar.SECOND);  
  13.   try   
  14.   {  
  15.    FileWriter fw = new FileWriter("d:/permanentserv/time123.txt"true);  
  16.    fw.write("\n starts ->" + str);  
  17.    System.out.println("data written to File...");  
  18.    fw.close();  
  19.   } catch (Exception e) {}  
  20.  }  
  21.  public void destroy()   
  22.  {  
  23.   GregorianCalendar gc = new GregorianCalendar();  
  24.   String str = "" + gc.get(Calendar.HOUR);  
  25.   str = str + ":" + gc.get(Calendar.MINUTE);  
  26.   str = str + ":" + gc.get(Calendar.SECOND);  
  27.   try   
  28.   {  
  29.    FileWriter fw = new FileWriter("d:/permanentserv/time123.txt"true);  
  30.    fw.write("\n sutting down ->" + str);  
  31.    fw.close();  
  32.   }   
  33.   catch (Exception e) {}  
  34.  }  
  35. }  
Web.xml settings
  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2. <!DOCTYPE web-app  
  3. PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"  
  4. "http://java.sun.com/dtd/web-app_2_3.dtd">  
  5. <web-app>  
  6.   
  7. <servlet>  
  8. <servlet-name>wl</servlet-name>  
  9. <servlet-class>write_log</servlet-class>  
  10. <load-on-startup>1</load-on-startup>  
  11. </servlet>  
  12. </web-app>  
Storing and Compiling
 
Please follow the below link
 
http://www.c-sharpcorner.com/UploadFile/satyapriyanayak/8515/

 


Similar Articles