Write a note on Session Tracking, Cookies

8.B] Write a note on:
i) Session Tracking
ii) Cookies

Answer:

i) Session Tracking

  • Session simply means a particular interval of time.
  • Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet.
  • Http protocol is a stateless so we need to maintain state using session tracking techniques.
  • Each time user requests to the server, server treats the request as the new request.
  • So we need to maintain the state of an user to recognize to particular user.

There are 2 techniques used in Session tracking:

  • Cookies
  • HttpSession

ii) Cookies

A cookie is a small piece of information that is persisted between the multiple client requests.

By default, each request is considered as a new request.
In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

Advantage of Cookies
  1. Simplest technique of maintaining the state.
  2. Cookies are maintained at client side.
Disadvantage of Cookies
  1. It will not work if cookie is disabled from the browser.
  2. Only textual information can be set in Cookie object.

Note: Additional Expected Question below:

Example Demonstrating Usage of Cookies

Here is a complete example of how to use cookies to store and retrieve user information across different servlets:

1. HTML Form (index.html)

    <form method="post" action="MyServlet">
        Name: <input type="text" name="user" /><br/>
        Password: <input type="password" name="pass" /><br/>
        <input type="submit" value="Submit" />
    </form>

2. Servlet to Handle Form Submission (MyServlet.java)

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

public class MyServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Retrieve form parameters
        String name = request.getParameter("user");
        String pass = request.getParameter("pass");

        // Check password
        if ("1234".equals(pass)) {
            // Create and add cookie
            Cookie ck = new Cookie("username", name);
            response.addCookie(ck);

            // Set content type and write response
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<html><body>");
            out.println("<h2>Login Successful</h2>");
            out.println("<form action='First' method='get'>");
            out.println("<input type='submit' value='Go'>");
            out.println("</form>");
            out.println("</body></html>");
            out.close();
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid password");
        }
    }
}

3. Servlet to Display Welcome Message (First.java)

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

public class First extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Retrieve cookies
        Cookie[] cookies = request.getCookies();
        String userName = "Guest"; // Default value

        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName())) {
                    userName = cookie.getValue();
                    break;
                }
            }
        }

        // Set content type and write response
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html><body>");
        out.println("<h2>Welcome, " + userName + "!</h2>");
        out.println("</body></html>");
        out.close();
    }
}

Summary

index.html:

  • Contains a form to collect username and password.
  • Submits data to MyServlet.

MyServlet.java:

  • Handles POST requests.
  • Validates password and creates a cookie with the username.
  • Provides a button to navigate to First servlet.

First.java:

  • Handles GET requests.
  • Retrieves the cookie and displays a welcome message with the username.

This example demonstrates how to use cookies to store user information and use it across different servlets.

Leave a Reply

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