Using a list of checkboxes
In this recipe, you'll learn how to display a list of checkboxes and when the form is submitted, how to retrieve the selected values in a controller method.
How to do it…
In the controller, add a
@ModelAttribute
method returning aMap
object:@ModelAttribute("languages") public Map<String, String>languages() { Map<String, String> m = new HashMap<String, String>(); m.put("en", "English"); m.put("fr", "French"); m.put("de", "German"); m.put("it", "Italian"); return m; }
If a default value is necessary, use a
String[]
attribute of the default object (refer to the Setting a form's default values using a model object recipe) initialized with some of theMap
keys:String[] defaultLanguages = {"en", "fr"}; user.setLanguages(defaultLanguages);
In the JSP, use a
form:checkboxes
element initialized with the@ModelAttribute
Map:<form:checkboxes items="${
languages
}" path="languages" />
In the controller that processes the form submission, make...