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 packagejson-default
and not, as usual, thestruts-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.
Can I have a full code?
please send me example project with struts2 and jquery
I am now using JQUERY to achieve AJAX, Can you provide me this project source?
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
Hello, Very useful post. Would appreciate a copy of the source. Thank you.
Glad I’ve finally found soetminhg I agree with!
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.
I’ve been looking for this. Could you please mail me a copy of the source? TIA
Hello, Very Nice post. Please share the copy of the source. Thank you.
best to use struts2-jquery plugin
code.google.com/p/struts2-jquery-plugin/
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
http://justlikeinschool.blogspot.com/2010/06/struts-2-and-jquery-without-fuss.html
showcase of Struts2 and jQuery without usign plugins 😀
Thank about lesson, but can you send for me this example? it’s useful for me,please, thank you so much.
andyphamtpvn@yahoo.com
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
http://justlikeinschool.blogspot.com/2010/06/struts-2-and-jquery-without-fuss.html
showcase of Struts2 and jQuery without using plugins 😀
Good work, can you send for me this example? Thank’s for all
Good post, Awesome work!
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.
They simply triggers that AJAX effect on the onclick event of the < a > element.
You can see those examples http://api.jquery.com/click/
Gracias compadre por el codigo, me sirvió mucho.
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.
i am new to struts2jquery i need rrid with multiple search code please send me sir,
advanced thanks,
sreekanth
sreekanth.you@gmail.com
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.
Thks for this, can you share the source code ?
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.
Ԍ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ѕ =)
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!!
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.
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.
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.
With conventional mortgage, your home mortgage repayment could not surpass 28 % of your gross regular monthly income.
Dansinger recommends eating a diet plan that minimizes starches, added sugars, and animal
fat from meat and dairy foods.
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.
It is most necessary that you just communicate your needs to your health care suppliers
and work with them to find the absolute best strategy to symptom management.
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!!
Elle est parfaite pour débuter et développer sa bankroll.
Look at our real quotes here to get an approximation of what you can pay for your courier van insurance.
Plan Insurance Brokers supply intelligent options to the UK’s specialist roadway customers.
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?
Hi there friends, good paragraph and good arguments commented at this place, I am in fact enjoying by these.
Inside days of. restrict games with a klikněte na dostanu.
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.
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.
This is very attention-grabbing, You’re a very skilled blogger.
I have joined your rss feed and sit up for seeking extra of your excellent post.
Also, I’ve shared your website in my social networks
absolutely working fine after 2 years of use
Hi, all the time i used to check weblog posts here early in the dawn, for the reason that i like to
gain knowledge of more and more.
Excellent article, great to read genuine content we can all share between all users. I do as make tutorials and videos for others, if you have Instagram I would be glad to have you as follower : https://www.instagram.com/earthbydrones Have a great day! Earth By Drones Com Paul
Some really quality articles on this website, saved to bookmarks.
There is apparently a bunch to identify about this. I believe you made various good points in features also.
Cyber sex live cams SaraConors: I`m a sexy girl that has both
a sweet and a naughty side, so you decide
between share tenderness and love, or let me seduce you with my smile and
glare. I`m easy going and I like to know new people.
cam video chat room
I enjoyed your article so much! I just like how the writer clarified the thoughts.
I think it is at least as fantastic as the post of the guys http://id.fm-p.jp/index.php?module=jumper&action=pjump&url=https://makeup-reviews.com/polishes/colour-go-121-gold-fever/. Thank you a lot for this guide,
I’ll wait for your next publications.
Hi Sir,Allow me to introduce myself,My name is Minfei and I am
from Lunar Media Solutions Sdn. Bhd. A digital
marketing agency based in Kuala Lumpur, Malaysia.We specialize
in a variety of digital marketing solutions such as database marketing, database rental, bulk sms
solutions, bulk email solutions, wechat marketing
& whatsapp marketing solutions.
I want to introduce a revolutionary new marketing software for your perusal.
– Whatsapp Bulk Marketing Suite 1.0
The most COMPREHENSIVE Whatsapp Bulk Software!!
What does it do?
– Send UNLIMITED messages :-
a) Audio Only
b) Audio then Text
c) Audio then vCard
d) Image Only
e) Image then Text
f) Image then vCard
g) Text Only
h) Text then vCard
i) vCard Only
j) vCard then Text
k) Video Only
l) Video then Text
m) Video then vCard
– Message sending at LIGHTNING SPEED :
-100,000 text messages in just 2 hours or LESS!
– Upload any text/CSV contact list files at just a click!
– No database? NO PROBLEM!Ability to generate UNLIMITED valid whatsapp number database for
your campaign!
– Ability to track LAST SEEN status on your current/previous campaigns!
– Ability to track message SENDING AND DELIVERED
& RECEIVED STATUS!
– Ability to change channel’s PROFILE picture
– Chat function to be able to reply to recipient’s message immediately after campaign is delivered!
– Able to support UNLIMITED amounts of channels without any
need of proxies- Able to customize Whatsapp Channels display name- Enable
autoreply to not miss a single client ever again
– Free updates available for a single lifetime license
– PDPA (2010) compliant software
– Malaysian Communications And Multimedia Commission Act
(1998) compliant software Whatsapp Channels (International Physical Sims)
– Most secured method compared to any available Whatsapp Channels up to date.
– Able to send a minimum of 30-40 messages per channel/day
– Affordable- 1 to 1 Replacement for invalid numbers
– 6 month Validity Period guarantee
– No need for reload, maintenance fee, any other .misc payments
– Largest Physical Sims Whatsapp Channels supplier worldwide- Express delivery
Merely a smiling visitor here to share the love (:, btw outstanding design .
It’s wonderful that you are getting ideas from this piece of writing as well as from our dialogue made here.|