Servlets Hits Counter

This example illustrates about counting how many times the servlet is accessed. When first time servlet (CounterServlet) runs then session is created and value of the counter will be zero and after again accessing of servlet the counter value will be increased by one. In this program isNew() method is used whether session is new or old and getValue() method is used to get the value of counter.

Following are the steps to be taken to implement a simple page hit counter which is based on Servlet Life Cycle:

Popular Tutorials

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

public class CounterServlet extends HttpServlet{
  public void doGet(HttpServletRequest request, 
  HttpServletResponse response)
  throws ServletException, IOException {
  HttpSession session = request.getSession(true);
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  Integer count = new Integer(0);
  String head;
  if (session.isNew()) {
  head = "This is the New Session";
  } else {
  head = "This is the old Session";
  Integer oldcount =(Integer)session.getValue("count"); 
  if (oldcount != null) {
  count = new Integer(oldcount.intValue() + 1);
  }
  }
  session.putValue("count", count);
  out.println("<HTML><BODY BGCOLOR=\"#FDF5E6\">\n" +
  "<H2 ALIGN=\"CENTER\">" + head + "</H2>\n" + 
  "<TABLE BORDER=1 ALIGN=CENTER>\n"
  + "<TR BGCOLOR=\"#FFAD00\">\n" 
  +"  <TH>Information Type<TH>Session Count\n" 
  +"<TR>\n" +" <TD>Total Session Accesses\n" +
  "<TD>" + count + "\n" +
  "</TABLE>\n" 
  +"</BODY></HTML>" );
  }
}

Mapping of Servlet ("CounterServlet.java") in web.xml file
<servlet>
  <servlet-name>CounterServlet</servlet-name>
  <servlet-class>CounterServlet</servlet-class>
</servlet> 
<servlet-mapping>
  <servlet-name>CounterServlet</servlet-name>
  <url-pattern>/CounterServlet</url-pattern>
</servlet-mapping>

Running the servlet by this url:
http://localhost:8080/CounterServlet
displays the figure below:
Servlets Hits Counter

When servlet is hit six times by the user the counter value will be increased by six as shown in figure below:

Example Servlets Hits Counter


Servlet Related Posts
  1. Java Servlets Overview
  2. Servlet Life Cycle
  3. Servlet Example
  4. Difference between ServletConfig and ServletContext
  5. Difference between GenericServlet and HttpServlet
  6. What is web application?
  7. Advantages of Servlets over CGI
  8. GenericServlet Example
  9. RequestDispatcher Example
  10. ServletConfig
  11. ServletContext
  12. Servlet Filter Example
  13. Database Access Example using Sevlet
  14. File Uploading Example using Servlet


<<Previous <<   || Index ||   >>Next >>



Labels: