Pages Navigation Menu

Coding is much easier than you think

AJAX implementation in Struts 2 using JQuery and JSON

 
Dynamic Dependent Select Box using Jquery in struts2
 
In this post, we will learn to implement AJAX calls from a JSP page to a Struts 2 Action class using JQuery and update the same JSP page back with the Json response from the Struts 2.
 

Library required

 
Since the response to be sent to jQuery is of type JSON, to handle it you need struts2-json-plugin-2.x.x.jar. This plugin allows you to serialize the Action class attribute which has getter and setter into a JSON object.
 

Steps done to set up our action for JSON

 
From the browser perspective: jQuery

jQuery allows you to issue an ajax request and expects a JSON object as a response.
 

Jsp Page

 
Now, let us create a JSP page with two drop down lists, one contains values for countries and the other that is going to be populated with values for states based on the value selected in the first drop down list. This is done without a page refresh, by making AJAX calls to the Struts 2 action on first drop down list change event.
 
Recommended reading :

 

<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>AJAX in Struts 2 using JSON and jQuery</title>
<script src="js/jquery-1.8.2.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
   $('#country').change(function(event) {
      var country = $("select#country").val();
      $.getJSON('ajaxAction', {
	countryName : country
      }, function(jsonResponse) {
	$('#ajaxResponse').text(jsonResponse.dummyMsg);
	var select = $('#states');
	select.find('option').remove();
	$.each(jsonResponse.stateMap, function(key, value) {
	  $('<option>').val(key).text(value).appendTo(select);
	});
      });
      });
});
</script>
</head>
<body>
   <h3>AJAX calls to Struts 2 using JSON and jQuery</h3>
   <s:select id="country" name="country"
	list="{'Select Country','India','US'}" label="Select Country" />
   <br />
   <br />
   <s:select id="states" name="states" list="{'Select State'}"
	label="Select State" />
   <br />
   <br />
   <div id="ajaxResponse"></div>
</body>
</html>

 
Note that I have referenced jQuery files in the head section of the jsp which is responsible for the AJAX call made to the struts 2 action and for displaying the response back in the JSP.
 
Whenever the value is selected in the “country” drop down list, its change event is fired and the ‘getJSON’ function executes ajaxAction (first argument of ‘getJSON’) configured in struts.xml. I have explained about the parameters of ‘getJSON’ method in the article here.
 
From the server’s perspective: Struts 2
 
In action class you need to create instance variables and its respective getter and setter methods. Here all the variables that have a setter can be set to the values received as parameters from jQuery and all the variables that have a getter method can be retrieved in the client javascript code.
 
Also read :

Action class

 

package com.action;

import java.util.LinkedHashMap;
import java.util.Map;

import com.opensymphony.xwork2.Action;

public class AjaxJsonAction implements Action{

private Map<String, String> stateMap = new LinkedHashMap<String, String>();
private String dummyMsg;
//Parameter from Jquery
private String countryName;

public String execute() {
	if (countryName.equals("India")) {
		stateMap.put("1", "Kerala");
		stateMap.put("2", "Tamil Nadu");
		stateMap.put("3", "Jammu Kashmir");
		stateMap.put("4", "Assam");
	} else if (countryName.equals("US")) {
		stateMap.put("1", "Georgia");
		stateMap.put("2", "Utah");
		stateMap.put("3", "Texas");
		stateMap.put("4", "New Jersey");
	} else if (countryName.equals("Select Country")) {
		stateMap.put("1", "Select State");
	}
	dummyMsg = "Ajax action Triggered";
	return SUCCESS;
}

public Map<String, String> getStateMap() {
	return stateMap;
}

public String getDummyMsg() {
	return dummyMsg;
}

public String getCountryName() {
	return countryName;
}

public void setStateMap(Map<String, String> stateMap) {
	this.stateMap = stateMap;
}

public void setDummyMsg(String dummyMsg) {
	this.dummyMsg = dummyMsg;
}

public void setCountryName(String countryName) {
	this.countryName = countryName;
}
}

 
In the above code, we create a maps and populates its value based on the country parameter passed to the action class by the AJAX call made by the JQuery’s getJSON() method.
 

struts.xml

 
Since the response needed by jQuery is of type json, so we need to convert this map objects to json strings, for this you need to configure this Action class in struts.xml such that it returns a json object. This configuration is as follows:

Create a package in struts.xml file, which extend json-default and specify the result type of your action class inside this package to be json. The json-default package contains an interceptor and the result type configuration for JSON requests and responses.

<struts>
<package name="default" extends="json-default">
   <action name="ajaxAction" class="com.action.AjaxJsonAction">
   <result type="json">
	<param name="excludeNullProperties">true</param>
	<param name="noCache">true</param>
   </result>
   </action>
</package>
</struts>

 
Note: json-default package extends struts-default

Please read the Struts 2 JSON plugin documentation for more details.

 

Web.xml

 

<display-name>Struts2</display-name>
<filter>
  <filter-name>struts2</filter-name>
  <filter-class>
    org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
  </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>

 
Recommended Article :

  • How to Call Struts2 action from java script
  •  

    Demo

     
    On selecting ‘India’ in the first dropdown list
     
    Struts2_ajax_json_jquery
     
    On selecting ‘US’ in the first dropdown list
     
    Struts2_ajax_json_jquery _2
     
    download

    About Mohaideen Jamil


    Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.