Tutorials Logic, IN +91 8092939553 info@tutorialslogic.com
FAQs Support
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Interview Questions Website Development
Compiler Tutorials

JSP Session Management

Why Session Management?

HTTP is a stateless protocol — each request is independent and the server doesn't remember previous requests. Session management techniques allow web applications to maintain state across multiple requests from the same user. There are four main techniques:

  • Cookies — Small data stored on the client's browser
  • URL Rewriting — Session ID appended to every URL
  • Hidden Form Fields — Data stored in hidden HTML inputs
  • HttpSession — Server-side session object (most common)
Cookies in JSP
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<html><body>

<h3>Creating a Cookie</h3>
<%
    // Create a cookie
    Cookie userCookie = new Cookie("username", "Alice");
    userCookie.setMaxAge(60 * 60 * 24 * 7); // 7 days in seconds
    userCookie.setPath("/");                  // Available to entire app
    userCookie.setHttpOnly(true);             // Not accessible via JavaScript
    response.addCookie(userCookie);

    Cookie themeCookie = new Cookie("theme", "dark");
    themeCookie.setMaxAge(60 * 60 * 24 * 30); // 30 days
    response.addCookie(themeCookie);
%>
<p>Cookies set!</p>

<h3>Reading Cookies</h3>
<%
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            out.println("<p>" + c.getName() + " = " + c.getValue() + "</p>");
        }
    } else {
        out.println("<p>No cookies found.</p>");
    }
%>

<h3>Deleting a Cookie</h3>
<%
    // To delete: set max age to 0
    Cookie deleteCookie = new Cookie("username", "");
    deleteCookie.setMaxAge(0);
    deleteCookie.setPath("/");
    response.addCookie(deleteCookie);
%>
<p>Cookie deleted!</p>

</body></html>

HttpSession

HttpSession is the most widely used session management technique. The server creates a session object and assigns it a unique session ID, which is typically stored in a cookie (JSESSIONID) or appended to URLs.

HttpSession and URL Rewriting
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<html><body>

<h3>HttpSession Operations</h3>
<%
    // Get or create session
    HttpSession sess = request.getSession(true); // true = create if not exists

    // Store data in session
    sess.setAttribute("username", "Alice");
    sess.setAttribute("role", "admin");
    sess.setAttribute("loginTime", new java.util.Date());

    // Set session timeout (in seconds)
    sess.setMaxInactiveInterval(30 * 60); // 30 minutes

    // Retrieve data
    String username = (String) sess.getAttribute("username");
    String role     = (String) sess.getAttribute("role");
    String sessId   = sess.getId();
    boolean isNew   = sess.isNew();
%>
<p>Username: <%= username %></p>
<p>Role: <%= role %></p>
<p>Session ID: <%= sessId %></p>
<p>Is New Session: <%= isNew %></p>

<h3>URL Rewriting (fallback when cookies disabled)</h3>
<%
    // encodeURL appends ;jsessionid=... if cookies are disabled
    String encodedUrl = response.encodeURL("profile.jsp");
    String encodedRedirect = response.encodeRedirectURL("dashboard.jsp");
%>
<a href="<%= encodedUrl %>">My Profile</a>

<h3>Hidden Form Fields</h3>
<form action="process.jsp" method="post">
    <input type="hidden" name="userId" value="<%= sess.getAttribute("userId") %>"/>
    <input type="text" name="comment" placeholder="Enter comment"/>
    <button type="submit">Submit</button>
</form>

</body></html>
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<%
    // Invalidate the session (logout)
    HttpSession sess = request.getSession(false);
    if (sess != null) {
        sess.removeAttribute("username"); // Remove specific attribute
        sess.invalidate();                // Destroy entire session
    }

    // Delete session cookie
    Cookie sessionCookie = new Cookie("JSESSIONID", "");
    sessionCookie.setMaxAge(0);
    sessionCookie.setPath("/");
    response.addCookie(sessionCookie);

    // Redirect to login page
    response.sendRedirect("login.jsp");
%>

Ready to Level Up Your Skills?

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