Meyyappan has posted 101 posts at DZone. View Full User Profile

Spring Annotations Tutorial

06.15.2012
| 72767 views |
  • submit to reddit

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;

@Controller
@RequestMapping("/userRegistration.htm")
@SessionAttributes("user")
public class UserController {

	private UserService userService;

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	@ModelAttribute("countryList")
	public List<Country> populateCountryList() {
		return userService.getAllCountries();
	}
	
	@ModelAttribute("communityList")
	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) {
		userService.add(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(userService.getAllCountries());
    model.addAttribute(userService.getAllCommunities());
    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
Published at DZone with permission of its author, Meyyappan Muthuraman.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags: