Counter In init() method

Counter In init() method


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

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

Counter In init() method

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

In this example I used the init() method into which I initialize the count variable to zero. Into the doGet() service method increment the count variable and print the incremented count variable with the help of PrintWriter object pw.

Example :

CounterInit.java

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

public class CounterInit extends HttpServlet {
int count;
public void init(){
count = 0;
}
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
count++;
if(count == 1)
pw.println("From the time of loading this servlet "+
"has been called '" + count + "' time");
else
{
pw.println("From the time of loading this servlet "+
"has been called '" + count + "' times");
}
}
}

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>counterByInit</display-name>
<servlet>
<servlet-name>CounterInit</servlet-name>
<servlet-class>CounterInit</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CounterInit</servlet-name>
<url-pattern>/CounterInit</url-pattern>
</servlet-mapping>
</web-app>

Output :

When you will execute this example first time you will find the following output.

When executing or refreshing it second time and so on you will get that call (number of visiting) is increased according to the number of times executing or refreshing.

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics