Home Servlets A Holistic counter in Servlet



A Holistic counter in Servlet
Posted on: March 12, 2008 at 12:00 AM
In this program we are going to make a such a servlet which will count the number it has been accessed and the number of threads created by the server.

A Holistic counter in Servlet

     

In this program we are going to make a such a servlet which will count the number it has been accessed and the number of threads created by the server.

In this example firstly we are going to create one class named as HolisticCounterInServlet. Now declare a variable counter of int with initial value 0, the value of this counter will be different for each servlet and create a Hashtable object. This object will be shared by all the threads in the container. Inside the doGet() method use the method getWriter() method of the response object which will return the PrintWriter object. 

The code of the program is given below:

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

public class HolisticCounter extends HttpServlet{
int counter = 0//separate For Each Servlet
static Hashtable hashTable = new Hashtable()//Shared by all the threads 

public void doGet(HttpServletRequest request, HttpServletResponse response)
     
throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  counter++;
  pw.println("This servlet has been accessed" + counter + "times<br>");
  hashTable.put(this,this);
  pw.println("There are currently" + hashTable.size() "threads<br>");
  }
}

The output of the program is given below:

Download this example:

Related Tags for A Holistic counter in Servlet:
cideclassliststlservertablehashobjectdiffservletcountmakemethodvariablesedprintgethashtablethreadsvaluenumberreadthreadnamereturnintriathisidresponseaiwritecreatetabsharedcontainerifforexamplewithshareprogramtoiniramexameachhtassecountersheilitadsliinitvarusefirstceinnoshadifferentasmntsidsidestiletjadclesdeclareallnamedmehriccobjprodoxawhichxampwritersurnsuspcreatedeeessespetwatkisirhallmplgoeaandarccrvvatwssrirenthstaccessabablalufeeclinitialjepleplprprintwriterndonogrolo


More Tutorials from this section

Ask Questions?    Discuss: A Holistic counter in Servlet   View All Comments

Post your Comment


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

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.