Struts 2 AJAX Autocomplete dropdown example

I started playing with struts 2.0.14 showcase application and thought of extracting a simple AJAX Autocomplete dropdown example from it.
In this example I am trying to create a autocomplete textbox and when you select one value from this autocomplete drop down the other will populate accordingly.

This post is for developers who are new to Struts 2.

This example uses

- Struts 2.0.14 - Download Struts
- apache-tomcat-6.0.18 - Download Tomcat
- java version "1.6.0_10"
- freemarker template (2.3.8) for the second dropdown.

You can use this example as is or play around with it based on your need.

index.jsp :

This page redirects the request to the demo page where autocomplete text box is diplayed.


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



autocomplete.jsp

This page contains the core of this example, the Struts tags for Autocomplete.

  
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<s:head theme="ajax"/>
<html>
<head>
<title>AutoComplete</title>
</head>
<body>
<s:url id="detailUrl" action="DetailResponse"/>

Link two autocompleter elements. When the selected value in 'Autocompleter 1' changes,
the available values in 'Autocompleter 2' will change also.
<br/>
<form id="selectForm">
<p>Autocompleter 1 <s:autocompleter theme="simple" name="select" list="selectList" value="Colors" notifyTopics="/Changed" forceValidOption="true" id="sel"/></p>
</form>
Autocompleter 2 <s:autocompleter theme="ajax" href="%{#detailUrl}" autoComplete="false" formId="selectForm" listenTopics="/Changed" forceValidOption="true" id="ops"/>
</body>
</html>



options.ftl

This is Freemarker template to render the second drop down, which is populated based on selection in first autocomplete drop down.

  
[
<#list options as option>
["${option}"],

]


ListingAction.java

This action class is to populate values in the first autocomplete drop down.

  

package ajaxdemo.action;

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

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class ListingAction extends ActionSupport {
private List selectList = null;

public String execute() throws Exception {
selectList = new ArrayList();
selectList.add("Fruits");
selectList.add("Colors");
return SUCCESS;
}

public List getSelectList() {
return selectList;
}

public void setSelectList(List selectList) {
this.selectList = selectList;
}

}


DetailAction.java

This is a action class to populate the second autocomplete drop down based on selection value in first drop down.

  
package ajaxdemo.action;

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

import com.opensymphony.xwork2.ActionSupport;

public class DetailAction extends ActionSupport {
private String select;
private List options = new ArrayList();

private static final long serialVersionUID = -8481638176160014396L;

public String execute() throws Exception {
if ("Fruits".equalsIgnoreCase(select)) {
options.add("apple");
options.add("banana");
options.add("grape");
options.add("pear");
} else if ("Colors".equalsIgnoreCase(select)) {
options.add("red");
options.add("green");
options.add("blue");
}
return SUCCESS;
}

public String getSelect() {
return select;
}

public void setSelect(String select) {
this.select = select;
}

public List getOptions() {
return options;
}
}


struts.xml

Struts config file for action mappings.

  

<?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>
<package name="demo" extends="struts-default">
<action name="ShowDemo" class="ajaxdemo.action.ListingAction">
<result>/autocomplete.jsp</result>
</action>
<action name="DetailResponse" class="ajaxdemo.action.DetailAction">
<result type="freemarker">/options.ftl</result>
</action>
</package>
</struts>



web.xml

The application deployment descriptor.

  

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>



Output

Go the URL http://localhost:8080/ajaxdemo/ in your favorite web browser. The page should look like this.




Web application directory Structure
This is how the application war directory structure should look like.



  
ajaxdemo/
ajaxdemo/index.jsp
ajaxdemo/autocomplete.jsp
ajaxdemo/options.ftl
ajaxdemo/WEB-INF/web.xml
ajaxdemo/WEB-INF/classes/struts.xml
ajaxdemo/WEB-INF/classes/ajaxdemo/action/DetailAction.class
ajaxdemo/WEB-INF/classes/ajaxdemo/action/ListingAction.class
ajaxdemo/WEB-INF/lib/*.jar



Here are the list of jar files you need to have in your application WEB-INF/lib dir.

  

antlr-2.7.2.jar
aopalliance-1.0.jar
classworlds-1.1.jar
commons-beanutils-1.7.0.jar
commons-chain-1.1.jar
commons-codec-1.3.jar
commons-collections-2.1.jar
commons-collections-3.1.jar
commons-digester-1.6.jar
commons-digester-1.8.jar
commons-el-1.0.jar
commons-fileupload-1.1.1.jar
commons-io-1.1.jar
commons-lang-2.1.jar
commons-logging-1.0.4.jar
commons-logging-api-1.1.jar
commons-validator-1.3.0.jar
dwr-1.1-beta-3.jar
freemarker-2.3.8.jar
jstl-1.1.0.jar
log4j-1.2.9.jar
myfaces-api-1.1.2.jar
myfaces-impl-1.1.2.jar
ognl-2.6.11.jar
oro-2.0.8.jar
plexus-container-default-1.0-alpha-10.jar
plexus-utils-1.2.jar
sitemesh-2.2.1.jar
spring-beans-2.0.5.jar
spring-context-2.0.5.jar
spring-core-2.0.5.jar
spring-web-2.0.5.jar
struts-core-1.3.5.jar
struts2-codebehind-plugin-2.0.14.jar
struts2-config-browser-plugin-2.0.14.jar
struts2-core-2.0.14.jar
struts2-jsf-plugin-2.0.14.jar
struts2-sitemesh-plugin-2.0.14.jar
struts2-struts1-plugin-2.0.14.jar
struts2-tiles-plugin-2.0.14.jar
tiles-api-2.0.4.jar
tiles-core-2.0.4.jar
tiles-jsp-2.0.4.jar
velocity-1.4.jar
velocity-dep-1.4.jar
velocity-tools-1.1.jar
xml-apis-1.0.b2.jar
xwork-2.0.7.jar




Download ajaxdemo.war here


struts form, struts 2 ajax autocomplete drop down code example, Struts2 ajax autocomplete tutorial with sample code, struts 2 ajax auto complete drop down code download, struts training, apache struts training online

18 Post Comment

Dave said...

Hey, Thanks for this handy example. I just tried running the same code using Struts 2.1.8 dependancies and got this error. Do you have some clue?

SEVERE: Exception starting filter struts2
Class: com.opensymphony.xwork2.spring.SpringObjectFactory
File: SpringObjectFactory.java
Method: getClassInstance
Line: 209 - com/opensymphony/xwork2/spring/SpringObjectFactory.java:209:-1
at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:431)
at org.apache.struts2.dispatcher.FilterDispatcher.i n it(FilterDispatcher.java:190)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:275)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:397)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:108)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:3709)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4363)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:830)
at org.apache.catalina.startup.HostConfig.deployWARs(HostConfig.java:719)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:490)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1149)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:578)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.NullPointerException
at com.opensymphony.xwork2.spring.SpringObjectFactory.getClassInstance(SpringObjectFactory.java:209)
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.verifyResultType(XmlConfigurationProvider.java:519)
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addResultTypes(XmlConfigurationProvider.java:490)
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.addPackage(XmlConfigurationProvider.java:446)
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.loadPackages(XmlConfigurationProvider.java:264)
at org.apache.struts2.config.StrutsXmlConfigurationProvider.loadPackages(StrutsXmlConfigurationProvider.java:111)
at com.opensymphony.xwork2.config.impl.DefaultConfiguration.reloadContainer(DefaultConfiguration.java:193)
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:55)
at org.apache.struts2.dispatcher.Dispatcher.in it_PreloadConfiguration(Dispatcher.java:374)
at org.apache.struts2.dispatcher.Dispatcher.in it(Dispatcher.java:418)
... 28 more
Oct 29, 2009 5:43:17 PM org.apache.catalina.core.StandardContext start
SEVERE: Error filterStart

Software Wikipedia said...

@Dave - I have not tested this example on Struts 2.1.8 and from my experience I can say it will NOT work as it is.

1. I tried running this directly on struts 2.1.8 dependencies and I can see there are much more errors to fix.

2. There are some tag lib changes in Struts 2.1.8 which needs to be incorporated in the JSPs.

3. Will update this post if I am able to get a Struts 2.1.8 version for same example.

BTW, on a sidenote, I don't really understand why Struts 2.1.8 is not easily backward compatible with 2.0.14?

Software Wikipedia said...

Update 1: I tried checking the showcase application for struts 2.1.8 and it seems this example doesn't work on showcase application either. So there must be something broken in 2.1.8

Shashi said...

Hi ,
I worked with this code , it works successfully it shows the value into the 1st dropdown list .
we are able to select the value from 1st dropdown list but second dropdown list is empty....
could you tell me reson....

Anonymous said...

hi

I want to populate table from database using autocompleter value. any help will be appreciated.
thanks

Java said...

WTHAT'S DIS..WHY SO MANY JARS...SPRING JARS ETC ????

Java said...

how to implement this in Struts 2.2 or struts 2.3...we dont have struts' autocompleter tag..we have struts' dojo tag..
do anyone know anything about this???

Anonymous said...

above code in not working

Anonymous said...

No one would like to be forced to help make their exercising tools a
part with the room furnishings.

Feel free to visit my web-site :: bowflex selecttech 552 adjustable dumbbells pair

Anonymous said...

That you are accomplishing exercises and also your body completely requirements calories.


Also visit my weblog Góra strony

Anonymous said...

The inside workouts tend to be more strength education that
cardio.

Here is my blog :: bowflex dumbbells

Anonymous said...

After you use air as your resistance mechanism you increase or decrease the resistance according for your personal efforts, which means you have
got quite a bit considerably less chance of overdoing it
or injuring on your own.

Have a look at my blog; bowflex selecttech 552 dumbbells used

Anonymous said...

my code is working but second drop down don't work..
can u tell me the reason??

groovy said...

Chained autocomplete would be very cool as an example

Anonymous said...

nike free, kate spade outlet, prada handbags, coach factory outlet, oakley sunglasses, true religion, coach purses, oakley sunglasses, louboutin, michael kors outlet, ray ban, louis vuitton outlet online, jordan shoes, coach factory, longchamp outlet, ray ban sunglasses, louis vuitton handbags, coach outlet, nike shoes, true religion outlet, tiffany and co, michael kors outlet, true religion jeans, oakley sunglasses, gucci outlet, louboutin, chanel handbags, polo ralph lauren outlet, oakley sunglasses, ray ban sunglasses, toms shoes, oakley sunglasses, tory burch outlet, air max, coach outlet store, nike air max, polo ralph lauren, burberry outlet online, burberry outlet online

Anonymous said...

air max, nfl jerseys, nike free, marc jacobs, chi flat iron, air max, hogan, air jordan, nike free, mcm handbags, new balance shoes, ghd, mont blanc, louis vuitton, yoga pants, louis vuitton, bottega, karen millen, longchamp, juicy couture outlet, louboutin, abercrombie and fitch, rolex watches, nike air max, ralph lauren, reebok outlet, birkin bag, ralph lauren, nike air max, vans, lancel, north face outlet, insanity, supra shoes, lululemon, ferragamo shoes, beats by dre, timberland, hollister, converse shoes, mulberry

pai young said...

Shame uttered after, his face flushed pity if the text is difficult to maintain a normal state of mind is no longer North Face Fleece Clearance under Cheap North Face Fleece the watchful eyes and ran away like jumped out of the ring disappeared in the crowd.

A corner of the edge North Face Fleece Jackets of the grandstand, a fluttering white woman body trembling, peerless extremely pale face at this time, perhaps, ultimately this is a dream, right Goodbye North Face Fleece Clearance language under North Face Fleece Sale pale beauty, beautiful eyes of sadness in two lines of tears shed down, long-sleeved Qingbai, already turned quietly away.

These certainly do not North Face Fleece Sale know that he was also fascinated on a pair of soft, without the slightest North Face Fleece Jackets relenting meaning. Whining. Originally indulge them if unfortunately the referee gave the Qing Ke Wen suddenly woke up, I do not know where's an effort to one open.

pai young said...

Pas cher pas de mots ont immédiatement pris le téléphone et moncler pas cher composer le moncler pas cher numéro de la maison pas cher. Non loin derrière celle de la moncler pas cher brique suivante est cachée moncler pas cher Qui ne doudoune moncler pas cher connaît pas un héros sur le champ moncler pas cher de bataille est toujours le premier à mourir. Porte céleste. moncler pas cher Homme émacié dit que deux mots, moncler pas cheroncle Sept frère envoyé, oncle Sept en ce moment à travers le téléphone avec l'oncle Sept, il a déclaré que le jour de la porte, l'autre moncler soldes n'a pas dit, j'ai vu le gars a pris Allen l'appel téléphonique . moncler pas cher Qu'est-ce que vous avez dit.

Post a Comment

Search Web......