AIM:
To write a program in HTML for invoking a servlet using session tracking.
ALGORITHM:
- Define an HTML form to capture user input (Name) and submit it to the servlet.
- In the servlet, create or retrieve an existing session using
HttpSession. - Track the visit count using session attributes.
- Display the user’s name and visit count on the response page.
- Provide a button to reset the visit count using session attributes.
- Compile and run the servlet on a web server like Tomcat.
- Test the servlet by submitting the form multiple times and observing session behavior.
PROGRAM:
HTML Form (index.html)
<!DOCTYPE html>
<html>
<head>
<title>Session Tracking Form</title>
</head>
<body>
<center>
<h2 style="color:red">Enter Your Name to Start Session</h2>
<form action="SessionServlet" method="POST">
<label>Name:</label>
<input type="text" name="name" required><br><br>
<input type="submit" value="Submit">
</form>
</center>
</body>
</html>
Servlet Code (SessionServlet.java)
import java.io.IOException;
import java.io.PrintWriter;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
public class SessionServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String name = request.getParameter("name");
Integer visitCount = (Integer) session.getAttribute("visitCount");
if (visitCount == null) {
visitCount = 1;
} else {
visitCount++;
}
session.setAttribute("visitCount", visitCount);
if (name != null && !name.trim().isEmpty()) {
session.setAttribute("userName", name);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName = (String) session.getAttribute("userName");
out.println("<html><body><center>");
out.println("<h2>Hello, " + userName + "!</h2>");
out.println("<p>You have visited this page " + visitCount + " times in this session.</p>");
out.println("<a href='index.html'>Go Back to Home</a><br><br>");
out.println("<form action='SessionServlet' method='POST'>");
out.println("<input type='hidden' name='reset' value='yes'>");
out.println("<input type='submit' value='Reset Visit Count'>");
out.println("</form>");
out.println("</center></body></html>");
}
}
Sample Output:
RESULT:
Thus, the invocation of a servlet with session tracking has been developed and tested successfully.