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
@ModelAttributemethod returning aMapobject:@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 theMapkeys:String[] defaultLanguages = {"en", "fr"}; user.setLanguages(defaultLanguages);In the JSP, use a
form:checkboxeselement initialized with the@ModelAttributeMap:<form:checkboxes items="${languages}" path="languages" />
In the controller that processes the form submission, make...