JavaRush /Java Blog /Random EN /Part 8. Writing a small application in spring-boot

Part 8. Writing a small application in spring-boot

Published in the Random EN group
This material is the final part of the “Introduction to Enterprise Development” series. Previous articles: Part 8. Writing a small application in spring-boot - 1Let's look at the simplest example of MVC implementation using Spring-MVC as an example. To do this, let's write a small Hello World application in spring-boot. So that you can repeat everything yourself, I will give you step-by-step instructions. First we will write a small application, and then we will analyze it.

Step 1: Create a spring-boot application in IntelliJ IDEA

Using File -> New -> Project... create a new project. In the window that opens, in the left side menu, select Spring Initializr, select Project SDK, and leave the Initializr Service URL option as default. Part 8. Writing a small application in spring-boot - 2Click the Next button. In the next window we need to select project parameters. We will have a Maven project. Select Type - Maven Project, fill in Group and Artifact Part 8. Writing a small application in spring-boot - 3and click Next. In the next window we need to select the Spring Framework components that we will use. We only need two:
  • Spring Web is a component that will allow us to create Web applications. This component includes Spring MVC.
  • Thymeleaf - The so-called template engine. A thing that will allow us to transfer data from Java to HTML pages
Part 8. Writing a small application in spring-boot - 4Part 8. Writing a small application in spring-boot - 5In the next window, select the name and location of the project in the file system: Part 8. Writing a small application in spring-boot - 6Click the Finish button. The project has been created. We have the following project structure: Part 8. Writing a small application in spring-boot - 7Here we are interested in 2 files: pom.xml - deployment descriptor. A thing that allows you to quickly and easily import libraries from different frameworks into our project, as well as a thing in which we configure the assembly of our application. Our application is built using Maven, pom.xml is the configuration file of this build system. Java class - MvcDemoApplication. This is the main class of our application, from which we will launch our spring-boot project. To start, just run the main method in this class. Here is 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.javarush</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. Create web pages

Our application will be extremely simple. We will have a main page - index.html, inside which there will be a link to the welcome page - greeting.html. On the greeting page we will display the greeting. Let's implement the ability to send a greeting name to the greeting.html page via url parameters. Let's create the main page of our application - 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 let's 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>
Here, from an atypical html page, you can see a tag: The tag <p th:text="'Hello, ' + ${name} + '!'" /> attribute is a tool of the Thymeleaf template engine. Thanks to it, the value of the tag will be the text “Hello, “ + the value of the variable , which we will set from Java code. thppname

Step 3: Create a Controller

Inside the mvc_demo package we will create a contoller package, inside 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 the analysis. The @Controller annotation indicates that this class is a controller. Controllers in Spring process HTTP requests to specific addresses. Our class has a helloWorldController method, which is marked with the annotation - @RequestMapping(value = "/greeting"). This annotation tells us that this method processes HTTP GET requests to the /greeting address. In other words, this method will work if someone goes to /greeting. This method returns String. According to Spring-MVC, the controller method must return the name of the view. Next, Spring will look for an html file with the same name, which will be returned as a response to the HTTP request. As you can see, our method returns the name of the web page we created earlier - greeting. Our method takes 2 arguments. Let's look at them: Parameter 1: @RequestParam(name = "name", required = false, defaultValue = "World") String name. The @RequestParam annotation states that the String name parameter is a url parameter. The annotation parentheses indicate that this parameter in the url is optional (required = false), if it is absent, the value of the String name parameter will be World (defaultValue = "World"), and if it is present, then this parameter in the url will be be called name (name = "name") There may be a lot that is unclear here. Let's give examples. The table below shows what the value of the String name parameter will be for different options for accessing the /greeting address (with and without parameters in the URL)
Example URL String name parameter value
/greeting World
/greeting?name=Amigo Amigo
/greeting?name=Zor Zor
Parameter 2: The second parameter is Model model. This parameter is a model. This model consists internally of various attributes. Each attribute has a name and a value. Something like key-value pairs. Using this parameter, we can transfer data from Java code to html pages. Or, in MVC terminology, transfer data from the Model to the View. It remains to parse the last line. The way we pass data from Java to html or from Model to View. The body of the method contains 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, just recently we discussed the tag: <p th:text="'Hello, ' + ${name} + '!'" /> We said that the value of the p tag will be the text “Hello, “ + the value of the name variable, which we will set from Java code. We set this value using the line model.addAttribute("name", name);

Step 5. Launch

To launch, we need to run the main method in the MvcDemoApplication class: Part 8. Writing a small application in spring-boot - 9In the launch logs, we will see that our web application started on port 8080: Part 8. Writing a small application in spring-boot - 10And this means that we can go to the page in the browser: http://localhost:8080 : Part 8. Writing a small application in spring-boot - 11Here the page index.html was displayed to us. Let's follow the link to greetin: Part 8. Writing a small application in spring-boot - 12During this transition, our controller worked. We did not pass any parameters through the URL, therefore, as stated in the annotation, the value of the name attribute took the default value World. Let's now try to pass the parameter via url: Part 8. Writing a small application in spring-boot - 13Everything works as intended. Now try to trace the path of the name variable:
  1. The user passed the value of the parameter name = Amigo -> via url
  2. The controller processed our action, accepted the name variable and set the model attribute, with the name name and the accepted value ->
  3. From the model, this data went to the View, to the greeting.html page and was displayed to the user
That's all!

Today we introduced you to a rather large and interesting topic of MVC (Model - View - Controller). This is the end of the series, the purpose of which is to introduce you to what you need to know before starting Enterprise development.

Leave topics that interest you in the comments - we’ll do it!

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION