This material is the concluding part of the "Introduction to Enterprise Development" series. Previous articles:
Let'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.
Click 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.
In 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
In the next window, select the project's name and location in the file system:
Click the "Finish" button. The project is created. We end up with the following project structure:
Here 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:
In the logs, we will see that our web application started on port 8080:
And this means that in a browser, we can go to the page at
http://localhost:8080:
Here we have the index.html page. Let's follow the link to the greeting page:
Our 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:
Everything works as intended. Now try to trace the path of the name variable:
- The user passed "name=Amigo" in the URL ->
- The controller processed our action, received the name variable, and set a model attribute called name equal to the received value ->
- 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!
|
GO TO FULL VERSION