Introduction

The Struts-Layout Suggest tag allows to render a text field with a suggestions list: when a user types a character, the tag shows suggestions matching typed word, and the user just have to use keyboard or mouse in order to choose one of these suggestions.

Creating a Suggest field

Here are the required steps to create a suggest field:

  • Creation of a particular Struts Action class
  • Configuration of this action
  • Creation of the JSP

This tutorial is based on the demo application named CountrySuggest, which shows an example of a suggest field allowing to type easily country names. Here is the result:

Creation of a particular Struts Action class

In fact, when a user types a character, a Struts action is called. This action class has two particularities:

  • It must extends the fr.improve.struts.taglib.layout.suggest.SuggestAction class.
  • It must implement an inherited abstract method named getSuggestionList(HttpServletRequest in_request, String in_word): this method returns a suggestions list (as a String Collection) from the typed word (as in_word).

package fr.improve.demosuggest.countries;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.servlet.http.HttpServletRequest;
import fr.improve.struts.taglib.layout.suggest.SuggestAction;

public class CountrySuggestAction extends SuggestAction {
	
	public Collection getSuggestionList(HttpServletRequest in_request, String in_word) {
		
		// Get all the country names
		Collection allCountries = CountryCollection.getAllCountries();
		
		// Start to build the suggestions list
		ArrayList suggestions = new ArrayList();
		
		if (in_word != null && in_word.length() > 0)
		{
			Iterator iter = allCountries.iterator();
			
			while(iter.hasNext())
			{
				String currentWord = (String) iter.next();
				
				if(currentWord.toLowerCase().startsWith(in_word.toLowerCase()))
					suggestions.add(currentWord);
			}
		}
		
		return suggestions;
	}
	
}				
			

Note that this code is based on a class named CountryCollection providing a method called getAllCountries() returning all country names.

Configuration of this action

Just add these lines into your struts-config.xml file (in the <action-mappings> ... </action-mappings> part):

<struts-config>

	...
	
	<action-mappings>

		<action path="/getCountrySuggestions"
			type="fr.improve.demosuggest.countries.CountrySuggestAction">
		</action>
	
	</action-mappings>
	
	...
	
</struts-config>
			

Creation of the JSP

Finally just add the <layout:suggest> tag into a JSP page:

<%@ taglib uri="/WEB-INF/struts-layout.tld" prefix="layout" %>

<layout:html>

	<layout:suggest suggestAction="/getCountrySuggestions" key="Country" styleId="myTextField" value="" suggestCount="8" />
	
</layout:html>
			

Note that you can also specify the 'property' attribute in order to bound this field to a property of an action form.