Build a Spring Boot MVC Application in Under 10 Minutes

Previous Lesson: Spring Boot Hello World Example in Eclipse - Build a Spring Boot Application in Under 5 Minutes

Prerequisites

  1. Have Eclipse installed
  2. Have a basic knowledge of Java, How Classes Work, How HTTP Requests Work
  3. Recommended: Have Spring Tool Suite Installed

What is Model View Controller (MVC)?

MVC is a design pattern in which the code is separated into three categories:


View

It's intuitive why we would need something that dictates how elements appear on a page. That's what the view does. It takes in data to be displayed from the controller, and then it arranges that data on the page. The view is some sort of file that ultimately produces HTML. It could be a .jsp file, a .cshtml file (in ASP.NET), an HTML file (e.g. with Thymeleaf) itself.

Controller

A controller is the piece of code (a class if we're talking Java) that looks for a particular HTTP request (either an exact URL or some sort of URL pattern), executes logic, and then sends the output to a specific view.

Model

A model is a data structure (e.g. a class) that holds data and executes logic. It can be used to persist data in a database, and in Spring MVC it can be passed along to the view to provide it data.

But where is "Business Logic" executed?

Simplistic explanations might say that business logic is only executed in the model. But logic happens in both the model AND the controller. The logic in the model should be limited to things that only apply to the model itself, e.g. for a webpage model, "a valid URL contains period," or a user model, "a valid userid must be greater than 0" or a rectangle model, "the area of this rectangle is length times width." Any logic that is application specific, or combines multiple models, should be placed in the controller, e.g. "calculate the amount of space left after filling a large rectangle with several smaller rectangles and several circles"

Let's get started making a Spring MVC App!

Navigate to the Spring Initializr page, and fill out the form as shown, then click Generate to generate the maven Spring Boot project.

Side Note: An alternative to the Spring Initializr is using the STS plugin to generate a project, as described in my previous Spring Boot Hello World tutorial.

In Eclipse, select file -> Import... Project.
Select Existing Maven Projects.
Select the folder mvcdemo.
The pom file is automatically found. Select finish. The project is now imported.

Add a Controller

Now, let's add a class. Create a class in the existing package. Name it MainController. Add the below code.


package com.example.mvcdemo;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class MainController {

	@GetMapping("/sendmedata")
	public String passDataThrough(@RequestParam(name="var", required=false, defaultValue="hello mvc") String var, Model model) {
		model.addAttribute("var", var);
		return "hellomvc";
	}

} 

Like in my previous tutorial, we have a @GetMapping annotation that tells the controller to look for a URL ending in /sendmedata. However, unlike the previous tutorial, we aren't simply sending literal text back to the client. With the Thymeleaf dependency in pom.xml, SpringBoot smartly assumes the string we return here is an Thymeleaf HTML file's name. This is an example of where SpringBoot is considered an "opinionated" framework. Because Thymeleaf is included as a dependency, it automatically assumes you want to return a Thymeleaf template file name. If you remove Thymeleaf as a dependency and run this, you'll get a "circular view path" error.

Side Note: You could specify a different file type by providing an extension. For example, if you wanted to use a jsp file, you could add the tomcat-jasper dependency to your pom.xml, and then you could return "hellomvc.jsp". Spring Boot would then look for a jsp file with this name to render. I do not recommend trying to combine jsp and Thymeleaf templates in a single project, as it's best to stay consistent. If you are just starting out, Thymeleaf is the better choice over jsp, because you can easily preview Thymeleaf files.

Also take note of the model object here. At this time we are only using it to pass data to the view. By providing the model as an argument, Spring Boot magically takes care of making the model available to the view here.

Finally, we are taking another argument with the @RequestParam annotation. This tells Spring Boot we are looking for an input in the URL, with the name "var", with the format /sendmedata?var=x, where x can be anythign we want to send. When we attempt to access this URL, the value of x will be inserted into the variable var and passed as an input argument to this method. We specify that it is not required, and if it is not provided, the value "hello mvc" will be passed into this method.

Create The View

Add a folder called templates under src/main/resources, and in this folder create a file called hellomvc.html. Add the below code:

<head>
<title>Spring MVC Output
</title>
</head>
<body>
<h1>Spring MVC Output
</h1>
<p th:text="'You provided the input: ' + ${var} + '!'" />
</body>
</html>


Here we can see the variable we specified previously with "var" in model.addAttribute("var", var); is available to us by using a special notation.

In source/main/resources, you should see a file called application.properties. We're going to add one property to it that will make your development easier. Simply add:

server.port=82

This is an arbitrary port number that will ensure our app does not use any ports that are already in use.

To test the app, enter this into your browser URL bar localhost:82/sendmedata?var=sup.

You should see this:


Troubleshooting


Seeing the above? Follow these steps.