Book Image

SPRING COOKBOOK

By : Jerome Jaglale, Yilmaz
Book Image

SPRING COOKBOOK

By: Jerome Jaglale, Yilmaz

Overview of this book

This book is for you if you have some experience with Java and web development (not necessarily in Java) and want to become proficient quickly with Spring.
Table of Contents (14 chapters)
13
Index

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…

  1. In the controller, add a @ModelAttribute method returning a Map object that contains the select field 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;
    }
  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:select element initialized with the @ModelAttribute Map:

    <form:select path="country" items="${countries}" />
  4. In the controller that processes the form submission, make sure that the @ModelAttribute object (the one...