Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Servlets Hit Counter Servlet Example

Related Tutorials


 
 

Share on Google+Share on Google+

Hit Counter Servlet Example

Advertisement
This example illustrates about counting how many times the servlet is accessed.

Hit Counter Servlet Example

     

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.

Here is the source code of 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/CodingDiaryExample/CounterServlet  displays the figure below:

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

Download Source Code

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 26, 2008

Related Tutorials

Discuss: Hit Counter Servlet Example   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:1
Rahul Tiwari
April 25, 2012
discuss

what is the mean of line: HttpSession session = request.getSession(true);
DMCA.com