Starter Tutorials Blog
Tutorials and articles related to programming, computer science, technology and others.
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.
Home » Programming » Advanced Java » Servlets » Java program to create a Servlet for counting the number of times a servlet page is accessed
Suryateja Pericherla Categories: Servlets. No Comments on Java program to create a Servlet for counting the number of times a servlet page is accessed
Join Our Newsletter - Tips, Contests and Other Updates
Email
Name

Aim

Write a java program to create a Servlet for counting the number of times a servlet page is accessed.

 

Theory

Session Object

Session object allows the user to store session data on the server-side. This may be a burden on the server if the application is accessed by large number of users. Servlet API provides HttpSession interface to manage the session objects.

 

We can get the reference of a session object by calling  getSession() of HttpServletRequest as shown below:

HttpSession  session = request.getSession();

 

HttpSession interface provides the following functionality:

  • Object getAttribute(String name)
  • Enumeration getAttributeNames()
  • String getId()
  • void invalidate()
  • void setAttribute(String name, Object value)
  • void removeAttribute(String name)

 

Program

index.html

<html>
<head>
<title>Login</title>
</head>
<body>
	<form action="PageHitCount" method="get">
		<input type="submit" value="Get Hit Count" />
	</form>
</body>
</html>

 

PageHitCount

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

public class PageHitCount extends HttpServlet {
	
	HttpSession session;
	int count;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		session = request.getSession();
		if(session.getAttribute("count") != null) {
			count = Integer.parseInt(session.getAttribute("count").toString());
			count++;
			session.setAttribute("count", count);
			response.getWriter().print("Hit count = " + count);
		}
		else {
			count = 0;
			session.setAttribute("count", count);
			response.getWriter().print("Hit count = " + count);
		}
	}
}

 

Input and Output

index.html

Servlet Hit Count Client

 

PageHitCount

Servlet Hit Count Server Side

 

 

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Leave a Reply

Your email address will not be published. Required fields are marked *

Facebook
Twitter
Pinterest
Youtube
Instagram
Blogarama - Blog Directory