Spring Annotations Tutorial

DZone 's Guide to

Spring Annotations Tutorial

· ·
Free Resource

In this example you will see how to populate a form using Spring annotations. The annotated user controller class is shown below.

package com.vaannila.web;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.vaannila.domain.Community;
import com.vaannila.domain.Country;
import com.vaannila.domain.User;
import com.vaannila.service.UserService;

public class UserController {

	private UserService userService;

	public void setUserService(UserService userService) {
		this.userService = userService;
	public List<Country> populateCountryList() {
		return userService.getAllCountries();
	public List<Community> populateCommunityList() {
		return userService.getAllCommunities();
	@RequestMapping(method = RequestMethod.GET)
	public String showUserForm(ModelMap model) {
		User user = new User();
		model.addAttribute("user", user);
		return "userForm";

	@RequestMapping(method = RequestMethod.POST)
	public String onSubmit(@ModelAttribute("user") User user) {
		return "redirect:userSuccess.htm";

The populateCountryList() and populateCommunityList() methods are used to populate the country and community list respectively. The @ModelAttribute annotation when used at the method level is used to indicate that the method contain reference data used by the model, so it should be called before the form is loaded. This is similar to overriding the referenceData() method when extending the SimpleFormController.

You can also do this in the showUserForm() method like this.

@RequestMapping(method = RequestMethod.GET)
public String showUserForm(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    return "userForm";

Since we use ModelMap here by default the names of the list will be countryList and communityList.

You can download and try the example here.

Source :Download
War :Download

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}