Controller
Learn how to create a controller class in a Spring MVC application.
Controllers are Java classes that map a URL and HTTP request to a method such that when a user goes to an address and sends a request, the controller sends back the appropriate response. Every controller is annotated with information about the URL that it handles and the HTTP methods that it supports.
A typical web application has a number of controllers, so when a request comes, Spring MVC examines the list of controllers to find a match for the URL and the incoming HTTP request. It then maps the request to a particular method of a controller. The controller returns a response which Spring MVC converts to an appropriate format. For a REST controller, the response is automatically converted to JSON.
We will now show how to create a controller for our application. The TennisPlayerController
will handle a web request and display a response in the browser.
@Controller
annotation
Create a class, TennisPlayerController
in the io.datajek.springmvc.tennisplayerweb
package. In Spring MVC, we use the @Controller
annotation to notify that the class is a controller. @Controller
is a specialized form of @Component
that supports web MVC. So, when Spring does a component scan, it also picks up classes marked with @Controller
. By using this annotation, Spring will know that our class will handle web requests.
Level up your interview prep. Join Educative to access 80+ hands-on prep courses.