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.
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
- You log in as olivia. The server creates a session with an id and keeps
user = oliviainside it. - The answer brings two cookies:
JSESSIONID(just that id) andusername. - You open
/tasks. The browser sendsJSESSIONID, the id finds the session, and the server says "Hello, olivia". - You log out. The server deletes the session, but the
usernamecookie 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
}
}
}
doGetshows the form. It reads the cookies (getCookies()isnullwhen the browser sent none), and ausernamecookie 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
doPostruns. - On the right credentials,
getSession().setAttribute("user", name)keeps the user on the server.new Cookie,setMaxAge(30 days, in seconds) andaddCookiesend the username cookie. Then a redirect to/tasks. - Wrong credentials go back to
/loginto 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
/loginitself,chain.doFilterlets 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
| Lives | Holds | API | |
|---|---|---|---|
| Session | on the server | who is logged in | getSession().setAttribute, invalidate() |
| Cookie | in the browser | an id or a preference | new Cookie, addCookie, getCookies |
| Filter | in front of every servlet | one check for all pages | @WebFilter, chain.doFilter |
Common mistakes
- Dropping the
/loginexception from the filter. Now/loginredirects 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. Withoutfalseit creates an empty session for every visitor. - Forgetting that
getCookies()returnsnullon 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.
StudyEasy AI Community
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
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.
