YOUR FEEDBACK
andy.mulholland wrote: intriguing !!! We have full scale 'Mashup Factories' in Chicago USA and Utrec...


2008 East
DIAMOND SPONSOR:
Data Direct
Frontiers in Data Access: The Coming Wave in Data Services
PLATINUM SPONSORS:
Red Hat
The Opening of Virtualization
Intel
Virtualization – Path to Predictive Enterprise
Green Hills
IT Security in a Hostile World
JBoss / freedom oss
Practical SOA Approach
GOLD SPONSORS:
Software AG
The Art & Science of SOA: How Governance Enables Adoption
PlateSpin
Effective Planning for Virtual Infrastructure Growth
Fujitsu
Automated Business Process Discovery & Virtualization Service
Ceedo
Workspace Virtualization
Click For 2007 West
Event Webcasts

2008 East
PLATINUM SPONSORS:
Appcelerator
Think Fast: Accelerate AJAX Development with Appcelerator
GOLD SPONSORS:
DreamFace Interactive
The Ultimate Framework for Creating Personalized Web 2.0 Mashups
ICEsoft
AJAX and Social Computing for the Enterprise
Kaazing
Enterprise Comet: Real–Time, Real–Time, or Real–Time Web 2.0?
Nexaweb
Now Playing: Desktop Apps in the Browser!
Sun
jMaki as an AJAX Mashup Framework
POWER PANELS:
The Business Value
of RIAs
What Lies Beyond AJAX?
KEYNOTES:
Douglas Crockford
Can We Fix the Web?
Anthony Franco
2008: The Year of the RIA
Click For 2007 Event Webcasts
SYS-CON.TV
TOP THREE LINKS YOU MUST CLICK ON


Java Feature — Jakarta Struts & JavaServer Faces
The add-and-remove pattern

A previous article compared Jakarta Struts and JavaServer Faces implementations of five simple design patterns for list selection. (JDJ, Vol. 11, Issue 3).

Long lists and ordered selections require a more complex design pattern. This pattern displays available items in one list and chosen items in another so the user's choices are always visible and easily modified.

This design pattern is commonly called a Dual List or Dual Listbox selector. It is also known as the Selection Summary or List Builder pattern. In the Java Look and Feel Design Guidelines, it's called the Add-and-Remove pattern:

Typical Struts implementations of this pattern require JSPs, Java, and JavaScript. JavaServer Faces doesn't need JSPs, but they're used here for easy comparison.

Listing 1 shows the JSP for Struts and Listing 2 shows the JSP for JavaServer Faces. Complete code listings for the backing beans, config files, and other code for all six list selection patterns can be downloaded from the JDJ Web site.

Jakarta Struts Implementation
Using Jakarta Struts, the JSP for this pattern defines a table layout with three columns. In the first and third columns, the Available and Chosen lists are implemented using the Struts tags <html:select> and <html:optionsCollection>. For internationalization, the labels can use the <fmt:message> tag from the JavaServer Pages Standard Tag Library. Many people find Struts and JSTL tags a powerful combination.

<table border="0" cellpadding="0" cellspacing="5">
   <tr align="middle" valign="center">
     <td>
       <fmt:message key="titles.available"/><br />
       <html:select property="availableValues"
         multiple="true" size="7"
         style="width:80px;" styleId="available"
         onchange="doUpdate( false, true );">
         <html:optionsCollection
         property="availableList"/>
       </html:select>
     </td>
...
     <td>
       <fmt:message key="titles.chosen"/><br />
       <html:select property="chosenValues"
         multiple="true" size="7"
         style="width:80px;" styleId="chosen"
         onchange="doUpdate( true, false );">
         <html:optionsCollection
         property="chosenList"/>
       </html:select>      </td>
   </tr>
</table>

The form bean contains the "availableList," "availableValues," "chosenList," and "chosenValues" properties used in the JSP.

private List availableList = new ArrayList();
private String[] availableValues = new String[ 0 ];
private List chosenList = new ArrayList();
private String[] chosenValues = new String[ 0 ];
    ...
public List getAvailableList()
public void setAvailableList( List list )
public String[] getAvailableValues()
public void setAvailableValues( String[] list )
public List getChosenList()
public void setChosenList( List list )
public String[] getChosenValues()
public void setChosenValues( String[] list )
    ...

The "availableList" and "chosenList" properties store the lists of available values as LabelValueBeans. The "availableValues" and "chosenValues" properties store the selected values as arrays of Strings.

For the Add-and-Remove pattern, these selected values are of no interest. We don't have to tell the server which values are selected but which items appear in the list contents. However, when forms are submitted, list contents don't get sent back to the server; only their selected values do. This is usually the most efficient way to process forms, but for this design pattern it's a problem. (see Figure 1)

There are several ways to solve this problem. One way is to submit the form every time the list contents change. This produces excess screen refreshes and network traffic. Another way is to use AJAX technology to communicate with the server. This reduces screen refreshes, but still generates network traffic. There's no need to generate network traffic until the user completes their changes.

The best solution is to store the selected values in a hidden control. This way the values get sent back to the server only once, when the form is submitted. It's sufficient to store only the chosen values; changes to both lists can be derived from them. In this example, we'll store the chosen values as a delimited string in a hidden text field.

Using this hidden field, the buttons in the middle column can be implemented as follows:

<td>
   <br />
   <input type="button" style="width:100px;" id="add" onclick="
doMove( 'available', 'chosen', false );" value="<fmt:message key='add'/>" /><br />
   <input type="button" style="width:100px;" id="addAll" onclick=
"doMove( 'available', 'chosen', true );" value="<fmt:message key='addAll'/>" /><br />
   <br />
   <input type="button" style="width:100px;" id="remove" onclick=
"doMove( 'chosen', 'available', false );" value="<fmt:message key='remove'/>" /><br />
   <input type="button" style="width:100px;" id="removeAll" onclick=
"doMove( 'chosen', 'available', true );" value="<fmt:message key='removeAll'/>" />
   <html:hidden styleId="chosenItem" property="chosenItem" />
</td>

The buttons are implemented using standard HTML <input> tags. The <html:hidden> field stores the chosen items as a delimited string. The items are stored by invoking the JavaScript "doMove()" function, which performs all four of the button actions:

/**
* Move selected items between lists.
* <p>
* @param sourceId ID of source list
* @param destId ID of destination list
* @param all true iff moving all
*/
function doMove( sourceId, destId, all )
{
    // Move the items between the lists.
    var sourceElem = document.getElementById( sourceId );
    var destElem = document.getElementById( destId );
    for( var i = 0; ( i < sourceElem.length ); )
    { if( sourceElem.options[ i ].selected || all )
       { var newOption = document.createElement( "OPTION" );
       newOption.text = sourceElem.options[ i ].text;
       newOption.value = sourceElem.options[ i ].value;
       destElem.options[ destElem.length ] = newOption;
       sourceElem.remove( i );
       }
       else
         i++;
    }

    // Update the button states.
    doUpdate( false, false );

    // Store the chosen items in a hidden field.
    var chosenItem = document.getElementById( "chosenItem" );
    var chosenList = document.getElementById( "chosen" );
    chosenItem.value = "";
    for( var i = 0; ( i < chosenList.length ); i++ )
    { chosenItem.value += chosenList.options[ i ].value + '|';
    }
}

Besides implementing the button actions, it eases the users' learning curve to disable these actions when they don't make sense. For example, when there are no selected items, the "Add" and "Remove" buttons can't be used. When the available list or chosen list is empty, the "Add All" or "Remove All" button can't be used.

The "doUpdate()" function enables or disables the buttons based on the user's selections and the list contents. (see Figure 2) The "doUpdate()" function is invoked from the "doMove()" function above as an "onchange" handler for the lists, and as an "onload" handler in the <body> tag to initialize the button states.

/**
* Update the button states based on whether
* lists have contents and selected items.
* Deselect list items if requested to ensure
* at most one list contains selections.
* <p>
* @param offAvailable deselect available list
* @param offChosen deselect chosen list
*/
function doUpdate( offAvailable, offChosen )
{
   // Get the lists and deselect if requested.
   var availableList = document.getElementById( "available" );
   var chosenList = document.getElementById( "chosen" );
   if( offAvailable ) availableList.selectedIndex = -1;
   if( offChosen ) chosenList.selectedIndex = -1;
   // Update the button states.
     document.getElementById( "addAll" ).disabled =
( availableList.length == 0 );
     document.getElementById( "removeAll" ).disabled =
( chosenList.length == 0 );
     document.getElementById( "add" ).disabled =
( availableList.selectedIndex < 0 );
     document.getElementById( "remove" ).disabled =
( chosenList.selectedIndex < 0 );
}

Using these JavaScript functions, list contents are correctly updated and the user's chosen items are stored in the hidden field. When the form is submitted, the user's "chosen" list is read from the hidden field. In this example, it's used to re-populate both lists to reflect the user's choices.

Lists are re-populated by using the "languageList" in the form bean. This is a constant list containing all possible choices. The "move" method of the form bean manipulates the "available" and "chosen" lists based on the contents of the hidden "chosenItem" field.

private List languageList = new ArrayList();
private String chosenItem = "";
    ...
public List getLanguageList()
public void setLanguageList( List list )
public String getChosenItem()
public void setChosenItem( String items )
public void move( List sourceList, String[] sourceValues, List destList )
    ...


About Heman Robinson
Heman Robinson is a senior developer with SAS Institute in Cary, N.C. He holds a BS in mathematics from the University of North Carolina and an MS in computer science from the University of Southern California. He has specialized in GUI design and development for 15 years and has been a Java developer since 1996.

YOUR FEEDBACK
Bill Dornbush wrote: "Complete code listings for the backing beans, config files, and other code for all six list selection patterns can be downloaded from the JDJ Web site." Where is it?
n d wrote: A previous article compared Jakarta Struts and JavaServer Faces implementations of five simple design patterns for list selection. (JDJ, Vol. 11, Issue 3). Long lists and ordered selections require a more complex design pattern. This pattern displays available items in one list and chosen items in another so the user's choices are always visible and easily modified.
n d wrote: A previous article compared Jakarta Struts and JavaServer Faces implementations of five simple design patterns for list selection. (JDJ, Vol. 11, Issue 3). Long lists and ordered selections require a more complex design pattern. This pattern displays available items in one list and chosen items in another so the user's choices are always visible and easily modified.
n d wrote: A previous article compared Jakarta Struts and JavaServer Faces implementations of five simple design patterns for list selection. (JDJ, Vol. 11, Issue 3). Long lists and ordered selections require a more complex design pattern. This pattern displays available items in one list and chosen items in another so the user's choices are always visible and easily modified.
LATEST JAVA STORIES & POSTS
The one thing that unifies the distributed computing style known as SOA, in most of its manifestations, is self-describing data via the Extensible Markup Language (XML). The benefits of XML over opaque message formats in data interchange are well established. No matter if your fo...
In the past couple of years, interest in Jetty has surged. Jetty is an open source Java-based web and application server and servlet container, but what else do you know about it? To commemorate the 12th anniversary of Jetty, here are 12 things that might surprise you
JavaScript is one of the most interesting and misunderstood programming languages in common use today. Most developers will go their entire careers without realizing its full potential. It's not often that you get a language that supports the feature set that JavaScript does, whi...
JavaScript 2 is becoming increasingly important. Learn how to take advantage of JavaScript 2 while still running in today's browsers. Leverage your current JavaScript and HTML skills to build applications that run in Flash 7-9, DHTML and more with no code changes! OpenLaszlo 4.2 ...
JavaScript is a language with more than its share of bad parts. It went from non-existence to global adoption in an alarmingly short period of time. It never had an interval in the lab when it could be tried out and polished. JavaScript has some extraordinarily good parts. In Jav...
Cloud computing is an opportunity for businesses to implement low-cost, low-power and high-efficiency systems to deliver scalable infrastructure. But moving to a cloud infrastructure is not necessarily as nice and clean as the providers would want you to think. With cloud infrast...
SUBSCRIBE TO THE WORLD'S MOST POWERFUL NEWSLETTERS
SUBSCRIBE TO OUR RSS FEEDS & GET YOUR SYS-CON NEWS LIVE!
Click to Add our RSS Feeds to the Service of Your Choice:
Google Reader or Homepage Add to My Yahoo! Subscribe with Bloglines Subscribe in NewsGator Online
myFeedster Add to My AOL Subscribe in Rojo Add 'Hugg' to Newsburst from CNET News.com Kinja Digest View Additional SYS-CON Feeds
Publish Your Article! Please send it to editorial(at)sys-con.com!

Advertise on this site! Contact advertising(at)sys-con.com! 201 802-3021


SYS-CON FEATURED WHITEPAPERS

SPONSORED BY INFRAGISTICS
In every field of design one of the first things students do is learn from the work of others. They ...
There are many forces that influence technological evolution. After a decade of building enterprise ...
2008 is going to be an important year for Rich Internet Applications. Most organizations are deliver...
The OpenAjax Alliance is developing an Ajax industry wishlist for future browsers, using a dedicated...
Infragistics announced the availability of two Community Technology Preview (CTP) User Interface (UI...
The YUI development team has released version 2.5.2; you can download the new release from SourceFor...
ADS BY GOOGLE