Struts 2 Ajax Tutorial with Example

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.

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.
struts2-ajax-jar-files

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.
struts2-ajax-drop-down

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.



55 Comments

  • Ann 12 March, 2010, 20:12

    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..

  • SV 3 May, 2010, 20:31

    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)

  • Julien 15 May, 2010, 23:42

    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,

  • Michael Phoenix 14 July, 2010, 0:55

    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.

  • dWang 4 August, 2010, 18:02

    the dropdown list is not working

  • Anu 17 August, 2010, 2:38

    If you add the same library(jar) files it works fine.

  • Anu 17 August, 2010, 2:40

    Hi Viral, Excellent Job. I have tried all the Struts2 tutorials. Thanks for the cool tutorials

  • reza 19 October, 2010, 13:07

    hi Anu,

    what jars did you add?

  • Furqan 19 October, 2010, 16:18

    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

  • Larry 20 October, 2010, 15:38

    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.

  • chengaReddy 23 October, 2010, 15:20

    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

  • gasper 27 December, 2010, 22:25

    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 ?

    • Viral Patel 27 December, 2010, 22:29

      @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 :)

  • sriram 6 January, 2011, 10:31

    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..

  • Amit K 3 March, 2011, 18:03

    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

  • Jayesh 16 March, 2011, 0:27

    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

  • KB 12 April, 2011, 21:16

    The article didn’t mention about adding this entry to tiles.xml (though your downloadable source code has it) :

  • pratibha 18 July, 2011, 19:28

    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

  • Boyko 5 August, 2011, 19:23

    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

  • vrk 24 August, 2011, 8:45

    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

  • jcarlos 9 September, 2011, 4:58

    Hi. I have problem with ajax example . I use all jars with the same version. please upload the example + jars..

    • jcarlos 9 September, 2011, 5:50

      Hi again.. nice tutorial. people the example with ajax and others use apache-tomcat-7.0.20.. and fun ….XD

  • Murali dharan.E 20 September, 2011, 19:26

    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….

    • Murali dharan.E 20 September, 2011, 19:28

      For what purpose You have given action tag after closing autocompleter…

  • Murali dharan.E 20 September, 2011, 19:29

    In AjaxDemo.jsp what is /action tag ??????

  • Murali dharan.E 20 September, 2011, 19:31

    In AjaxDemo.jsp
    Why do want to give /action tag?????

  • swathi 27 September, 2011, 15:48

    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…

  • José Manuel 12 December, 2011, 3:37

    Hello,

    Do you ppl know if Struts 2 is supporting Dojo plugin in the future?

    ty

  • Abhi 18 December, 2011, 16:15

    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.

  • Ankit 19 December, 2011, 11:41

    Nice example to understand the basic functionality…..

    Thanx
    Ankit

  • lokesh 28 December, 2011, 19:21

    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)

  • Everett Zhou 29 December, 2011, 19:50

    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.

  • Everett Zhou 29 December, 2011, 19:51

    All those tags in my above post are gone.

  • BainS 30 December, 2011, 19:05

    Thanks for this nice example… Could you please provide an example on using log4j logger utility in struts2 ??

  • Arivudainambi 3 January, 2012, 20:00

    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

  • sunil 7 January, 2012, 16:13

    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…

  • Girish 9 January, 2012, 0:17

    Very Clear Explanation…. Helps a lot … Hope to see more extensions, as there is still lot about struts 2 ….

  • as 1 March, 2012, 14:43

    Very Clear Explanation…. Helps a lot … Hope to see more extensions, as there is still lot about struts 2

  • as 1 March, 2012, 14:44

    one bug detected.

  • Mohammad Zeeshan 26 March, 2012, 16:54

    Very straightforward and to-the-point tutorial.

  • Vijay 30 April, 2012, 16:56

    Thanks Viral! I tried ur autocomplete example and it worked fine.Tanks A lot!

  • avs 4 May, 2012, 12:25

    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&#040;Ljava/lang/String&#059;Ljava/lang/Class&#059;Z&#041;Ljava/lang/Object&#059;
    	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'.
    
    • Viral Patel 8 May, 2012, 0:30

      Check the version of Struts2 JARs you using in project. This seems to be issue with version mismatch.

  • Andre Morua 18 June, 2012, 17:24

    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

    • Viral Patel 18 June, 2012, 17:40

      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.

  • ramesh 13 July, 2012, 17:08

    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

  • selven 20 July, 2012, 14:38

    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!

  • Gaurav 31 July, 2012, 15:23

    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.

  • rahul Shukla 21 August, 2012, 14:33

    could i able to know which struts version compatible with Ajax auto completer tag.
    Because in my case auto completer is not working.

  • Thae Ei Htwe 16 November, 2012, 11:03

    Hi Viral Patel,
    Thanks for your struts 2 examples, it’s very helpful to me.
    I absolutely love it.

  • Tushar 3 December, 2012, 1:44

    Could you write for simple web application using Struts2-jQuery plugin to populate data in grid

  • Ajit Shetty 9 January, 2013, 15:58

    Good Explanation. Thanx Viral.

  • nizar 15 January, 2013, 16:23

    thanks very much !!!!
    it’s work
    i passed a long time to search a solution
    with your code it’s ok
    thanks !!

  • vaibhav 14 February, 2013, 12:28

    thanks
    but there no need to create getter/setter of public String country

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]