Home Servlets Simple Counter In Servlet



Simple Counter In Servlet
Posted on: July 14, 2007 at 12:00 AM
In this example we are going to know how we can make a program on counter which will keep track how many times the servlet has been accessed.

Simple Counter in Servlet

     

In this example we are going to know how we can make a program on counter which will keep track how many times the servlet has been accessed. 

To make this program firstly we have to make one class SimpleCounterInServlet. The name of the class should follow the  naming convention. Remember to keep the name of the class in such a way that it becomes easy to understand what the program is going to do just by seeing the class name. After making a class define one variable counter which will keep record for how many times the servlet has been accessed. Now use method either doGet() or doPost() to write a logic of the program. Our program logic is simple. We have to just increment the value of the counter by 1. To display the output use the method getWriter() method of the response object which will in turn return the object  of the PrintWriter class. Now display the value of the counter. 

The code of the program is given below:

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

public class SimpleCounter extends HttpServlet{
  int counter = 0;
  public void doGet(HttpServletRequest request, HttpServletResponse
    response
)throws ServletException, IOException {
  response.setContentType("text/html");
  PrintWriter pw = response.getWriter();
  counter++;
  pw.println("At present the value of the counter is " + counter);
  }
}

The output of the program is given below:

Download this example:

Related Tags for Simple Counter In Servlet:
ccomclassstltimeioservletcountmakevariablesednamingnameriathissimpledefineforrecordprogramtorammembersseldcountersheilitconventionvarulimmanfirstceinamiasstamntminminletjafterclesemmehowprodowhichsremembersueeessatanykisirhaimellmplgofolloweaandarccrvsimvassrirdthshoavstaccessabablafhatfinmanypleplprmindonomogrolo


More Tutorials from this section

Ask Questions?    Discuss: Simple 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.