Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

JSP and Servlets
  • Servlets and JSP: What a Servlet Container Does and How a JSP Becomes a Servlet
  • Set Up Tomcat 11 and a Maven Web Project in IntelliJ IDEA
  • The Servlet Request Lifecycle: @WebServlet, web.xml, init, doGet and destroy
  • Servlet Request Parameters, and Forward vs Redirect
  • Run a Java Web App in Docker: Tomcat 11 With One Compose Command
  • Sessions, Cookies and Filters in Java Servlets: Log In Once, Stay Logged In
  • Servlets and JSP: What a Servlet Container Does and How a JSP Becomes a Servlet
  • JSP Scripting: Expressions, Scriptlets, Declarations, Comments and Includes
  • JavaBeans and JSP Scopes: Page, Request, Session and Application
  • JSP Expression Language Step by Step: ${...} for Beans, Maps, Lists, Params and Scopes
  • JSTL Core Tags: c:set, c:out, c:if, c:choose and c:forEach
  • JSTL Functions and Formatting: fn:length, fn:toUpperCase, fn:contains, fmt:formatNumber and fmt:formatDate
  • Maintaining and Migrating Legacy JSP With AI: Explain the Page, Refactor to a DAO, Servlet and JSTL, Then Move It to React
  • MVC and the Front Controller With Servlets and JSP
  • Forms With JSP and Servlets: Handle the POST and Validate on the Server
  • Mini App With Servlets and JSP: Login, Logout and a Shared Web Template
  • SQLite and a JDBC Connection Pool in a Java Web App
  • Users CRUD With Servlets and JSP, Part 1: Add and List Through a DAO
  • Users CRUD With Servlets and JSP, Part 2: Update and Delete
  1. Blog
  2. /
  3. JSP and Servlets
  4. /
  5. Servlets

Sessions, Cookies and Filters in Java Servlets: Log In Once, Stay Logged In

HTTP treats every request as a stranger. A session on the server, a JSESSIONID cookie in the browser and one LoginFilter on /* let you log in once and keep every page behind the login.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Servlets

What you will learn

  • Explain why HTTP forgets you and how a session plus a JSESSIONID cookie fixes it
  • Store the logged-in user in HttpSession and a preference in a cookie
  • Guard every page with one @WebFilter that lets /login through
  • Log out with session.invalidate

Before you start

  • Servlet Request Parameters, and Forward vs Redirect
  • Forms With JSP and Servlets

HTTP is a stateless protocol: the server doesn't know who you are from one request to the next. You log in as Olivia and the server says "Welcome, Olivia". Then you open /tasks, and that's a brand-new request, so the server asks "who are you?" all over again. Sessions, cookies and filters together fix that. You log in once, you stay logged in, and every page sits behind the login.

How the server remembers you

The browser holds two cookies, JSESSIONID and username. The server holds a session with that id, containing user equals olivia. On every request the browser sends JSESSIONID, and the server uses it to find the session. Browser: cookies JSESSIONID = the id username = olivia Server: sessions session with that id user = "olivia" kept on the server sent on every request Like a cloakroom: the coat stays inside, you carry the token.
The session lives on the server; the browser only carries its id in a cookie.
  1. You log in as olivia. The server creates a session with an id and keeps user = olivia inside it.
  2. The answer brings two cookies: JSESSIONID (just that id) and username.
  3. You open /tasks. The browser sends JSESSIONID, the id finds the session, and the server says "Hello, olivia".
  4. You log out. The server deletes the session, but the username cookie stays and fills in the login form next time.

A cookie is just two headers

A cookie is a small value the browser keeps for a website. On login the server answers with Set-Cookie headers, one for JSESSIONID and one for username with a max age of 30 days. Every later request carries them back in a Cookie header.

Users can see and edit their cookies. So keep only an id or a preference (dark mode, a remembered username) in a cookie, never "this user is logged in". Without a max age, a cookie disappears when the browser closes; with one, it's kept until it expires.

Login: a session and a cookie go out

package org.studyeasy.web;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String name = "";
        if (req.getCookies() != null) {             // null when the browser sent none
            for (Cookie cookie : req.getCookies()) {
                if (cookie.getName().equals("username")) name = cookie.getValue();
            }
        }
        resp.setContentType("text/html");
        resp.getWriter().println("<h2>Log in</h2>"
                + "<p>Demo login: olivia / <demo-password></p>"
                + "<form method='post'>"
                + "<p>Username: <input name='username' value='" + name + "'></p>"
                + "<p>Password: <input name='password' type='password'></p>"
                + "<button>Log in</button></form>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        String name = req.getParameter("username");
        String password = req.getParameter("password");
        if ("olivia".equals(name) && "<demo-password>".equals(password)) {
            req.getSession().setAttribute("user", name);    // on the server
            Cookie cookie = new Cookie("username", name);   // in the browser
            cookie.setMaxAge(60 * 60 * 24 * 30);            // 30 days, in seconds
            resp.addCookie(cookie);
            resp.sendRedirect(req.getContextPath() + "/tasks");
        } else {
            resp.sendRedirect(req.getContextPath() + "/login");   // try again
        }
    }
}
  • doGet shows the form. It reads the cookies (getCookies() is null when the browser sent none), and a username cookie pre-fills the box. In a private window there's no cookie, so the box stays empty.
  • The form has no action, so it posts back to the same URL and doPost runs.
  • On the right credentials, getSession().setAttribute("user", name) keeps the user on the server. new Cookie, setMaxAge (30 days, in seconds) and addCookie send the username cookie. Then a redirect to /tasks.
  • Wrong credentials go back to /login to try again.

The username and password in this demo are hard-coded teaching values. A real app checks a database, as you'll see in the Users CRUD with a DAO.

Tasks: read the session

package org.studyeasy.web;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/tasks")
public class TasksServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        // the browser sent its JSESSIONID cookie, so the server finds the session
        String user = (String) req.getSession().getAttribute("user");
        resp.setContentType("text/html");
        resp.getWriter().println("<h2>Hello, " + user + "</h2>"
                + "<p>Write the report</p><p>Email Daniel</p>"
                + "<p><a href='logout'>Log out</a></p>");
    }
}

getSession().getAttribute("user") reads the user back, because the browser sent its JSESSIONID. There's no login check in here; that's the filter's job.

LoginFilter: the gate

package org.studyeasy.web;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;

// "/*": every request comes here first, before any servlet
@WebFilter("/*")
public class LoginFilter extends HttpFilter {

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse resp,
            FilterChain chain) throws IOException, ServletException {
        String path = req.getServletPath();             // e.g. "/tasks"
        HttpSession session = req.getSession(false);    // false: only look, never create
        boolean loggedIn = session != null && session.getAttribute("user") != null;
        System.out.println("filter: " + path + (loggedIn ? " (logged in)" : ""));

        if (loggedIn || path.equals("/login")) {
            chain.doFilter(req, resp);                  // on to the servlet
        } else {
            resp.sendRedirect(req.getContextPath() + "/login");
        }
    }
}
  • @WebFilter("/*") means every request comes here first, before any servlet.
  • getSession(false) only looks; it never creates a new session. Logged in means a session exists and has a user.
  • If you're logged in, or the request is for /login itself, chain.doFilter lets it through to the servlet.
  • Everyone else is redirected to /login, and the servlet never runs.

Open /tasks while logged out and you land on the login page. The log shows the filter ran twice, once for /tasks and once for /login.

Logout: invalidate

package org.studyeasy.web;

import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        req.getSession().invalidate();                  // the server forgets the user
        resp.sendRedirect(req.getContextPath() + "/login");
    }
}

invalidate() and the server forgets the user. The username cookie survives, so the login form still shows olivia.

Session, cookie and filter side by side

LivesHoldsAPI
Sessionon the serverwho is logged ingetSession().setAttribute, invalidate()
Cookiein the browseran id or a preferencenew Cookie, addCookie, getCookies
Filterin front of every servletone check for all pages@WebFilter, chain.doFilter

Common mistakes

  • Dropping the /login exception from the filter. Now /login redirects to /login, and the browser stops with "too many redirects". Nobody could ever reach the login page.
  • Keeping "logged in" in a cookie. The user can edit it. Keep the user in the session.
  • Calling getSession() in a filter just to check. Without false it creates an empty session for every visitor.
  • Forgetting that getCookies() returns null on a first visit, and looping over it anyway.

Quick recap

Log in and you get a session on the server and a cookie in the browser. Every request goes through the filter, which only lets logged-in users (and the login page) through. Log out is invalidate(). For the same ideas built into a small app with a shared page template, see the login, logout and web template mini app.

Keep going in JSP and Servlets · 6 of 19

Previous
Run a Java Web App in Docker: Tomcat 11 With One Compose Command
Next post
Servlets and JSP: What a Servlet Container Does and How a JSP Becomes a Servlet
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Servlets and JSP: What a Servlet Container Does and How a JSP Becomes a Servlet

A JSP looks like HTML with a little Java, yet Tomcat runs it as a servlet. See what a servlet container does for each request, what the generated hello_jsp.java looks like, what a .war holds, and Tomcat vs TomEE.

Set Up Tomcat 11 and a Maven Web Project in IntelliJ IDEA

Set JAVA_HOME, install Tomcat 11 on a free port, create a Jakarta EE web application with Maven in IntelliJ IDEA, read its folders and pom.xml, and run it on Tomcat.

The Servlet Request Lifecycle: @WebServlet, web.xml, init, doGet and destroy

A servlet is a Java class that answers a URL. Follow one request through Tomcat, map servlets with @WebServlet and web.xml, build a page from a list, and watch init, doGet and destroy run.

Servlet Request Parameters, and Forward vs Redirect

Read ?name=Emma with getParameter, then hand a request on two ways: a forward keeps one request and its attributes, a redirect makes the browser ask again and the attribute is gone.

On this page

  • How the server remembers you
  • A cookie is just two headers
  • Login: a session and a cookie go out
  • Tasks: read the session
  • LoginFilter: the gate
  • Logout: invalidate
  • Session, cookie and filter side by side
  • Common mistakes
  • Quick recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.