Using a list of radio buttons

In this recipe, you'll learn how to display a list of radio buttons. When the form is submitted, retrieve the selected value in a controller method.

How to do it…

  1. In the controller, add a @ModelAttribute method returning Map object:
    @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;
    }
  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 one of the Map keys:
    user.setCountry("ca");
  3. In the JSP, use a form:radiobuttons element initialized ...

Get Spring Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.