Using a select field
In this recipe, you will learn how to display a select field. When the form is submitted, retrieve the selected value in a controller method.
How to do it…
In the controller, add a
@ModelAttributemethod returning aMapobject that contains theselectfield options:@ModelAttribute("countries") public Map<String, String>countries() { Map<String, String> m = new HashMap<String, String>(); m.put("us", "United States"); m.put("ca", "Canada"); m.put("fr", "France"); m.put("de", "Germany"); return m; }If a default value is necessary, use a
Stringattribute of the default object (refer to the Setting a form's default values using a model object recipe) initialized with one of theMapkeys:user.setCountry("ca");In the JSP, use a
form:selectelement initialized with the@ModelAttributeMap:<form:select path="country" items="${countries}" />In the controller that processes the form submission, make sure that the
@ModelAttributeobject (the one...