What You'll Learn

All we're going to do in this tutorial is add the ability to show dynamic content.

We're going to add our first Spring Boot component (otherwise known as a Spring Bean). It will be a Controller bean. It is known as a Controller because it fulfils the role of the Controller in the Model-View-Controller (MVC) pattern that Spring implements with its Spring MVC project.

Create a new package in the main/java tree. Let the package structure guide you.

package uk.ac.cf.cs.cm6213.tutorialcompanion.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {

    @GetMapping({"/", "index"})
    public String home() {
        return "index.html";
    }
}

Move the index.html file into templates

Move the index.html file from static to templates.

To test this, run gradle > build > classes again and then go to http://localhost:8080/.

This simple change (that has no real impact to the application) has introduced some key elements of the Spring framework.

The @Controller annotation

The class is annotated with @Controller. This tells Spring that this class should be treated as a Spring component or bean. Spring will register this fact within its application context (think of that has a look-up table for components amongst other things).

Since it is a controller, Spring will know that this component may contain methods that can handle web requests. In order to know how to route which web request to which method, we need to annotate the method. This is the purpose of the @GetMapping annotation. In our example, we are saying that any HTTP GET request to either the "/" address or the "/index" address of our server should be handled by the home() method.

Spring handles the initial request and parses it to determine the URL (and other parts of the request) and the delegates responsibility to the relevant controller method. This is an example of the "Hollywood Principle" that can be used to describe the difference between a framework and a library. Here, Spring (the framework) is calling our code (the controller method).

The controller method home() does nothing more than return the Java String "index.html". Since Spring called us, we return that value to Spring and Spring uses it to identify the view (or template) that should be used to return the HTML response.

This is why we moved the index.html file into the /templates folder as that is where (by convention) Spring Boot will look for the specified template. In MVC terms, the Controller has identified the View.

We will introduce some real dynamic content shortly.

In this tutorial, we've introduced the notion of dynamic content, even if it doesn't look like it. We now have the foundations to deliver dynamic content and have introduced two parts of the MVC pattern.