Lab 1: Creating the application

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 Web application with Java.

After completing this lab, you should be able to:

  • Create a Web application with Java
  • Start an embedded Tomcat server (Servlet Container) to run your Java application
  • Make http requests through an HTML form and capture the request data in a Servlet

This lab is also available as a video lesson on YouTube

Car Store #01 - Criando o Projeto Java Web a partir de um Archetype Maven · Video in Portuguese.
Car Store #02 - Criando a primeira Servlet · Video in Portuguese.

Task 1: Create a Java application with IntelliJ

1 - Make sure IntelliJ is installed on your computer. If it is not, install the Community Edition, as shown in this YouTube video: Installing IntelliJ on Windows (in Portuguese). Or click the following link to download it: IntelliJ download link

animated gif showing how to install IntelliJ on Windows

2 - Open IntelliJ

NOTE: If this is the first time you open IntelliJ on your machine, you need to tick the checkbox to confirm that you have read the terms of use and then click the continue button.

On the next screen, you need to choose whether to share your usage data anonymously. Click Don’t Send.

If this is not the first time you use IntelliJ on this computer, ignore this information.

3 - Once IntelliJ is open, on the welcome screen, click the Projects menu and then click the New Project button.

4 - In the new project wizard, click Maven Archetype and, in this section, set:

  • Name: carstore
  • Location: Keep the default value
  • JDK: Choose the installed JDK from the drop-down menu NOTE: If you have no JDK installed, click Download JDK, select version 11 in the version field of the drop-down menu and then click the Download button.
  • Catalog: Keep the default value
  • Archetype: maven-archetype-webapp

In the Advanced Settings section, set:

  • GroupId: br.com.carstore
  • ArtifactId: carstore
  • Version: 1.0-SNAPSHOT

5 - Click the Create button

animated gif showing how to create a new project from a Maven archetype for a web project

After that, just wait for the whole loading step to finish. At the end, your application will be ready.

NOTE: The loading process may take a few minutes. It is essential to wait for the whole loading step to finish.

6 - Review everything you have done so far!


Task 2: Add the Tomcat plugin and the Maven War Plugin

Now that the application is created, it is time to add the Tomcat (Servlet Container) plugin. This way, you can run the Web application on the Tomcat server with no extra effort.

1 - With the application created, open the pom.xml file

2 - The pom.xml file is used by Maven to build and package a Java application. It is made up of several sections. Find the <build> section and, inside it, add the following block of code.

NOTE: No code should be removed in this step. Just add the following code inside the <build> block:

<plugins>
  <plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <version>2.1</version>
    <configuration>
      <path>/</path>
    </configuration>
    <executions>
      <execution>
        <id>tomcat-run</id>
        <goals>
          <goal>exec-war</goal>
        </goals>
        <phase>package</phase>
        <configuration>
            <enableNaming>false</enableNaming>
        </configuration>
      </execution>
    </executions>
  </plugin>
</plugins>

animated gif showing how to add the Tomcat plugin

3 - Add a second plugin inside the plugins block created in the previous step, as in the following code:

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.2.2</version>
    <configuration>
        <webXml>src\main\webapp\WEB-INF\web.xml</webXml>
        <warSourceDirectory>src/main/webapp</warSourceDirectory>
    </configuration>
</plugin>

animated gif showing how to add the maven-war plugin

4 - The resulting code should look like the following:

<plugins>
  <plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <version>2.1</version>
    <configuration>
      <path>/</path>
    </configuration>
    <executions>
      <execution>
        <id>tomcat-run</id>
        <goals>
          <goal>exec-war</goal>
        </goals>
        <phase>package</phase>
        <configuration>
            <enableNaming>false</enableNaming>
        </configuration>
      </execution>
    </executions>
  </plugin>
  <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>3.2.2</version>
    <configuration>
        <webXml>src\main\webapp\WEB-INF\web.xml</webXml>
        <warSourceDirectory>src/main/webapp</warSourceDirectory>
    </configuration>
  </plugin>
</plugins>

5 - Still in the pom.xml file, we need to tell Maven which Java version to use to compile the project. The archetype does not set this version and, without it, the project does not compile on current Java versions (the error shown is Source option 5 is no longer supported).

Find the line that contains the <url> tag and, right below it, add the following block:

<properties>
  <maven.compiler.source>11</maven.compiler.source>
  <maven.compiler.target>11</maven.compiler.target>
</properties>

NOTE: If your pom.xml already has a <properties> block with the values 1.7, just change these values to 11.

6 - Save all changes (CTRL + S) and then click the Load Maven Changes button. Maven will detect that new plugins were added to the project and will download them automatically. Wait for the loading to finish.

7 - You can now run the application and render your first web page in the browser. To do so, go to the Maven menu in IntelliJ, expand the carstore project, then click plugins, then tomcat7 and finally double-click the tomcat7:run option. This starts the web server (Servlet Container).

8 - After the loading process, open a tab in your browser and type the following address: http://localhost:8080

9 - A web page should be rendered with the message Hello World!

animated gif showing how to run the project that was created

10 - Review everything you have done so far!


Task 3: Creating your first Servlet and making an http request

Now that your application is created and you have started your web server, it is time to create your first Servlet and make your first http request

1 - Open the pom.xml file again

2 - Find the <dependencies> block. You must add two dependencies inside the <dependencies> block of your application’s pom.xml, as in the following code.

NOTE: No code should be removed in this step. Just add the following code inside the <dependencies> block:

<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>

animated gif showing how to add the dependencies to the project’s pom.xml

3 - Save all changes (CTRL + S) and then click the Load Maven Changes button. Maven will detect that two new dependencies were added to your project and will download them automatically for you. Wait for the loading to finish.

4 - Once the loading / download of the new dependencies finishes, go back to the Project tab and browse your project by clicking the carstore folder, src and then main. Right-click the main folder and choose New and then Directory. The new directory wizard opens; select the Java option.

5 - Once the Java directory is created, let’s create a package so we can create our first Java class. To do so, right-click the Java directory, choose New and then Package, and type in the wizard: br.com.carstore.servlet. This will be the default package of our application.

animated gif showing how to create the java directory and the br.com.carstore package

6 - Now let’s create our first Java class (a Servlet). Right-click the package we have just created (br.com.carstore.servlet), select New and then Java Class. In the wizard, type the class name: CreateCarServlet

7 - Now that your first servlet is created, you need to add the @WebServlet annotation. This annotation must go one line above the line where the CreateCarServlet class is declared. Then make the class extend the HttpServlet class. The resulting code should look like the following:

package br.com.carstore.servlet;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

@WebServlet("/create-car")
public class CreateCarServlet extends HttpServlet {

}

animated gif showing how to create the CreateCarServlet class and add the @WebServlet annotation

8 - The next step is to override the doPost() method. This is the method that will receive the http requests made with the POST method through the HTML form.

To override the doPost() method, just type doPost inside your class declaration and then press the shortcut (CTRL + space bar). The autocomplete will show a suggestion; just press enter and the method will be overridden. The resulting code should look like the following:

package br.com.carstore.servlet;

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 {

        super.doPost(request, response);

    }

}

animated gif showing how to override the doPost method

9 - With the doPost method overridden, let’s implement the call to req.getParameter(“car-name”). This is how we get the information sent through the html form.

Inside the doPost() method, delete the line super.doPost(req, resp) and then implement the following code:

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

System.out.println(carName);

request.getRequestDispatcher("index.html").forward(request, response);

The complete code should look like the following:

package br.com.carstore.servlet;

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");

        System.out.println(carName);

        request.getRequestDispatcher("index.html").forward(request, response);

    }

}

animated gif showing how to implement the call to the getParameter method

10 - The last step is to implement the HTML form. This form must have three elements: a label with the field name, an input so the user can type the value as text, and a button the user can click to submit the http request to the server.

In your project, go to the directory: carstore/src/main/webapp. The archetype created a file called index.jsp in this directory (it is the Hello World! page you saw in Task 2). Delete this file (right-click it and choose Delete).

Then right-click the webapp folder, choose New and then File, and create a new file called index.html.

The form implementation 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">

    <button type="submit">Register</button>

</form>

</body>
</html>

11 - Review everything you have done so far!


Congratulations! 👍

You created a new Web application with Java, Maven and a Web Archetype. You added the Tomcat Embed plugin and the Maven Build plugin. You created your first Servlet and overrode the doPost method, preparing it to receive an attribute that will reach your Java code when your html form is submitted. Then you created an html form with a text input field so the user can make the request. With this, you can start the server, render your first web page, make the first request and get the submitted value in your Java Servlet.