Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Servlets: GET/POST Requests, Redirecting, Session Tracking, and Cookies

Lesson 44 of 46 in the free Web Technologies notes on Siksha Sarovar, written by Rohit Jangra.

Servlets: GET/POST Requests, Redirecting, Session Tracking, and Cookies

Handling HTTP GET Requests

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String name = req.getParameter("name"); // e.g., /greet?name=Alice
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    out.println("<h2>Hello, " + name + "!</h2>");
}

Handling HTTP POST Requests

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    String username = req.getParameter("username");
    String password = req.getParameter("password");

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    out.println("<p>Login received for: " + username + "</p>");
}

GET vs POST in Servlets

FeaturedoGetdoPost
Data locationURL query stringRequest body
VisibilityVisible in browser URL/historyHidden from URL
Data sizeLimited (URL length)Large payloads allowed
IdempotentYesNo
Use caseFetching/searchingSubmitting forms, login

Redirecting Requests to Other Resources

sendRedirect() — Client-side redirect

resp.sendRedirect("welcome.jsp"); // browser makes a NEW request; URL changes

RequestDispatcher — Server-side forward/include

RequestDispatcher rd = req.getRequestDispatcher("welcome.jsp");
rd.forward(req, resp);   // hands off control internally; URL stays the same
// rd.include(req, resp); // includes another resource's output, then continues
FeaturesendRedirectRequestDispatcher.forward
New requestYes (round-trip to browser)No (internal, same request)
URL in browserChangesStays the same
Request attributes preservedNo (new request)Yes
Can redirect to external siteYesNo (same server only)

Session Tracking

HTTP is stateless — each request is independent. Session tracking techniques let a server recognize a user across multiple requests.

TechniqueHow it works
Hidden form fieldsSession data embedded in a hidden <input> on every form
URL rewritingSession ID appended to every URL (;jsessionid=...)
CookiesSession ID stored in a small file on the client, sent with every request
HttpSessionServer-side object; combines cookies/URL rewriting under one API

Cookies

// Creating and sending a cookie
Cookie userCookie = new Cookie("username", "alice");
userCookie.setMaxAge(60 * 60 * 24); // 1 day, in seconds
resp.addCookie(userCookie);

// Reading cookies on a later request
Cookie[] cookies = req.getCookies();
if (cookies != null) {
    for (Cookie c : cookies) {
        if (c.getName().equals("username")) {
            System.out.println("Welcome back, " + c.getValue());
        }
    }
}

Session Tracking with HttpSession

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    HttpSession session = req.getSession(); // creates one if it doesn't exist

    Integer visitCount = (Integer) session.getAttribute("visitCount");
    if (visitCount == null) {
        visitCount = 1;
    } else {
        visitCount++;
    }
    session.setAttribute("visitCount", visitCount);

    resp.setContentType("text/html");
    resp.getWriter().println("<p>Visit count: " + visitCount + "</p>");
}

Key HttpSession Methods

MethodPurpose
req.getSession()Gets the current session, creating one if needed
req.getSession(false)Gets the current session, or null if none exists
setAttribute(name, value)Stores data in the session
getAttribute(name)Retrieves session data
invalidate()Ends the session (e.g., on logout)
getId()Returns the unique session ID
setMaxInactiveInterval(int seconds)Sets session timeout
Key Takeaway: doGet and doPost handle the two main HTTP methods differently — GET via query parameters, POST via the request body. Use sendRedirect for a full client round-trip and RequestDispatcher.forward for an internal handoff. HttpSession is the standard way to track a user across the stateless HTTP protocol, typically backed by a cookie holding the session ID.