In the previous tutorial, you learned about the components of a controller in Spring MVC, in this tutorial, we will learn together how to define a controller in Spring MVC.
Continue with the project which I created in the previous tutorial, as you can see, a class defined with the @Controller annotation will be considered a controller in Spring MVC. The object of this class is used to process requests to a certain page defined in this class.
The example of the HomeController class in our project has been defined with the @Controller annotation.
1 2 3 4 5 6 7 8 |
package com.huongdanjava.springmvc; import org.springframework.stereotype.Controller; @Controller public class HomeController { ... } |
The name of this class you can put whatever name does not matter, it is important to have the @Controller annotation declared at the beginning of the class definition.
For example, here we rename the class to ExampleController:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
package com.huongdanjava.springmvc; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Handles requests for the application home page. */ @Controller public class ExampleController { private static final Logger logger = LoggerFactory.getLogger(ExampleController.class); /** * Simply selects the home view to render by returning its name. */ @RequestMapping(value = "/", method = RequestMethod.GET) public String home(Locale locale, Model model) { logger.info("Welcome home! The client locale is {}.", locale); Date date = new Date(); DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); String formattedDate = dateFormat.format(date); model.addAttribute("serverTime", formattedDate); return "home"; } } |
when running, the result is the same.