- Get Started Using Spring MVC for Your Java EE Applications
- DispatcherServlet
- Home Controller / Home View
Home Controller
Controller classes in Spring are used to prepare the model that will be mapped to a view for a particular resource. In this example, Spring created the following Home Controller that will be used to return the default view for our application:
@Controller public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.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.toString()); 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 the user doesn't specify a resource by using a request mapping with just a slash, this controller returns the home view. Inside the home class, the time for the server the app is hosted on is returned to the view through a model attribute. Another nice thing about Spring is that there are no Model classes. Spring assumes the name of your controller class will be the same as your Model class. This forces you to keep the business logic in the controllers and out of the model. The Home View will display the model attribute for server time to the user.
Home View
For every Controller class, there is a corresponding view that renders the model attributes to the user. Spring created this basic Home view for our example:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <%@ page session="false" %> <html> <head> <title>Home</title> </head> <body> <h1> Hello world! </h1> <P> The time on the server is ${serverTime}. </P> </body> </html>
As you can see, the model attribute for server time is displayed to the user.
Conclusion
There are other types of controllers (i.e., multi-action, command) you can use with Spring, but this example is only meant to get you familiar with a basic Spring MVC application. From here, you can experiment by adding other controllers and views. Once familiar with using multiple controllers, models, and views, you can then move on to implementing other types of controllers.
In a later article, I'd like to show you how to integrate Spring with Hibernate (a Java Persistence technology).