Struts 2 Ajax Tutorial with Example
- By Viral Patel on January 13, 2010
Welcome to the last part of 7 article series of Struts 2 Framework tutorials. In previous article we saw how to implement File Upload functionality in Struts 2. In this article we will see how we can implement Ajax support in a webapplication using Struts2 framework.
Struts 2 Tutorials
- Part 1: Introduction to Struts 2
- Part 2: Create Hello World Application in Struts 2
- Part 3: Struts 2 Validation Framework Tutorial with Example
- Part 4: Struts 2 Tiles Plugin Tutorial with Example
- Part 5: Struts 2 Interceptors Tutorial with Example
- Part 6: Struts 2 File Upload and Save Example
- Part 7: Struts 2 Ajax Tutorial with Example
AJAX support in Struts 2
Struts 2 provides built-in support to AJAX using Dojo Toolkit library. If you are new to Dojo, you may want to go through the Introduction of DOJO Toolkit.
Struts 2 comes with powerful set of Dojo AJAX APIs which you can use to add Ajax support. In order to add Ajax support, you need to add following JAR file in your classpath:
struts2-dojo-plugin.jar
Also once we add this JAR file, we need to add following code snippet in whatever JSP file we need to add AJAX support.
<%@ taglib prefix="sx" uri="/struts-dojo-tags"%>
First define the taglib sx which we will use to add AJAX enabled tags.
<sx:head/>
Add this head tag in your JSP between <head> … </head> tags. This sx:head tag will include required javascript and css files to implement Ajax.
AJAX Example: Struts2 Ajax Drop Down
Let us add simple AJAX support in our StrutsHelloWorld web application. We will use the base code that we used in previous articles and add Ajax on top of it.
We will create a drop down which will Autocomplete and suggest the input. For this we will add Dojo support to our webapp.
Step 1: Adding JAR file
As discussed earlier we will add struts2-dojo-plugin.jar in classpath (WEB-INF/lib). Thus, following is the list of required jar files. Note that these jars are needed to run full application including all the samples of previous parts of this tutorial series.

Step 2: Create AJAX Action class
We will create an action class which will get called for our Ajax example. Create a file AjaxAutocomplete.java in net.viralpatel.struts2 package and copy following content into it.
AjaxAutocomplete.java
package net.viralpatel.struts2;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import com.opensymphony.xwork2.ActionSupport;
public class AjaxAutocomplete extends ActionSupport {
private String data = "Afghanistan, Zimbabwe, India, United States, Germany, China, Israel";
private List<String> countries;
private String country;
public String execute() {
countries = new ArrayList<String>();
StringTokenizer st = new StringTokenizer(data, ",");
while (st.hasMoreTokens()) {
countries.add(st.nextToken().trim());
}
return SUCCESS;
}
public String getCountry() {
return this.country;
}
public List<String> getCountries() {
return countries;
}
public void setCountries(List<String> countries) {
this.countries = countries;
}
public void setCountry(String country) {
this.country = country;
}
}
In above code we have created a simple action class with attribute String country and List countries. The countries list will be populated with country names when execute() method is called. Here for this example, we have loaded static data. You may feel free to change this and add data from database.
Step 3: Create JSP
Create JSP file to display Autocomplete textbox for our Ajax action. Create AjaxDemo.jsp in WebContent directory.
AjaxDemo.jsp
<%@ page contentType="text/html; charset=UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags"%> <%@ taglib prefix="sx" uri="/struts-dojo-tags"%> <html> <head> <title>Welcome</title> <sx:head /> </head> <body> <h2>Struts 2 Autocomplete (Drop down) Example!</h2> Country: <sx:autocompleter size="1" list="countries" name="country"></sx:autocompleter> </action> </body> </html>
In above JSP file we have used sx:autocompleter tag to render an autocomplete drop down which users Ajax class to fetch data internally. Note that we have mapped the list attribute with List countries.
Step 4: Creating Struts.xml entry
Add following action entry in Struts.xml file:
<action name="ajaxdemo" class="net.viralpatel.struts2.AjaxAutocomplete"> <interceptor-ref name="loggingStack"></interceptor-ref> <result name="success" type="tiles">/ajaxdemo.tiles</result> <result type="tiles">/ajaxdemo.tiles</result> </action>
Notice that we are using Tiles here in this example. You may want to use AjaxDemo.jsp instead of /ajaxdemo.tiles to render the output directly in JSP.
That’s All Folks
Compile and Run the application in eclipse.

Download Source Code
Click here to download Source Code without JAR files (24KB)
Conclusion
Struts2 Framework provides wide variety of features to create a rich web application. In this Struts2 series we saw different aspects of Struts 2 like introduction of struts2, hello world application, validation framework, tiles plugin, strurts2 interceptors, file upload and ajax support.
Get our Articles via Email. Enter your email address.
hi..
I tried the helloworld appin part 2..donno what happened, but it wasnt working at all..and 2-3 days I played around with it with no luck..today I just saw that this app has exactly the jar files I have and i just tried, luckily its working..phew!!
Now I need to go in detail to the specifics..to see what happened wrong last time..mostly some jar file mismathc i guess..
Anyways thanks..
hi
Hi-
I have tried the above example and it is not working for me, may be I am missing something which I was unable to figure out. Here the error log that I am getting:
I have included all the dependency jars, still I am getting the below error. There are two jars in my project library which has the class ValueStack, xwork-2.1.2.jar & xwork-core-2.1.5.jar. I even tried keeping one at a time, still getting the same error. Please help me to resolve this issue.
Thanks in advance.
org.apache.jasper.JasperException: javax.servlet.ServletException: java.lang.NoSuchMethodError: com.opensymphony.xwork2.util.ValueStack.findValue(Ljava/lang/String;Z)Ljava/lang/Object;
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:527)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:401)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
I have the same problem
, help:
java.lang.NoSuchMethodError: com.opensymphony.xwork2.util.ValueStack.findValue(Ljava/lang/String;Ljava/lang/Class;Z)Ljava/lang/Object;
at org.apache.struts2.components.Component.findValue(Component.java:382)
at org.apache.struts2.components.UIBean.evaluateParams(UIBean.java:668)
at org.apache.struts2.components.UIBean.end(UIBean.java:510)
at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:42)
at org.apache.jsp.pages.choice1_jsp._jspx_meth_s_005ftextfield_005f0(choice1_jsp.java:290)
at org.apache.jsp.pages.choice1_jsp._jspx_meth_s_005fform_005f0(choice1_jsp.java:144)
Don’t know what’s the problem… Can I have some help ?
Thanks,
Correction:
You need to be more explicit how to get this to run. A couple of things that should be added to the tutorial:
1) Code for the tiles.xml file, simialr to the following:
2) Instructions telling the user to use “ajaxdemo” in the URL when running the application: http://localhost:8080/StrutsTutorial/ajaxdemo.
If you try to run it given only the instructions here, you end up getting a 404 or 500 http error.
the dropdown list is not working
If you add the same library(jar) files it works fine.
Hi Viral, Excellent Job. I have tried all the Struts2 tutorials. Thanks for the cool tutorials
hi Anu,
what jars did you add?
I have tried the above example the customer add and file upload modules modules are working properly.
The autocomplete ajax is not fetching the array list .. anyone has any clue
Furqan, i’m having the same issue. I’m guessing it has something to do with a lack of a method=”execute” in AjaxDemo.jsp but i’m not sure.
Hi viralpatel
iam using struts2.0 i need to use autocompleter .itry with <s:autocompleter autoComplete="true" theme="ajax" list="domainVO.glPricingVO.pricingRecordVO.autoClassCode" name="domainVO.glPricingVO.pricingRecordVO.classCode" id="classCode_”> its not working iam using without tiles .i need to aply inside table 1colums with 10 rows .i want to enter state code or description .please suggest me its very needfulll Thnks
Simingly, there is a bug in your example, the country israel doesn’t existe in the List. Are you sure that you use the same example ?
@Gasper: Thanks for pointing out the bug. It seems that my working copy was different and I forgot to update the country list with Israel. I have updated now
I am very new to struts2.. So, can someone explain how this code can be used to “select multiple values separated by a delimiter” Eg: Languages: C++; Java; PHP?
I have to use struts2, AJAX autocompleter, jsp in my web application. Can you point me to some example explained properly..
Hi Viral,
I have a requirement of adding the above functionality to the dynamically added row in javascript.
var newRow = table.insertRow(1);
oCell = newRow.insertCell(3);
ocell.innerHTML = assign that ajax supported select box.
Not sure whether its acheivable.
Thanks
Amit
Hi,
I am facing issue while using the required attribute of the dojo. Its not working it gets skipped while using with struts2 textfield. Can you tell me how to stop this rendering or make the change in this behaviour of required field of struts text field.
Regards,
Jayesh
The article didn’t mention about adding this entry to tiles.xml (though your downloadable source code has it) :
Hello,
When I try n load more than 100 data here, I get the typical IE error of “Stop running this script”, Can you please tell what could be the reason
hi i download above code and add required jar but i get below error
SEVERE: Actual exception
Caught Exception while registering Interceptor class net.viralpatel.struts2.interceptor.MyLoggingInterceptor – interceptor – file:/D:/pratik/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/StrutsHelloWorld/WEB-INF/classes/struts.xml:20:69
at org.apache.struts2.impl.StrutsObjectFactory.buildInterceptor(StrutsObjectFactory.java:77)
at com.opensymphony.xwork2.config.providers.InterceptorBuilder.constructInterceptorReference(InterceptorBuilder.java:59)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ClassNotFoundException: net.viralpatel.struts2.interceptor.MyLoggingInterceptor
at org.apache.struts2.impl.StrutsObjectFactory.buildInterceptor(StrutsObjectFactory.java:52)
… 25 more
6 Aug, 2010 7:43:14 AM com.opensymphony.xwork2.util.logging.commons.CommonsLogger error
SEVERE: Dispatcher initialization failed
Unable to load configuration. – action – file:/D:/pratik/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/StrutsHelloWorld/WEB-INF/classes/struts.xml:28:47
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:58)
at java.lang.Thread.run(Unknown Source)
Caused by: Action class [net.viralpatel.struts2.LoginAction] not found – action – file:/D:/pratik/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/StrutsHelloWorld/WEB-INF/classes/struts.xml:28:47
at com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.verifyAction(XmlConfigurationProvider.java:409)
… 15 more
6 Aug, 2010 7:43:14 AM org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter struts2
Unable to load configuration. – action – file:/D:/pratik/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/StrutsHelloWorld/WEB-INF/classes/struts.xml:28:47
at org.apache.struts2.dispatcher.Dispatcher.init(Dispatcher.java:431)
at java.lang.Thread.run(Unknown Source)
Caused by: Unable to load configuration. – action – file:/D:/pratik/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/StrutsHelloWorld/WEB-INF/classes/struts.xml:28:47
at com.opensymphony.xwork2.config.ConfigurationManager.getConfiguration(ConfigurationManager.java:58)
… 13 more
Caused by: Action class [net.viralpatel.struts2.LoginAction] not found – action – file:/D:/pratik/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/StrutsHelloWorld/WEB-INF/classes/struts.xml:28:47
Hi
i want to display table from database by selecting value from select box and the select box and table should be in same page. how to achive this using ajax and struts 2.
thanks
Hi. I have problem with ajax example . I use all jars with the same version. please upload the example + jars..
Hi again.. nice tutorial. people the example with ajax and others use apache-tomcat-7.0.20.. and fun ….XD
If you are providing tutorial, That shoul be very clear.
Less Explanation !! And google is giving importance for this site..
For what purpose you have given after …
Why do you want to post such like tutorial with lot of errors….
For what purpose You have given action tag after closing autocompleter…
In AjaxDemo.jsp what is /action tag ??????
In AjaxDemo.jsp
Why do want to give /action tag?????
Hi,
I want to change the name of checkbox dynamically in jsp.and then the values of this checkbox should be accessed in struts2.0 action file
How can I??
Waiting for reply…
Hello,
Do you ppl know if Struts 2 is supporting Dojo plugin in the future?
ty
Hello Viral,
I am developing application using struts 2 .On entering username and passwd I want to check for username n passwd in one file.after successful login,I want to display acount details for that user(fetching from file) in my welcome page.but i am unable to get that acount details.
Please help me in this.
many thanks in advance.
Nice example to understand the basic functionality…..
Thanx
Ankit
I download application from the above link Click here to download Source Code without JAR files (24KB) it is not working
please any body help me i am new for struts 2……..
i am getting error is ………….
Servlet.service() for servlet jsp threw exception
org.apache.jasper.JasperException: /AjaxDemo.jsp(3,46) File “/struts-dojo-tags” not found
at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:40)
at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:407)
at java.lang.Thread.run(Unknown Source)
Dec 28, 2011 7:01:17 PM org.apache.tiles.jsp.taglib.RoleSecurityTagSupport doEndTag
SEVERE: IO Error executing tag: JSPException including path ‘/AjaxDemo.jsp’.
org.apache.tiles.util.TilesIOException: JSPException including path ‘/AjaxDemo.jsp’.
at org.apache.tiles.servlet.context.ServletTilesRequestContext.wrapServletException(ServletTilesRequestContext.java:300)
I have two questions:
1. In AjaxDemo.jsp, there is tag. Do we really need it? If we do, where is the open tag?
2. in struts.xml, after I add
/ajaxdemo.tiles
/ajaxdemo.tiles
I got the error, saying “Multiple results with the name success not allowed”.
I think it causes error, because we already have:
/welcome.tiles
Login.jsp
Please spend a few minutes to give some explanation.
many thanks.
All those tags in my above post are gone.
Thanks for this nice example… Could you please provide an example on using log4j logger utility in struts2 ??
Hi Patel,
it is excellent and I have tried all the examples and these are working fine after some lib depencies I have resolved.
thanks and keep it up !
Nambi
It is ok.
here my query is that…
how get List which is stored in Database table.
like example .. when i enter only ‘a’ in textbox that time all data which started with ‘a’ in database field display..
in short data display through database not a manually enter String…
Very Clear Explanation…. Helps a lot … Hope to see more extensions, as there is still lot about struts 2 ….
Very Clear Explanation…. Helps a lot … Hope to see more extensions, as there is still lot about struts 2
one bug detected.
Very straightforward and to-the-point tutorial.
Thanks Viral! I tried ur autocomplete example and it worked fine.Tanks A lot!
Hi-
I have tried the above example and it is not working for me, may be I am missing something which I was unable to figure out. Here the error log that I am getting:
I have included all the dependency jars, still I am getting the below error. There are two jars in my project library which has the class ValueStack, xwork-2.1.2.jar & xwork-core-2.1.5.jar. I even tried keeping one at a time, still getting the same error. Please help me to resolve this issue.
Thanks in advance.
[5/4/12 12:29:29:145 IST] 00000046 servlet E com.ibm.ws.webcontainer.servlet.ServletWrapper service SRVE0014E: Uncaught service() exception root cause /jsp/mastType.jsp: com.ibm.websphere.servlet.error.ServletErrorReport: java.lang.NoSuchMethodError: com/opensymphony/xwork2/util/ValueStack.findValue(Ljava/lang/String;Ljava/lang/Class;Z)Ljava/lang/Object; at org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:695) at com.ibm._jsp._mastType._jspService(_mastType.java:101) at com.ibm.ws.jsp.runtime.HttpJspBase.service(HttpJspBase.java:99) Caused by: java.lang.NoSuchMethodError: com/opensymphony/xwork2/util/ValueStack.findValue(Ljava/lang/String;Ljava/lang/Class;Z)Ljava/lang/Object; at org.apache.struts2.components.Component.findValue(Component.java:382) at com.ibm._jsp._mastType._jspService(_mastType.java:93) ... 122 more [5/4/12 12:29:29:148 IST] 00000046 RenderTag E org.apache.tiles.jsp.taglib.RenderTag doEndTag IO Error executing tag: JSPException including path '/jsp/mastType.jsp'. org.apache.tiles.util.TilesIOException: JSPException including path '/jsp/mastType.jsp'.Check the version of Struts2 JARs you using in project. This seems to be issue with version mismatch.
What the sence to copy everything from apache documents. Nothing new ….
No jars? Wow, it is good light weight. Where is a reference to jar.
Where is pom.xml? if there is no jars?
Please don’t trash the cyber space — it is important today.
-Andre
Hi Andre, No pom.xml because this is not a maven project. Next you can see the list of JAR files in the screenshot above. Also this tutorial is part of Struts 2 Tutorial series, so you can get all the required JARs in previous articles.
There’s no clarity in the application. Where is /ajax-tiles page i did n’t get u
Can send the calrification regarding this.
Because i am new to struts2.
Thanks in advnce
Magnificent!! Viral your writings are so interesting and I love to read the whole tutorials, and really appreciate for sharing helpful and interesting information. Thanks a lot!
I want to develop a utility to upload files using AJAX in struts2. I tried to search for any samples or examples on the web but didnt find anything of much help. Can you please guide me in doing this? Again my requirement is to have a file upload feature in struts 2 using AJAX so that the page does not get refreshed after the upload.
thanks.
could i able to know which struts version compatible with Ajax auto completer tag.
Because in my case auto completer is not working.
Hi Viral Patel,
Thanks for your struts 2 examples, it’s very helpful to me.
I absolutely love it.
Could you write for simple web application using Struts2-jQuery plugin to populate data in grid
Good Explanation. Thanx Viral.
thanks very much !!!!
it’s work
i passed a long time to search a solution
with your code it’s ok
thanks !!
thanks
but there no need to create getter/setter of public String country