In this tutorial, you will learn what the @Controller annotation is and how to use it in Spring.
You will use @Controller annotation to mark a class as a Spring MVC controller. It is generally used with @RequestMapping annotation to map HTTP requests to specific methods in a controller class.
How to User @Controller Annotation
To use @Controller annotation in Spring Boot, follow the below steps:
Step 1: Annotate Java class with @Controller Annotation
The first step is to create a Java class and annotate it with @Controller annotation.
@Controller public class MyWelcomeController { }
Step 2: Add Request Mapping Methods
The next step is to define methods in the controller class and annotate them with @RequestMapping annotation. @RequestMapping annotation maps HTTP requests to specific methods in the controller class.
For example, in the below code example, the @GetMapping annotation will map HTTP GET request to a Java method it uses.
@RequestMapping("/welcome") public String welcome() { return "welcome"; }
The above Java method will be triggered if the user sends HTTP GET request to a /welcome URL path.
Step 3: Create a View File
In the above code example, the welcome() method returns a string value “welcome”. This means that we need to create a view file called welcome.jsp. If your project is not configured to support JSP, you can read the following tutorial: Configure JSP Support in Spring MVC Application.
<html> <head><title>Welcome Page</title></head> <body> <h1>Welcome</h2> </body> </html>
Step 5: Run Your Application
Now, you can run the Spring Boot application and access the URL corresponding to the @RequestMapping value (e.g. http://localhost:8080/welcome). This will trigger the corresponding method in the controller class and render the view file. In our case, it will trigger the welcome() method defined in the MyWelcomeController class.
Conclusion
@Controller annotation is a useful tool in Spring Boot for creating MVC controllers and handling HTTP requests. It allows developers to easily map specific methods in a controller class to specific HTTP requests, making it easy to develop web applications with Spring Boot.
To learn more, check out the Spring Web MVC tutorials page.