Key Aspects of @Controller
Purpose of
@Controller:- The
@Controllerannotation 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.
- The
Handling HTTP Requests:
- Methods within the class marked with
@Controllercan 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/homeURL.
- Methods within the class marked with
Returning Views:
- Typically, a
@Controllermethod 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 filehome.htmlorhome.jspbased on the configured view resolver.
- Typically, a
Model Binding:
@Controllermethods can receiveModelorModelAndViewobjects 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.
Example of a
@ControllerClass:
@Controller: This annotation tells Spring Boot that this class,MainController, will handle web requests.@GetMapping("/home"): This annotation means that the methodHomePage()will respond to the URL/home. So, if you go tohttp://localhost:8080/home, this method will execute.public String HomePage(): This is the method that gets called when someone visits the/homeURL. It returns a string, which is the name of the HTML file to display.return "HomePage.html";: This tells Spring Boot to render theHomePage.htmlfile. Make sure this file is saved in thesrc/main/resources/templatesfolder so Spring can find it.
In summary, this controller maps the URL /home to display the HomePage.html file.


Comments
Post a Comment