lishman levelup
«previous  next»

Getting Started
Form Processing
IoC Container
Hibernate ORM

The Spring MVC Controller

A controller receives web requests from the user, performs some business logic, and populates the model with JavaBean components for the view to present.
public class CountryController {

  private WorldService worldService = new MockWorldService();

  public Collection<Country> getCountries() {
    return worldService.getAllCountries();

  public Country getCountry(@RequestParam(value="id", required=true) int countryId) {
    return worldService.getCountryById(countryId);


Info @Controller is a specialization of @Component. The other types of @Component are @Service and @Repository, both of which are covered later in this tutorial.
The @Controller annotation designates an arbitrary (POJO) class as a web controller. Spring can automatically detect controller classes using class path scanning, and make them available to receive requests from end users.


The @RequestMapping annotation maps web requests to Java classes and methods. The above example maps the URL paths /countryList.html and /countryDetails.html to the getCountries() and getCountry() methods respectively. We see later how Spring implements the front controller pattern to dispatch web requests to the appropriate handler.


The @ModelAttribute annotation binds the return value of a method to a named attribute in the model. The getCountries() method returns a collection of Country JavaBeans, and the @ModelAttribute annotation binds it to an attribute called countries, for subsequent retrieval by the view.

The getCountry() method also returns a Country object into the model, but this time no @ModelAttribute annotation is specified. In this case, Spring uses the non-qualified class name, country, as the attribute name.

Tip - for consistency and clarity, we could include @ModelAttribute("country") on the getCountry() method, but this is purely a matter of choice.


The @RequestParam annotation binds HTTP request parameters to method arguments in the controller.

In our example, the getCountry() method needs to know the identifier of the country that it is to be returned. The @RequestParam annotation takes the 'id' request parameter from the URL, and maps it to the countryId parameter of the method. The parameter is mandatory so the URL must look like this /countryDetails.html?id=53, or an exception will be thrown.