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.
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> <h4> Lucky Number : <s:property value="yourLuckyNumber"/> </h4> <h4> Web Appication Frameworks : <s:property value="yourFavWebFramework"/> </h4> </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








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.
[...] 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 [...]
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?
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
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..)
dojo added ajax effect. So, it’s still work even no dojo library is added?
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
dojo is a JavaScript library, as long as client stop the browser JavaScript support function, your validation will never execute. For critical validation, you should move it to your server side.
Works well!
How about if I need to connect to a database to fetch the collections based on the input?
Hi,
Really gud work..superb material..
Thanks,
R.Santhosh
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)
private List webframeworks = new ArrayList();
But when I check the version of Maven, I’m using the correct version :
C:\$user\todelete\Struts2Example>mvn -version
Apache Maven 2.2.1 (r801777; 2009-08-06 21:16:01+0200)
Java version: 1.6.0_17
Java home: C:\Program Files\Java\jdk1.6.0_17\jre
Default locale: nl_BE, platform encoding: Cp1252
OS name: “windows xp” version: “5.1″ arch: “x86″ Family: “windows”
You need to configure Maven to use JDK 1.5 or 1.6 compiler to compile your source, see this URL http://www.mkyong.com/maven/how-to-compile-maven-project-with-different-jdk-version/
[...] last Struts 2 autocompleter example, you learn about how to generate a list of the select options to the autocompleter [...]
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
Here’s another example using s:url and sx:autocompleter. Hope help.
http://www.mkyong.com/struts2/struts-2-autocompleter-json-example/
Hard to say what’s wrong in your code, unless i have the full codes, please refer to the above link. If it’s still not working, may be you can drop me a mail with your project attach.
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
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.
Thanks for sharing your thoughts on this.
But the point 1 is not necessary, check this url – http://struts.apache.org/2.1.8/docs/autocompleter.html , the “id” is not a require field.