Sometimes, you'll want to know the overall number of visitors to a specific page on your website. Because the life cycle of a servlet is governed by the container in which it runs, counting these hits with a servlet is fairly straightforward. The following steps are based on the implementation of a basic Servlet life cycle page hit counter:
- In the init() function, create a global variable.
- Every time the doGet() or doPost() methods are used, the global variable is increased.
- You may utilize a database table to save the value of a global variable in the destroy() method if necessary. When the servlet is next initialized, this value may be read from the init() function. This step is optional.
- If you want to count just unique page hits within a session then you may use the isNew() function to verify if the same page already has been hit within that session. This is an optional step.
- The value of the global counter may be shown to represent the overall number of hits on your website. This is also an optional step.
We'll presume that the Web container can't be restarted in this case. The counter will be reset if you restart or if the Servlet is deleted.
Example
This example demonstrates how to create a simple page hit counter.
Java
import java.io.*;
import java.sql.Date;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GfgServletExample extends HttpServlet {
private int hitCount;
public void init()
{
// Reset hit counter.
hitCount = 0;
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");
// This method executes whenever the servlet is hit
// increment hitCount
hitCount++;
PrintWriter out = response.getWriter();
String title = "Count of total number of hits";
String docType
= "<!doctype html public \"-//w3c//dtd html 4.0 "
+ "transitional//en\">\n";
out.println(
docType + "<html>\n"
+ "<head><title>" + title + "</title></head>\n"
+ "<body bgcolor = \"#f0f0f0\">\n"
+ "<h1 align = \"center\">" + title + "</h1>\n"
+ "<h2 align = \"center\">" + hitCount
+ "</h2>\n"
+ "</body>"
+ "</html>");
}
public void destroy()
{
// This is an optional step,
// however you may store the hitCount value in your
// database if you like.
}
}
Now compile the Servlet above and add the following item to the web.xml file:
XML
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>HitCounter</display-name>
<servlet>
<servlet-name>GfgServletExample</servlet-name>
<servlet-class>GfgServletExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GfgServletExample</servlet-name>
<url-pattern>/GfgServletExample</url-pattern>
</servlet-mapping>
</web-app>
Now by visiting http: to call the Servlet localhost:8080/HitCounter/GfgServletExample. This will refresh the page every time, to increase the value of counter 1, the result is as follows:
Website Hit Counter
You may be interested in knowing the overall number of hits on your entire website on many occasions. In Servlet, this is also quite straightforward, and we can do it by using filters. As a result, the methods to create a basic website hit counter based on the Filter Life Cycle are outlined.
- In the init() method of a filter, set a global variable.
- Every time the doFilter method is run, the global variable is increased.
- You may utilize a database table to save the value of a global variable in the filter's destroy() function if necessary. When the filter is initialized the following time, this value may be read from the init() function. This is an optional step.
We are assuming that the web container will not be restarted at this point. The hit counter will be reset if it is restarted or if the servlet is destroyed.
Java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GfgServletExample implements Filter {
private int hitCount;
public void init(FilterConfig config)
throws ServletException
{
// Reset hit counter.
hitCount = 0;
}
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws java.io.IOException, ServletException
{
// increase counter by one
hitCount++;
// Print the counter.
System.out.println("Visits count is :" + hitCount);
// Pass request back down the filter chain
chain.doFilter(request, response);
}
public void destroy()
{
// This is an optional step,
// however you may store the hitCount value in your
// database if you like.
}
}
Now compile the Servlet above and add the following item to the web.xml file:
XML
...
<filter>
<filter-name>GfgServletExample</filter-name>
<filter-class>GfgServletExample</filter-class>
</filter>
<filter-mapping>
<filter-name>GfgServletExample</filter-name>
<url-pattern>/GfgServletExample</url-pattern>
</filter-mapping>
...
Now by visiting http: to call the Servlet localhost:8080/HitCounter/GfgServletExample. This will refresh the page every time, to increase the value of counter 1, the result is as follows:
Visits count is : 1
Visits count is : 2
Visits count is : 3
Visits count is : 4
Visits count is : 5
...........
Similar Reads
Servlet Container in Java
A Servlet Container is the critical component of the Java's web application architecture and providing an environment where the Java Servlets are the executed. Servlets are the Java programs that can be extend capabilities of the servers, often the used to create dynamic web content. The servlet con
8 min read
Servlet - Cookies
Cookies are the textual information that is stored in key-value pair format to the client's browser during multiple requests. It is one of the state management techniques in session tracking. Basically, the server treats every client request as a new one so to avoid this situation cookies are used.
4 min read
Servlet - FilterChain
A filter is an object that is used throughout the pre-and post-processing stages of a request. Conversion, logging, compression, encryption and decryption, input validation, and other filtering operations are commonly performed using it. Servlet Filter Chain We will learn how to correlate a chain of
5 min read
Servlet - Filter
A filter is an object that is used throughout the pre-and post-processing stages of a request. Filters are mostly used for filtering tasks such as server-side logging, authentication, and authorization, input validation, and so on. The servlet is pluggable, which means that the entry is specified in
3 min read
Servlet - Client HTTP Request
When the user wants some information, he/she will request the information through the browser. Then the browser will put a request for a web page to the webserver. It sends the request information to the webserver which cannot be read directly because this information will be part of the header of t
3 min read
Generic Servlet Class
GenericServlet implements the Servlet interface and provides an implementation for all its method except the service() method hence it is abstract. GenericServlet class defines a protocol-independent(HTTP-less) servlet. However, while building a website or an online application, we may want to have
3 min read
Servlet - Login Form
Using Java, we can prepare elegant web pages that serve the purpose of registering/logging in to the application, and upon authorized authenticated credentials, the rest of the application screens can be seen. Hence it is much essential to have a login form to accept the inputs from users and then v
6 min read
CSS Counters
CSS counters allow you to number elements like lists or sections automatically. They are "variables" maintained by CSS, and their values can be incremented with CSS rules, tracking how many times they are used. To work with CSS counters, we use a set of properties: counter-reset: Creates or resets a
3 min read
Java Servlet Filter
Filters are part of Servlet API Since 2.3. Like a Servlet, a filter object is instantiated and managed by the Container and follows a life cycle that is similar to that of a Servlet. A Servlet has 4 stages as depicted below Instantiate.Initialize.Filter.destroy. These stages are similar to a servlet
4 min read
Servlet - HTTP Status Codes
For each HTTP request and HTTP response, we have messages. The format of the HTTP request and HTTP response messages are similar and will have the following structure â An initial status line + CRLFCRLF = Â ( Carriage Return + Line Feed i.e. New Line )Zero or more header lines + CRLFA blank line, i.e
5 min read