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
PageHitCount

Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.



Leave a Reply