Spring @Controller Annotation Examples
- Details
- Written by Nam Ha Minh
- Last Updated on 28 October 2023   |   Print Email
You know, @Controller is a very popular annotation in Spring framework. In this post, I’d love to share what it is and when it is used with some code examples.
Basically, we use the @Controller annotation to indicate the role of the annotated class is a web controller that is responsible for handing requests from clients. It is usually used in combination with the handler methods annotated by the @RequestMapping annotation. Below is a very typical example:
package net.codejava; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class MainController { @RequestMapping("") public String viewHomePage() { return "index"; } }
In this example, the role of the MainController class is a web controller and it has one handler method viewHomePage() that handles requests with empty path (context root). In other words, it serves requests to the homepage of the application.
This annotation can be used only at class level, and it is a specialization of the @Component annotation. That means technically you can have a component that acts as a controller like this:
@Component public class MainController { @RequestMapping("") public String viewHomePage() { return "index"; } }
However, it’s strongly recommended to use the @Controller annotation to specify the exact role of the class, semantically.
And this annotation has only one optional parameter of type String, that specifies the logical component name explicitly. For example:
@Controller("primaryController") public class MainController { @RequestMapping("") public String viewHomePage() { return "index"; } }
In a Spring MVC application, there can be multiple controller classes with each annotated by the @Controller annotation.
Above I have shared with you some examples of using the @Controller annotation in Spring framework. I hope you find this post helpful. You can also watch the video below to see the coding in action:
Reference:
Annotation Interface Controller (Spring Docs)
Other Spring Annotations:
- Spring @Service Annotation Examples
- Spring @Component Annotation Examples
- Spring @Repository Annotation Examples
- Spring @Configuration Annotation Examples
- Spring @RestController Annotation Examples
Comments