Lab 2: Creating the INSERT method and setting up the database connection
Video lesson published on
This page was originally written in Portuguese. Read the original.
Lab overview and objectives
This lab presents the basic concepts for creating a Java Web application with a data persistence layer!
After completing this lab, you should be able to:
- Provision a persistence layer for the Java Web application;
- Start a Tomcat server (Servlet Container) and an embedded database (H2 DB) to run your Java application and persist its data;
- Make http requests through an HTML form and capture the request data in a Servlet;
- Save the data captured from an HTML form and persist it in a database (insert).
This lab is also available as a video lesson on YouTube
Task 1: Add a new dependency to your project
Now that your application is created and you have started your web server, it is time to add a data persistence layer to your application.
1 - Open the pom.xml file
2 - Find the dependencies block. You must add a new dependency inside this block.
NOTE: No dependency should be removed in this process. Add the following dependency inside the dependencies block:
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.1.214</version>
</dependency>- The resulting code should look like the following:
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.1.214</version>
</dependency>
</dependencies>4 - Review everything you have done so far!
Congratulations! 👍
You added the H2 DB (embedded database) dependency.
Task 2: Registering the H2 DB listener in the web.xml file
⚠️ To learn more about H2 DB, see the official documentation at this link: H2 Database Engine
1 - Now that the H2 dependency has been added to the project, you need to register the H2 listener in the web.xml file. To do so, go to the web.xml file, located in the directory: carstore/src/main/webapp/WEB-INF/web.xml
2 - With the web.xml file open, add the listener inside the web-app block, as in the following code:
<listener>
<listener-class>org.h2.server.web.DbStarter</listener-class>
</listener>
<servlet>
<servlet-name>H2Console</servlet-name>
<servlet-class>org.h2.server.web.WebServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>H2Console</servlet-name>
<url-pattern>/console/*</url-pattern>
</servlet-mapping>NOTE: No configuration should be removed in this process.
3 - Besides the listener, we need to update the file header. The web.xml generated by the archetype uses version 2.3 of the Servlet specification. In that version, the ${...} expressions we will use in the JSP pages in the next labs do not work. So replace the whole content of the web.xml file with the following code, which already uses version 3.0:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>car-store</display-name>
<listener>
<listener-class>org.h2.server.web.DbStarter</listener-class>
</listener>
<servlet>
<servlet-name>H2Console</servlet-name>
<servlet-class>org.h2.server.web.WebServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>H2Console</servlet-name>
<url-pattern>/console/*</url-pattern>
</servlet-mapping>
</web-app>4 - Save all changes (CTRL + S) and run your application (tomcat7:run). With the H2 DB listener registered, you can access the management console at: http://localhost:8080/console
5 - Once in the H2 DB console, log in with the following information:
* Driver Class: org.h2.Driver
* JDBC URL: jdbc:h2:~/test
* User Name: sa
* Password: sa
NOTE: Although it is an embedded database (it starts together with the application), H2 stores the data in a file called test.mv.db in your user folder (that is what the ~ in the JDBC URL means). That is why the data is not lost when the application restarts.
6 - After logging in, you can create your first table. You must create a table called CAR. To do so, use the following SQL command:
CREATE TABLE CAR(ID INT PRIMARY KEY AUTO_INCREMENT, NAME VARCHAR(255));
7 - Review everything you have done so far!
Congratulations! 👍
You added an embedded database (H2 DB) dependency to your Java Web application. Now that the H2 DB dependency is in your application’s pom.xml file, when you start the application (tomcat7:run) you have a relational database at your disposal, along with a console to manage it.
Task 3: Creating the first Model and the first DAO
Now that the database is set up, it is time to create the first model class (Car) and the first DAO class (CarDao).
1 - Let’s create two new packages: the first one is called dao and the second one model. To do so, go to the main package (br.com.carstore). In your project, go to the directory carstore/src/main/java/br.com.carstore, right-click the main package (br.com.carstore), choose New / Package and type the name of the first package (dao). Repeat the operation to create the second package (model).
At the end, we expect to have three subpackages inside the main package, following this hierarchy:
carstore/
|..| src/
| |..| main/
| | |..| java/
| | | |..| br.com.carstore
| | | | |..| dao
| | | | |..| model
| | | | |..| servlet
| | |..| webapp/
| | | |..| WEB-INF/
| | | | |..| web.xml
| | | |..| index.html
2 - With the new packages created, let’s create our model class called Car. To do so, right-click the model package, choose New, Java Class, type Car and press ENTER. The IntelliJ wizard will create a new Java class called Car.
3 - With the Car class created, let’s add a String attribute to it, with the private access modifier, called name.
4 - Create the accessor methods (getters and setters) for the attribute we have just created (private String name).
The resulting code should look like the following:
package br.com.carstore.model;
public class Car {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}5 - Now that the Car class is created, we can create our CarDao class. To do so, right-click the dao package, choose New, Java Class, type CarDao and press ENTER. The IntelliJ wizard will create a new Java class called CarDao.
6 - With the CarDao class created, let’s implement a method called createCar that returns void (returns nothing) and receives a Car object as a parameter.
At this step, the resulting code should look like the following:
package br.com.carstore.dao;
import br.com.carstore.model.Car;
public class CarDao {
public void createCar(Car car) {
}
}7 - With the createCar method created, let’s implement the logic that persists the values of the car object in our database. At this step, the resulting code should look like the following:
package br.com.carstore.dao;
import br.com.carstore.model.Car;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class CarDao {
public void createCar(Car car) {
String SQL = "INSERT INTO CAR (NAME) VALUES (?)";
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.execute();
System.out.println("success in insert car");
connection.close();
} catch (Exception e) {
System.out.println("fail in database connection");
}
}
}8 - Now we need our CreateCarServlet servlet to use the CarDao class. So far, it only writes the car name to the console. Open the CreateCarServlet class, in the br.com.carstore.servlet package, and replace the line System.out.println(carName); with the creation of a Car object and the call to the createCar() 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;
@WebServlet("/create-car")
public class CreateCarServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String carName = request.getParameter("car-name");
Car car = new Car();
car.setName(carName);
new CarDao().createCar(car);
request.getRequestDispatcher("index.html").forward(request, response);
}
}9 - Pay attention to the whole implementation and to the imports. At this step, your IDE should not report any error. If your IDE reports an error, review all the previous steps to make sure everything is correct.
10 - With everything implemented, you can now test the project to make sure it works correctly.

11 - Review everything you have done so far!
Congratulations! 👍
You added an embedded database (H2 DB) dependency to your Java Web application and created the first model and dao classes. You implemented the logic that opens a connection to the database (H2) and the command that persists (insert) the data in the database.
Now, when you start the application (tomcat7:run), you have a relational database at your disposal, along with a console to manage it. At this point, the create part of our CRUD is implemented and working.