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 ?.
What you will learn
- Give each class one job: servlet, DAO, JSP
- Insert and select rows with PreparedStatement in a UserDao
- Post a form to a servlet, insert, then redirect back to the list
- Explain why ? placeholders stop broken SQL and SQL injection
Before you start
- SQLite and a JDBC Connection Pool in a Java Web App
- JSTL Core Tags
The users table from the JDBC connection lesson is empty. In this part we fill it from a form and list every row on a page, using a DAO, a data access object.
The result: /users first says "No users yet". The Add user link (users?action=add) opens a small form. After saving three users, the same page lists them from the database, and /db-check says "Rows in users: 3".
Each class has one job
The one small exception is the /db-check servlet, which runs its own little count. The pool (Database) and the listener that opens it at startup are the same as in the previous lesson; before anyone clicks, the log already says "pool ready" and "tables ready".
One servlet, two pages
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") // the users pages: the list and the add form
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 {
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);
}
}
getParameter("action") reads the URL. action=add shows the empty form; anything else asks the DAO for all users, puts the list on the request and forwards to users.jsp. Opening /users, then adding three users, logs:
users: 0 listed
users: 3 listed
All the SQL, in one class
package org.studyeasy.web.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.studyeasy.web.db.Database;
import org.studyeasy.web.model.User;
// The only class that writes SQL for users: servlets and JSPs never do.
public class UserDao {
public void insert(User user) {
String sql = "INSERT INTO users (name, email) VALUES (?, ?)";
try (Connection con = Database.getDataSource().getConnection();
PreparedStatement ps = con.prepareStatement(sql)) {
// the values travel apart from the SQL: a ' is just a letter
ps.setString(1, user.getName());
ps.setString(2, user.getEmail());
ps.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException("Could not add " + user.getName(), e);
}
}
public List<User> findAll() {
String sql = "SELECT id, name, email FROM users ORDER BY id";
List<User> users = new ArrayList<>();
try (Connection con = Database.getDataSource().getConnection();
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) { // one pass per row
users.add(new User(rs.getInt("id"),
rs.getString("name"), rs.getString("email")));
}
} catch (SQLException e) {
throw new RuntimeException("Could not list the users", e);
}
return users;
}
}
insert takes a User. Its SQL has two question marks, places for values. setString(1, ...) and setString(2, ...) fill them with the name and email, and executeUpdate() runs it. findAll selects the rows and loops over the ResultSet; each row becomes a User in the list.
A form that posts
<%@ page contentType="text/html;charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<title>Add user</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<main>
<h1>Add user</h1>
<%-- a POST: the form changes the database, a link never does --%>
<form method="post" action="save-user">
<label>Name
<input name="name" required></label>
<label>Email
<input name="email" type="email" required></label>
<button>Save</button>
<a href="users">Cancel</a>
</form>
</main>
</body>
</html>
The method is post and the action is save-user. The input names, name and email, are the keys the servlet will read.
Insert, 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
public class SaveUserServlet extends HttpServlet {
private final UserDao userDao = new UserDao();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String name = req.getParameter("name");
String email = req.getParameter("email");
// no id yet: a new row, SQLite picks the id
userDao.insert(new User(0, name, email));
System.out.println("users: added " + name);
// redirect after a POST: F5 on the list does not post again
resp.sendRedirect("users");
}
}
users: added Emma Clark
users: added Liam Turner
users: added Olivia Brooks
There's no id yet, so the servlet passes 0 and SQLite picks the id. Then sendRedirect("users") sends the browser back to the list. Redirecting after a POST means pressing refresh on the list just reloads the list; it doesn't post the form again.
A JSTL table
<%@ 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></tr>
<c:forEach var="user" items="${users}">
<tr>
<td>${user.id}</td>
<td>${user.name}</td>
<td>${user.email}</td>
</tr>
</c:forEach>
</table>
</c:if>
</main>
</body>
</html>
Users
Add user
ID | Name | Email
1 | Emma Clark | emma.clark@example.com
2 | Liam Turner | liam.turner@example.com
3 | Olivia Brooks | olivia.brooks@example.com
c:if with empty users shows "No users yet." Otherwise c:forEach writes one row per user, and EL reads each value. All three rows live in that one file, studyeasy.db; Emma's id of 1 is the one SQLite picked. You can open the file with a viewer such as DB Browser for SQLite.
What a user types stays data
Why the question marks? Imagine gluing the name straight into the SQL string instead.
- Someone types
Noah O'Neil. The apostrophe ends the SQL string early, the SQL breaks, and the page is an HTTP 500. With a?the name is simply saved. - Worse, someone types a name that contains a quote, a comma and a small
SELECT. Glued in, that query runs as part of your insert, and every email in the table lands on the page. With a?, it's saved as a plain, odd-looking name.
Glued strings let a user write SQL. A ? never does, because the values travel separately from the SQL.
Common mistakes
- Forwarding instead of redirecting after the save:
getRequestDispatcher("users").forward(...). A forward keeps the POST, andUserControllerhas nodoPost, so you get HTTP 405, even though the user was saved. - Writing SQL in a servlet or a JSP. Keep it in the DAO, so there's one place to read and fix it.
- Building SQL with
+and user input. Always use?andsetString/setInt.
Quick recap
Add is insert, list is findAll, and safe means a ? for every value. All of it with plain servlets and JSP, no framework. Part 2 adds update and delete.
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
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.
