Ryan has been working with web technologies since 2004 and is a lover all all things design, especially jQuery and HTML. Big fan of open source. Preferred Languages - Javascript/Java, Preferred Framework-jQuery, Preferred Design Tools - GIMP/Inkscape. Ryan has posted 40 posts at DZone. You can read more from them at their website. View Full User Profile

Using Struts 2 with JSON and jQuery

01.13.2011
| 63572 views |
  • submit to reddit
It took a decent amount of time to figure out how to set up struts 2 with JSON. and how to extract the data using jQuery. So, i thought that i'd better make a note of the stuff i learned and just restate the rules, few as they are, so that me or someone else can cross verify them when writing code.
There are a few things that need to be done in order to use JSON with struts 2. Basically, struts provides you with a few result types. For JSON, you will require a new Result Type, because, obviously, since the response is a JSON response, you dont have a page to redirect to.
So, first you need to download the JSON plugin, if you already dont have it in your struts download. As usual, keep it in the lib folder of your application.
The struts 2 JSON plugin allows you to create an action that can be serialized into a JSON object. Ok, what that means in basic terms is that in the response that is sent back to the client, the response is the Javascript object that represents the Action class, and the attributes of the javascipt object are actually named after the public getter methods of the action. If the value of any getter method returns a null, the value of the javascript attribute will be null and vice versa.
The plugin not only handles basic types but also complex types like lists and arrays. We will see a code snippet shortly.
First things first. Lets see what needs to be done for setting up our action for JSON.
Keep the json plugin jar in your lib directory.In struts.xml, create a new package that extends json-default. If you want to use an existing package, you can simply use a comma separated value for the package names as the value of the extends parameter of the package tag. That is what I will be doing here. (TIP : json-default package extends struts-default.)Specify the result type of your action class to be 'json'
Thats pretty much all you need to do to get things going from the struts configuration perspective.
The json-default package contains an interceptor and the result type configuration for JSON requests and responses.
Now lets get to the code.

  1. From the browser perspective : jQuery
    jQuery allows you to issue an ajax request that expects a JSON object as a response by the getJSON method. Like all other ajax requests, the syntax for making the call is the same. You need to pass the url, a javascript object representing the form parameters, and a function that will be invoked upon the return of the invocation. In the returned function, the data that is returned from the server can be treated as a JSON object.
  2. From the server's perspective : Struts 2 
    All you need to do is to create instance variables and respective getter and setter methods for variables that need to be accessed via javascript. Once in the execute method, you can simply set the values of these instance variables. Then the action need to be configured to return a json object in the struts configuration file.


The point to be noted here is that all the variables that have a setter can be set to the values as received by the form parameters. And all the variables that have a getter method can be retrieved in the client javascript code.
In the following code sections, we will see how we can not only handle simple data types, but also, lists and maps as JSON objects.
First the HTML. This is just an ordinary form that contains nothing but a text field for the user to enter a name. The struts action that we will write will just be used to say Hi to the user.
<form action="" id="introForm"><label for="name">Enter Your Name</label>
<input name="name">
<input type="submit">
</form>
The form id is introForm. Lets handle the submit event of this form in the code to return false, since we do not want to be going anywhere when the user submits. All the action must stay on this page itself.
$(function(){

$("#introForm").submit(function(){

return false;

});

});

So, now that we know that the action will stay here, what we need to do is serialize the form inputs and issue a request to the server with the form inputs. But before we do that, we must first create the action class and then configure the action and its url in the struts configuration file. So, lets jump towards the server code for once.
Creating the action class is as simple as it has ever been. Since this is a demo, I have created a few instance variables of type List and Map and will populate some dummy values in them so that they can be retrieved using javascript later. Also note that for all my instance variables, I have created getter methods so that their values can be retrieved.
public class AjaxActions extends ActionSupport{

private String name;
private String greeting;
private List<string> countryList;
private Map<string,long> countryMap;

public String sayHi(){

greeting="HI " +name;

countryList=new ArrayList();
countryList.add("US");
countryList.add("UK");
countryList.add("Russia");

countryMap= new HashMap();
countryMap.put("US",1L);
countryMap.put("UK",2L);
countryMap.put("Russia",3L);

return ActionSupport.SUCCESS;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getGreeting() {
return greeting;
}

public void setGreeting(String greeting) {
this.greeting = greeting;
}

public List<string> getCountryList() {
return countryList;
}

public void setCountryList(List<string> countryList) {
this.countryList = countryList;
}

public Map<string, long=""> getCountryMap() {
return countryMap;
}

}
</string,></string></string></string,long></string>
 So, basically what i have done here in the sayHi() function is to initialize an instance variable call greeting, that says hi to the user. Then i populated a dummy list with the names of a few countries. Then i populated a dummy map with the country codes of those countries. My objective is to fetch the greetig, the list and the map on the action from the javascript code.
In the struts configuration file, the following lines would be sufficient to configure the JSON action.
<struts>
<package extends="struts-default,json-default" name="ajax-package" namespace="/ajax">

<action class="sample.AjaxActions" method="sayHi" name="sayHi">
<result type="json">
</result></action>

</package>
</struts>

Now my server side code is ready.
Getting back to the javascript code, I am simply going to print the values on the firefox console, you can choose to do whatever you feel like!
$(function(){

$("#introForm").submit(function(){

var formInput=$(this).serialize();

$.getJSON('ajax/sayHi.action', formInput,function(data) {

$('.result').html('' + data.greeting + '
');

$.each(data.countryList,function(index, value){
console.log("value " + value);
});

$.each(data.countryMap,function(key, value){
console.log("key "+ key + ", value " + value);
});
});

return false;

});

});

That does it! Last but not the least, many thanks to the programmers to write such a easy to use plugin. Kudos to all of you!
Happy Programming :)

 

From http://mycodefixes.blogspot.com/2011/01/using-struts-2-with-json-and-jquery.html

Published at DZone with permission of its author, Ryan Sukale.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Fabien Bergeret replied on Thu, 2011/01/13 - 5:32am

I still don't understand the point in having JSon being sent from the server to the client. It requires extra processing power on the client side.

When a page receives a lot of data, the whole JSon data has to be parsed before data is refreshed on the browser. On 'old' IE6 clients (and a lot of people still use it), it can take a while between the time the client receives the data and the time data is displayed to the client. I've already seen absurdities like a server responding in 1s, and display displayed in 1 min.

On the other hand, if the server sends 'ready to use' HTML, the client displays the data without any overhead, and the applicationsi much more fluid.

Don't forget that browsers are made for displaying HTML, not for processing data (even if it's less and less the case)!

Ryan Sukale replied on Thu, 2011/01/13 - 10:58am in response to: Fabien Bergeret

I agree that most of the time is is always more comfortable to allow the server to return a well formed xhml component. That is the preferred way. But i still believe that JSON can be pretty useful when the final output for the request is not something that has to be displayed to the user. Maybe, the JSON object contains some arbitrary flag that if set ,can be used to enable/disable an existing component on the already visible UI.

Moreover, as you stated, for requests that return a huge amount of data, or even moderate amount of data, you may simply want to return an Xhtml. Thats probably the best way to handle such requests, as it makes the code more maintainable. But there are always corner cases, especially when the quantity of data is almost negligible. I probably would prefer to handle such cases using JSON, rather than designing tiny components(xhtml pages).

Dave Newton replied on Tue, 2011/02/08 - 8:24am in response to: Fabien Bergeret

There are many reasons why returning JSON may be better than returning HTML. Believing otherwise is a relic of the past. IE6 usage is now below 20% and the pain of getting a modern website to work on IE6 is *not* a good ROI. And it *is* old, a decade old. If you're seeing a display rendered in 1 minute then they're not doing it right. Move on.

Dani Dailey replied on Sun, 2011/02/20 - 11:54am

Wish I had this last week.  I just started using struts 2 last week so this question may be obvious.  I am developing using JSP - not javascript.  I have an opening form with a submit that uses an action and execute method to get the data.  Then, the only way I could get jquery to work was to put an action and execute method that just returns 'success' and then I go onto my jquery grid with a 3rd action.  I'm not sure why this works - I don't know very much about JSON.  The question/problem I have is that the form data is available from the 1st action to the 2nd action but it is null when I want to use it in the 3rd action/execute.  I have some business logic in the 2nd execute to get the data for the grid and that is null when I get to where I want to display the grid.  Any help?

 

I have a simple example if you would like to see it.  Thanks.

Manjunath Kadroli replied on Sat, 2012/09/15 - 1:23am

 hi Dani Dailey 

 can u provide the simple example u have  ?

 

 

Manjunath Kadroli replied on Sat, 2012/09/15 - 1:28am in response to: Dani Dailey

hi 

Dani Dailey

can u provide me the simple example...?

 

actually iam trying implement three dropdown in struts 2 where 2nd populates based on first, thrid

populates based on first and second. 

second is populated using struts2 double select but the third select iam not able to......

so ......is there any solution u can provide me.........

 

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.