Ajax Dynamic Content with Struts2, JQuery and JSON plugin
Ajax, Java EE, JQuery, Struts2 July 12th, 2009
This guide explains how to create a simple web application that dynamically populates a page through AJAX, using both Struts2 and the JSON features of JQuery.
First of all it’s required the Json Plugin (available at http://jsonplugin.googlecode.com) that should be placed in the /WEB-INF/lib/ directory (where obviously are placed all the Struts2 jar as explained in other tutorials of this site).
The plugin adds (through its struts-plugin.xml) a new result type defined this way:
<package name="json-default" extends="struts-default"> <result-types> <result-type name="json" class="com.googlecode.jsonplugin.JSONResult"/> </result-types> ... </package>
Since it’s defined in the json-default package, in order to use that result inside custom action mappings, there are two choices:
- the packages containing actions with
jsonresult-type have to extend the packagejson-defaultand not, as usual, thestruts-defaultpackage - in the packages where
jsonresult-type is used, it’s to possible to add the previous<result-types>...</result-types>lines that simply refers to a class contained in the json plugin.jaradded to the application.
It’s now possible to define action mappings using json as result type, like the following one:
<package name="testPackage" extends="json-default" namespace="/test"> <action name="giveMeJsonData" class="testAction" method="giveMe"> <result type="json"> <param name="root">jsonData</param> </result> </action> ... </package>
The above definition states that the url /test/giveMeJsonData.action will cause the execution of the method public String giveMe() defined inside the class testAction (in this case it’s a Spring managed bean, but it can be even a qualified name of a Struts2 action class, obviously extending ActionSupport class).
The result of that action (with a SUCCESS result code) is the json data structure stored in the jsonData property of the action class, and so available through its getter getJsonData().
An example of the behavior for giveMe() method:
public String giveMe() {
jsonData = new LinkedHashMap<String, Object>();
jsonData.put("shoppingCartId", getCartId());
jsonData.put("datetime", new Date());
Set<Map<String, Object>> items = new HashSet<Map<String, Object>>();
for (Item item : businessMethod.findItemsForCart(getCartId())) {
HashMap<String, Object> itemMap = new HashMap<String, Object>();
itemMap.put("id", item.getId());
itemMap.put("quantity", item.getQuantity());
itemMap.put("price", item.getPrice);
items.add(itemMap);
}
jsonData.put("items", items);
return SUCCESS;
}
The final step is to use JQuery to call (on a specific event) through AJAX the URL where the action has been defined, and obviously to use the returned data to dynamically populate the page HTML.
function testingJsonAndAjax(cartId) {
$.getJSON(
/test/giveMeJsonData.action ,
{
cartId: cartId
},
function(json) {
$('#cartId').html(json.shoppingCartId);
$('#cartCreation').html(json.datetime);
itemsHtml = "<table>";
for (i in json.items) {
itemsHtml += “<tr>”;
itemsHtml += “<td>” + json.items[i].id + “</td>”;
itemsHtml += “<td>” + json.items[i].quantity + “</td>”;
itemsHtml += “<td>” + json.items[i].price + “</td>”;
itemsHtml += “</tr>”;
}
itemsHtml += “</table>”;
$('#cartItems').html(itemsHtml);
}
);
return false;
}
A sample HTML would look like this
Cart 32233 <a href=”#” onclick="return testingJsonAndAjax(32233)>Refresh</a> <br /> Cart 82382 <a href=”#” onclick="return testingJsonAndAjax(82382)>Refresh</a> <br /> <div id=”cartId”>JQuery will replace this text with the Cart Id returned by the json action</div> <div id=”cartCreation”>JQuery will replace this text with the Cart creation date returned by the json action</div> <div id=”cartItems”>Jquery wil replace this text with a HTML table containg all the items of the selected cart</div>
The id will be used by the JQuery selector to determine in which of them the data returned by the json action will be written in.
I hope this tutorial has been useful for a simple introduction to AJAX and JSON using JQuery and Struts2.
EDIT 1: on the Struts User Mailing List, Wes Wannemacher suggested that it would be better to directly put the item object inside the root object returned through JSON.
This is absolutely right and would lead to cleaner code. But I didn’t used that technique for a security reason, i.e. if the Item object is a JPA entity, it may contain some properties that is better not to show to the end users. In the case of a User entity, it would be no good to return in the json data its hashed password.
So I created that ugly workaround, defining some HashMaps and putting there just the specific properties I wish to return in the Json result (and maybe this will save too some HTTP traffic
)
EDIT 2: on the Struts User Mailing List, Nils-Helge Garli Hegvik suggested that it’s even possible to use the “includeProperties” or “excludeProperties” parameters (as described here) in the result configuration to simply return some objects and the JSON plugin will do the trick of filtering just the specific properties to show.
July 12th, 2009 at 2:17 pm
Can I have a full code?
July 13th, 2009 at 5:03 am
Awesome! Thanks for share this knowledgement.
o/
August 3rd, 2009 at 9:14 am
please send me example project with struts2 and jquery
November 2nd, 2009 at 11:27 pm
I am now using JQUERY to achieve AJAX, Can you provide me this project source?
November 8th, 2009 at 1:05 pm
Please public the application in total so that people will find it easy to integrate and understand better.
Did find the post useful. Please so send me the source to play around
November 11th, 2009 at 3:51 pm
Hello, Very useful post. Would appreciate a copy of the source. Thank you.
April 17th, 2011 at 11:31 pm
Glad I’ve finally found soetminhg I agree with!
November 13th, 2009 at 7:31 pm
Very good post. Thanks a lot.
For those who haven’t upgraded to struts 2.1.8 yet and are still working with 2.0, a good tip is that you should use jsonplugin-0.32.jar ( not jsonplugin-0.34.jar )
I had that problem making this work.
December 19th, 2009 at 9:13 pm
I’ve been looking for this. Could you please mail me a copy of the source? TIA
January 4th, 2010 at 10:46 pm
Hello, Very Nice post. Please share the copy of the source. Thank you.
February 2nd, 2010 at 4:12 am
best to use struts2-jquery plugin
code.google.com/p/struts2-jquery-plugin/
June 13th, 2010 at 9:14 pm
Hi-
I tried using the struts2-jquery-plugin, but it is not getting triggered “onchange” event on the the autocomplete component in IE.
I need a json return data from sturts2 action and onchange event on the component side.
Does anybody have a working copy?
Could you please post the code?
Thanks in Advance,
Suresh
June 17th, 2010 at 7:01 am
http://justlikeinschool.blogspot.com/2010/06/struts-2-and-jquery-without-fuss.html
showcase of Struts2 and jQuery without usign plugins
March 31st, 2010 at 8:07 pm
awesome work..
April 1st, 2010 at 6:49 pm
Thank about lesson, but can you send for me this example? it’s useful for me,please, thank you so much.
andyphamtpvn@yahoo.com
June 13th, 2010 at 9:17 pm
Hi-
I tried using the struts2-jquery-plugin, but the “onchange” event on the the autocomplete component is not getting triggered in IE with JSON data.
I need a json return data from sturts2 action and onchange event on the component side.
Does anybody have a working copy for with struts 2.1.8, struts2-jquery-plugin 2.1.8.1?
Could you please post the code?
Thanks in Advance,
Suresh
June 17th, 2010 at 7:02 am
http://justlikeinschool.blogspot.com/2010/06/struts-2-and-jquery-without-fuss.html
showcase of Struts2 and jQuery without using plugins
November 8th, 2010 at 12:07 pm
Good work, can you send for me this example? Thank’s for all
April 12th, 2011 at 5:17 am
Good post, Awesome work!
May 8th, 2011 at 4:05 am
This is great post, but does anyone know how these guys do this? http://www.aquim.com/approach.html . If you click on any of the links at the bottom of the content it slides open and dynamically loads content. I think it’s ajax, but looking at the source there appears to be a link loading it. I’ve been trying to figure it out for weeks.
May 8th, 2011 at 4:34 am
They simply triggers that AJAX effect on the onclick event of the < a > element.
You can see those examples http://api.jquery.com/click/
September 14th, 2011 at 7:49 am
Gracias compadre por el codigo, me sirvió mucho.
September 22nd, 2011 at 6:26 am
Can you please elaborate on the point where we can specify the exact object that we send as json reponse instead of the complete Action.Say I have 10 properties defined in my Action. I want to send only one property as the response. I lookedup the link provided, but it has been moved.Would be helpful If you can provide it for Annotation based Struts2 project.
November 9th, 2011 at 9:28 am
i am new to struts2jquery i need rrid with multiple search code please send me sir,
advanced thanks,
sreekanth
sreekanth.you@gmail.com
November 29th, 2011 at 3:18 pm
Ich würde zu prüfen mit Ihnen hier. Was nicht eins I oft zu tun! I get Freude lesen a submit das wird die Personen denken. Zusätzlich, vielen Dank für erlaubt mir comment !
December 14th, 2011 at 4:36 pm
Heya folks,
Imagine that I have a JSON string data ready to send to the server in order to build an object of its type there. It is the inverse of this example.
How can I do it in Struts 2?
Thank you.
January 9th, 2012 at 5:40 pm
Bei Patientinnen mit ein klein bisschen Unterhaut-Fettgewebe ist eine Platzierung unter den Brustmuskel vorzuziehen, um insbesondere in dem Kompetenz der Oberbrust fließende, harmonische Übergänge zu erreichen.