Use of @Controller Annotation

Controller are like servlets which are mapped to one or more URI. Whenever any HTTP request comes it is handled by the Controller Class. The controller classes in spring MVC are usually annotated with @Controller annotation .

@Controller is a specialization of @Component and is auto-detected through classpath scanning. The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API.

It is typically used in combination with annotated handler methods based on the @RequestMapping annotation. @RestController is a sibling convenience annotation for creating Restful controllers.

Lets understand the use of @Controller using an example :

  • First create a simple spring boot project. Check this article here
  • Add a web dependency in the pom.xml
  • Create a new package, name it "controller". Project Structure looks like this :
    Fig : Project Structure
  • Inside the controller package, create a new class WelcomeController and put the below code in it :
  •     import org.springframework.stereotype.Controller;
        import org.springframework.web.bind.annotation.RequestMapping;
        public class WelcomeController 
            public String greeting() {
                return "Welcome from TutorialBox";
  • Now, lets run it.
  • Open the browser, in search bar, search localhost:9001/welcome
  • You will see following result.
Fig : Output