Java Servlet

Java Servlet and JSP CRUD Application Tutorial | Step-by-Step Guide to Build a Product Management System

Step-by-Step Guide to Building a Product Management System

In this comprehensive tutorial, we will walk through the process of building a simple Product Management System using Java Servlets and JSP (JavaServer Pages). This project will demonstrate the essential CRUD (Create, Read, Update, Delete) operations, enabling users to manage products in a MySQL database.

By the end of this tutorial, you’ll have a fully functional CRUD application that follows industry best practices, with clear explanations of each step involved.


Table of Contents

  1. Introduction
  2. Project Structure
  3. Database Setup
  4. Configuring Maven Dependencies
  5. Creating the Database Utility Class
  6. Defining the Product Model
  7. Creating the Data Access Object (DAO)
  8. Building the Product Servlet
  9. Developing JSP Pages for CRUD Operations
  10. Configuring web.xml
  11. Running the Application
  12. Summary

Introduction

What is a CRUD Application?

A CRUD (Create, Read, Update, Delete) application is a fundamental project in web development. It allows users to:

  • Create new records in a database.
  • Read and display existing records.
  • Update and modify records.
  • Delete records when no longer needed.

This tutorial uses Java Servlets and JSP, two of the most popular technologies in the Java ecosystem for building dynamic web applications. Our application will manage a list of products, each with the following attributes:

  • ID (auto-incremented primary key)
  • Name (product name)
  • Description (details about the product)
  • Price (product price)
  • Color (product color)

Prerequisites

To follow this tutorial, you need the following:

  • Java 17+
  • Apache Tomcat Server (version 9 or later)
  • MySQL Database
  • Maven for dependency management
  • Basic knowledge of Java, SQL, and HTML

1. Project Structure

Here’s the directory structure for the project:

servletcrud/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── acesoftech/
│   │   │       ├── DBUtil.java            <!-- Database utility -->
│   │   │       ├── Product.java           <!-- Product model -->
│   │   │       ├── ProductDAO.java        <!-- Data Access Object (DAO) -->
│   │   │       └── ProductServlet.java    <!-- Servlet for handling requests -->
│   │   └── webapp/
│   │       ├── WEB-INF/
│   │       │   └── web.xml                <!-- Web configuration -->
│   │       └── views/
│   │           ├── add-product.jsp        <!-- Add product form -->
│   │           ├── edit-product.jsp       <!-- Edit product form -->
│   │           └── product-list.jsp       <!-- Display product list -->
└── pom.xml                                 <!-- Maven configuration file -->


2. Database Setup

First, create a MySQL database to store product information:

CREATE DATABASE servletcrud;
USE servletcrud;

CREATE TABLE product (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
description VARCHAR(255),
price DECIMAL(10, 2) NOT NULL,
color VARCHAR(50)
);

This table will store the details of each product.


3. Configuring Maven Dependencies

Create a pom.xml file to manage the project dependencies:

<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.acesoftech</groupId>
    <artifactId>servletcrud</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <!-- MySQL Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>

        <!-- Servlet API -->
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>5.0.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- JSP and JSTL -->
        <dependency>
            <groupId>jakarta.servlet.jsp.jstl</groupId>
            <artifactId>jakarta.servlet.jsp.jstl-api</artifactId>
            <version>2.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>jakarta.servlet.jsp.jstl</artifactId>
            <version>2.0.0</version>
        </dependency>
    </dependencies>
</project>

 


4. Creating the Database Utility Class

DBUtil.java manages the connection to the MySQL database:

package acesoftech;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {
    private static final String URL = "jdbc:mysql://localhost:3306/servletcrud";
    private static final String USER = "root"; 
    private static final String PASSWORD = "password";

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }
}

 


5. Defining the Product Model

Product.java defines the properties of a product:

package acesoftech;

public class Product {
    private int id;
    private String name;
    private String description;
    private double price;
    private String color;

    // Getters and Setters
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public String getDescription() { return description; }
    public void setDescription(String description) { this.description = description; }
    public double getPrice() { return price; }
    public void setPrice(double price) { this.price = price; }
    public String getColor() { return color; }
    public void setColor(String color) { this.color = color; }
}

 


6. Creating the Data Access Object (DAO)

ProductDAO.java handles all database operations:

package acesoftech;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Data Access Object (DAO) class for managing Product data.
 * This class provides methods to perform CRUD operations
 * on the 'product' table in the database.
 */
public class ProductDAO {

    /**
     * Adds a new product to the database.
     *
     * @param product the product to be added
     * @throws SQLException if a database error occurs
     */
    public void addProduct(Product product) throws SQLException {
        String sql = "INSERT INTO product (name, description, price, color) VALUES (?, ?, ?, ?)";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, product.getName());
            statement.setString(2, product.getDescription());
            statement.setDouble(3, product.getPrice());
            statement.setString(4, product.getColor());
            statement.executeUpdate();
        }
    }

    /**
     * Retrieves all products from the database.
     *
     * @return a list of all products
     * @throws SQLException if a database error occurs
     */
    public List<Product> getAllProducts() throws SQLException {
        List<Product> products = new ArrayList<>();
        String sql = "SELECT * FROM product";
        try (Connection connection = DBUtil.getConnection();
             Statement statement = connection.createStatement();
             ResultSet rs = statement.executeQuery(sql)) {
            while (rs.next()) {
                Product product = new Product();
                product.setId(rs.getInt("id"));
                product.setName(rs.getString("name"));
                product.setDescription(rs.getString("description"));
                product.setPrice(rs.getDouble("price"));
                product.setColor(rs.getString("color"));
                products.add(product);
            }
        }
        return products;
    }

    /**
     * Retrieves a product by its ID from the database.
     *
     * @param id the ID of the product
     * @return the product with the specified ID, or null if not found
     * @throws SQLException if a database error occurs
     */
    public Product getProductById(int id) throws SQLException {
        Product product = null;
        String sql = "SELECT * FROM product WHERE id = ?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, id);
            try (ResultSet rs = statement.executeQuery()) {
                if (rs.next()) {
                    product = new Product();
                    product.setId(rs.getInt("id"));
                    product.setName(rs.getString("name"));
                    product.setDescription(rs.getString("description"));
                    product.setPrice(rs.getDouble("price"));
                    product.setColor(rs.getString("color"));
                }
            }
        }
        return product;
    }

    /**
     * Updates an existing product in the database.
     *
     * @param product the product with updated data
     * @throws SQLException if a database error occurs
     */
    public void updateProduct(Product product) throws SQLException {
        String sql = "UPDATE product SET name = ?, description = ?, price = ?, color = ? WHERE id = ?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setString(1, product.getName());
            statement.setString(2, product.getDescription());
            statement.setDouble(3, product.getPrice());
            statement.setString(4, product.getColor());
            statement.setInt(5, product.getId());
            statement.executeUpdate();
        }
    }

    /**
     * Deletes a product from the database.
     *
     * @param id the ID of the product to be deleted
     * @throws SQLException if a database error occurs
     */
    public void deleteProduct(int id) throws SQLException {
        String sql = "DELETE FROM product WHERE id = ?";
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setInt(1, id);
            statement.executeUpdate();
        }
    }
}

 


7. Product Servlet (Detailed Implementation)

The ProductServlet class is the controller that handles user requests for the CRUD operations. It interacts with the ProductDAO to fetch or modify data from the database and forwards responses to the appropriate JSP pages for display.

package acesoftech;

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.sql.SQLException;
import java.util.List;

@WebServlet("/products")
public class ProductServlet extends HttpServlet {
    private ProductDAO productDAO;

    @Override
    public void init() {
        productDAO = new ProductDAO();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        try {
            switch (action) {
                case "new":
                    showNewForm(request, response);
                    break;
                case "edit":
                    showEditForm(request, response);
                    break;
                case "delete":
                    deleteProduct(request, response);
                    break;
                default:
                    listProducts(request, response);
                    break;
            }
        } catch (SQLException ex) {
            throw new ServletException(ex);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String action = request.getParameter("action");
        try {
            switch (action) {
                case "insert":
                    insertProduct(request, response);
                    break;
                case "update":
                    updateProduct(request, response);
                    break;
                default:
                    response.sendRedirect("products");
                    break;
            }
        } catch (SQLException ex) {
            throw new ServletException(ex);
        }
    }

    private void listProducts(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        List<Product> listProduct = productDAO.getAllProducts();
        request.setAttribute("listProduct", listProduct);
        request.getRequestDispatcher("views/product-list.jsp").forward(request, response);
    }

    private void showNewForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("views/add-product.jsp").forward(request, response);
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Product existingProduct = productDAO.getProductById(id);
        request.setAttribute("product", existingProduct);
        request.getRequestDispatcher("views/edit-product.jsp").forward(request, response);
    }

    private void insertProduct(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException {
        String name = request.getParameter("name");
        String description = request.getParameter("description");
        double price = Double.parseDouble(request.getParameter("price"));
        String color = request.getParameter("color");

        Product newProduct = new Product();
        newProduct.setName(name);
        newProduct.setDescription(description);
        newProduct.setPrice(price);
        newProduct.setColor(color);

        productDAO.addProduct(newProduct);
        response.sendRedirect("products");
    }

    private void updateProduct(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String description = request.getParameter("description");
        double price = Double.parseDouble(request.getParameter("price"));
        String color = request.getParameter("color");

        Product product = new Product();
        product.setId(id);
        product.setName(name);
        product.setDescription(description);
        product.setPrice(price);
        product.setColor(color);

        productDAO.updateProduct(product);
        response.sendRedirect("products");
    }

    private void deleteProduct(HttpServletRequest request, HttpServletResponse response)
            throws SQLException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        productDAO.deleteProduct(id);
        response.sendRedirect("products");
    }
}

 


8. JSP Pages for CRUD Operations

These JSP pages provide the user interface to interact with the product data.

add-product.jsp (Add New Product Form)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Add Product</title>
</head>
<body>
<h2>Add New Product</h2>
<form action="products" method="post">
<input type="hidden" name="action" value="insert">
Name: <input type="text" name="name" required><br>
Description: <input type="text" name="description"><br>
Price: <input type="number" step="0.01" name="price" required><br>
Color: <input type="text" name="color"><br>
<input type="submit" value="Save">
</form>
<a href="products">Back to Product List</a>
</body>
</html>

 


edit-product.jsp (Edit Product Form)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Edit Product</title>
</head>
<body>
<h2>Edit Product</h2>
<form action="products" method="post">
<input type="hidden" name="action" value="update">
<input type="hidden" name="id" value="${product.id}">
Name: <input type="text" name="name" value="${product.name}" required><br>
Description: <input type="text" name="description" value="${product.description}"><br>
Price: <input type="number" step="0.01" name="price" value="${product.price}" required><br>
Color: <input type="text" name="color" value="${product.color}"><br>
<input type="submit" value="Update">
</form>
<a href="products">Back to Product List</a>
</body>
</html>


product-list.jsp (Product List Page)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Product List</title>
</head>
<body>
<h2>Product List</h2>
<a href="products?action=new">Add New Product</a>
<table border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Color</th>
<th>Actions</th>
</tr>
<c:forEach var="product" items="${listProduct}">
<tr>
<td>${product.id}</td>
<td>${product.name}</td>
<td>${product.description}</td>
<td>${product.price}</td>
<td>${product.color}</td>
<td>
<a href="products?action=edit&id=${product.id}">Edit</a>
<a href="products?action=delete&id=${product.id}" onclick="return confirm('Are you sure?');">Delete</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>

 


9. web.xml Configuration

The web.xml file is used to map the servlet to a specific URL pattern.

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0"><servlet>
<servlet-name>ProductServlet</servlet-name>
<servlet-class>acesoftech.ProductServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProductServlet</servlet-name>
<url-pattern>/products</url-pattern>
</servlet-mapping>
</web-app>

10. Running the Application

  1. Build the Project:
    Open a terminal and navigate to the project directory. Run the following Maven command to build the project:

    mvn clean install
  2. Deploy the WAR file:
    Copy the generated WAR file from the target/ directory to the Tomcat webapps/ folder.
  3. Start Tomcat:
    Start the Tomcat server and open your browser. Navigate to:

    http://localhost:8080/servletcrud/products

You should now see the product list and can perform CRUD operations.


Summary

In this tutorial, we built a simple Product CRUD Application using Java Servlets, JSP, and MySQL. We covered:

  • Setting up the project structure with Maven.
  • Creating a database and setting up tables for product data.
  • Developing the DAO layer to interact with the database.
  • Implementing the Servlet to handle CRUD operations.
  • Designing JSP pages to display and manage products.
  • Deploying the application to a Tomcat server.

This CRUD system can be a foundation for more advanced applications with additional features like authentication, validation, and RESTful APIs.

Leave a Reply

Your email address will not be published. Required fields are marked *