Java Servlets are powerful tools for building dynamic web applications. This tutorial will able you to creating a basic Java Servlets CRUD Operations (Create, Read, Update, Delete) application using Java Servlets. By the end of this guide, you’ll have a solid understanding of how to implement CRUD operations with Java Servlets.
Table of Contents
ToggleWhat is a Java Servlet?
A Java Servlet is a Java program that runs on a web server, handling client requests and generating dynamic responses. Servlets are a crucial part of Java’s server-side programming capabilities, enabling developers to build robust and scalable web applications.
Setting Up Your Environment for Java Servlets CRUD Operations
Before we dive into the code, ensure you have the following setup:
- JDK (Java Development Kit) installed.
- Apache Tomcat server.
- A MySQL database (or any other preferred database).
- An IDE like Eclipse or IntelliJ IDEA.
Project Structure
Let’s outline the basic structure of our project:
JavaServletCRUD
│ README.md
│ pom.xml
└───src
└───main
└───java
│ └───com
│ └───example
│ └───servlet
│ │ UserServlet.java
│ │ UserDao.java
│ │ User.java
└───webapp
│ index.jsp
│ user-form.jsp
│ user-list.jsp
└───WEB-INF
│ web.xml
Step-by-Step Guide
1. Create the User Model
The User
class represents the data model for our CRUD operations.
package com.example.servlet;
public class User {
private int id;
private String name;
private String email;
public User() {}
public User(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
// Getters and Setters
}
2. Create the UserDao Class
The UserDao
class handles database operations.
//UserDao Class for Java servlets crud operations
package com.example.servlet;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
private String jdbcURL = "jdbc:mysql://localhost:3306/yourdatabase";
private String jdbcUsername = "root";
private String jdbcPassword = "password";
private static final String INSERT_USERS_SQL = "INSERT INTO users (name, email) VALUES (?, ?)";
private static final String SELECT_USER_BY_ID = "SELECT id, name, email FROM users WHERE id = ?";
private static final String SELECT_ALL_USERS = "SELECT * FROM users";
private static final String DELETE_USERS_SQL = "DELETE FROM users WHERE id = ?";
private static final String UPDATE_USERS_SQL = "UPDATE users SET name = ?, email = ? WHERE id = ?";
protected Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
} catch (SQLException | ClassNotFoundException e) {
e.printStackTrace();
}
return connection;
}
public void insertUser(User user) throws SQLException {
try (Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) {
preparedStatement.setString(1, user.getName());
preparedStatement.setString(2, user.getEmail());
preparedStatement.executeUpdate();
} catch (SQLException e) {
printSQLException(e);
}
}
public User selectUser(int id) {
User user = null;
try (Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(SELECT_USER_BY_ID)) {
preparedStatement.setInt(1, id);
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
String name = rs.getString("name");
String email = rs.getString("email");
user = new User(id, name, email);
}
} catch (SQLException e) {
printSQLException(e);
}
return user;
}
public List selectAllUsers() {
List users = new ArrayList<>();
try (Connection connection = getConnection();
PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_USERS)) {
ResultSet rs = preparedStatement.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
users.add(new User(id, name, email));
}
} catch (SQLException e) {
printSQLException(e);
}
return users;
}
public boolean deleteUser(int id) throws SQLException {
boolean rowDeleted;
try (Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement(DELETE_USERS_SQL)) {
statement.setInt(1, id);
rowDeleted = statement.executeUpdate() > 0;
}
return rowDeleted;
}
public boolean updateUser(User user) throws SQLException {
boolean rowUpdated;
try (Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement(UPDATE_USERS_SQL)) {
statement.setString(1, user.getName());
statement.setString(2, user.getEmail());
statement.setInt(3, user.getId());
rowUpdated = statement.executeUpdate() > 0;
}
return rowUpdated;
}
private void printSQLException(SQLException ex) {
for (Throwable e : ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}
You may also like:
3. Create the UserServlet Class
The UserServlet
class handles HTTP requests and directs them to the appropriate methods in UserDao
.
//UserServlet Class for Java servlets crud operations
package com.example.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
@WebServlet("/")
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDao userDao;
public void init() {
userDao = new UserDao();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getServletPath();
try {
switch (action) {
case "/new":
showNewForm(request, response);
break;
case "/insert":
insertUser(request, response);
break;
case "/delete":
deleteUser(request, response);
break;
case "/edit":
showEditForm(request, response);
break;
case "/update":
updateUser(request, response);
break;
default:
listUser(request, response);
break;
}
} catch (SQLException ex) {
throw new ServletException(ex);
}
}
private void listUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException, ServletException {
List listUser = userDao.selectAllUsers();
request.setAttribute("listUser", listUser);
request.getRequestDispatcher("user-list.jsp").forward(request, response);
}
private void showNewForm(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
dispatcher.forward(request, response);
}
private void showEditForm(HttpServletRequest request, HttpServletResponse response)
throws SQLException, ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
User existingUser = userDao.selectUser(id);
RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
request.setAttribute("user", existingUser);
dispatcher.forward(request, response);
}
private void insertUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
User newUser = new User(name, email);
userDao.insertUser(newUser);
response.sendRedirect("list");
}
private void updateUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String email = request.getParameter("email");
User user = new User(id, name, email);
userDao.updateUser(user);
response.sendRedirect("list");
}
private void deleteUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
userDao.deleteUser(id);
response.sendRedirect("list");
}
}
4. Configure web.xml
The web.xml
file maps URLs to servlets.
UserServlet
com.example.servlet.UserServlet
UserServlet
/
5. Create JSP Pages
index.jsp
Home
Welcome to the User Management Application
List Users
Add New User
user-form.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
User Form
${user == null ? "New User" : "Edit User"}
user-list.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
User List
User List
Add New User
ID
Name
Email
Actions
${user.id}
${user.name}
${user.email}
Edit
Delete
In this tutorial, we’ve covered the basics of Java Servlets CRUD operations using Java Servlets. You learned how to set up your environment, create the necessary Java classes and JSP pages, and configure your application for deployment. This foundation can be expanded upon to create more complex applications as your understanding of Java Servlets grows.