244 CHAPTER 5: Building Java Web Applications with Spring Web MVC
- 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";
- }
- }
Line 17: The @Controller annotation is used to specify that this class is a Spring
controller. DispatcherServlet scans such annotated classes for mapped handler
methods by means of @RequestMapping annotations.
Line 25: The @RequestMapping annotation specifies that the home() method will
handle a GET request with the URL / (the default page of the application).
Line 26 to 37: The home() method creates a String object to hold the current
date based on the current locale and adds this object to the model with the
name serverTme. And finally the method returns a view named home, which will
be resolved by the view resolver specified in the servlet-context.xml file, to
find the actual view file. In one controller class, we can write many methods to
handle different URLs.
@Controller and @RequestMapping and a number of other annotations form the basis for the Spring
MVC implementation. To define a controller class in Spring 3.0 and newer, you have to mark the
class with the @Controller annotation. When an @Controller-annotated class receives a request,
it looks for an appropriate handler method to handle the request. Each method to which the request
is to be mapped is decorated with the @RequestMapping annotation, making the method a handler
method to which the request is mapped by means of handler mappings.
As you saw in Listing 5-38, the home() method in HomeController returns a view named home, which
is resolved by the view resolver specified in servlet-context.xml. Now it is time to look at the view,
which is the home.jsp file generated in the /WEB-INF/views directory. Listing 5-39 illustrates home.jsp.
Listing 5-39. home.jsp of the Hello World Application
- <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
- <%@ page session="false" %>
Home
- Hello world!