<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Web2.0 Tutorials &#187; json-default</title>
	<atom:link href="http://www.zulutown.com/blog/tag/json-default/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.zulutown.com/blog</link>
	<description>All the Guides You Need to Become a Web2.0 Expert</description>
	<lastBuildDate>Mon, 13 Jul 2009 07:50:00 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Ajax Dynamic Content with Struts2, JQuery and JSON plugin</title>
		<link>http://www.zulutown.com/blog/2009/07/12/ajax-dynamic-content-with-struts2-jquery-and-json-plugin/</link>
		<comments>http://www.zulutown.com/blog/2009/07/12/ajax-dynamic-content-with-struts2-jquery-and-json-plugin/#comments</comments>
		<pubDate>Sun, 12 Jul 2009 19:46:02 +0000</pubDate>
		<dc:creator>Zulutown Webmaster</dc:creator>
				<category><![CDATA[Ajax]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[Java EE]]></category>
		<category><![CDATA[Struts2]]></category>
		<category><![CDATA[actionsupport]]></category>
		<category><![CDATA[dynamically]]></category>
		<category><![CDATA[jar]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[json-default]]></category>
		<category><![CDATA[jsonplugin]]></category>
		<category><![CDATA[JSONResult]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[struts-default]]></category>
		<category><![CDATA[struts-plugin.xml]]></category>

		<guid isPermaLink="false">http://www.zulutown.com/blog/?p=118</guid>
		<description><![CDATA[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&#8217;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 [...]]]></description>
			<content:encoded><![CDATA[<p>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.<br />
﻿First of all it&#8217;s required the Json Plugin (available at <a href="http://jsonplugin.googlecode.com" target="_blank">http://jsonplugin.googlecode.com</a>) that should be placed in the <code>/WEB-INF/lib/</code> directory (where obviously are placed all the Struts2 jar as explained in other tutorials of this site).</p>
<p>The plugin adds (through its struts-plugin.xml) a new result type defined this way:</p>
<pre>&lt;package name="json-default" extends="struts-default"&gt;
 &lt;result-types&gt;
  &lt;result-type name="json" class="com.googlecode.jsonplugin.JSONResult"/&gt;
 &lt;/result-types&gt;
 ...
&lt;/package&gt;</pre>
<p>Since it&#8217;s defined in the <code>json-default</code> package, in order to use that result inside custom action mappings, there are two choices:</p>
<ul>
<li> the packages containing actions with <code>json</code> result-type have to extend the package <code>json-default</code> and not, as usual, the <code>struts-default</code> package</li>
<li>in the packages where <code>json</code> result-type is used, it&#8217;s to possible to add the previous <code>&lt;result-types&gt;...&lt;/result-types&gt;</code> lines that simply refers to a class contained in the json plugin <code>.jar</code> added to the application.</li>
</ul>
<p>It&#8217;s now possible to define action mappings using <code>json</code> as result type, like the following one:</p>
<pre>&lt;package name="testPackage" extends="json-default" namespace="/test"&gt;
 &lt;action name="giveMeJsonData" class="testAction" method="giveMe"&gt;
  &lt;result type="json"&gt;
   &lt;param name="root"&gt;jsonData&lt;/param&gt;
  &lt;/result&gt;
 &lt;/action&gt;
...
&lt;/package&gt;</pre>
<p>The above definition states that the url <code>/test/giveMeJsonData.action</code> will cause the execution of the method <code>public String giveMe()</code> defined inside the class <code>testAction</code> (in this case it&#8217;s a Spring managed bean, but it can be even a qualified name of a Struts2 action class, obviously extending ActionSupport class).</p>
<p>The result of that action (with a <code>SUCCESS</code> result code) is the json data structure stored in the <code>jsonData</code> property of the action class, and so available through its getter <code>getJsonData()</code>.</p>
<p>An example of the behavior for <code>giveMe()</code> method:</p>
<pre>public String giveMe() {
 jsonData = new LinkedHashMap&lt;String, Object&gt;();
 jsonData.put("shoppingCartId", getCartId());
 jsonData.put("datetime", new Date());
 Set&lt;Map&lt;String, Object&gt;&gt; items = new HashSet&lt;Map&lt;String, Object&gt;&gt;();
 for (Item item : businessMethod.findItemsForCart(getCartId())) {
  HashMap&lt;String, Object&gt; itemMap = new HashMap&lt;String, Object&gt;();
  itemMap.put("id", item.getId());
  itemMap.put("quantity", item.getQuantity());
  itemMap.put("price", item.getPrice);
  items.add(itemMap);
 }
 jsonData.put("items", items);
 return SUCCESS;
}</pre>
<p>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.</p>
<pre>function testingJsonAndAjax(cartId) {
 $.getJSON(
  /test/giveMeJsonData.action ,
  {
   cartId: cartId
  },
  function(json) {
   $('#cartId').html(json.shoppingCartId);
   $('#cartCreation').html(json.datetime);
   itemsHtml = "&lt;table&gt;";
   for (i in json.items) {
    itemsHtml += “&lt;tr&gt;”;
    itemsHtml += “&lt;td&gt;” + json.items[i].id + “&lt;/td&gt;”;
    itemsHtml += “&lt;td&gt;” + json.items[i].quantity + “&lt;/td&gt;”;
    itemsHtml += “&lt;td&gt;” + json.items[i].price + “&lt;/td&gt;”;
    itemsHtml += “&lt;/tr&gt;”;
   }
   itemsHtml += “&lt;/table&gt;”;
   $('#cartItems').html(itemsHtml);
  }
 );
 return false;
}</pre>
<p>A sample HTML would look like this</p>
<pre>Cart 32233 &lt;a href=”#” onclick="return testingJsonAndAjax(32233)&gt;Refresh&lt;/a&gt; &lt;br /&gt;
Cart 82382 &lt;a href=”#” onclick="return testingJsonAndAjax(82382)&gt;Refresh&lt;/a&gt; &lt;br /&gt;

&lt;div id=”cartId”&gt;JQuery will replace this text with the Cart Id returned by the json action&lt;/div&gt;
&lt;div id=”cartCreation”&gt;JQuery will replace this text with the Cart creation date returned by the json action&lt;/div&gt;
&lt;div id=”cartItems”&gt;Jquery wil replace this text with a HTML table containg all the items of the selected cart&lt;/div&gt;</pre>
<p>The <code>id</code> will be used by the JQuery selector to determine in which of them the data returned by the json action will be written in.</p>
<p>I hope this tutorial has been useful for a simple introduction to AJAX and JSON using JQuery and Struts2.</p>
<p><strong>EDIT 1:</strong> on the Struts User Mailing List, <a href="http://www.manning.com/wannemacher">Wes Wannemacher</a> suggested that it would be better to directly put the item object inside the root object returned through JSON.</p>
<p>This is absolutely right and would lead to cleaner code. But I didn&#8217;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.</p>
<p>So I created that <em>ugly</em> 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 <img src='http://www.zulutown.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  )</p>
<p><strong>EDIT 2:</strong> on the Struts User Mailing List, Nils-Helge Garli Hegvik suggested that it&#8217;s even possible to use the &#8220;includeProperties&#8221; or &#8220;excludeProperties&#8221; parameters (as described <a href="http://cwiki.apache.org/S2PLUGINS/json-plugin.html">here</a>) 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.</p>
<div id="_mcePaste" style="overflow: hidden; position: absolute; left: -10000px; top: 0px; width: 1px; height: 1px;">in the packages where “json” result-type is used, it&#8217;s to possibile to add the previous &amp;lt;result-types&amp;gt;&#8230;&amp;lt;/result-types&amp;gt; lines that simply refers to a class contained in the .jar added to the application (contained in the json-plugin jar).</div>
]]></content:encoded>
			<wfw:commentRss>http://www.zulutown.com/blog/2009/07/12/ajax-dynamic-content-with-struts2-jquery-and-json-plugin/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
	</channel>
</rss>
