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. [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 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; } }
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.

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.

View Comments

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

    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.

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

Share
Published by
Viral Patel
Tags: AJAX Struts Struts2 struts2-series

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago