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

Users CRUD With Servlets and JSP, Part 2: Update and Delete

Edit and Delete links on every row: one form does add and edit with a hidden id, a confirm page asks before deleting, and only a POST changes the database, then redirects back to the list.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026MVC

What you will learn

  • Map the four CRUD actions to INSERT, SELECT, UPDATE and DELETE
  • Reuse one form for add and edit with a hidden id
  • Delete only on a POST from a confirm page, never from a link
  • Trace which file answers each click

Before you start

  • Users CRUD With Servlets and JSP, Part 1
  • JSTL Core Tags

The users app can add and list. Now every row gets an Edit and a Delete link. Edit on Liam Turner loads /users?action=edit&id=2, and because there's an id, the form comes up already filled from the database. Delete on Olivia Brooks shows a warning page that asks before anything happens. Afterwards Liam's email has changed and Olivia is gone.

CRUD: four actions, four SQL words

ActionCRUDSQL
Add a userCreateINSERT
List usersReadSELECT
Edit a userUpdateUPDATE
Delete a userDeleteDELETE

Part 1 covered insert and select. This part adds the other two, and every value still goes in with a ?.

Every click takes one path

Five clicks. Open the list: GET /users, UserController, users.jsp. Edit: GET /users?action=edit&id=2, UserController, user-form.jsp. Save: POST /save-user, SaveUserServlet, 302 to users. Delete link: GET /users?action=delete, UserController, user-delete.jsp, nothing deleted. Yes, delete: POST /delete-user, DeleteUserServlet, 302 to users. ClickRequestFile that runsAnswer Open listGET /usersUserControllerusers.jsp EditGET /users?action=edit&id=2UserControlleruser-form.jsp SavePOST /save-userSaveUserServlet302 to users Delete linkGET /users?action=deleteUserControlleruser-delete.jsp Yes, deletePOST /delete-userDeleteUserServlet302 to users
Only the two POSTs change the database. The Delete link only shows a page that asks.

Knowing which file runs for each click matters more than typing the code. The project even ships a small data-flow.html diagram, made with AI. When you can't follow how data moves through code, ask an AI assistant to draw the flow for you, understand it, and then give your instructions.

One servlet, a page per action

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.List;
import org.studyeasy.web.dao.UserDao;
import org.studyeasy.web.model.User;

@WebServlet("/users")   // every users page: the list and three forms
public class UserController extends HttpServlet {

    private final UserDao userDao = new UserDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String action = req.getParameter("action");
        String view;
        if ("add".equals(action)) {
            view = "user-form.jsp";                   // an empty form
        } else if ("edit".equals(action)) {
            req.setAttribute("user", findUser(req));  // the form, filled
            view = "user-form.jsp";
        } else if ("delete".equals(action)) {
            req.setAttribute("user", findUser(req));  // ask before deleting
            view = "user-delete.jsp";
        } else {
            List<User> users = userDao.findAll();
            System.out.println("users: " + users.size() + " listed");
            req.setAttribute("users", users);
            view = "users.jsp";
        }
        req.getRequestDispatcher("/WEB-INF/views/" + view)
                .forward(req, resp);
    }

    private User findUser(HttpServletRequest req) {
        int id = Integer.parseInt(req.getParameter("id"));
        return userDao.findById(id);
    }
}

edit puts the user on the request and shows the same form used for adding, filled in. delete shows a different page, the one that asks. findUser reads the id from the link and gets that user from the DAO.

Edit and Delete on every row

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<!DOCTYPE html>
<html>
<head>
    <title>Users</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<main>
<h1>Users</h1>
<p><a href="users?action=add">Add user</a></p>
<c:if test="${empty users}">
    <p>No users yet.</p>
</c:if>
<c:if test="${not empty users}">
<table>
    <tr><th>ID</th><th>Name</th><th>Email</th><th></th></tr>
    <c:forEach var="user" items="${users}">
    <tr>
        <td>${user.id}</td>
        <td>${user.name}</td>
        <td>${user.email}</td>
        <td class="actions">
            <a href="users?action=edit&id=${user.id}">Edit</a>
            <a href="users?action=delete&id=${user.id}">Delete</a>
        </td>
    </tr>
    </c:forEach>
</table>
</c:if>
</main>
</body>
</html>
1 | Emma Clark | emma.clark@example.com | Edit Delete
2 | Liam Turner | liam.turner@example.com | Edit Delete
3 | Olivia Brooks | olivia.brooks@example.com | Edit Delete

The id rides in each link, which is how the controller knows which row you clicked. The Delete link only asks; it doesn't delete anything.

One form, two jobs

<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<!DOCTYPE html>
<html>
<head>
    <title>User</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<main>
<%-- one form, two jobs: no "user" means add, a "user" means edit --%>
<c:choose>
    <c:when test="${user == null}"><h1>Add user</h1></c:when>
    <c:otherwise><h1>Edit user ${user.id}</h1></c:otherwise>
</c:choose>
<form method="post" action="save-user">
    <input type="hidden" name="id" value="${user.id}">
    <label>Name
        <input name="name" value="${user.name}" required></label>
    <label>Email
        <input name="email" type="email" value="${user.email}" required>
    </label>
    <button>Save</button>
    <a href="users">Cancel</a>
</form>
</main>
</body>
</html>

No user on the request means Add user; a user means Edit user. The hidden id says which row is being edited, and it's simply empty when adding. The value attributes come from user.name and user.email, which is how the form gets filled from the database.

Insert or update, then 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 org.studyeasy.web.dao.UserDao;
import org.studyeasy.web.model.User;

@WebServlet("/save-user")   // user-form.jsp posts here, to add or to edit
public class SaveUserServlet extends HttpServlet {

    private final UserDao userDao = new UserDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String email = req.getParameter("email");
        if (id.isEmpty()) {
            // no id yet: a new row, SQLite picks the id
            userDao.insert(new User(0, name, email));
            System.out.println("users: added " + name);
        } else {
            userDao.update(new User(Integer.parseInt(id), name, email));
            System.out.println("users: updated " + id);
        }
        // redirect after a POST: F5 on the list does not post again
        resp.sendRedirect("users");
    }
}

Change Liam's email and click Save. The log says users: updated 2 and the list shows the new email. An empty id means there's no row yet, so it's an insert; otherwise it's an update. Then the usual redirect after a POST, so F5 on the list doesn't post the form again.

A page that asks first

<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <title>Delete user</title>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<main>
<h1>Delete user</h1>
<p>Delete <b>${user.name}</b> (${user.email})? This cannot be undone.</p>
<%-- the link only showed this page; only this POST deletes --%>
<form method="post" action="delete-user">
    <input type="hidden" name="id" value="${user.id}">
    <button class="danger">Yes, delete</button>
    <a href="users">Cancel</a>
</form>
</main>
</body>
</html>
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 org.studyeasy.web.dao.UserDao;

// POST only: a link (GET) can never delete, only the confirm form can.
@WebServlet("/delete-user")
public class DeleteUserServlet extends HttpServlet {

    private final UserDao userDao = new UserDao();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        int id = Integer.parseInt(req.getParameter("id"));
        userDao.delete(id);
        System.out.println("users: deleted " + id);
        resp.sendRedirect("users");
    }
}

After Yes, delete the log says:

users: deleted 3
users: 2 listed

The servlet has a doPost and no doGet. A link is always a GET, so a link can never delete a row. Only the confirm form can.

Change one, delete one

Both servlets end up in the DAO, still the only class with SQL for users. The three new methods:

public User findById(int id) {
    String sql = "SELECT id, name, email FROM users WHERE id = ?";
    try (Connection con = Database.getDataSource().getConnection();
         PreparedStatement ps = con.prepareStatement(sql)) {
        ps.setInt(1, id);         // fills the first ?
        try (ResultSet rs = ps.executeQuery()) {
            if (rs.next()) {
                return new User(rs.getInt("id"),
                        rs.getString("name"), rs.getString("email"));
            }
            return null;          // no user with this id
        }
    } catch (SQLException e) {
        throw new RuntimeException("Could not find user " + id, e);
    }
}

public void update(User user) {
    String sql = "UPDATE users SET name = ?, email = ? WHERE id = ?";
    try (Connection con = Database.getDataSource().getConnection();
         PreparedStatement ps = con.prepareStatement(sql)) {
        ps.setString(1, user.getName());
        ps.setString(2, user.getEmail());
        ps.setInt(3, user.getId());
        ps.executeUpdate();
    } catch (SQLException e) {
        throw new RuntimeException("Could not update " + user.getId(), e);
    }
}

public void delete(int id) {
    String sql = "DELETE FROM users WHERE id = ?";
    try (Connection con = Database.getDataSource().getConnection();
         PreparedStatement ps = con.prepareStatement(sql)) {
        ps.setInt(1, id);
        ps.executeUpdate();
    } catch (SQLException e) {
        throw new RuntimeException("Could not delete " + id, e);
    }
}

The update has three question marks and the id is the last one, so setInt(3, ...) fills it. The delete removes one row by id.

Common mistakes

  • Deleting the hidden id input. Save then posts no id at all, getParameter("id") is null in SaveUserServlet, and you get HTTP 500, a NullPointerException. The form can't say which row it edits.
  • Deleting on a GET link. Browsers, crawlers and prefetchers follow links; a row should only change on a POST.
  • Letting an AI agent reorganise your folders while adding a feature. In a real app the structure is often fixed. Check the folders after it works.

Quick recap

findById gets the row, update and delete change it, and the safe way to finish any change is a POST, then a redirect. Next, the same app without hand-written SQL: why an ORM, from JDBC to Hibernate.

Keep going in JSP and Servlets · 19 of 19

Previous
Users CRUD With Servlets and JSP, Part 1: Add and List Through a DAO
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.

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.

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.

On this page

  • CRUD: four actions, four SQL words
  • Every click takes one path
  • One servlet, a page per action
  • Edit and Delete on every row
  • One form, two jobs
  • Insert or update, then redirect
  • A page that asks first
  • Change one, delete one
  • 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.