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. MVC

Mini App With Servlets and JSP: Login, Logout and a Shared Web Template

Four pages and one template: a login form that posts to a servlet, a session that remembers the user, a filter that guards home.jsp and account.jsp, and a logout that ends it, plus when each step forwards or redirects.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026MVC

What you will learn

  • Split a page template into a header and footer under WEB-INF
  • Log in with doPost: redirect on success, forward with an error on failure
  • Guard two members-only pages with a filter
  • Log out with invalidate and follow every click through the app

Before you start

  • Sessions, Cookies and Filters in Java Servlets
  • JSP Scripting: Expressions, Scriptlets, Declarations, Comments and Includes

Time to put sessions, filters, includes and forward/redirect into one small app, Team Tasks. It has four pages and one template:

  • login.jsp, the only page open to everyone (two demo accounts, Emma and James, listed on the page itself; the demo passwords are left out of this article, they are in the project files)
  • home.jsp, where you land after logging in
  • account.jsp, which shows the session that lives on the server
  • Log out, which ends the session and takes you back to the login page

The page is GET, the form is POST

Loading a page is a GET; submitting a form is a POST. That gives three cases for the login:

RequestWho answersResult
GET /login.jspthe JSP200, the form
POST /loginLoginServlet.doPost302 when it works, the form again when it doesn't
GET /loginnobody, there's no doGet405

So a plain link to /login is refused. The start page links to login.jsp instead.

The login form

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/includes/header.jsp" %>
<h1>Log in</h1>
<%-- set by LogoutServlet's redirect: login.jsp?loggedOut=true --%>
<% if (request.getParameter("loggedOut") != null) { %>
<p class="note">You have logged out.</p>
<% } %>
<%-- set by LoginServlet's forward when the password is wrong --%>
<% String error = (String) request.getAttribute("error"); %>
<% if (error != null) { %>
<p class="error"><%= error %></p>
<% } %>
<p class="note">Demo accounts: Emma / <demo-password>, James / <demo-password></p>
<form method="post" action="login">
    <label>Username <input name="username"></label>
    <label>Password <input name="password" type="password"></label>
    <button>Log in</button>
</form>
<%@ include file="/WEB-INF/includes/footer.jsp" %>

It starts with the header include and ends with the footer include. It looks for a loggedOut parameter (set by the logout redirect) and an error attribute (set by the servlet on a wrong password). The form posts to login.

Check, remember, redirect

package org.studyeasy.web;

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

@WebServlet("/login")   // login.jsp posts its form here
public class LoginServlet extends HttpServlet {
    // two demo accounts: a real app reads them from a database
    private final Map<String, String> passwords =
            Map.of("Emma", "<demo-password>", "James", "<demo-password>");

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        boolean ok = username != null && password != null
                && password.equals(passwords.get(username));
        if (ok) {
            // remember this browser, then redirect: F5 will not re-post
            req.getSession().setAttribute("user", username);
            System.out.println("login ok: " + username);
            resp.sendRedirect("home.jsp");
        } else {
            System.out.println("login failed: " + username);
            // forward: the same request, so the error travels with it
            req.setAttribute("error", "Wrong username or password");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        }
    }
}

A wrong password, then <demo-password>, gives this log:

login failed: Emma
login ok: Emma

On success the user goes into the session and the servlet redirects to home.jsp. That's a 302, so pressing F5 on the home page reloads the home page instead of posting the password again. On failure it sets an error attribute and forwards back to login.jsp. It's the same request, so the error rides along.

The template: header and footer in one place each

<%-- The top of the template, copied into every page.
     Under WEB-INF, so no browser can open it on its own. --%>
<% String user = (String) session.getAttribute("user"); %>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Team Tasks</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<header class="top">
    <span class="brand">Team Tasks</span>
    <nav>
        <% if (user != null) { %>
        <a href="home.jsp">Home</a>
        <a href="account.jsp">Account</a>
        <a href="logout">Log out</a>
        <span class="who">Signed in as <%= user %></span>
        <% } else { %>
        <a href="login.jsp">Log in</a>
        <% } %>
    </nav>
</header>
<main>
<%-- The bottom of the template: closes what header.jsp opened --%>
</main>
<footer>Team Tasks &middot; built on the Simple Starter template</footer>
</body>
</html>

Both live under WEB-INF, so no browser can open them on their own. The header reads user from the session and changes the navigation with it. Its <main> tag is left open on purpose; the footer closes it.

Every page is then three parts: header include, its own content, footer include.

<%@ page contentType="text/html;charset=UTF-8" %>
<%-- the include directive pastes header.jsp in here,
     so its variable "user" is a variable of this page too --%>
<%@ include file="/WEB-INF/includes/header.jsp" %>
<h1>Welcome back, <%= user %></h1>
<p>Your tasks for today:</p>
<ul>
    <li>Review the sprint board</li>
    <li>Reply to Olivia about the release</li>
    <li>Book the team meeting room</li>
</ul>
<%@ include file="/WEB-INF/includes/footer.jsp" %>

The include directive pastes the header into this page before compiling, so the header's user variable exists here too, and Welcome back, <%= user %> works. The account page is the same idea with a different middle:

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/includes/header.jsp" %>
<h1>Your account</h1>
<%-- the session lives on the server; the browser only holds its id --%>
<p>Username: <b><%= user %></b></p>
<p>Session id: <code><%= session.getId() %></code></p>
<p>Logs you out after
    <%= session.getMaxInactiveInterval() / 60 %> idle minutes</p>
<%@ include file="/WEB-INF/includes/footer.jsp" %>

It shows the username, the session id (the browser only holds this id) and getMaxInactiveInterval() / 60, the idle minutes before the session ends. Here that's 30.

No session, no page

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;

// the guard: runs before the members-only pages
@WebFilter({"/home.jsp", "/account.jsp"})
public class LoginFilter extends HttpFilter {

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse resp,
                            FilterChain chain)
            throws IOException, ServletException {
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            System.out.println("blocked: " + req.getRequestURI());
            resp.sendRedirect("login.jsp");
            return;
        }
        // logged in: let the request through to the page
        chain.doFilter(req, resp);
    }
}

This filter names only the two members-only pages. Open /home.jsp while logged out and the log says blocked: /home.jsp, and the browser gets a 302 to login.jsp. Logged in, chain.doFilter lets the request go on.

Invalidate the session, redirect

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 jakarta.servlet.http.HttpSession;
import java.io.IOException;

// the "Log out" link in header.jsp
@WebServlet("/logout")
public class LogoutServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        // false: do not create a session just to throw it away
        HttpSession session = req.getSession(false);
        if (session != null) {
            System.out.println("logout: " + session.getAttribute("user"));
            session.invalidate();
        }
        // redirect: the address bar leaves /logout behind
        resp.sendRedirect("login.jsp?loggedOut=true");
    }
}

It's a doGet, because the Log out link in the header sends a GET. getSession(false) again, since there's no point creating a session only to throw it away. The log says logout: Emma, and the browser gets a 302 to login.jsp?loggedOut=true.

Every click, and who answers it

Six steps. 1, GET home.jsp with no session: the filter redirects to login.jsp. 2, POST a wrong password: the servlet forwards back with an error. 3, POST <demo-password>: the session gets user Emma and the servlet redirects to home.jsp. 4, GET home.jsp: the filter lets it through, Welcome back, Emma. 5, Log out: invalidate, redirect. 6, Back button: no session, blocked again. 1 GET /home.jsp, no sessionfilter: redirect to login.jsp 2 POST /login, wrong passwordforward to login.jsp with error 3 POST /login, <demo-password>session user = Emma, redirect 4 GET /home.jspfilter lets it through: Welcome back, Emma 5 GET /logoutinvalidate, redirect to login.jsp 6 Back button to /home.jspno session: blocked again
Redirect when something changed; forward when the same request still has something to show.
MomentForward or redirectWhy
Wrong passwordforwardthe error is a request attribute
Right passwordredirectF5 must not post the password again
Not logged inredirectthe guard sends the browser away
Log outredirectthe session is gone; start clean

Common mistakes

  • Forwarding to home.jsp after a good login. The page shows, but the address bar still says /login and F5 posts the password again.
  • Mapping the filter on /*. It guards login.jsp too, and the login page redirects to itself: ERR_TOO_MANY_REDIRECTS.
  • Swapping the header directive for <jsp:include>. The action runs the header as a separate page, so user doesn't exist in home.jsp: HTTP 500, user cannot be resolved.
  • Deleting session.invalidate(). The page says "You have logged out", but home.jsp still opens.

Quick recap

Split the template into a header and a footer under WEB-INF. Remember the user in the session. Guard the members-only pages with a filter. End it all with invalidate(). Behind every step is one decision: forward inside one request, or redirect so the browser asks again.

Keep going in JSP and Servlets · 16 of 19

Previous
Forms With JSP and Servlets: Handle the POST and Validate on the Server
Next post
SQLite and a JDBC Connection Pool in a Java Web App
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

MVC and the Front Controller With Servlets and JSP

A Book model, a BookController servlet and a books.jsp view behind WEB-INF show MVC in plain Java. Then one servlet on /app/* becomes a front controller, the idea Spring's DispatcherServlet grew from.

Forms With JSP and Servlets: Handle the POST and Validate on the Server

Post a sign-up form straight to a JSP and anything gets accepted. Post it to a servlet instead: doPost checks name and email, forwards back with errors and the typed values, or on to the welcome page.

SQLite and a JDBC Connection Pool in a Java Web App

A whole database in one file, studyeasy.db, and a Java web app that talks to it: one HikariCP pool, a @WebListener that opens it and runs schema.sql at startup, and a /db-check servlet that borrows a connection.

Users CRUD With Servlets and JSP, Part 1: Add and List Through a DAO

Fill an empty users table from a form and list every row: UserController picks the page, UserDao holds all the SQL, SaveUserServlet inserts and redirects, and a JSTL table shows the rows. Plus why every value goes in as a ?.

On this page

  • The page is GET, the form is POST
  • The login form
  • Check, remember, redirect
  • The template: header and footer in one place each
  • No session, no page
  • Invalidate the session, redirect
  • Every click, and who answers it
  • 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.