Struts 2 autocompleter example

In Struts 2, the <sx:autocompleter> tag is a combo box that will automatic prompt drop down suggestion lists while user typing on the text box.

This feature is implemented by dojo library, So, make sure you include “struts2-dojo-plugin.jar” as dependency library, put “struts-dojo-tags” tag on top of the page and output its header information via <sx:head />.

For example,


<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>
<html>
<head>
<sx:head />
</head>
<body>
<sx:autocompleter label="What's your lucky number?" 
name="yourLuckyNumber" autoComplete="false"
list="{'1','12','13','14'}" />

Resulting the following HTML


<html> 
<head> 
<script language="JavaScript" type="text/javascript"> 
    // Dojo configuration
    djConfig = {
        isDebug: false,
        bindEncoding: "UTF-8"
          ,baseRelativePath: "/Struts2Example/struts/dojo/"
          ,baseScriptUri: "/Struts2Example/struts/dojo/"
         ,parseWidgets : false
        
    };
</script> 
<script language="JavaScript" type="text/javascript"
        src="/Struts2Example/struts/dojo/struts_dojo.js"></script> 
		
<script language="JavaScript" type="text/javascript"
        src="/Struts2Example/struts/ajax/dojoRequire.js"></script> 
		
<link rel="stylesheet" href="/Struts2Example/struts/xhtml/styles.css" 
type="text/css"/> 

<script language="JavaScript" src="/Struts2Example/struts/utils.js" 
type="text/javascript"></script> 

<script language="JavaScript" src="/Struts2Example/struts/xhtml/validation.js" 
type="text/javascript"></script> 

<script language="JavaScript" src="/Struts2Example/struts/css_xhtml/validation.js" 
type="text/javascript"></script> 
</head> 
...
<tr>
<td class="tdLabel">
<label for="resultAction_yourLuckyNumber" class="label">
What's your lucky number?:</label></td>
<td>  
<select dojoType="struts:ComboBox" id="resultAction_yourLuckyNumber" 
autoComplete="false" name="yourLuckyNumber" 
keyName="yourLuckyNumberKey" visibleDownArrow="true" >
    <option value="1">1</option>
    <option value="12">12</option>
    <option value="13">13</option>
    <option value="14">14</option>
</select>
</td>
</tr>
<script language="JavaScript" type="text/javascript">
djConfig.searchIds.push("resultAction_yourLuckyNumber");</script>

Struts 2 <s:autocompleter> example

A complete example of the <s:autocompleter> tag, generate the drop down suggestion lists while user typing on the corresponding text box.

1. pom.xml

Download the Struts 2 dojo dependency libraries.

pom.xml


//...
    <!-- Struts 2 -->
    <dependency>
      <groupId>org.apache.struts</groupId>
	  <artifactId>struts2-core</artifactId>
	  <version>2.1.8</version>
    </dependency>
	
    <!-- Struts 2 Dojo Ajax Tags -->
    <dependency>
      <groupId>org.apache.struts</groupId>
	  <artifactId>struts2-dojo-plugin</artifactId>
	  <version>2.1.8</version>
    </dependency>
//...

2. Action class

Action class to generate a list of the web frameworks options to the “autocompleter” component.

AutoCompleterAction.java


package com.mkyong.common.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class AutoCompleterAction extends ActionSupport{

	private List<String> webframeworks = new ArrayList<String>();
	
	private String yourFavWebFramework;
	private String yourLuckyNumber;
	
	public AutoCompleterAction(){
		webframeworks.add("Spring MVC");
		webframeworks.add("Struts 1.x");
		webframeworks.add("Struts 2.x");
		webframeworks.add("JavaServer Faces (JSF)");
		webframeworks.add("Google Web Toolkit (GWT)");
		webframeworks.add("Apache Wicket");
		webframeworks.add("Apache Click");
		webframeworks.add("Apache Cocoon");
		webframeworks.add("JBoss Seam");
		webframeworks.add("Stripes");
		webframeworks.add("Apache Tapestry");
		webframeworks.add("Others");
	}
	
	public String getYourLuckyNumber() {
		return yourLuckyNumber;
	}

	public void setYourLuckyNumber(String yourLuckyNumber) {
		this.yourLuckyNumber = yourLuckyNumber;
	}

	public String getYourFavWebFramework() {
		return yourFavWebFramework;
	}

	public void setYourFavWebFramework(String yourFavWebFramework) {
		this.yourFavWebFramework = yourFavWebFramework;
	}

	public List<String> getWebframeworks() {
		return webframeworks;
	}

	public void setWebframeworks(List<String> webframeworks) {
		this.webframeworks = webframeworks;
	}

	public String display() {
		return NONE;
	}
	
}

3. Result Page

Render the “autocompleter” component via “<s:autocompleter>” tag, and generate the auto drop down suggestion lists via Java list and OGNL.

autocompleter.jsp


<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="sx" uri="/struts-dojo-tags" %>

<html>
<head>
<sx:head />
</head>

<body>
<h1>Struts 2 autocompleter example</h1>

<s:form action="resultAction" namespace="/" method="POST" >

<sx:autocompleter label="What's your lucky number?" 
name="yourLuckyNumber" autoComplete="false"
list="{'1','12','13','14','21','22','23','24',
'31','32','33','34','41','42','43','44'}" />

<sx:autocompleter label="What's your favorite web framework?" 
list="webframeworks" name="yourFavWebFramework" />

<s:submit value="submit" name="submit" />
	
</s:form>

</body>
</html>

result.jsp


<%@ taglib prefix="s" uri="/struts-tags" %>
<html>

<body>
<h1>Struts 2 autocompleter example</h1>

<h2>
   Lucky Number : <s:property value="yourLuckyNumber"/> 
</h2> 

<h2>
   Web Appication Frameworks : <s:property value="yourFavWebFramework"/> 
</h2> 

</body>
</html>

3. struts.xml

Link it all ~


<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
 
<struts>

 <constant name="struts.devMode" value="true" />
	
<package name="default" namespace="/" extends="struts-default">
		
  <action name="autoCompleterAction" 
	class="com.mkyong.common.action.AutoCompleterAction" 
        method="display">
	<result name="none">pages/autocompleter.jsp</result>
  </action>
		
  <action name="resultAction" 
        class="com.mkyong.common.action.AutoCompleterAction" >
	<result name="success">pages/result.jsp</result>
  </action>
</package>
	
</struts>

4. Demo

http://localhost:8080/Struts2Example/autoCompleterAction.action

Struts 2 AutoCompleter example
Struts 2 AutoCompleter example
Here’s another example to show the use of JSON data to provide a list of the select options to the autocompleter component – Struts 2 autocompleter + JSON example.

Reference

  1. Struts 2 autocompleter documentation
  2. Struts 2 ajax and javascript recipes
  3. Struts 2 combo box example

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Praveen Inbasekaran
Guest
Praveen Inbasekaran

Hi, I used this autocompleter and it works well but I face the problem in fetching the value. When I display the value of the selected option I’m getting the listValue (String) in place of listKey(integer) in my javascript in the jsp page. This is causing me parsing error as I need the listKey value to be fetched instead of the listValue. Can you give me a solution?

The autocompleter works fine. Also if I use normal struts text tag javascript fetches the listKey for the selected value properly.

trackback
Tech List | lazzycrazzy
Jagan Ramesh
Guest
Jagan Ramesh
I’m Also facing the same issue.I’m maven based struts-spring webapp, I want to call a JS function from based on selection of sx:autocompleter tag. **POM.XML** org.apache.struts struts2-dojo-plugin 2.1.8 org.apache.struts struts2-json-plugin 2.1.8 org.apache.struts struts2-convention-plugin 2.1.8 **STRUTS.XML** InvalidSessionAction /jsp/pending.jsp /jsp/index.jsp /jsp/approve.jsp /jsp/index.jsp **Request.JSP** function loadColumns() { var value = document.getElementById(tablename); alert(“tablename : ” + value); if(value == 0 || value == null) { alert(“Please select the tablename”); } else { window.location.href = “menugetColumnDetails.action?tablename=” +tablename; } } I want to call the loadColumns() function based on the selection of sx:autocompleter (Should be a combo-box where i can select from drop-down and also i… Read more »
naveen
Guest
naveen

does this autocpmlete only work with list of string s? every where we have only this example

manish agarwal
Guest
manish agarwal

it is a good example but when resulting dropdownlist appears it overlaps with other controls over jsp page.how to solve that

saido
Guest
saido

Thank you very much

harish
Guest
harish

Action “autoCompleterAction” in struts.xml is not at all used in autocompleter.jsp how will the action class be called? dont know if thats the reason i am not able to fetch the drop down list for “Apache,……” but 1st column luckynumber is working fine.
Any help plzzzzzzzzzzz

Amit
Guest
Amit

Same here.
Any help plz

Sascha
Guest
Sascha

Hi,

“Struts 2 example

A complete example of the tag, generate the drop down suggestion lists while user typing on the corresponding text box.”

it has to be , from the dojo-tag-list, not . Headline is wrong, could be misleading. ;-)

Sascha
Guest
Sascha

It deleted my code from the comment, sorry… ;-(

Got a question though:

What if I have only an ArrayList() available in the JSP containing Database-Entity-Objects which have a property “name”, and I want to get all the names for the autocompleter… Is it somehow possible to tell “sx:autocompleter to only print the “name”-property of each object?

Bala
Guest
Bala

sx:autocompleter load the list and shows the list with matching chars typed in, but is it possible to avoid the display of the drop down list. Can it be render just as a text field with autocompleter feature.

Rose
Guest
Rose

Hi mkyong..

I am trying to implement autocompleter in struts2 since two days. The problem i am facing is, when i hardcode the list values in the tag, the autopopulate functionality works.
But when i am using the list i get in my Action class, it does not work.
below are the lines of code i used in jsp:

stateNamesList : is the arraylist of strings in action and it has getters and setters.

Please suggest.

trackback
Struts 2 Tutorial

[…] append a calender icon behind, click on the calender icon will prompt a date time picker component.autocompleter example Struts 2 <s:autocompleter>, a combo box that will automatic prompt drop down suggestion lists […]

Gaurav Goel
Guest
Gaurav Goel

Hi Sir,
Its a very good article, helped me a lot. But here is the thing, suppose the list contains thousands of results, wouldn’t it become too heavy for a single page? How do we use auto-completer in those cases?

praful
Guest
praful

Hi,
I am trying to call a javascript function onChange of the sx:autoCompleter field. Somehow it doesn’t invoke it.I am using struts 2.1.8. Is there any issue with this.

Thanks in advance.
Regards,
-Praful

TroX
Guest
TroX

Thank you very much, it works well for me :D (I just don’t know what are dojo’s dependencies for… I didn’t need them..)

Jayesh
Guest
Jayesh

Hi,

Can you tell me how to avoid the skipping of required field that we use for dojo validation in struts text box.

Regards,
Jayesh

Harsha
Guest
Harsha

Works well!
How about if I need to connect to a database to fetch the collections based on the input?

Santhosh
Guest
Santhosh

Hi,

Really gud work..superb material..

Thanks,
R.Santhosh

Stefaan Somers
Guest
Stefaan Somers
I’m trying to run it, but get the following message : C:\$user\todelete\Struts2Example>mvn jetty:run-war [INFO] Scanning for projects… [INFO] Searching repository for plugin with prefix: ‘jetty’. [INFO] ———————————————————————— [INFO] Building Struts2Example Maven Webapp [INFO] task-segment: [jetty:run-war] [INFO] ———————————————————————— [INFO] Preparing jetty:run-war [INFO] [resources:resources {execution: default-resources}] [WARNING] Using platform encoding (Cp1252 actually) to copy filtered resources, i.e. build is platform dependent! [INFO] Copying 1 resource [INFO] [compiler:compile {execution: default-compile}] [INFO] Compiling 2 source files to C:\$user\todelete\Struts2Example\target\classes [INFO] ———————————————————————— [ERROR] BUILD FAILURE [INFO] ———————————————————————— [INFO] Compilation failure C:\$user\todelete\Struts2Example\src\main\java\com\mkyong\common\action\AutoCompleterAction.java:[10,13] generics are not supported in -source 1.3 (use -source 5 or higher to enable generics)… Read more »
trackback
Struts 2 autocompleter + JSON example

[…] last Struts 2 autocompleter example, you learn about how to generate a list of the select options to the autocompleter […]

Dipak
Guest
Dipak

sorry forgot to add error page
NOTE: im using SX:URL with SX:autocomeplete…

java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.String

Dipak
Guest
Dipak
Hi, i followedthe references given by you to use with autocompleter…. but gettting error…. in my struts.xml options ======================== in my E2workAction.java public Map getOptions() { Map options = new HashMap(); options.put(“Florida”, “FL”); options.put(“Alabama”, “AL”); options.put(“Maharastra”, “MH”); options.put(“AndhraPadesh”, “AP”); return options; } ======================== in my jsp =============== in firebug im getting error… Im not able to get whats the problem… Please help…. GET http://localhost:8888/dec/getStates.html 500 Internal Server Error
Dipak
Guest
Dipak

Hi,
Yong Mook Kim
Thanks for such quick reply…..
I implemented it in my application.
I found out some points need to be taken care while implementing autocompleter…
1. We should add ‘id’ to otherwise it was not working for me.

2. We Should provide getter and setter for the list otherwise list is not accessible in jsp.