Book Image

SPRING COOKBOOK

Book Image

SPRING COOKBOOK

Overview of this book

Table of Contents (19 chapters)
Spring Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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…

  1. In the controller, add a @ModelAttribute method returning a Map 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;
    }
  2. 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 the Map keys:

    String[] defaultLanguages = {"en", "fr"};
    user.setLanguages(defaultLanguages);
  3. 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...