Counter in Init and Destroy method

Counter in Init and Destroy method


Posted in : Java Posted on : June 24, 2011 at 7:07 PM Comments : [ 0 ]

In this section we will discuss how can we specify a counter values with init and destroy method.

Counter in Init and Destroy method

In this section we will discuss how can we specify a counter values with init and destroy method.

The servlet that has given the feature to store their state in destroy() method and the state is reloaded into init() method. init() and destroy() method approaches to the persistancy through the load that a counter doesn't start over.

Example :

CountInitDestroy.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CountInitDestroy extends HttpServlet {
int count;
public void init(){
try {
FileReader fr = new FileReader("CountInitDestroy.begining");
BufferedReader br = new BufferedReader(fr);
String begining = br.readLine();
count = Integer.parseInt(begining);
return;

} catch (FileNotFoundException f) {
} 
catch (IOException io) {
}
catch (NumberFormatException nf) {
} 
String beginning = getInitParameter("beginning");
try {
count = Integer.parseInt(beginning);
return;
} catch (NumberFormatException ignored) {
} 
count = 0;
}

public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter pw = res.getWriter();
count++;
if(count==1)
pw.println("From the beginning, this servlet has been accessed "
+ count + " time.");
else
{
pw.println("From the beginning, this servlet has been accessed "
+ count + " times.");
}
}

public void destroy() {
state();
}

public void state() {
try {
FileWriter fileWriter = new FileWriter("CountInitDestroy.beginning");
String begin = Integer.toString(count);
fileWriter.write(begin, 0, begin.length());
fileWriter.close();
return;

} catch (IOException e) {
}
}
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>counterByInitDestroy</display-name>
<servlet>
<servlet-name>CountInitDestroy</servlet-name>
<servlet-class>CountInitDestroy</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CountInitDestroy</servlet-name>
<url-pattern>/CountInitDestroy</url-pattern>
</servlet-mapping>
</web-app>

Output :

When you will execute the example you will find the following output.

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics