Q. Explain the purpose of session handling in Servlets with example.
1.
Introduction
HTTP is a stateless protocol, meaning it does not remember users between requests.
Session handling in Servlets helps to maintain state across multiple client requests, allowing
web applications to remember users and their data temporarily.
2.
Purpose of Session Handling
Use Case Description
User Login Retains login info across pages
Shopping Cart Stores selected items until checkout
User Preferences Stores temporary choices (language, theme, etc.)
Secure Access Ensures only logged-in users can access certain pages
3.
Session Management Techniques in Servlets
1. Cookies – Small files stored in the browser.
2. URL Rewriting – Adds session ID to the URL.
3. Hidden Form Fields – Passes data using forms.
4. HttpSession (Recommended) – Built-in object to manage sessions easily.
4.
Common HttpSession Methods
Method Description
getSession() Returns current session or creates new
setAttribute(name, value) Stores data in session
Method Description
getAttribute(name) Retrieves data from session
invalidate() Ends the session
5.
Simple Example Program
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Create session or get existing
HttpSession session = request.getSession();
// Set session attribute
session.setAttribute("username", "Arun");
// Get session attribute
String name = (String) session.getAttribute("username");
// Display welcome message
out.println("<h2>Welcome, " + name + "!</h2>");
}
}
6.
Output in Browser
Welcome, Arun!
7.
Life Cycle of a Session
1. Created – When getSession() is first called.
2. In Use – While user interacts with the application.
3. Timeout/Invalidated – Ends after inactivity or by invalidate().
8.
Advantages of Using HttpSession
• Stores data per user
• Easy to use with built-in methods
• Secure and scalable
• Eliminates need for manual tracking
9.
Conclusion
Session handling using HttpSession in Servlets is crucial for building interactive and user-
friendly web applications. It enables the server to track user activity across multiple requests,
supporting personalized and secure experiences.