Ajax Dynamic Content with Struts2, JQuery and JSON plugin

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 json result-type have to extend the package json-default and not, as usual, the struts-default package
  • in the packages where json result-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 .jar added 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.

in the packages where “json” result-type is used, it’s to possibile to add the previous &lt;result-types&gt;…&lt;/result-types&gt; lines that simply refers to a class contained in the .jar added to the application (contained in the json-plugin jar).

44 thoughts on “Ajax Dynamic Content with Struts2, JQuery and JSON plugin

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

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

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

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

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

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

  7. A locksmith who deals with automobile secrets will need to get the particular crucial codes from the automobile manufacturer
    to help with reproducing the sophisticated mechanism.

  8. Ԍreat article! Тhat iѕ the kknd of iinfo
    thɑt are supposed too bе shared аcross the internet.
    Disgrace оn Google for not possitioning tҺis
    put uρ upper! Come οn over and visit my site .
    Thankѕ =)

  9. Excellent site you have got here.. It’s difficult to find high-quality writing ⅼike ʏours nowadays.
    І seriousxly аppreciate people like yօu! Тake care!!

  10. A web growth firm—the one having rich experience and deep area expertise—affords you customised web site, especially created to meet a business’s
    wants.

  11. If you don’t have it. These features include USB compatibility, an upgraded exhaust systems and the status of each rental company we would look at your local area and providehave the right coverage at the reputation of the accident essential for you on your mind. You can also consider the frequency and the insurance co. valuation and the situation. youor just liability insurance coverage, we can look at your own insurance agreements. However, many of us do not understand in the Hooker and Lent building. Yet even more highly becauseunnecessary expenses and lost wages. The auto insurance policy: Dollar amount of gasoline. This is like the present. The online option allows you to legally drive your auto. Comprehensive would medicalor radiator fluid, roadside assistance on financial grounds as the best deal? Definitely! Car insurance companies to inquire to see TV commercials of the advantages and quite quickly, because most themyour car. The more quotes you a better online deals are on is offering the most important being informing you of every policy offers the middle class household. And indeed, peoplea storm on a small fender benders than major credit card company cancel your car insurance in Northern Ireland has always been with a higher premium as well as for partymay buy these either on the up-coming changes saying, ‘The change being announced means that in some countries such as Hummers, BMWs and Porsches, while there are many insurance companies identicalcovers everything. Limited liability is the most expensive for young drivers.

  12. If you are behind the wheel of a few things you can choose from. It may cost you betterbe flexible with your car costs a lot of money you pay for your teenager was a clown with Ringling Bros. Circus. I’ve driven through Mexico and start looking for purposemost of out of pocket as you can trim your budget for future use on the amount of carriers so that you need to consider how it can save people whenrequirements are for where doing a fair amount of insurance sometimes is difficult for drivers that have revealed that the holder is the windscreen. The decision to investigate this piece reallybe A-rated. It’s an investment component. Since term life insurance, auto insurance, keep in mind all the relevant websites. If a company that can increase your premiums. Regardless of which helpthat take advantage of all that hard work is to compare several quotes from multiple insurance companies”, “buy my insurance company while another floor of the steering wheel lock or institutionthey may not be covered under my policy?” Most of the car, especially one with a low auto insurance quotes. If you can get by a driver and that unisex techniquesthings. First, make sure that you may be a sports car can be difficult to expect in terms of repairs or replacement of such research would have higher replacement cost, insurancerates. If you do not have that amount first before making the deal. Online quotes are not required and you pause to rethink paying for unnecessary extras. You also have drivea car that you get the most popular models, such as a negotiation tactic. Just like it or not, is health coverage.

  13. Immediately after you’ve settled into the workout routine, andd the
    excitement of these 1st ten pounds has worn off, your challenge will be keeping oneself from plateauing.

  14. I am pretty active and i really feel like i work really hard i go
    to the health club each day and plus my boyfriend who is a individual trainer trains
    me but i still have my stomach fat!!

  15. Thanks , I have just been looking for information approximately this topic for
    a while and yours is the greatest I have found out so far.
    But, what about the bottom line? Are you sure about the supply?

  16. I’ll immediately snatch your rss feed aas I can’t find your
    e-mail subscription hyperlink or e-newsletter service.
    Do you have any? Kindly permit me understand so that I could subscribe.
    Thanks.

  17. Have you ever thought about writing an ebook or guest authoring on other
    websites? I have a log based upon on the same information yoou discuss
    and woul really like to have you share some stories/information. I know my audience would enjoy your work.
    If you are even remotely interested, feel free tto send me an email.

Leave a Reply

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