Explain following with example:(i) Cookies.(ii) Session Tracking.

Cookies

Cookies are small pieces of data stored on the client-side, typically by a web browser, to maintain state information between HTTP requests. They are commonly used to store user preferences, track user activities, and facilitate features like shopping carts in web applications. Cookies are sent between the client (browser) and the server with each HTTP request and response, allowing web applications to remember and recognize users.

Anatomy of a Cookie:

A cookie consists of key-value pairs along with additional attributes that define its behavior. The key-value pairs store data, and the attributes control the cookie’s lifespan, security, and accessibility.

Example of a Set-Cookie Header:

Set-Cookie: username=johndoe; expires=Thu, 10 Dec 2023 12:00:00 GMT; path=/; domain=.example.com; secure; HttpOnly

In this example:

  • username=johndoe: The key-value pair representing the data.
  • expires: Sets the expiration date of the cookie.
  • path: Specifies the URL path for which the cookie is valid.
  • domain: Specifies the domain to which the cookie belongs.
  • secure: Indicates that the cookie should only be sent over secure (HTTPS) connections.
  • HttpOnly: Restricts access to the cookie to HTTP requests and prevents JavaScript access for added security.

Cookie Creation and Retrieval (Servlet Example):

Let’s illustrate cookie creation and retrieval in a Java servlet.

  1. Creating a Cookie (Java Servlet):
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/SetCookieServlet")
public class SetCookieServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Create a new cookie
        Cookie usernameCookie = new Cookie("username", "johndoe");

        // Set additional cookie attributes
        usernameCookie.setMaxAge(3600); // Cookie will expire in 1 hour
        usernameCookie.setPath("/");    // Cookie is valid for the entire application context

        // Add the cookie to the response
        response.addCookie(usernameCookie);

        response.getWriter().println("Cookie set successfully.");
    }
}
  1. In this example, a servlet named SetCookieServlet creates a cookie named username with the value johndoe. Additional attributes like expiration time and path are set.
  2. Retrieving a Cookie (Java Servlet):
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/GetCookieServlet")
public class GetCookieServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Retrieve cookies from the request
        Cookie[] cookies = request.getCookies();

        // Check if cookies exist
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                // Check for the desired cookie
                if (cookie.getName().equals("username")) {
                    String username = cookie.getValue();
                    response.getWriter().println("Username from Cookie: " + username);
                    return;
                }
            }
        }

        response.getWriter().println("Cookie not found.");
    }
}
  1. The GetCookieServlet retrieves cookies from the request and looks for a specific cookie named username. If found, it retrieves and prints the username.

Pros and Cons of Cookies:

Pros:

  1. Simplicity: Cookies are easy to implement and use.
  2. Versatility: They can store various types of data, including user preferences and session information.
  3. Client-Side Storage: Since cookies are stored on the client side, they help offload server-side storage.

Cons:

  1. Size Limitations: Cookies have size limitations, typically around 4 KB.
  2. Security Concerns: Cookies may pose security risks if not handled properly. Attributes like HttpOnly and Secure help mitigate risks.
  3. Limited Lifespan: Cookies have an expiration date and are deleted after that time.

Session Tracking

Session tracking is a mechanism used to maintain state information about a user across multiple requests in a web application. Unlike cookies, which are stored on the client-side, session tracking involves storing data on the server to maintain user-specific information. Sessions are critical for managing user authentication, personalization, and tracking user activities during a web session.

Types of Session Tracking:

  1. Cookies-based Session Tracking:
    • A unique session identifier is stored on the client-side as a cookie. The server associates this identifier with the user’s session data.
// Creating a session and setting a session attribute (Java Servlet)
HttpSession session = request.getSession();
session.setAttribute("username", "johndoe");
  • The session ID is sent back and forth between the client and server with each request.

URL Rewriting:

  • Session information is encoded and appended to URLs. This technique is less common today due to security concerns.
// Encoding session ID in URL (Java Servlet)
String url = response.encodeURL("example.jsp");

Hidden Form Fields:

  • Session data is embedded as hidden fields in HTML forms. This data is submitted back to the server when the form is submitted.
<!-- Hidden form field for session ID -->
<input type="hidden" name="sessionId" value="ABC123">

HTTP Session Object:

  • The HttpSession object allows the storage of session data on the server side. It is identified by a unique session ID sent to the client as a cookie.
// Creating a session and setting a session attribute (Java Servlet)
HttpSession session = request.getSession();
session
JOIN OUR NEWSLETTER
And get notified everytime we publish a new blog post.

Add a Comment

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