Drop Downs and SelectOption Lists


Drop Downs and Select/Option Lists

This section provides information on the following tags:

  • <html:select> ” Render an HTML <select> drop-down or multi-select element

  • <html:option> ” Define an individual <option> element within a <select> element

  • <html:options> ” Define one or more <option> elements within a <select> element

  • <html:optionsCollection> ” Define one or more <option> elements within a <select> element based on a collection

If you point your browser to the URL http://myAppServer/StrutsTaglibs/html.jsp

you'll bring up the main page that links to all the sample code for the Struts tag chapters. This section uses the Select and Option Tags page at /StrutsTaglibs/HtmlSelects.do . The rendered page is shown in Figure 12.5.

Figure 12.5. The Select and Option Tags page at /StrutsTaglibs/HtmlSelects.do .

graphics/12fig05.gif

Listing 12.6 is the JSP file that creates this page.

Listing 12.6 JSP File Demonstrating the Use of <html:select> , <html:option> , <html:options> , and <html:optionsCollection> Tags ( HtmlSelects.jsp )
 <%@ page language="java" import="ch12.*, java.util.*" %> <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %> <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %> <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %> <html:html> <head> <title>Select and Option Tags</title> </head> <body bgcolor="white"> <h3>Select and Option Tags</h3> <p>This page provides examples of the following Struts HTML tags:<br> <ul> <li>&lt;html:select&gt;</li> <li>&lt;html:option&gt;</li> <li>&lt;html:options&gt;</li> <li>&lt;html:optionsCollection&gt;</li> </ul> <html:form action="HtmlSelects.do"> <table border="1" width="100%">   <tr>     <%       Vector colorCollection = new Vector();       colorCollection.add(          new org.apache.struts.util.LabelValueBean("Pink", "ch12.pink"));       colorCollection.add(          new org.apache.struts.util.LabelValueBean("Brown", "ch12.brown"));       pageContext.setAttribute("colorCollection", colorCollection);     %>     <th align="left" width="25%" >Select a customer: </th>     <th align="left" width="25%" >Select some colors: </th>     <th align="left" width="50%" >You last submitted: </th>   </tr>   <tr>     <td align="left" width="25%" >       <html:select property="custId">         <html:optionsCollection property="customers"                                 label="name"                                 value="custId" />       </html:select>     </td>     <td align="left" width="25%" >       <html:select property="colors" size="6" multiple="true" >         <%-- Specify some options using the basic version of the tag --%>         <html:option value="ch12.orange">Orange</html:option>         <html:option value="ch12.purple" value="Purple" />         <%-- Specify some by referring to a properties file --%>         <html:option value="ch12.red" bundle="ch12.Colors" key="ch12.red"/>         <html:option value="ch12.blue" bundle="ch12.Colors" key="ch12.blue"/>         <%-- Specify some from our collection of LabelValueBean's --%>         <html:options collection="colorCollection"                       property="value"                       labelProperty="label" />       </html:select>     </td>     <td align="left" width="50%" >         <ul>           <li>Name: <bean:write name="HtmlSelectsForm" property="cust.name" />           <logic:iterate id="element" name="HtmlSelectsForm" property="cust.favColors">           <li>Colors: <bean:write name="element" />           </logic:iterate>         </ul>     </td>   </tr> </table> <table border="1" width="100%">   Status of all customers:<br>     <td align="left">         <ul>           <logic:iterate id="c" name="HtmlSelectsForm" property="customers">             <li><bean:write name="c" />           </logic:iterate>         </ul>     </td> </table> <table border="0" width="100%">   <tr>     <td align="left" width="20%">&nbsp;</td>     <td align="left">       <html:submit>Submit</html:submit>       <html:reset>Reset</html:reset>       <html:cancel>Cancel</html:cancel>     </td>   </tr> </table> </html:form> </html:html> 

For this example, it's valuable to review the form bean to help demonstrate how these three types of elements are managed. Listing 12.7 is the form bean that goes with this JSP file ( HtmlSelectsForm.java ).

Listing 12.7 Form Bean That Corresponds with HtmlSelects.jsp ( HtmlSelectsForm.java )
 package ch12; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; /**  * @author Kevin Bedell & James Turner  * @version 1.0  *  */ public class HtmlSelectsForm extends ActionForm {   private CustomerBean customers[];   public CustomerBean [] getCustomers() { return this.customers; }   public void setCustomers(CustomerBean [] customers) {     this.customers = customers;   }   private CustomerBean cust = new CustomerBean();   public CustomerBean getCust() { return cust; }   public void setCust(CustomerBean cust) { this.cust = cust; }   private int custId;   public int getCustId() { return this.custId; }   public void setCustId(int custId) { this.custId = custId; }   private String colors[];   public String [] getColors() { return this.colors; }   public void setColors(String [] colors) { this.colors = colors; }   // Default bean constructor   public HtmlSelectsForm() {     customers = new CustomerBean[3];     for (int i=0; i<3 ; i++ ) {       customers[i] = new CustomerBean();       customers[i].setCustId(i);     }     customers[0].setName("Mr. Hand");     customers[1].setName("Brad Hamilton");     customers[2].setName("Jeff Spicoli");   }   public void reset(ActionMapping mapping, HttpServletRequest request) {     this.cust = new CustomerBean();     this.colors = new String[0];     this.custId = -1;   }   public ActionErrors validate(ActionMapping mapping,                                HttpServletRequest request) {      ActionErrors errors = new ActionErrors();      // if custId is -1, then no customer was chosen yet.      if (custId == -1) {        return errors;      }      /*       * No real validation done. Just set values based on input.       */      this.customers[this.custId].setFavColors(this.colors);      this.cust = this.customers[this.custId];      return errors;   } } 

The properties and methods in this class are discussed in the following sections.

The <html:select> Tag

The <html:select> tag renders an HTML <select> tag. These tags are used for both drop-down lists and multiselect or scrolling lists. Figure 12.5 shows examples of both these elements.

The basic format of this tag is

 <html:select property="custId">   [1 or more <html:option>, <html:options>, <html:optionCollections> tags] </html:select> 

That is, all the option elements can be mixed in a single <html:select> tag.

A drop-down list is rendered if the size attribute is set to 1 (or is omitted) and the multiple attribute isn't set to true (or is omitted). Otherwise, a multiselect list is rendered.

The property attribute defines the property in the form bean that this element is tied to. When the page is rendered, the value of this property becomes the initial value and is shown as selected.

If the multiple attribute is omitted, only a single value is submitted from the <select> element when the form is submitted. In that case, the property in the form bean must be a simple property (that is, not an array). If the multiple attribute is set to true, the underlying property must be an array because more than one value could be submitted.

By default, the property attribute specifies a property of the default form bean specified for this <html:form> element. It's possible to override this behavior by using the name attribute to specify the name of another bean.

The <html:option> Tag

The <html:option> tag renders an HTML <option> tag. It's the basic Struts tag for rendering a single <option> tag inside a <select> element.

This tag represents a possible value for the enclosing <select> element. If the value of the <select> element matches the value of the <option> tag, this <option> is shown as highlighted.

The display value of the <html:option> tag is taken from one of two places:

  • The value enclosed by <html:option> and </html:option> tags

  • A value in a properties file (resource bundle) as specified by the key , locale , and bundle attributes of the <html:option> tag

To specify a display value using a resource bundle, you should first define a <message-resources> element in the struts-config.xml file.

For example, consider the list of colors in the sample program. Here are the <option> tags that specify the first four elements in the list:

 <%-- Specify some options using the basic version of the tag --%> <html:option value="ch12.orange">Orange</html:option> <html:option value="ch12.purple">Purple</html:option> <%-- Specify some by referring to a properties file --%> <html:option value="ch12.red"  bundle="ch12.Colors" key="ch12.red"/> <html:option value="ch12.blue"  bundle="ch12.Colors" key="ch12.blue"/> 

As you can see, <option> tags can be mixed and used in multiple forms. The Orange and Purple options have their values specified directly in the tag. The Red and Blue options are defined in the message resource bundle defined as ch12.Colors .

The resource bundle is defined by this line in the struts-config.xml file:

 <message-resources parameter="ch12.Colors" key="ch12.Colors" /> 

The parameter attribute identifies the properties as being in the ch12.Colors. properties file. Here are the contents of that file:

 ch12.red=Red ch12.blue=Blue 

If you wanted to provide locale-specific <option> values, you could simply provide properties files for each locale that you must support.

The <html:options> Tag

The <html:options> tag is very flexible and enables you to generate HTML <option> elements in a number of ways. For a complete description, please refer to the Struts documentation. This section presents only some of the ways the tag can be used.

No matter how the HTML <option> elements are used, the basic idea is they're generated from a collection (or array) of values. The differences in the attributes you specify determine where the collection is fetched from and where the labels and values for each element come from.

The <html:options> tag works differently depending on whether the collection attribute is specified. In general,

  • If the collection attribute is specified, the bean referred to is itself the collection .

  • If the collection attribute is not specified, the bean referred to contains a property holding the collection .

Here are some examples to help clarify this concept. First, here's an example in which the collection attribute is specified:

 <html:options collection="coll" property="value" labelProperty="label" /> 

In English, this means, "The options are stored in a bean named coll . This bean itself is a collection that holds individual option elements. The value property of each element holds the value to be submitted if this option is selected. The label property of each element holds the value of the label to show each user on the list."

Second, here's an example in which the collection attribute isn't specified:

 <html:options property="values" labelProperty="labels" /> 

In English, this means, "A form bean property named values holds the collection of option values. A form bean property named labels holds the collection of option labels to display to the user."

Finally, here's an example in which the labels and values are stored in collections in different beans:

 <html:options name="valueBean" property="values"               labelName="labelsBean" labelProperty="labels" /> 

In English, this means, "The values are stored in a bean named valueBean in a property named values , which is a collection holding the value elements. The labels are stored in a bean named labelsBean in a property named labels , which is a collection holding the label elements."

There are many combinations of these attributes. As you can see, the flexibility of this tag is extreme!

Given this background, let's interpret the <html:options> tag used in the sample program:

 <%-- Specify some from our collection of LabelValueBean's --%> <html:options collection="colorCollection"                  property="value"                  labelProperty="label" /> 

In English, this means, "The values are stored in a bean named colorCollection , which itself is a collection. Each element of the collection has a property named value containing the value and a property named label containing the label to display to the user."

The need for a bean with properties named value and label came up so often in Struts that a Struts utility class based on this was added to the framework. The class is named org.apache.struts.utility.LabelValueBean and its use is demonstrated in this sample program.

The following is the code in which the colorCollection is initialized . It demonstrates the use of the Struts LabelValueBean utility class.

 <%   Vector colorCollection = new Vector();   colorCollection.add(      new org.apache.struts.util.LabelValueBean("Pink", "ch12.pink"));   colorCollection.add(      new org.apache.struts.util.LabelValueBean("Brown", "ch12.brown"));   pageContext.setAttribute("colorCollection", colorCollection); %> 

The preceding code takes advantage of the constructor that takes label and value properties and returns the initialized object.

The <html:optionsCollection> Tag

The <html:optionsCollection> is very similar to the <html:options> tag. The approach you should take depends on the specifics of the classes and data you're working with.

In the sample application, the list of user options in the drop-down box is displayed using the following tag:

 <html:select property="custId">     <html:optionsCollection property="customers"                             label="name"                             value="custId" /> </html:select> 

The form bean contains an array of objects in the property customers that we want the labels and values to come from. For each object in the array, the <option> label comes from the name property and the value comes from the custId property.

The <html:optionsCollection> tag is designed to work well with the LabelValueBean described in the previous section. If the label and value properties in each element of the collection are literally named label and value , these attributes can be omitted!

That means if the sample application used LabelValueBean objects instead of the custom bean that was used, this section could have been written as

 <html:select property="custId">         <html:optionsCollection property="customers" /> </html:select> 

Whether you should use the Struts <html:options> or <html:optionsCollection> tag for a particular application depends on exactly how your application is written and the nature of the objects you're using to store your labels and values.



Struts Kick Start
Struts Kick Start
ISBN: 0672324725
EAN: 2147483647
Year: 2002
Pages: 177

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net