Simple Form Controller - Multiple Drop Down List

In this section, we will see how to populate a drop down list based on item selection in previous drop down list box using Spring Simple Form Controller.

For example, consider that there are two drop down lists "Countries" and "States".

Based on the country selected in "Countries" drop down list, the "States" drop down list should be populated with that country's respective states.

Create a Registration controller as follows

RegistrationController class

/**
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package in.techdive.spring.examples;

import java.net.BindException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RegistrationController extends SimpleFormController
{
    private ModelMap modelMap = new ModelMap();

    public RegistrationController()
    {
        setCommandClass(User.class);
        setCommandName("user");
    }

    protected Map referenceData(HttpServletRequest request) throws Exception
    {
        List countries = new ArrayList();
        countries.add("INDIA");
        countries.add("US");
        countries.add("AUSTRALIA");

        HttpSession session = request.getSession();
        session.setAttribute("listCountries", countries);

        System.out.println("In referenceData Registration...");
        return modelMap;
    }

    protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception
    {
        User user = (User)command;

        List listIndiaStates = new ArrayList();
        listIndiaStates.add("Andhra Pradesh");
        listIndiaStates.add("Bihar");
        listIndiaStates.add("Maharashtra");
        listIndiaStates.add("Karnataka");
        listIndiaStates.add("Tamil Nadu");
        listIndiaStates.add("West Bengal");

        List listUSStates = new ArrayList();
        listUSStates.add("Arizona");
        listUSStates.add("California");
        listUSStates.add("Massachusetts");
        listUSStates.add("New Jersey");
        listUSStates.add("New York");
        listUSStates.add("Washington");

        List listAUSStates = new ArrayList();
        listAUSStates.add("New South Wales");
        listAUSStates.add("QueensLand");
        listAUSStates.add("Victoria");
        listAUSStates.add("Northern Territory");

        Map> stateCountryMap = new HashMap>();
        stateCountryMap.put("INDIA", listIndiaStates);
        stateCountryMap.put("US", listUSStates);
        stateCountryMap.put("AUSTRALIA", listAUSStates);

        List listStates = new ArrayList();
        System.out.println(user.getCountry());
        if(user.getCountry()!=null)
        {
            listStates = stateCountryMap.get(user.getCountry());
            System.out.println(listStates);
        }

        request.setAttribute("listStates", listStates);
        ModelAndView mv = new ModelAndView("/register","user",user);
        return mv;
    }
}

The referenceData(HttpServletRequest) method is similar to the previous example, except that here we have used HttpSession instead of HttpRequest object to store the drop down list values. This is because we need the "Countries" list to be available between subsequent requests.

Consider how the onSubmit(...) method is implemented. Initially we create lists of states for all the available countries. Based on the selection from the form we fill up the states list with the respective states for that country and return the response.

Instead of adding the lists every time in OnSubmit(..) method, we can also do the same in referenceData(...) method and add the lists to session. That optimization part is left as homework for user... :)

The following is the register.jsp file with list of fields along with the Countries and States drop down list. It uses the Spring tag library tag to display the list.

Register.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>User Registration</title>
</head>

<script language="javascript">
function submitForm()
{
    document.registerForm.submit();
}
</script>

<body>
<form:form method="POST" commandName="user" name="registerForm">
    <table>
    <tr>
        <td>First Name :</td>
        <td><form:input path="firstName" ></form:input></td>
    </tr>
    <tr>
        <td>Last Name :</td>
        <td><form:input path="lastName" ></form:input></td>
    </tr>
    <tr>
        <td>User Name :</td>
        <td><form:input path="userName" ></form:input></td>
    </tr>
    <tr>
        <td>Password :</td>
        <td><form:password path="passWord" /></td>
    </tr>
    <tr>
        <td>Country :</td>
        <td>
            <form:select path="country" onchange="submitForm()">
                <form:option value="0" >Select </form:option>
                <form:options items="${listCountries}" />
            </form:select>
        </td>
    </tr>
    <tr>
        <td>State :</td>
        <td>
            <form:select path="state">
                <form:option value="0" >Select </form:option>
                <form:options items="${listStates}" />
            </form:select>
        </td>
    </tr>
    <tr>
        <td>email :</td>
        <td><form:input path="email" /></td>
    </tr>
    <tr>
        <td colspan="2"><input type="submit"></td>
    </tr>
</table>
</form:form>
</body>
</html>

The Spring configuration file is same as the one shown in previous article.

Technology: 

Search