Build Spring MVC Application using Spring Boot Framework

Introduction

Spring MVC is one of the other frameworks of spring. It implements Model-View-Controller or MVC design patterns, which provide a unique and clean approach for building web sites. Therefore, this architecture helps the developers to manage the development by separating the different aspects of the application.

MVC Structure

Furthermore, the MVC (Model-View-Controller) structure consists of three kinds of phases. Including model, view, and controller. Therefore, the purpose of this architecture is to decouple different aspects of the application. As a result, it can increase the flexibility and reusability of the codes in web development.

  • The model defines the data or object, which is providing inputs and output to the end-users of the application. For example, the object can be a person’s entity. Including its name, age, address, and more.
  • The view represents the image of an objects that display on the user interface of the application. For example, personal details like the name will show “Joe”, and age is “24”, etc.
  • The controller defines the behavior of the application. For example, the application responses after the user submit his complete inputs. And then, if the inputs are valid, a success message will be displayed, if not, the error message will show.

What you need

Spring MVC configuration in Spring Tool Suite (STS)

Spring Boot provides quick and easy steps to generate web MVC project using Spring Tool Suite (STS).

If you don’t have any idea what is STS, you can refer to this link for Eclipse STS setup: http://lgeratech.com/2020/05/spring-framework-quick-start/#Eclipse_setup

Or if you don’t have eclipse yet, you can download STS directly to this link: https://spring.io/tools

Let’s start creating spring project for our web MVC application. I will call the project WebMVCApplication, and select project dependencies. Including Spring Boot DevTools, Spring Web ( with Web MVC), and Thymeleaf:

Thymeleaf

Thymeleaf provides features that allowing us to integrate web content or HTML file to our application. And it is also consider as a substitute for JSP or JavaServer Pages in Spring MVC applications

Maven Structure

Maven is the build automation tool used for java projects. And it automatically generate all dependencies that defined in the XML file. However, in STS we don’t need to manually define the dependencies at the start of the project configuration. As a result, STS does it for you, but if you forgot to add something during configuration. Therefore, you need to define it manually in the pom.xml file. For our project make sure the pom.xml file looks like below:

<?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.3.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.lgeratech</groupId>
	<artifactId>WebMVCApplication</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>WebMVCApplication</name>
	<description>Demo project for Spring Boot</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-devtools</artifactId>
			<scope>runtime</scope>
			<optional>true</optional>
		</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>

Web Application Walkthrough

Before we start, we must know what pages and functions that need to develop on our application. For our example, we are going to develop pages that will ask the user for registration. And the pages that we need to develop are registration, home, and profile pages.

We will take the example page design in How to build a website using HTML5, CSS3, and JavaScript tutorial:

Home Page

The home page is the starting point of our application. Therefore, when the page is loaded, the Click Here link will appear on the page body. After clicking the link, the application will navigate you on the registration page.

Registration Page

The registration page contains fields that ask for the user’s input. When the input fields are completed, and the submit button is clicked. As a result, the application will navigate into another page to display the user’s information.

Profile Page

Once the user reaches the profile page, he will see the input he made after the registration. Go to the Test the Application for the demo video.

Web Model

Let’s start our web development by creating a model since this is the easiest part of MVC. And then add new class, name it as User, And then place it in com.lgeratech.demo.models package.

In the User.java, add fields for name, age, and gender. And then encapsulate fields with getter and setter. Therefore, the encapsulation uses for data mapping that allows the spring framework to modify the fields. The code is the same as the code below:

package com.lgeratech.demo.models;
public class User {
	private String name;
	private String age;
	private String gender;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public String getGender() {
		return gender;
	}
	public void setGender(String gender) {
		this.gender = gender;
	}
}

Web Controller

Create another file name as UserController.java for the controller of our application. and then add new package com.lgeratech.demo.controllers to place all controllers if there is any. And then copy and paste the code below into the UserController.java file:

package com.lgeratech.demo.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import com.lgeratech.demo.models.User;
@Controller
public class UserController {
	@GetMapping(value = "/registration")
	public String registration() {
		return "registration";
	}	
	@PostMapping(value = "/profile")
	public String profile(@ModelAttribute User user, Model model) {
		model.addAttribute("user", user);
		return "profile";
	}	
}

The controller file can easily identify by @Controller annotation. Therefore, the controller handles the HTTP requests, which use to allow other applications to communicate with the application. Additionally, the communication will be done by providing an HTTP response back to other applications after the HTTP request. However, in MVC it can also use as communication between the view and the controller.

Registration HTTP Request

The code below defines the mapping request for the registration page. Therefore, defining done by adding @GetMapping annotation and mapping value /registration. And then, after invoking the request the method will return the MVC view, which renders HTML content. The name of the HTML file should be the same as return value as we defined below:

@GetMapping(value = "/registration")
public String registration() {
	return "registration";
}

Later in Web View section we will create HTML file name registration to align with the method return above.

Profile HTTP Request

Another request mapping below is for the profile page. However, the HTTP request is different from the HTTP request if the registration. Therefore, the profile page use @PostMapping to define POST request which consists of parameters for user inputs and model:

@PostMapping(value = "/profile")
public String profile(@ModelAttribute User user, Model model) {
    model.addAttribute("user", user);
    return "profile";
}   

The model parameter is accessible to the HTML content, which later we will see the use of it in the HTML.

Web View

Let’s start the view by creating a CSS file first for the content design. Copy and paste the script below, and create style.css in /src/main/resources/static. And then add a new css folder to place the style.css inside of it:

body {
  margin: 0;
}
* {
  font-family: "Courier New", Courier, monospace;
}
#header {
  border-radius: 0 0 4px 4px;
  box-shadow: 0px 5px #90888888;
  background-color: #f2f5f3;
  margin: 0 auto;
  margin-top: 0;
  margin-bottom: 80px;
  padding: 10px;
  width: 700px;
  height: 80px;  
}
#title{
  letter-spacing: 3px;
  font-size: 35px;
  color: #000000;
  text-align: center;
  margin: 0;
  text-transform: uppercase;
}
#subtitle{
  letter-spacing: 3px;
  font-size: 20px;
  color: #000000;
  text-align: center;
  text-transform: uppercase;
  
}
#footer {
  text-align: center;
  font-size: 20px;
  width: 100%;
  height: 50px; 
  position: absolute;
  bottom: 10px;
}
.active a{
  background-color: #CCC;
  color: white;
}
#body-container {
  background: #f2f5f3;
  margin: 0 auto;
  margin-top: 0;
  padding: 10px;
  width: 700px;
}
#message{
   letter-spacing: 1px;
   text-indent: 50px;
   word-spacing: 4px;
   line-height: 2;
   padding-left: 24px;
   font-size: 20px;
}
#form-container{
  background: #f2f5f3;
  margin: 60px auto;
  padding: 10px;
  width: 700px;
	
}
input{
  width: 90%;
  display: inline-block;
  border: 1px solid #90888888;
  border-radius: 4px;
  box-sizing: border-box;
  padding: 10px 10px;
  margin: 20px 40px;
  font-size: 20px;
  
}
select{
  width: 90%;
  display: inline-block;
  border: 1px solid #90888888;
  border-radius: 4px;
  padding: 10px 10px;
  margin: 20px 40px;
  font-size: 20px;
}
#profile-container{
  background: #f2f5f3;
  margin: 0 auto;
  padding: 10px;
  width: 700px;
  text-align:center;
}
label{
	font-size: 25px;
}
strong{
	font-size: 20px;
}

The static resources folder is the right location for your HTML, CSS, and JavaScript files. Therefore, there will be three HTML contents for our application, including home, registration, and profile pages.

Create a Home Page

As you noticed in the controller section, we didn’t add HTTP requests for the home page yet. However, it is not necessary to add it to your controller since the home page is your front page. Therefore, the Thymeleaf handles the front page request by scanning the index.html file. If the index.html is existing, it will serve as a defualt page of the MVC application. Add index.html and copy and paste the script below:

<!DOCTYPE html>  
<html>  
<head> 
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  	<title>LGeratech.com</title> 
	<link rel="stylesheet" href="/css/style.css">
</head> 
<body> 
    <header id="header"> 
	    <h1 id="title" >Welcome to LGeratech.com!</h1> 
	    <p id="subtitle" >Home page</p> 
    </header> 
	<div id="body-container">
		<p id="message"><a href="/registration">Click Here</a> for Registration</p>
	</div>
    <footer id="footer"> 
		<p>Created on May 2020, by <a href = "http://lgeratech.com/">LGeratech.com</a></p> 
    </footer> 
</body> 
</html> 

Don’t forget to place it inside of a static folder in resources. And additional info, the default request for the front page will be localhost:8080/ or /.

Create a registration page

Now we are going to create an HTML content for /registration request which we already defined in the controller section. The name of the HTML file, should be the same as the return view of the /registration request which is "registration". Therefore, the html will be registration.html and add it inside of folder template which in /src/main/resources/ path. And then copy and paste the HTML script below for registration page:

<!DOCTYPE html>  
<html> 
<head> 
	<title>LGeratech.com</title> 
	<link rel="stylesheet" href="/css/style.css">
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head> 
<body>
	<header id="header"> 
		<h1 id="title">WELCOME TO LGERATECH.COM!</h1>
		<p id="subtitle" >Registration page</p> 
	</header> 
	<div id="body-container">
		<form action="profile" method="post">
			<input type="text" name="name" placeholder="Enter Name">
			<input type="number" name="age" placeholder="Enter your Age">
			<select name="gender">
				<option value="Male">Male</option>
				<option value="Female">Female</option>
			</select><br><br>
			<input type="submit" value="Submit">
		</form> 
	</div>
	<footer id="footer"> 
		<p>Created on May 2020, by <a href = "http://lgeratech.com/">LGeratech.com</a></p> 
	</footer> 
</body> 
</html> 

Create a profile page

For the final page, which is for the profile page, we will do the same procedure as the registration page. Create profile.html and place it inside of template folder, and then copy and paste the HTML script below:

<!DOCTYPE html>  
<html xmlns:th="http://www.thymeleaf.org">   
<head> 
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title>LGeratech.com</title> 
	<link rel="stylesheet" href="/css/style.css">
</head> 
<body> 
	<header id="header"> 
		<h1 id="title">WELCOME TO LGERATECH.COM!</h1> 
		<p id="subtitle" >Profile page</p> 
	</header> 
	<div id="profile-container">
		<br><img src="http://lgeratech.com/cropped-lionlogi4-png" alt="face" height="130" width="150"><br><br>
		<label>Name: </label><strong th:text="${user.name}"></strong><br>
		<label>Age: </label><strong th:text="${user.age}"></strong><br>
		<label>Gender: </label><strong th:text="${user.gender}"></strong><br>
	</div>
	<footer id="footer"> 
		<p>Created on May 2020, by <a href = "http://lgeratech.com/">LGeratech.com</a></p> 
	</footer> 
</body> 
</html> 

With the help of this xmlns:th="http://www.thymeleaf.org" extension, we are now enable to use a parser of Thymeleaf themplate in HTML contents. Therefore, profile.html evaluates the th:text property to parse ${user.name} that set in controller using the model property model.addAttribute("user", user);.

Source Structure

Additionally, make sure that the packages have the same name as the parent package. For example, com.lgeratech.demo and the child packages are com.lgeratech.demo.controllers and com.lgeratech.demo.models. Therefore. spring framework will able to scan all of the annotated components or class, including the class with @Controller, @Configuration, and more. However, if the packages have different names the spring will get an error because it doesn’t find the classes since they have different package names. But we can fix that issue by enforcing the spring to scan those components, by using @ComponentScan. And then defining the packages with a different name.

Launch the application

If you know how to execute the application please skip this section.

You can now launch the application, using your eclipse, STS or using Cmd, in eclipse click the green icon , then look for the WebMVCApplication, and then right click and click the (Re)start . In Cmd go to your project location then run this script ./mvnw spring-boot:run.

Test the Application

Now when the web application is running, we can now visit the home page using the default URL http://localhost:8080/. And then click Click Here link on the home page to navigate on the registration page. After that, you can now fill up all fields and then click submit to navigate in the final page which profile page.

Conclusion

Congratulation you have done building your application usinng Spring MVC framework. For the next tutorial we will learn more about Spring RESTful which is for HTTP request that we defined in MVC controller section.

You can use the URL to clone the project source code: https://github.com/LeoBernabe/WebMVCApplication1.0.git

Leave a Reply

Your email address will not be published. Required fields are marked *.

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.

BCF Theme By aThemeArt - Proudly powered by WordPress.
BACK TO TOP