Lab 3: Creating the SELECT method

Video lesson published on

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

Lab overview and objectives

This lab presents the basic steps to create a query layer in the data persistence layer!

After completing this lab, you should be able to:

  • Make http requests through an HTML form and capture the request data in a Servlet;
  • Query the data persisted in the database (select * from car) and display it in an HTML page.

This lab is also available as a video lesson on YouTube

Car Store #05 - Implementando a segunda operação do CRUD - READ · Video in Portuguese.

Task 1: Creating the findAllCar() method

Your application is created, your web server is running and you can already save data to the database. Now it is time to implement a layer that queries the data persisted in your application’s database.

1 - First, let’s refactor the Car model class, removing the setter method and creating an overloaded constructor. Open the Car class, delete the setName() method and create a constructor that receives name as a parameter.

The resulting code should look like the following:

package br.com.carstore.model;

public class Car {

    private String name;

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

    public String getName() {
        return name;
    }

}

2 - Because of this refactoring in the Car class, you need to adjust the CreateCarServlet.java class, replacing the lines Car car = new Car(); and car.setName(carName); with the line Car car = new Car(carName);, which passes the carName parameter through the constructor.

After the refactoring, the code of the CreateCarServlet.java class should look like the following:

package br.com.carstore.servlet;

import br.com.carstore.dao.CarDao;
import br.com.carstore.model.Car;

import javax.servlet.ServletException;
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("/create-car")
public class CreateCarServlet extends HttpServlet {

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

        String carName = req.getParameter("car-name");

        Car car = new Car(carName);

        new CarDao().createCar(car);

        req.getRequestDispatcher("index.html").forward(req, resp);

    }

}

3 - Now let’s create a new method called findAllCars in the CarDao class. To do so, open the CarDao class.

Create the findAllCars method, which returns a list of Car. The resulting code should look like the following:

public List<Car> findAllCars() {

}

At this point, your IDE will report an error because the return statement has not been implemented yet. Don’t worry, this will be fixed in the next step.

4 - Now let’s implement the logic that fetches the data from the database. The first step is to create our SQL string with the query command (SELECT * FROM).

The resulting code should look like the following:

public List<Car> findAllCars() {

     String SQL = "SELECT * FROM CAR";

}

This command queries the CAR table in our database and returns all the records in it.

5 - The rest of the implementation is very similar to 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 List<Car> findAllCars() {

        String SQL = "SELECT * FROM CAR";

        try {

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

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

            PreparedStatement preparedStatement = connection.prepareStatement(SQL);

            ResultSet resultSet = preparedStatement.executeQuery();

            List<Car> cars = new ArrayList<>();

            while (resultSet.next()) {

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

                Car car = new Car(carName);

                cars.add(car);

            }

            System.out.println("success in select * car");

            connection.close();

            return cars;

        } catch (Exception e) {

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

            return Collections.emptyList();

        }

    }

NOTE: For this code to compile, the CarDao class needs the following imports. In IntelliJ, you can place the cursor on each class underlined in red and use the (ALT + ENTER) shortcut to import it.

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

6 - Now that we have implemented the findAllCars method, which returns a list with all the cars registered in our Car table, we can move on to creating the Servlet that receives the query requests.

In the servlet package, select New and then Java Class. In the wizard, type the class name: ListCarServlet.

This servlet’s structure will be similar to the CreateCarServlet servlet, but the endpoint set in the @WebServlet annotation must be find-all-cars, and the method to override is doGet().

The resulting code should look like the following:

package br.com.carstore.servlet;

import br.com.carstore.dao.CarDao;
import br.com.carstore.model.Car;

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

@WebServlet("/find-all-cars")
public class ListCarServlet extends HttpServlet {

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

        super.doGet(req, resp);

    }

}

7 - With the ListCarServlet class created and the doGet method overridden, we can implement the logic that calls the CarDao class and the findAllCars() method.

The resulting code should look like the following:

package br.com.carstore.servlet;

import br.com.carstore.dao.CarDao;
import br.com.carstore.model.Car;

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

@WebServlet("/find-all-cars")
public class ListCarServlet extends HttpServlet {

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

        List<Car> cars = new CarDao().findAllCars();

        req.setAttribute("cars", cars);

        req.getRequestDispatcher("dashboard.jsp").forward(req, resp);

    }

}

Notice that we are now redirecting the user to a new page called dashboard.jsp. This page does not exist yet; we will create it in the next step.

8 - Now let’s create the page that displays the result of our query in a table on our HTML page.

Create a new page called dashboard.jsp inside the webapp folder. In this page, create a table with two columns: one for the ID property and the other for the Name property.

The resulting code should look like the following:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Dashboard</title>
</head>
<body>
  <div>
    <h1>Cars</h1>
    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
        </tr>
        <tr>
            <td></td>
            <td></td>
        </tr>
    </table>
  </div>
</body>
</html>

9 - Now let’s add the import of the JSTL taglib (The JavaServer Pages Standard Tag Library). This tag library is what lets us use IF or FOR in our page.

After adding the tag library import and the for loop, the resulting code should look like the following:

<!DOCTYPE html>
<html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<head>
    <meta charset="UTF-8">
    <title>Dashboard</title>
</head>
<body>
  <div>
    <h1>Cars</h1>
    <table>
        <tr>
            <th>ID</th>
            <th>Name</th>
        </tr>
        <c:forEach var="car" items="${cars}">
            <tr>
                <td></td>
                <td>${car.name}</td>
            </tr>
        </c:forEach>
    </table>
  </div>
</body>
</html>

10 - The last step is to redirect the user to the new page after a new car is created (insert) in our database. To do so, in the CreateCarServlet class, replace the line that contains the code:

 req.getRequestDispatcher("index.html").forward(req, resp);

With the following line:

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

After that, when a new car is created, the request is redirected to our new ListCarServlet servlet, which runs the doGet() method, queries the database and finally redirects the user to the dashboard.jsp page, where the cars registered in the database are rendered in the browser.

11 - Review everything you have done so far!


Congratulations! 👍

You created the second part of the CRUD (read). You implemented the findAllCars method, and now the data is queried from the database and displayed on our new HTML page.