In this tutorial you will learn two different ways to populate a dropdown box using Struts HTML select tags.
In this example we will see two different methods to populate a dropdown box in the jsp page. We use HTML select tag to do this. The dropdown values are stored in two ArrayList namely countryList and stateList. We use HTML optionsCollection tag to display the values present in the ArrayList.
In order to use the Struts HTML Tags you need to include the following taglib directive in the jsp page.
The CountryData class is used to hold the details regarding the country. The CountryData class has countryId and countryName as attributes and the corresponding getter and setter methods. In the jsp page we use the following code to display the country list.
Here we need to display the countryName as the label and the countryId as the corresponding value. We do this using the label and the value attribute of the HTML optionsCollection tag.
The property attribute of the HTML optionsCollection tag holds the ArrayList.
The property attribute of the HTML select tag hold the country value selected by the user.
The input form contains the following attributes.
// holds the country selected by the user
private String country;
// holds the state selected by the user.
private String state;
// holds the list of countries to be displayed.
private ArrayList countryList;
// holds the list of state to be displayed.
private ArrayList stateList;
Here we use DispatchAction. One method is used to populate the values and the other method is used to save the selected values. Inside the populate method we populate the values for countryList and the stateList. The following code is used to add a list of countries to the countryList.
We add CountryData object inside the countryList. Creating a seperate class like this and adding it to ArrayList will be helpful if we have a few more attributes and methods corresponding to it other than the label and value.
If we have only label and value then we can use the LabelValueBean class to add the label and value to the ArrayList. We populate the stateList using the LabelValueBean class. The following code is used to populate the stateList in the action class.
ArrayList stateList = new ArrayList();
stateList.add(new LabelValueBean("New York", "New York"));
stateList.add(new LabelValueBean("California", "California"));
stateList.add(new LabelValueBean("Los Angeles", "Los Angeles"));
The following code is used to dispaly the state list in the jsp page.