@Controller

 

Key Aspects of @Controller

  1. Purpose of @Controller:

    • The @Controller annotation indicates that a particular class serves the role of a controller in the Spring MVC pattern. When this annotation is used, Spring automatically detects it through classpath scanning and registers it as a bean, enabling it to handle web requests.
  2. Handling HTTP Requests:

    • Methods within the class marked with @Controller can use mapping annotations, such as @GetMapping, @PostMapping, @RequestMapping, etc., to map specific HTTP request paths to those methods. For example, a method annotated with @GetMapping("/home") will handle GET requests to the /home URL.
  3. Returning Views:

    • Typically, a @Controller method returns a view name (the name of an HTML or JSP file, often processed by Thymeleaf or another view resolver) to be rendered as part of the HTTP response.
    • For example, if the method returns "home", Spring will resolve this to the file home.html or home.jsp based on the configured view resolver.
  4. Model Binding:

    • @Controller methods can receive Model or ModelAndView objects as parameters. This allows you to add data to the model, which is then passed to the view layer. The view can use this model data to dynamically display information.
  5. Example of a @Controller Class:


  • @Controller: This annotation tells Spring Boot that this class, MainController, will handle web requests.

  • @GetMapping("/home"): This annotation means that the method HomePage() will respond to the URL /home. So, if you go to http://localhost:8080/home, this method will execute.

  • public String HomePage(): This is the method that gets called when someone visits the /home URL. It returns a string, which is the name of the HTML file to display.

  • return "HomePage.html";: This tells Spring Boot to render the HomePage.html file. Make sure this file is saved in the src/main/resources/templates folder so Spring can find it.

In summary, this controller maps the URL /home to display the HomePage.html file.


Comments