Session Tracking in Servlets
Session Tracking is a way to maintain the state (data) of a user, and it is also known as session management in a servlet. Since the HTTP protocol is stateless, we need to use session tracking techniques to maintain the state of a user and identify the particular user on subsequent requests.
Why Use Session Tracking?
Session tracking is used to recognize the user across multiple requests. Since HTTP is stateless, each request is treated as a new one, making it necessary to maintain state between requests.
HTTP Protocol - Stateless
HTTP is stateless, meaning each request is treated independently. Below is a simple illustration of how HTTP treats requests:
Backward Skip 10s
Play Video
Forward Skip 10s
Session Tracking Techniques
There are four primary techniques used in session tracking:
- Cookies
- Hidden Form Field
- URL Rewriting
- HttpSession
1. Cookies
Cookies are small pieces of data stored on the client's browser. They can be used to store the session ID, which is sent back to the server on each subsequent request. Cookies are the most common mechanism used for session tracking.
2. Hidden Form Field
In this technique, the session ID is passed as a hidden field in HTML forms. When the user submits a form, the session ID is sent back to the server as part of the form data.
3. URL Rewriting
URL rewriting involves appending the session ID to the URL of every request. This ensures that the server can identify the session from the URL, even if cookies are disabled in the client's browser.
4. HttpSession
The HttpSession interface in servlets provides a way to store session-specific data on the server side. A session is created by calling request.getSession(), and you can store data using session.setAttribute().
Cookies in Servlets
A cookie is a small piece of information that is persisted between multiple client requests. It allows the server to store data on the client side, which can be retrieved on subsequent requests.
How Cookies Work
By default, each HTTP request is treated as a new request. However, with cookies, we can add a cookie to the response from the servlet. The cookie is then stored in the browser's cache. On subsequent requests, the browser sends the cookie along with the request, allowing the server to recognize the user and maintain state.
Types of Cookies
There are two types of cookies in Servlets:
- Non-persistent cookie: This cookie is valid for a single session and is removed when the user closes the browser.
- Persistent cookie: This cookie is valid for multiple sessions and is not removed when the browser is closed. It remains until the user logs out or explicitly deletes it.
Advantages and Disadvantages of Cookies
Advantages:
- Simple technique for maintaining state.
- Cookies are maintained on the client side, reducing server load.
Disadvantages:
- Cookies may not work if they are disabled in the browser.
- Only textual information can be stored in cookies.
Using Cookies in Servlets
The javax.servlet.http.Cookie class provides the functionality to manage cookies in a servlet.
Cookie Constructor
- Cookie(String name, String value): Constructs a cookie with a specified name and value.
Useful Methods of the Cookie Class
| Method | Description |
|---|---|
setMaxAge(int expiry) |
Sets the maximum age of the cookie in seconds. |
getName() |
Returns the name of the cookie. The name cannot be changed after creation. |
getValue() |
Returns the value of the cookie. |
setName(String name) |
Changes the name of the cookie. |
setValue(String value) |
Changes the value of the cookie. |
Example: Creating, Deleting, and Retrieving Cookies
Creating a Cookie
Here’s how to create a cookie and add it to the response:
Cookie ck = new Cookie("user", "Balaji Goddu"); // creating cookie object
response.addCookie(ck); // adding cookie to the response
Deleting a Cookie
To delete a cookie, you set its value to an empty string and its maximum age to zero:
Cookie ck = new Cookie("user", ""); // deleting the value of the cookie
ck.setMaxAge(0); // changing the maximum age to 0 seconds
response.addCookie(ck); // adding cookie in the response to delete it
Retrieving Cookies
To get the cookies sent with the request, you can use the getCookies() method:
Cookie[] ck = request.getCookies();
for (int i = 0; i < ck.length; i++) {
out.print("<br>" + ck[i].getName() + " " + ck[i].getValue()); // printing name and value of cookie
}
Example Servlet: Using Cookies for User Authentication
index.html
Below is the HTML form where the user inputs their name:
<form action="FirstServlet" method="post">
Name: <input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
The first servlet processes the form and stores the user's name in a cookie:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = request.getParameter("userName");
out.print("Welcome " + n);
// Creating cookie object
Cookie ck = new Cookie("uname", n);
response.addCookie(ck); // Adding cookie in the response
// Creating submit button
out.print("<form action='SecondServlet'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
SecondServlet.java
The second servlet retrieves the user's name stored in the cookie:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Retrieving cookies
Cookie[] ck = request.getCookies();
out.print("Hello " + ck[0].getValue());
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
HttpSession Object in Servlets
The HttpSession object is used to track the session of a user across multiple requests. It allows a server to store information about a user's interactions with the web application, such as login credentials, preferences, or other session-related data. The session is created when a user first visits a web application and persists as long as the user interacts with the application.
The HttpServletRequest interface provides two methods to get the object of HttpSession:
-
public HttpSession getSession():
Returns the current session associated with this request, or if the request does not have a session, creates one.
-
public HttpSession getSession(boolean create):
Returns the current
HttpSessionassociated with this request or, if there is no current session andcreateis true, returns a new session.
Key Methods in HttpSession
Here’s a breakdown of the key methods available in the HttpSession interface:
| Method | Description |
|---|---|
getId() |
Returns the unique session ID associated with the session. |
getAttribute(String name) |
Retrieves the value of an attribute stored in the session. |
setAttribute(String name, Object value) |
Stores an attribute in the session with a given name and value. |
removeAttribute(String name) |
Removes an attribute from the session. |
getCreationTime() |
Returns the time when the session was created. |
getLastAccessedTime() |
Returns the last time the session was accessed. |
invalidate() |
Invalidates the session, removing all attributes and ending the session. |
getMaxInactiveInterval() |
Returns the maximum time interval (in seconds) between client requests before the session is invalidated. |
setMaxInactiveInterval(int interval) |
Sets the maximum time interval (in seconds) before the session is invalidated. |
isNew() |
Returns true if the session is newly created, or false if it already exists. |
Login and Logout Functionality Example
In the following example, we will implement basic login and logout functionality using HttpSession:
- Login: The user will input their credentials (username and password), and the servlet will check if the credentials are valid. If so, a session will be created to store user information.
- Logout: When the user logs out, the session will be invalidated, and the user will be redirected to a logout page.
Login Page (index.html)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
<link rel="stylesheet" href="../css/styles.css">
</head>
<body>
<div id="header-container"></div>
<main>
<h2>Login</h2>
<form action="LoginServlet" method="post">
Username: <input type="text" name="username" required/><br/>
Password: <input type="password" name="password" required/><br/>
<input type="submit" value="Login"/>
</form>
</main>
<div id="footer-container"></div>
<script src="../js/scripts.js"></script>
</body>
</html>
LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get the user input
String username = request.getParameter("username");
String password = request.getParameter("password");
// Simple validation (this can be replaced with real authentication logic)
if ("user".equals(username) && "password".equals(password)) {
// Create session and store user information
HttpSession session = request.getSession();
session.setAttribute("username", username);
session.setAttribute("isLoggedIn", true);
// Redirect to the welcome page
response.sendRedirect("WelcomeServlet");
} else {
// Invalid login, redirect back to login page
response.sendRedirect("index.html");
}
}
}
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get the session
HttpSession session = request.getSession(false); // false to avoid creating a new session
// Check if session exists and user is logged in
if (session != null && session.getAttribute("isLoggedIn") != null && (boolean) session.getAttribute("isLoggedIn")) {
// Display welcome message
String username = (String) session.getAttribute("username");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h2>Welcome, " + username + "</h2>");
out.println("<a href='LogoutServlet'>Logout</a>");
} else {
// Redirect to login page if not logged in
response.sendRedirect("index.html");
}
}
}
LogoutServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Get the session and invalidate it
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate(); // End the session
}
// Redirect to the login page
response.sendRedirect("index.html");
}
}