@Controller in Spring Boot Example

In this tutorial, we show you how to use @Controller annotation in the Spring boot application.

@Controller Annotation

  1. Spring provides @Controller annotation to make a Java class as a Spring MVC controller. The @Controller annotation indicates that a particular class serves the role of a controller.
  2. The controller in Spring MVC web application is a component that handles incoming HTTP requests.
  3. @Controller annotation is simply a specialization of the @Component class, which allows us to auto-detect implementation classes through the classpath scanning.
  4. We typically use @Controller in combination with a @RequestMapping annotation for request handling methods.

@Controller Annotation Example

1. Create Spring MVC Controller

Create DemoController and add the following content to it:

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

@Controller
public class DemoController {

    @RequestMapping("/hello")
    public String demo(Model model){
        model.addAttribute("message", "hello world!");
        return "hello";
    }
}

Spring provides @Controller annotation to make a Java class as a Spring MVC controller. The @Controller annotation indicates that a particular class serves the role of a controller.

2. Create Thymeleaf View

Create hello.html with the following content:

<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
>
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
    <h1 th:text="${message}"></h1>
</body>
</html>3

Comments