Tutorials Logic, IN info@tutorialslogic.com

Servlet Session Management HttpSession, Cookies, URL Rewriting: Tutorial, Examples, FAQs & Interview Tips

Servlet Session Management HttpSession, Cookies, URL Rewriting

Servlet Session Management HttpSession, Cookies, URL Rewriting is an important Servlet topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.

For this page, focus on what problem Servlet Session Management HttpSession, Cookies, URL Rewriting solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: under 650 content words; limited checklist/practice/mistake/FAQ notes .

A strong understanding of Servlet Session Management HttpSession, Cookies, URL Rewriting should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.

Servlet Session Management HttpSession Cookies URL Rewriting should be studied as a practical Servlet lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the servlet > session-management page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

Session Management Techniques

HTTP is stateless, so web applications need mechanisms to track users across requests. Servlets support four techniques:

Technique Storage Pros Cons
HttpSession Server-side Secure, large data Server memory usage
Cookies Client-side Persistent, no server memory Size limit (4KB), security risks
URL Rewriting URL parameter Works without cookies Ugly URLs, security risk
Hidden Fields HTML form Simple Only works with forms

HttpSession in Servlet

HttpSession in Servlet
@WebServlet("/session-demo")
public class SessionServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        String username = req.getParameter("username");

        // Get or create session
        HttpSession session = req.getSession(true);

        // Store data
        session.setAttribute("username", username);
        session.setAttribute("loginTime", new java.util.Date());
        session.setAttribute("role", "user");

        // Configure session
        session.setMaxInactiveInterval(30 * 60); // 30 minutes timeout

        // Session info
        String sessionId   = session.getId();
        boolean isNew      = session.isNew();
        long creationTime  = session.getCreationTime();
        long lastAccess    = session.getLastAccessedTime();

        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.println("<p>Session ID: " + sessionId + "</p>");
        out.println("<p>Is New: " + isNew + "</p>");
        out.println("<p>Username: " + session.getAttribute("username") + "</p>");
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // Logout: invalidate session
        HttpSession session = req.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        resp.sendRedirect(req.getContextPath() + "/login");
    }
}

Cookies in Servlet

Cookie Management and URL Rewriting

Cookie Management and URL Rewriting
@WebServlet("/cookie-demo")
public class CookieServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        // ===== Create Cookie =====
        Cookie userCookie = new Cookie("username", "Alice");
        userCookie.setMaxAge(7 * 24 * 60 * 60); // 7 days
        userCookie.setPath("/");
        userCookie.setHttpOnly(true);   // Prevent XSS
        userCookie.setSecure(true);     // HTTPS only
        resp.addCookie(userCookie);

        // ===== Read Cookies =====
        Cookie[] cookies = req.getCookies();
        String username = null;
        if (cookies != null) {
            for (Cookie c : cookies) {
                if ("username".equals(c.getName())) {
                    username = c.getValue();
                    break;
                }
            }
        }

        // ===== Delete Cookie =====
        Cookie deleteCookie = new Cookie("username", "");
        deleteCookie.setMaxAge(0); // Expire immediately
        deleteCookie.setPath("/");
        // resp.addCookie(deleteCookie); // Uncomment to delete

        // ===== URL Rewriting (fallback when cookies disabled) =====
        String encodedUrl = resp.encodeURL(req.getContextPath() + "/profile");
        // Appends ;jsessionid=... if cookies are disabled

        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();
        out.println("<p>Username from cookie: " + username + "</p>");
        out.println("<a href='" + encodedUrl + "'>My Profile</a>");
    }
}

Detailed Learning Notes for Servlet Session Management HttpSession, Cookies, URL Rewriting

When studying Servlet Session Management HttpSession, Cookies, URL Rewriting, separate three things: the concept, the syntax, and the situation where it is useful. This prevents the lesson from becoming a list of commands with no practical meaning.

In Servlet, Servlet Session Management HttpSession, Cookies, URL Rewriting becomes easier when you build a tiny example first, then increase complexity. Add one realistic input, one invalid or boundary input, and one explanation of why the result changes.

  • Identify the main problem this topic solves.
  • Write the smallest possible working example.
  • Change one input or option and observe the result.
  • Note the mistake that would break the example.

Servlet Session Management HttpSession Cookies URL Rewriting Java review example

Servlet Session Management HttpSession Cookies URL Rewriting Java review example
class ServletSessionManagementHttpSessionCookiesURLRewritingReview {
    public static void main(String[] args) {
        String state = "ready";
        System.out.println("Servlet Session Management HttpSession Cookies URL Rewriting: " + state);
    }
}

Servlet Session Management HttpSession Cookies URL Rewriting guard example

Servlet Session Management HttpSession Cookies URL Rewriting guard example
String value = null;
if (value == null) {
    System.out.println("Servlet Session Management HttpSession Cookies URL Rewriting: handle the missing value before continuing");
}
Key Takeaways
  • Explain the purpose of Servlet Session Management HttpSession, Cookies, URL Rewriting before memorizing syntax.
  • Run or trace one small Servlet example and confirm the output.
  • Test one normal case, one edge case, and one mistake case for Servlet Session Management HttpSession, Cookies, URL Rewriting.
  • Write the rule in your own words after checking the example.
  • Connect Servlet Session Management HttpSession, Cookies, URL Rewriting to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Memorizing Servlet Session Management HttpSession Cookies URL Rewriting without the situation where it is useful.
RIGHT Connect Servlet Session Management HttpSession Cookies URL Rewriting to a concrete Servlet task.
Purpose makes syntax easier to recall.
WRONG Testing Servlet Session Management HttpSession Cookies URL Rewriting only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to Servlet Session Management HttpSession Cookies URL Rewriting.
Evidence keeps debugging focused.
WRONG Memorizing Servlet Session Management HttpSession Cookies URL Rewriting without the situation where it is useful.
RIGHT Connect Servlet Session Management HttpSession Cookies URL Rewriting to a concrete Servlet task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to Servlet Session Management HttpSession, Cookies, URL Rewriting, then fix it and explain the fix.
  • Summarize when to use Servlet Session Management HttpSession, Cookies, URL Rewriting and when another approach is better.
  • Write a small example that uses Servlet Session Management HttpSession Cookies URL Rewriting in a realistic Servlet scenario.
  • Change one important value in the Servlet Session Management HttpSession Cookies URL Rewriting example and predict the result first.

Frequently Asked Questions

The common mistake is memorizing syntax without understanding when the behavior changes or fails.

Remember the problem it solves in Servlet, then attach the syntax or steps to that problem.

You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.

They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.