Ad

Saturday 22 August 2009

To dynamically populate the dropdrownBox with the values in the List by using <html:optionsCollection> tag in Struts

Most of the time in wepApplications, we need to populate the dropdown box with the values available in the database.Struts provide a <html:optionsCollection> tag for populating the dropdown box with the list.There are two flavours of <html:optionsCollection> tags comes with struts.

Lets says we need to populate the dropdownbox with the city name available in the backendtable.The Value object for the table will look like

public Class Citydetails
{
private String cityName;//To hold the cityname available in the table
private String cityId; //To hold the cityid available in the table
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public String getCityId() {
return cityId;
}
public void setCityId(String cityId) {
this.cityId = cityId;
}
}

In the action we will construct the list of above bean object from the data available in the table.

//Ge the data from the city table and construct the list
List<Citydetails> cityList =new ArrayList<Citydetails>();
while(//there is a city row in the table)
{
//construct the Citydetails bean object and set cityid and city name from the table
cityList.add(citydetails);//add the bean to the list
}
request.setAttribute("cityList",cityList)//set the list in the request scope
return mapping.findForward("jsp");//forward to Jsp page


we can populate the dropdownbox with the list which is available in any scope by using the <html:optionsCollection> in Jsp as shown below

<html:select property="formbeancitycode">
<html:optionsCollection name="citylist" value="cityID" label="cityName" />
</html:select>

Name - The attribute name which we have set the list in request,session or application scope
value - The bean property value which will be posted to the server on form submit
label - The bean property value which should get populated in the dropdownbox.

The dropdownbox will have all the cityName which are fetched from the table.
once we select the dropdown and submit the form,the cityID of the selected cityName will be posted to the server.

Instead of setting the list in any scope,we can also set the list to a formbean property in the action.Then we can populate the list from the formbean property in the dropdownbox as shown below

<html:select property="formbeancitycode">
<html:optionsCollection property="citylist" value="cityID" label="cityName" />
</html:select>

property - The formbean property name which has the list.


Note: The list which is set in the scope or in the formbean property for populating the dropdown should be the list of Java bean objects.

1 comment: