In this tutorial, we show you how to use @Controller annotation in the Spring boot application.
@Controller Annotation
- 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.
- The controller in Spring MVC web application is a component that handles incoming HTTP requests.
- @Controller annotation is simply a specialization of the @Component class, which allows us to auto-detect implementation classes through the classpath scanning.
- 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
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course