Example 1. PersonController
The @Controller
indicates the class is a Spring MVC controller stereotype which is automatically registered
by context:component-scan. This controller handles multiple request mappings by specifying one above each method that should handle
the request. The Person
class specified in the save method's signature has any values that can be set on it automatically bound.
The info and delete methods both have a signature of @RequestParam("id") Integer id
which indicats the request parameter id should be bound to the id variable.
The create method returns the Person
instance. It will automatically be put into the model based on the class name (ex: Person --> 'person').
@Controller public class PersonController { final Logger logger = LoggerFactory.getLogger(PersonController.class); private static final String FORM_VIEW_KEY = "/form/person"; private static final String SEARCH_VIEW_KEY = "/search/person"; private static final String FORM_MODEL_KEY = "person"; private static final String SEARCH_MODEL_KEY = "persons"; @Autowired protected PersonDao personDao = null; /** * Creates a person object and forwards to person form. */ @RequestMapping(value="/form/person.html") public Person create() { return new Person(); } /** * Gets a person based on it's id. */ @RequestMapping(value="/info/person.html") public ModelAndView info(@RequestParam("id") Integer id) { Person result = personDao.findPersonById(id); return new ModelAndView(FORM_VIEW_KEY, FORM_MODEL_KEY, result); } /** * Saves a person. */ @RequestMapping(value="/save/person.html") public ModelAndView save(Person person) { personDao.save(person); return new ModelAndView(FORM_VIEW_KEY, FORM_MODEL_KEY, person); } /** * Deletes a person. */ @RequestMapping(value="/delete/person.html") public ModelAndView delete(@RequestParam("id") Integer id) { Person person = new Person(); person.setId(id); personDao.delete(person); return new ModelAndView(SEARCH_VIEW_KEY, search()); } /** * Searches for all persons and returns them in a * <code>Collection</code> as 'persons' in the * <code>ModelMap</code>. */ @RequestMapping(value="/search/person.html") public ModelMap search() { Collection<Person> lResults = personDao.findPersons(); return new ModelMap(SEARCH_MODEL_KEY, lResults); } }