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. [sc:Struts2_Tutorials]
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"%>
Code language: HTML, XML (xml)
First define the taglib sx which we will use to add AJAX enabled tags.<sx:head/>
Code language: HTML, XML (xml)
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 fileAjaxAutocomplete.java
in net.viralpatel.struts2
package and copy following content into it. AjaxAutocomplete.javapackage 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;
}
}
Code language: Java (java)
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>
Code language: HTML, XML (xml)
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>
Code language: HTML, XML (xml)
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.
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.
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
this example is not working plz help me
Thanks viral for all Struts2 tutorial…………….
Hello patel,
Its better to put Demo link so that we can see demo live and test application ..
Hi Manjunath, Thanks.. Although I always try to add demo links for html, css, javascript tutorials; for Struts its not that simple. You’ll need a running Java container in order to execute your application which is not always feasible. Also there is no reliable Java hosting that can be used to put such live demo. I hope you can download the application and run it in your local machine with easy.
Its ok Bro.. any how great explanation yar..
i want the country,state,city 3 dependent dropdown list boxes example by using struts mvc developed using myeclipse
Even I want this, did you solve this? please let me know.
can u provide jar files also…i need it…
I try to add exact the same code but it is not working. how AjaxDemo.jsp know which action to trigger in Struts.xml. I did not see any action in JSP link to “ajaxdemo” in Struts.xml?
Hi,
Can you put on an example showing on how to pass data from one action to another action, using scopemodeldriven or scope interceptors.
the use case is like this. we use ORM , so on the retrieval entire domain object is populated , say with 20 fields in database . Now in the form I can only update 10 fields , so these 10 fields data only to be updated , but as we are using ORM we need to update the object/table which has all the 20 fields. So if I can carry that 20 fields from one action to another action and then i will update only those fields that are visible in form.
good site best example
Simply the best on web :)
Thanks !
Thanks for Struts Example.
Best and Simple,
Thanks Again
I learn a lot from this tutorial :D
Thanks !
Is there anyway to achieve pure ajax call with dojo tag? that is list should populate only after I typed any text in field.?
use 3 dependent dropdown boxes example in strutsmvc using myeclipse ide
Hey virat,
Was a great learning experience, but can u help me to autocomplete from my database so i doesnt need to populate the “list”
Hi viral……. you mentioned we can add database content in ajax feature. Like in this case name of countries are displayed. So how could i get name of countries which are in database.
hi Viral,
Your tuts are good but could have been better if you could also provide jar files.
Hello, I want to know where are declaring action name=”ajaxdemo” and where is your opening action tag.
New to struts 2.
Hi Viral,
In AjaxDemo.jsp, there is a piece of code that went in the body as below( which don’t have any sense here). But seems more html piece of code missing. Can you please clarifiy on this
Self Correction:
Please remove the tag “” in the jsp body and it works well.
Also to load the countries in the drop down, please use the link as like below which works fine to me.
link: http://localhost:8080//ajaxdemo.action
Sir,
I am getting this error
Error reading included file template/~~~ajax/controlheader-core.ftl – Class: freemarker.core.Include
Even I am facing similar issue. On exploring a bit, found its a known issue with struts 2.3.16 and did not exist in 2.3.15. Could someone please confirm is any fix is available by now or is it still an issue. The error I got is :
Error reading included file template/~~~ajax/controlheader-core.ftl
The problematic instruction:
———-
==> include “/${parameters.templateDir}/${parameters.expandTheme}/controlheader-core.ftl” [on line 23, column 1 in template/xhtml/controlheader.ftl]
in include “/${parameters.templateDir}/xhtml/controlheader.ftl” [on line 24, column 9 in template/ajax/controlheader.ftl]
in include “/${parameters.templateDir}/ajax/controlheader.ftl” [on line 23, column 1 in template/ajax/autocompleter.ftl]
———-
hai can u please give code for three dynamic dropdowns in struts2
Hi Viral, can u please post an example of struts2 with html5.
In Struts 2 , my form contains 3 fields, one fields is of type file.
in struts.xml
If we submit from normally then control goes to MonitoredMultiPartRequest , but if form sumbiteed using Ajax, then control does not go to MonitoredMultiPartRequest. How to resolve this?
n Struts 2 , my form contains 3 fields, one fields is of type file.
in struts.xml
If we submit from normally then control goes to MonitoredMultiPartRequest , but if form sumbiteed using Ajax, then control does not go to MonitoredMultiPartRequest. How to resolve this?
I use struts2-dojo-plugin-2.3.20, should be empty, but the sample code include the content below, which one is correct.
=============================================
Struts 2 Autocomplete (Drop down) Example!
Country:
=============================================
Downloaded the source file and included all the .jar files in lib as mentioned.When I run I get
HTTP Status 404 – /StrutsHelloWorld
Please help!Struggling to learn Ajax with struts
Dojo is deprecated. Dojo is deprecated. Dojo is deprecated. I mean the struts-dojo is deprecated. The standalone Dojo is good, the other one is deprecated. Don’t use it, because is deprecated.
Give Me an error exception
there is No israel !! >> Free Palestine :)
multiple dropdown list gets shown at the page by using this method
the tag is it a mistake or something is missing from this code snippet?could you please tell me
thanks in advance