Lab 5: Creating the UPDATE 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 update data in 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;
- Update data persisted in the database (update … where id = ?).
This lab is also available as a video lesson on YouTube
Task 1: Creating the updateCar() method
Your application is created, your web server is running and you can already save, query and delete data in the database. Now it is time to implement the operation that updates data persisted in your application’s database.
1 - To do so, let’s create a new method called updateCar() that receives a car object as a parameter. This method must be created in the CarDao class.
NOTE: The CarDao class already exists and has three methods: createCar(), findAllCars and deleteCarById(). In this section, we will only add a new method to this class. The method name must be updateCar(). It receives a Car object as a parameter and its return type is void.
To do so, open the CarDao class and implement the updateCar() method. The resulting code should look like the following:
public void updateCar(Car car) {
}2 - Now let’s implement the logic that updates the data in our table. The first step is to create a string variable. We will call this variable SQL. Its value is a string with the SQL command for the update (UPDATE … WHERE ID = ?).
The resulting code should look like the following:
public void updateCar(Car car) {
String SQL = "UPDATE CAR SET NAME = ? WHERE ID = ?";
}NOTE: This command updates the data stored in our table according to the given ID. It updates the fields listed in the SET clause. This example is extremely simple. Be very careful when you replicate this function in your project.
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 updateCar(Car car) {
String SQL = "UPDATE CAR SET NAME = ? 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, car.getName());
preparedStatement.setString(2, car.getId());
preparedStatement.execute();
System.out.println("success in update car");
connection.close();
} catch (Exception e) {
System.out.println("fail in database connection");
System.out.println("Error: " + e.getMessage());
}
}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 updateCar() method, which receives a Car object as a parameter and runs the logic that updates a car record in our table, we can move on to refactoring the Servlet that receives the update requests.
In the br.com.carstore.servlet package, find the Servlet called CreateCarServlet.
This Servlet already exists and will get a few changes. Now, when it receives a request in the doPost() method, besides collecting the car-name parameter, we will also collect the ID and store it in a String variable called carId.
After this implementation, 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.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 IOException {
String carId = req.getParameter("id");
String carName = req.getParameter("car-name");
Car car = new Car(carName);
new CarDao().createCar(car);
resp.sendRedirect("/find-all-cars");
}
}5 - Now we need to check whether the value of the carId variable is blank. If it is blank (it has no ID), it is a create request. If the value of the carId variable is not blank (it has an ID), it is an update request.
To build this logic, we will use the isBlank() method of the String class, introduced in Java 11.
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.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 IOException {
String carId = req.getParameter("id");
String carName = req.getParameter("car-name");
CarDao carDao = new CarDao();
Car car = new Car(carId, carName);
if (carId.isBlank()) {
carDao.createCar(car);
} else {
carDao.updateCar(car);
}
resp.sendRedirect("/find-all-cars");
}
}NOTE: Notice that, for a create request (insert), we keep calling the createCar() method; otherwise, we now call the new updateCar() method. The rest of the logic stays the same.
Done: our DAO and Servlet classes are ready to receive the requests and run the update or create command in our database.
After calling the carDao class and the updateCar 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 dashboard.jsp page
Now that we have built the logic to update a car’s data, we need to refactor the dashboard.jsp page and add the anchor / hyperlink that redirects the request to the index.jsp page, sending the data already filled in the input fields.
1 - To do so, open the dashboard.jsp page. Find the form we created in the previous lab inside the table and add an anchor in the Actions column, next to the delete button, before the form closing tag. We will also add a label to visually separate the button from the anchor.
After the implementation, 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>
<span> | </span>
<a href="index.jsp?id=${car.id}&name=${car.name}">Update</a>
</form>
</td>
</tr>
</c:forEach>
</table>NOTE: Notice that the anchor creates a hyperlink to the index.jsp page. This sends some parameters, such as the car.id and car.name variables. This is needed so we can access these values on the index.jsp page, as shown below.
2 - Changing the extension of the index page
The next step is to change the extension of the index page from .html to .jsp. This is needed so we can access the values sent as parameters in the request made through the hyperlink from the dashboard.jsp page to the index.jsp page.
In IntelliJ, go to the index.html page in the directory: carstore/src/main/webapp. Right-click the index.html file, select refactor / rename and change the extension from .html to .jsp.

3 - Refactoring the index.jsp page
Now that the index page has the .jsp extension, we can make the necessary refactoring on the page so our update operation works correctly.
With the index.jsp page open, we will add a new hidden input field to store the ID variable ${param.id} and add the value property to the input field to store the ${param.name} variable. Also take the opportunity to change the button text from Register to Save, since it now serves both to register and to update.
After the refactoring, the resulting code should look like the following:
<html>
<body>
<h2>Create Car</h2>
<form action="/create-car" method="post">
<label>Car Name</label>
<input type="text" name="car-name" id="car-name" value="${param.name}">
<input type="hidden" id="id" name="id" value="${param.id}">
<button type="submit">Save</button>
</form>
</body>
</html>4 - Review everything you have done so far!
Save all changes (CTRL + S) and run your application (tomcat7:run). Open your application at http://localhost:8080 and register a car. Notice that now, after the registration screen, the table on the dashboard.jsp page shows a hyperlink labeled Update. Clicking this hyperlink takes you back to index.jsp, but with the fields filled in with the values shown in the table. Just change the value and click the Save button. The user is redirected to dashboard.jsp and the values are changed in the database, as shown in the animated gif below.

Congratulations! 👍
You created the fourth part of the CRUD (update). You implemented the updateCar() method, and now the data is updated in the database.