CodeGym /Java Blog /Java Developer /Part 8. Let's write a small application using Spring Boot...

Part 8. Let's write a small application using Spring Boot

Published in the Java Developer group
This material is the concluding part of the "Introduction to Enterprise Development" series. Previous articles: Part 8. Let's write a small application using Spring Boot - 1Let's look at the simplest implementation of MVC using Spring MVC as an example. To do this, we'll write a small Hello World application using Spring Boot. I'll give you step-by-step instructions, so you can repeat everything yourself. First, we'll write a small application, and then we will analyze it.

Step 1. Creating a Spring Boot application in IntelliJ IDEA.

Use File -> New -> Project… to create a new project. In the window that opens, in the left side menu, select Spring Initializr, and select the Project SDK. Leave the default for the Initializr Service URL option. Part 8. Let's write a small application using Spring Boot - 2Click the "Next" button. In the next window, we need to select the project settings. We're going to have a Maven project. Select Maven Project as the type. Fill out the Group and Artifact fields Click Next. Part 8. Let's write a small application using Spring Boot - 3In the next window, we need to select the Spring Framework components that we will use. Two are enough for us:
  • Spring Web is a component that lets us create web applications. This component includes Spring MVC.
  • Thymeleaf is our template engine. It's a thing that lets us send data from Java to HTML pages
Part 8. Let's write a small application using Spring Boot - 4Part 8. Let's write a small application using Spring Boot - 5In the next window, select the project's name and location in the file system: Part 8. Let's write a small application using Spring Boot - 6Click the "Finish" button. The project is created. We end up with the following project structure: Part 8. Let's write a small application using Spring Boot - 7Here we're interested in 2 files: pom.xml (deployment descriptor). This thing lets you quickly and easily import libraries from different frameworks into our project. It is also where we configure how our application is built. Our application is built using Maven, and pom.xml is the configuration file for this build system. The Java class is MvcDemoApplication. This is our application's main class. We will launch our Spring Boot project from it. To start, just run the main method of this class. Here's the code for this class, as well as the pom.xml file: MvcDemoApplication:

@SpringBootApplication
public class MvcDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(MvcDemoApplication.class, args);
    }

}
pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.codegym/groupId>
    <artifactId>mvc_demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mvc_demo</name>
    <description>Spring MVC Demo</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Step 2. Creating a webpage

Our application will be extremely simple. We will have a main page (index.html), which will contain a link to the welcome page (greeting.html). On the greeting page, we display a greeting. We'll use URL parameters to pass the name to be used in the greeting to the greeting.html page. Let's create our application's main page — index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Main page</title>
</head>
<body>
    <p>Get your greeting <a href="/greeting">here</a></p>
</body>
</html>
Now we'll create the greeting.html page:

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'" />
</body>
</html>
Our page has a <p th:text="'Hello, ' + ${name} + '!'" /> tag, which is not normal for HTML. The th attribute of the p tag is a mechanism used by the Thymeleaf template engine. The p tag's value will be "Hello, " + the value of the name variable , which we will set in Java code.

Step 3. Creating a controller

Inside the mvc_demo package, we'll create a contoller package, in which we will create our controller, HelloWorldController:

@Controller
public class HelloWorldController {

   @RequestMapping(value = "/greeting")
   public String helloWorldController(@RequestParam(name = "name", required = false, defaultValue = "World") String name, Model model) {
       model.addAttribute("name", name);
       return "greeting";
   }

}
On the one hand there is very little code, but on the other hand, there is a lot going on. Let's start our analysis. The @Controller annotation indicates that this class is a controller. In Spring, controllers process HTTP requests directed at specific URLs. Our class has a helloWorldController method that is marked with the @RequestMapping(value = "/greeting") annotation. This annotation indicates that this method processes HTTP GET requests directed at the /greeting URL. In other words, this method will be invoked if someone navigates to /greeting. This method returns a String. According to Spring MVC, the controller method should return the name of the view. Next, Spring will look for an HTML file with the same name, which it will return as the response to the HTTP request. As you can see, our method returns the name of the webpage we created earlier: greeting. Our method takes 2 arguments. Let's take a look at them: Parameter 1: @RequestParam(name = "name", required = false, defaultValue = "World") String name. The @RequestParam annotation indicates that the String name parameter is a URL parameter. If the annotation indicates that this URL parameter is optional (required = false), then if it is absent, the String name parameter's value will be "World" (defaultValue = "World"). If it is present, then the URL parameter will be "name" (name = "name"). There might be a lot you don't understand here. Let's provide some examples. The table below shows what the String name parameter's value will be, with various options for accessing /greeting (with and without URL parameters)
Example URL Value of String name
/greeting World
/greeting?name=Amigo Amigo
/greeting?name=Zor Zor
Parameter 2: The second parameter is a Model model. This parameter is some model. This model consists of various internal attributes. Each attribute has a name and a value. Something like key-value pairs. We can use this parameter to send data from Java code to HTML pages. Or, using MVC terminology, send data from the model to the view. It only remains to examine the last line. It is how we send data from Java to HTML, or from the model to the view. The method includes the following line: model.addAttribute("name", name); Here we create a new attribute called name and assign it the value of the name parameter. Remember, we recently discussed the <p th:text = "'Hello,' + ${name} + '!'" /> We said that the value of the p tag is "Hello, " + the value of the name variable, which we will set in Java code. We set this value using the line model.addAttribute("name", name);

Step 5. Run

To start, we need to run the main method of the MvcDemoApplication class: Part 8. Let's write a small application using Spring Boot - 9In the logs, we will see that our web application started on port 8080: Part 8. Let's write a small application using Spring Boot - 10And this means that in a browser, we can go to the page at http://localhost:8080: Part 8. Let's write a small application using Spring Boot - 11Here we have the index.html page. Let's follow the link to the greeting page: Part 8. Let's write a small application using Spring Boot - 12Our controller was invoked in this transition. We didn't pass any parameters through the URL. As a result, the name attribute takes on the default value ("World") indicated in the annotation. Let's try passing parameter via the URL: Part 8. Let's write a small application using Spring Boot - 13Everything works as intended. Now try to trace the path of the name variable:
  1. The user passed "name=Amigo" in the URL ->
  2. The controller processed our action, received the name variable, and set a model attribute called name equal to the received value ->
  3. This data came to view from the model, ending up in the greeting.html page, and was displayed to the user
That's it for now!

Today we got acquainted with the rather large and interesting topic of MVC (Model - View - Controller). This is the end of the series designed to introduce you to what you need to know before starting enterprise development.

In the comments, tell us which topics you are interested in — We'll address them!

Comments (6)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Dương Tiến Đạt Level 41, Ha Noi City, Viet Nam
10 May 2023
In the Step 2. Creating a webpage, It would be nice to mention that the HTML files should be location inside template directory. It took me a while to figure that out
matemate123 Level 50, Kraków, Poland
22 April 2023
https://start.spring.io/ when you haven't Intellij Ultimate Version
matemate123 Level 50, Kraków, Poland
22 April 2023
This Spring Initializr is only available in Intellij Ultimate version. Thank you
Surya Level 33, Newark, United States
17 July 2020
Can we have a detailed quest for Spring boot ( 10 levels ) like others. It may not be helpful for me as will learn it from somewhere else by the time it is published. But, the future students will be ready for industry standards. I'm now working in java as beginner, but really my company uses almost everything just beyond Java ( sql, spring boot, hibernate etc...).