Key Aspects of @Controller
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.
- The
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.
- Methods within the class marked with
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 filehome.html
orhome.jsp
based on the configured view resolver.
- Typically, a
Model Binding:
@Controller
methods can receiveModel
orModelAndView
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.
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 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/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 theHomePage.html
file. Make sure this file is saved in thesrc/main/resources/templates
folder so Spring can find it.
In summary, this controller maps the URL /home
to display the HomePage.html
file.
Comments
Post a Comment