Populating the values of the attribute in the form

The form can display the available list of choices to the user using checkboxes, drop-down menus, or radio buttons. The values in the view can be populated using List, Map, or Array for the values of the drop-down menu, checkboxes, or radio buttons.

The general syntax of the tags is as follows:

<form:name-of_tag path="name_of_data_memeber_of_bean" 
  items="name_of_attribute" itemLable="value_to display" 
itemValue="value_it_holds">

The following code can be used to display the hobbies of the user in checkboxes using hobbies as modelattribute to bind the value to the hobby data member of the bean:

<form:checkboxes path="hobby"items="${hobbies}" 
   itemLabel="hobbyName"itemValue="hobbyId"/> 

In the same way, we can generate drop-down menus and options for the select tag at runtime.

The itemLabel and itemValue attributes can be skipped while handling String values.

The complete example can be referred from the application Ch06_Form_PrePopulation.

Let's update the ReadMyBooks application to predefine some values of price in the bookForm.jsp file using ModelAttribute to discuss form preprocessing with the help of the following steps:

  1. As the form is returned by AddController to the Front Controller, we want predefined values for the prices; let's add the addPrices() method in it. Annotate the method by @ModelAttribute, as follows:
@ModelAttribute("priceList") 
  public List<Integer>addPrices() { 
  List<Integer> prices=new ArrayList<Integer>(); 
  prices.add(300); 
  prices.add(350); 
  prices.add(400); 
  prices.add(500); 
  prices.add(550); 
  prices.add(600); 
  return prices; 
} 

The preceding code creates an attribute priceList, which can be available to the view for use.

  1. Now the pricelist attribute can be used in the view to display the predefined values. In our case, it's a form for addition of a new book. Let's update the bookForm.jsp file to display the pricelist, as follows:
<form:selectpath="price"> 
  <form:options items="${priceList}"/> 
</form:select>
  1. Run the application, and click on the link; you can observe that the predefined prices will appear in a drop-down list, as shown in the following screenshot:

The users will enter values in the form, and submit it to process the form.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.191.22