Lab 4: Creating the DELETE method

Video lesson published on

This page was originally written in Portuguese. Read the original.

Lab overview and objectives

This lab aims to present a basic way to delete data from a database table!

After completing this lab, you should be able to:

  • Make http requests through an HTML form and capture the request data in a Servlet;
  • Delete / remove data persisted in the database (delete car where id = ?).

This lab is also available as a video lesson on YouTube

Car Store #06 - Implementando a terceira operação do CRUD - DELETE · Video in Portuguese.

Task 1: Creating the deleteCarById() method

Your application is created, your web server is running and you can already save and query data in the database. Now it is time to implement the operation that deletes / removes data persisted in your application’s database.

1 - To do so, let’s create a new method called deleteCarById(). This method must be created in the CarDao class.

NOTE: The CarDao class already exists and has two methods: createCar() and findAllCars. In this section, we will only create / add a new method to this class. The method name must be deleteCarById(). It receives a String as a parameter and its return type is void.

To do so, open the CarDao class and implement the deleteCarById() method. The resulting code should look like the following:

public void deleteCarById(String carId) {

}

2 - Now let’s implement the logic that removes / deletes the data from the database. The first step is to create a string variable that we will call SQL. Its value is a string with the SQL command for the delete (DELETE FROM CAR WHERE ID = ?).

public void deleteCarById(String carId) {

    String SQL = "DELETE FROM CAR WHERE ID = ?";

}

NOTE: This command removes the data stored in our table according to the given ID.

3 - The rest of the method’s implementation is very similar to what we did earlier in the createCar() method. We will have the try / catch block and also the feedback messages, so we know whether the operation succeeded.

The resulting code should look like the following:

public void deleteCarById(String carId) {

    String SQL = "DELETE FROM CAR WHERE ID = ?";

    try {

        Connection connection = DriverManager.getConnection("jdbc:h2:~/test", "sa", "sa");

        System.out.println("success in database connection");

        PreparedStatement preparedStatement = connection.prepareStatement(SQL);
        preparedStatement.setString(1, carId);
        preparedStatement.execute();

        System.out.println("success on delete car with id: " + carId);

        connection.close();

    } catch (Exception e) {

        System.out.println("fail in database connection");

    }

}

NOTE: Don’t worry about repeated code for now. In the next labs, we will refactor to remove the repeated code (Boilerplate).

4 - Now that we have implemented the deleteCarById() method, which receives an ID as a parameter and runs the logic that removes a car record from our table, we can move on to creating the Servlet that receives the delete requests.

In the br.com.carstore.servlet package, select New and then Java Class. In the wizard, type the class name: DeleteCarServlet.

This servlet’s structure will be similar to the CreateCarServlet servlet, but the endpoint set in the @WebServlet annotation must be /delete-car, and the method to override must be doPost().

The resulting code should look like the following:

package br.com.carstore.servlet;

import br.com.carstore.dao.CarDao;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/delete-car")
public class DeleteCarServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String carId = req.getParameter("id");

        new CarDao().deleteCarById(carId);

        resp.sendRedirect("/find-all-cars");

    }

}

Done: our DAO and Servlet classes are ready to receive the request and run the remove / delete command in our database.

After calling the carDao class and the deleteCarById method, a request is made to the /find-all-cars endpoint, which in turn runs a new query on the database and displays the updated data on the dashboard.jsp page.


Task 2: Refactoring the code to return the ID

For the remove / delete command to work correctly, we need the ID of each registered car to be returned by the query. To do so, we have to refactor our code.

1 - The first step is to refactor the Car model class, adding a new String variable called id and a new overloaded constructor that receives the ID and the Name as parameters. Open the Car class, located in the br.com.carstore.model package, create a new private String variable called ID and its getter method getId(). Then create a constructor that receives id and name as parameters.

NOTE: No code should be removed in this step. Just add a new variable and the overloaded constructor.

The resulting code should look like the following:

package br.com.carstore.model;

public class Car {

    private String id;
    private String name;

    public Car(String name) {
        this.name = name;
    }

    public Car(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

}

2 - Now we need to refactor the findAllCars() method created in Lab 3 so that, when iterating (while) over the resultSet, it reads two properties: id and name.

The existing code is the following:


while (resultSet.next()) {

    String carName = resultSet.getString("name");

    Car car = new Car(carName);

    cars.add(car);

}

After the refactoring, the resulting code should look like the following:


while (resultSet.next()) {

    String carId = resultSet.getString("id");
    String carName = resultSet.getString("name");

    Car car = new Car(carId, carName);

    cars.add(car);

}

3 - Now we need to refactor the html page (dashboard.jsp) to display the ID in the query result. Open the dashboard.jsp page and add the variable ${car.id}

The existing code is the following:

<c:forEach var="car" items="${cars}">
    <tr>
        <td></td>
        <td>${car.name}</td>
    </tr>
</c:forEach>

After the refactoring, the resulting code should look like the following:

<c:forEach var="car" items="${cars}">
    <tr>
        <td>${car.id}</td>
        <td>${car.name}</td>
    </tr>
</c:forEach>

4 - Review everything you have done so far!

Congratulations! 👍

5 - Make sure everything so far works properly. Save everything (CTRL + S) and test your application tomcat7:run: register a car and check that the ID is now displayed when the dashboard.jsp page is rendered, as in the following image:

animated gif showing the car ID being displayed in the table

Task 3: Refactoring the dashboard.jsp page

Now that the car ID is displayed on the page, it is time to implement the logic that removes a car in the dashboard.jsp html page.

1 - To do so, open the dashboard.jsp page again. In the table, add one more column (th). Its label will be Actions.

<table>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Actions</th>
    </tr>
    <c:forEach var="car" items="${cars}">
        <tr>
            <td>${car.id}</td>
            <td>${car.name}</td>
        </tr>
    </c:forEach>
</table>

2 - The value of this column will be a form that, when submitted, makes an HTTP request to our new DeleteCarServlet servlet, passing the vehicle ID as a parameter.

The resulting code should look like the following:

 <table>
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Actions</th>
    </tr>
    <c:forEach var="car" items="${cars}">
        <tr>
            <td>${car.id}</td>
            <td>${car.name}</td>
            <td>
                <form action="/delete-car" method="post">
                    <input type="hidden" id="id" name="id" value="${car.id}">
                    <button type="submit">Delete</button>
                </form>
            </td>
        </tr>
    </c:forEach>
</table>

image showing the delete button rendered on the listing page

3 - Review everything you have done so far!

animated gif showing the delete working


Congratulations! 👍

You created the third part of the CRUD (delete). You implemented the deleteCarById() method, and now the data is deleted from the database.