ajax struts2 jquery

26
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery Tutorials:Getting Started with jQuery Setup To start, we need a copy of the jQuery library, which we can get from the main download page . The jQuery Starterkit provides some markup and CSS to work with. After downloading and extracting its content we put jquery.js into the same directory and open starterkit.html and custom.js with our favorite editor and starterkit.html with a browser. Now we have everything to start with the notorious "Hello world" example. Hello jQuery We start with an empty html page: <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> // we will add our javascript code here </script> </head> <body> <!-- we will add our HTML content here --> </body> </html> This page just loads the jquery.js library (make sure the URL points to where you stored your copy of jquery! This example assumes that you store it in the same directory as this example file). Two comments indicate where we will expand this template with code. As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready. document.doc / 1

Upload: vgprasad

Post on 12-Feb-2016

243 views

Category:

Documents


0 download

DESCRIPTION

Ajax & Struts

TRANSCRIPT

Page 1: Ajax Struts2 Jquery

http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery

Tutorials:Getting Started with jQuerySetup

To start, we need a copy of the jQuery library, which we can get from the main download page. The jQuery Starterkit provides some markup and CSS to work with. After downloading and extracting its content we put jquery.js into the same directory and open starterkit.html and custom.js with our favorite editor and starterkit.html with a browser.

Now we have everything to start with the notorious "Hello world" example.

Hello jQuery

We start with an empty html page:

<html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> // we will add our javascript code here </script> </head> <body> <!-- we will add our HTML content here --> </body> </html>

This page just loads the jquery.js library (make sure the URL points to where you stored your copy of jquery! This example assumes that you store it in the same directory as this example file). Two comments indicate where we will expand this template with code.

As almost everything we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready.

To do this, we register a ready event for the document.

$(document).ready(function() { // do stuff when DOM is ready });

Putting an alert into that function does not make much sense, as an alert does not require the DOM to be loaded. So lets try something a little more sophisticated: Show an alert when clicking a link.

Add the following to the <body>:

<a href="">Link</a>

document.doc / 1

Page 2: Ajax Struts2 Jquery

Now update the $(document).ready handler:

$(document).ready(function() { $("a").click(function() { alert("Hello world!"); }); });

This should show the alert as soon as you click on the link.

Lets have a look at what we are doing: $("a") is a jQuery selector, in this case, it selects all a elements. $ itself is an alias for the jQuery "class", therefore $() constructs a new jQuery object. The click() function we call next is a method of the jQuery object. It binds a click event to all selected elements (in this case, a single anchor element) and executes the provided function when the event occurs.

This is similar to the following code:

<a href="" onclick="alert('Hello world')">Link</a>

The difference is quite obvious: We don't need to write an onclick for every single element. We have a clean separation of structure (HTML) and behavior (JS), just as we separate structure and presentation by using CSS.

With this in mind, we explore selectors and events a little further.

Interesting links for this section:

jQuery Base jQuery Expressions jQuery Basic Events

Find me: Using selectors and events

jQuery provides two approaches to select elements. The first uses a combination of CSS and XPath selectors passed as a string to the jQuery constructor (eg. $("div > ul a")). The second uses several methods of the jQuery object. Both approaches can be combined.

To try some of these selectors, we select and modify the first ordered list in our starterkit.

To get started, we want to select the list itself. The list has an ID "orderedlist". In classic JavaScript, you could select it by using document.getElementById("orderedlist"). With jQuery, we do it like this:

$(document).ready(function() { $("#orderedlist").addClass("red"); });

document.doc / 2

Page 3: Ajax Struts2 Jquery

The starterkit provides a stylesheet with a class "red" that simply adds a red background. Therefore, when you reload the page in your browser, you should see that the first ordered list has a red background. The second list is not modified.

Now lets add some more classes to the child elements of this list.

$(document).ready(function() { $("#orderedlist > li").addClass("blue"); });

This selects all child lis of the element with the id orderedlist and adds the class "blue".

Now for something a little more sophisticated: We want to add and remove the class when the user hovers the li element, but only on the last element in the list.

$(document).ready(function() { $("#orderedlist li:last").hover(function() { $(this).addClass("green"); },function(){ $(this).removeClass("green"); }); });

There are many other selectors similar to CSS and XPath syntax. More examples and a list of all available expressions can be found here.

For every onxxx event available, like onclick, onchange, onsubmit, there is a jQuery equivalent. Some other events, like ready and hover, are provided as convenient methods for certain tasks.

You can find a complete list of all events in the jQuery Events Documentation.

With those selectors and events you can already do a lot of things, but there is more.

$(document).ready(function() { $("#orderedlist").find("li").each(function(i) { $(this).append( " BAM! " + i ); }); });

find() allows you to further search the descendants of the already selected elements, therefore $("#orderedlist").find("li") is mostly the same as $("#orderedlist li").

each() iterates over every element and allows further processing. Most methods, like addClass(), use each() themselves.

In this example, append() is used to append some text to it and set it as text to the end of each element.

Another task you often face is to call methods on DOM elements that are not covered by jQuery. Think of a form you would like to reset after you submitted it successfully via AJAX.

document.doc / 3

Page 4: Ajax Struts2 Jquery

$(document).ready(function() { // use this to reset a single form $("#reset").click(function() { $("form")[0].reset(); }); });

This code selects the first form element and calls reset() on it. In case you had more than one form, you could also do this:

$(document).ready(function() { // use this to reset several forms at once $("#reset").click(function() { $("form").each(function() { this.reset(); }); }); });

This would select all forms within your document, iterate over them and call reset() for each. Note that in an .each() function, this refers to the actual element. Also note that, since the reset() function belongs to the form element and not to the jQuery object, we cannot simply call $("form").reset() to reset all the forms on the page.

An additional challenge is to select only certain elements from a group of similar or identical ones. jQuery provides filter() and not() for this. While filter() reduces the selection to the elements that fit the filter expression, not() does the contrary and removes all elements that fit the expression. Think of an unordered list where you want to select all li elements that have no ul children.

$(document).ready(function() { $("li").not(":has(ul)").css("border", "1px solid black"); });

This selects all li elements that have a ul element as a child and removes all elements from the selection. Therefore all li elements get a border, except the one that has a child ul.

The [expression] syntax is taken from XPath and can be used to filter by attributes. Maybe you want to select all anchors that have a name attribute:

$(document).ready(function() { $("a[name]").css("background", "#eee" ); });

This adds a background color to all anchor elements with a name attribute.

More often than selecting anchors by name, you might need to select anchors by their "href" attribute. This can be a problem as browsers behave quite inconsistently when returning what they think the "href" value is (Note: This problem was fixed recently in jQuery, available in any versions after 1.1.1). To match only a part of the value, we can use the contains select "*=" instead of an equals ("="):

document.doc / 4

Page 5: Ajax Struts2 Jquery

$(document).ready(function() { $("a[href*=/content/gallery]").click(function() { // do something with all links that point somewhere to /content/gallery }); });

Until now, all selectors were used to select children or filter the current selection. There are situations where you need to select the previous or next elements, known as siblings. Think of a FAQ page, where all answers are hidden first, and shown, when the question is clicked. The jQuery code for this:

$(document).ready(function() { $('#faq').find('dd').hide().end().find('dt').click(function() { $(this).next().slideToggle(); }); });

Here we use some chaining to reduce the code size and gain better performance, as '#faq' is only selected once. By using end(), the first find() is undone, so we can start search with the next find() at our #faq element, instead of the dd children.

Within the click handler, the function passed to the click() method, we use $(this).next() to find the next sibling starting from the current dt. This allows us to quickly select the answer following the clicked question.

In addition to siblings, you can also select parent elements (also known as ancestors for those more familiar with XPath). Maybe you want to highlight the paragraph that is the parent of the link the user hovers. Try this:

$(document).ready(function(){ $("a").hover(function(){ $(this).parents("p").addClass("highlight"); },function(){ $(this).parents("p").removeClass("highlight"); }); });

For all hovered anchor elements, the parent paragraph is searched and a class "highlight" added and removed.

Lets go one step back before continuing: jQuery is a lot about making code shorter and therefore easier to read and maintain. The following is a shortcut for the $(document).ready(callback) notation:

$(function() { // code to execute when the DOM is ready });

document.doc / 5

Page 6: Ajax Struts2 Jquery

Applied to the Hello world! example, we end with this:

$(function() { $("a").click(function() { alert("Hello world!"); }); });

Now, with the basics at hand, we want to explore some other aspects, starting with AJAX.

Interesting links for this chapter:

jQuery API documentation Visual jQuery - A categorized browsable API documentation. jQuery Selectors jQuery Events jQuery DOM Traversing

document.doc / 6

Page 7: Ajax Struts2 Jquery

API/1.1.2/DOM/Traversing/SelectorsjQuery selectors are a combination of CSS 1-3, XPath, plus some custom code to glue it together. Essentially, the best parts from both of these query languages were taken, combined, and used to create the final jQuery expression language. If you already know CSS (which most web developers do) then you're going to be fine.

If you are unsure about the general differences between the techniques discussed here, these articles in the English Wikipedia may help clarify a lot: XPath and [

Using CSS and XPath Together

This is a point of confusion, for some: How can you use CSS and XPath together, they're so different! jQuery makes some allowances to make this happen, but we think that developers will really appreciate the advantages of each language. Here are some examples:

Hide all Paragraph elements that contain a class attribute: $("p[@class]").hide();

Show the first paragraph on the page: $("p:eq(0)").show();

Hide all divs that are currently showing: $("div:visible").hide();

Get all list items that are children of an unordered list: $("ul/li") /* valid too: $("ul > li") */

Get all Paragraphs, with a class of 'foo', that have a link in them: $("p.foo[a]");

Get list item that contains link with "Register" text inside: $("li[a:contains('Register')]");

Get the input field's value with the name of 'bar': $("input[@name=bar]").val();

All checked radio buttons: $("input[@type=radio][@checked]")

If you still have questions concerning how this selector language works, please feel free to post to the mailing list.

document.doc / 7

Page 8: Ajax Struts2 Jquery

CSS Selectors

jQuery has full CSS 1-2 support and partial CSS 3 support, along with some custom CSS-like functionality (and XPath), as part of its expression.

For info on how CSS works feel free to read the various links: CSS 1 CSS 2 CSS 3

What follows is a list of supported CSS Selector expressions.

* any element E an element of type E E:nth-child(n) an E element, the n-th child of its parent E:first-child an E element, first child of its parent E:last-child an E element, last child of its parent E:only-child an E element, only child of its parent E:empty an E element that has no children (including text nodes) E:enabled a user interface element E which is not disabled E:disabled a user interface element E which is disabled E:checked a user interface element E which is checked (for instance a radio-button or checkbox) E:selected a user interface element E which is selected (one or more option elements inside a

select) - not in the CSS spec, but nonetheless supported by jQuery E.warning an E element whose class is "warning" E#myid an E element with ID equal to "myid". (Will only match, at most, one element.) E:not(s) an E element that does not match simple selector s E F an F element descendant of an E element E > F an F element child of an E element E + F an F element immediately preceded by an E element E ~ F an F element preceded by an E element E,F,G select all E elements, F elements, and G elements

Supported, but different

All attribute selectors are written like their XPath counter-parts (in that all attributes should begin with an @ symbol).

E[@foo] an E element with a "foo" attribute E[@foo=bar] an E element whose "foo" attribute value is exactly equal to "bar" E[@foo^=bar] an E element whose "foo" attribute value begins exactly with the string "bar" E[@foo$=bar] an E element whose "foo" attribute value ends exactly with the string "bar" E[@foo*=bar] an E element whose "foo" attribute value contains the substring "bar" E[@foo=bar][@baz=bop] an E element whose "foo" attribute value is exactly equal to "bar"

and whose "baz" attribute is exactly equal to "bop"

document.doc / 8

Page 9: Ajax Struts2 Jquery

Not supported jQuery only supports selectors that actually select DOM elements - everything else is ignored.

E:link E:visited an E element being the source anchor of a hyperlink of which the target is not yet

visited (:link) or already visited (:visited) E:active E:hover E:focus an E element during certain user actions E:target an E element being the target of the referring URI E::first-line the first formatted line of an E element E::first-letter the first formatted letter of an E element E::selection the portion of an E element that is currently selected/highlighted by the user E::before generated content before an E element E::after generated content after an E element

jQuery doesn't support the following selectors due to their lack of real-world usefulness: E:nth-last-child(n) an E element, the n-th child of its parent, counting from the last one E:nth-of-type(n) an E element, the n-th sibling of its type E:nth-last-of-type(n) an E element, the n-th sibling of its type, counting from the last one E:first-of-type an E element, first sibling of its type E:last-of-type an E element, last sibling of its type E:only-of-type an E element, only sibling of its type E:lang(fr) an element of type E in language "fr" E[foo~="test"] an E element whose "foo" attribute value is a list of space-separated values, one

of which is exactly equal to "test" E[hreflang|="en"] an E element whose "hreflang" attribute has a hyphen-separated list of

values beginning (from the left) with "en"

Context and Anchoring In jQuery, unlike real CSS, a selector expression may have a context other than the entire document, for instance with the function $(expr, context). You can anchor a CSS-like expression to the context root by starting it with one of the selectors >, +, or ~.

XPath Selectors

One of the selector languages that jQuery supports, as a part of its expression language is XPath. jQuery supports basic XPath expressions, in addition to CSS 1-3. Here are some samples:

Location Paths Relative to the entire HTML document

$("/html/body//p") $("body//p") $("p/../div")

Relative to the context node this $("p/*", this) $("/p//a", this)

document.doc / 9

Page 10: Ajax Struts2 Jquery

Supported Axis Selectors Descendant Element has a descendant element

$("//div//p") Child Element has a child element

$("//div/p") Preceding Sibling Element has an element before it, on the same axes

$("//div ~ form") Parent Selects the parent element of the element

$("//div/../p")

Supported Predicates [@foo] Has an attribute of foo

$("//input[@checked]") [@foo='test'] Attribute foo is equal to test

$("//a[@ref='nofollow']") [Nodelist] Element contains a node list, for example:

$("//div[p]") $("//div[p/a]")

Supported Predicates, but differently [last()] or [position()=last()] becomes :last

$("p:last") [0] or [position()=0] becomes :eq(0) or :first

$("p:first") $("p:eq(0)")

[position() < 5] becomes :lt(5) $("p:lt(5)")

[position() > 2] becomes :gt(2) $("p:gt(2)")

Custom Selectors jQuery includes some expressions that aren't available in either CSS or XPath, but were found to be very handy, so were included. The following expressions' syntax is based upon the various CSS selectors, of similar names.

Custom Selectors :even Selects every other (even) element from the matched element set. :odd Selects every other (odd) element from the matched element set. :eq(0) and :nth(0) Selects the Nth element from the matched element set :gt(N) Selects all matched elements whose index is greater than N. :lt(N) Selects all matched elements whose index is less than N. :first Equivalent to :eq(0) :last Selects the last matched element. :parent Selects all elements which have child elements (including text). :contains('test') Selects all elements which contain the specified text. :visible Selects all visible elements (this includes items that have a display of block or inline, a

visibility of visible, and aren't form elements of type hidden)

document.doc / 10

Page 11: Ajax Struts2 Jquery

:hidden Selects all hidden elements (this includes items that have a display of none, or a visibility of hidden, or are form elements of type hidden)

Some examples: $("p:first").css("fontWeight","bold"); $("div:hidden").show(); $("/div:contains('test')", this).hide();

Form Selectors

There are a few selectors for form elements:

:input Selects all form elements (input, select, textarea, button). :text Selects all text fields (type="text"). :password Selects all password fields (type="password"). :radio Selects all radio fields (type="radio"). :checkbox Selects all checkbox fields (type="checkbox"). :submit Selects all submit buttons (type="submit"). :image Selects all form images (type="image"). :reset Selects all reset buttons (type="reset"). :button Selects all other buttons (type="button"). :file Selects all <input type="file">.

Also available is :hidden, see the description above for details.

It is recommended to provide a context when using the above:

$('#myForm :input')

Or, if you have already a reference to your form:

$('input:radio', myForm)

This would select all input elements of type radio inside myForm. Using :radio is mostly the same as [@type=radio], but should be slightly faster. Good to know when working with large forms.

More Selectors The jQuery selector system can be extended by third parties:

More Selectors Plugin Mike Alsup on Custom Selectors Patch to allow selection by CSS property (full plugin to be released simultaneously with 1.1)

See Also Interactive jQuery selector tester

document.doc / 11

Page 12: Ajax Struts2 Jquery

Rate me: Using Ajax In this part we write a small Ajax application, that allows the user to rate something, just like it is done on youtube.com. We need some server code for this. My example uses a php file that reads the "rating" parameter and returns the number of ratings and the average rating. Have a look at rate.php for the server-side code. <?php

define('STORE', 'ratings.dat');

function put_contents($file,$content) {     $f = fopen($file,"w");     fwrite($f,$content);     fclose($f); }

if(isset($_REQUEST["rating"])) {     $rating = $_REQUEST["rating"];     $storedRatings = unserialize(file_get_contents(STORE));     $storedRatings[] = $rating;     put_contents(STORE, serialize($storedRatings));     $average = round(array_sum($storedRatings) / count($storedRatings), 2);     $count = count($storedRatings);     $xml = "<ratings><average>$average</average><count>$count</count></ratings>";     header('Content-type: text/xml');      echo $xml; }

?>We don't want this example to work without Ajax, although it may be possible, we therefore generate the necessary markup with jQuery and append it to a container div with an ID of "rating". $(document).ready(function() { // generate markup $("#rating").append("Please rate: "); for ( var i = 1; i <= 5; i++ ) $("#rating").append("<a href='#'>" + i + "</a> "); // add markup to container and apply click handlers to anchors $("#rating a").click(function(e){ // stop normal link click e.preventDefault(); // send request $.post("rate.php", {rating: $(this).html()}, function(xml) { // format and output result $("#rating").html( "Thanks for rating, current average: " + $("average", xml).text() + ", number of votes: " + $("count", xml).text() ); }); }); });

document.doc / 12

Page 13: Ajax Struts2 Jquery

This snippet generates five anchor elements and appends them to the container element with the id "rating". Afterwards, for every anchor inside the container, a click handler is added. When the anchor is clicked, a post request is send to rate.php with the content of the anchor as a parameter. The result returned as a XML is then added to the container, replacing the anchors. If you don't have a web server with PHP installed at hand, you can look at an online example. For a very nice example of a rating system that even works without JavaScript, visit softonic.de and click on "Kurz bewerten!" More documentation of the Ajax methods of jQuery can be found in the Ajax Documentation or on Visual jQuery filed under Ajax. A very common problem encountered when loading content by Ajax is this: When adding event handlers to your document that should also apply to the loaded content, you have to apply these handlers after the content is loaded. To prevent code duplication, you can delegate to a function. Example: function addClickHandlers() { $("a.remote", this).click(function() { $("#target").load(this.href, addClickHandlers); }); } $(document).ready(addClickHandlers);Now addClickHandlers is called once when the DOM is ready and then everytime when a user clicked a link with the class remote and the content has finished loading. Note the $("a.remote", this) query, this is passed as a context: For the document ready event, this refers to the document, and it therefore searches the entire document for anchors with class remote. When addClickHandlers is used as a callback for load(), this refers to a different element: In the example, the element with id target. This prevents that the click event is applied again and again to the same links, causing a crash eventually. Another common problem with callbacks are parameters. You have specified your callback but need to pass an extra parameter. The easiest way to achieve this is to wrap the callback inside another function: // get some data var foobar = ...; // specify handler, it needs data as a paramter function handler(data) { //... } // add click handler and pass foobar! $('a').click(function(){ handler(foobar); }); // if you need the context of the original handler, use apply: $('a').click(function(){ handler.apply(this, [foobar]); });With Ajax this simple we can cover quite a lot of "Web 2.0". Now that we've looked at some basic Ajax, let's add some simple effects and animations to the page. Interesting links for this chapter:

jQuery Ajax Documentation jQuery API - Contains description and examples for append and all other jQuery methods ThickBox - A jQuery plugin that uses jQuery to enhance the famous lightbox

document.doc / 13

Page 14: Ajax Struts2 Jquery

AJAX, JSON, JQuery with Struts 2http://www.arya199.com/struts-2/ajax-json-with-struts-2

It is assumed that readers of this article is familiar with Struts 2 Framework, Ajax and JSON. Oh, and of course, jQuery. Also a disclaimer, some Java code snippets depicted in this article is taken from Manning: Struts 2 in Action written by Donald Brown, Chad Michael Davis, and Scott Stanlick. Another caveat, should there be any error or something else that beg to be criticized and laughed at in this post, please don’t hesitate to do so and of course, enact a proper enlightenment to the author (me).

Here’s the idea, there’s an application, obviously a web application that presents its users with a form. A user submit the filled form, the application’s database contents are changed, and then the application updated its displayed values which related to the changed content without ever leaving the page. Ajax definitely comes to mind, and as I built the application using the Struts 2 framework, my quest to deliver this feature begins with a Google search for “Ajax with Struts 2.”

Cut to the chase, here’s my penciled writing on the issue.

1. There’s a jsp file, coupled with a JavaScript file, that contains the form handler and mechanism to submit the form to a server-side resource. As I’m using Ajax submit mechanism, rather than using HTML form and submit tag, I’m using a JavaScript onclick function that sends a request and receive a response in Ajax manners.

To further simplify request-response communication from the client to the server, I facilitate this transfer with JSON notations (in itself is a redundant elongation of the word since JSON already stands

document.doc / 14

Page 15: Ajax Struts2 Jquery

for JavaScript Object Notation) and with jQuery aid, I had this function in my JavaScript file to forward the request from client to a certain server-side resource using a jQuery function $.getJSON.

var divisionName = $('#divisionName').val();$.getJSON('addDivision.action', {'division.name': divisionName},

function(data) { $('.status') .css(({background: '#9f9', border: '#909 solid 1px'})) .fadeIn("slow") .animate({opacity: 1}, 1500) .fadeOut("slow"); var divisionList = (data.list); $('#divisionSelect').loadSelect(divisionList["arya199.entity.Division"]);}

);

The first line of the code, using a standard and well-known ‘$’ notation for jQuery, select an element from a DOM (Document Object Model) that made up the client’s HTML which identified by an id attribute named divisionName. In my case, the only element in the client’s code which has an id of divisionName is a HTML standard textfield, therefore the first line of this code selects the value from this textfield, and store it in a variable called divisionName.

The second line, up until the very last of the line, is a single function from jQuery (getJSON) and it has three parameters passed in. This function initiates a GET request to the server to the specified URL passed-in as its first parameter (addDivision.action), with parameters sent to the said URL passed-in as its second parameter ({'division.name': divisionName}. Here, it says that the URL is going to have its division.name parameter sets to a value taken from variable identified by divisionName). The third parameter is a callback function, invoked when the request completes. The JSON string value resulted from the response is passed to this function as its first parameter. Optionally, this function also has a second parameter, which is status and not shown here.

The callback function, as shown in the code above then sets the DOM element in the client code identified by a class named status with some simple animation. Again, using a standard (and hopefully trivial) jQuery. The function then reads the JSON string passed in as response, and then populate a certain select component in the resulted HTML page with the updated value using a custom and hand-made jQuery function loadSelect.

Now, back to the server resource called from this function, addDivision.action. I have a struts.xml configured to map this action. Here’s the configuration:

<result-types> <result-type name="customJSON" class="arya199.action.JSONResult"/></result-types>

document.doc / 15

Page 16: Ajax Struts2 Jquery

<action name="addDivision" method="addDivision" class="arya199.action.EmployeeAction"> <result-typeresult-type="customJSON">division</result-type></action-name>It is easy to see that line number 4 of the code above mapped addDivision.action request to a EmployeeAction class and to the addDivision method of that class. Now here’s some of the EmployeeAction class’ contents, by the way:

private Division division;

private List<Division> allDivision;

private Object jsonModel;

public String addDivision() {EntityTransaction et = getEntityManager().getTransaction();try {

et.begin();getEntityManager().persist(division);et.commit();

} catch (Exception ex) {ex.printStackTrace();

}setJSONModel(genericEntity.getAllDivisions());return SUCCESS;

}

// Getter and setter methods are not shown for simplicity

Now if you look into the first code excerpt (the JavaScript one) line number two, you’ll see that the client called addDivision.action which mapped with the method addDivision from EmployeeAction class through a struts.xml configuration (second code excerpt, the XML one). From the first excerpt you’ll also see that the request also passed a parameter division.name with a value identified by divisionName. With Struts 2 Framework, this parameter would translate into a call to setDivision(args).setName(args) from the called action class with a proper value passed in as its argument.

Finally, from the action class described in third code excerpt above (the Java one), you could see that the previous call described in the previous paragraph would set the private property Division (line 1 and further, the private property name in this class would have an equivalent JavaBeans getter and setter method which are not shown) from this class to hold the value divisionName passed in from the client. A call to addDivision method (line 7 and beyond) then tells the JPA (Java Persistence API) to persist this newly created division object to the database.

document.doc / 16

Page 17: Ajax Struts2 Jquery

One caveat, on line 17 of the action class example above, we sets a property called jsonModel with a value obtained from genericEntity.getAllDivisions() method execution. This method (not shown) retrieves all the Division objects from the database and populated them into an instance of List. Also note, that this property (jsonModel) is set to hold an instance of Object class.

2. This step pushes an object from the executed action class to a ValueStack and then informs the framework about this object and its type (JSONResult), and treats it as a result.

Back to the configuration XML shown in the second code excerpt line 5, you’ll see that the result of the addDivision.action is mapped with a type customJSON. Now, this type is defined properly in line 2, mapped to a class called arya199.action.JSONResult, and here’s the excerpt of that class.

public class JSONResult implements Result {  

public static final String DEFAULT_PARAM = "classAlias";  

String classAlias;  

public String getClassAlias() {  return classAlias;  

}  

public void setClassAlias(String alias) {  this.classAlias = alias;  

}  

Public void execute(ActionInvocation invocation) throws Exception { ServletActionContext.getResponse().setContentType("text/plain"); PrintWriter responseStream = ServletActionContext.getResponse().getWriter(); ValueStack valueStack = invocation.getStack(); Object jsonModel = valueStack.findValue("jsonModel"); XStream xstream = new XStream(new JettisonMappedXmlDriver()); if (classAlias == null) {

classAlias = "object"; } xstream.alias(classAlias, jsonModel.getClass()); responseStream.println(xstream.toXML(jsonModel)); }}

3. In order to get a proper treatment as a result by the Struts 2 framework, a class needs to implement Result class which is exactly what this class did as shown in line number one. Any class that

document.doc / 17

Page 18: Ajax Struts2 Jquery

implemented Result class therefore needs to implement execute method (line 15). To shorten the discussion, the method implemented here said that it’s going to return a response within a “text/plain” content type, then looks into ValueStack for a value id-ed with a string "jsonModel" which as shown in the third code excerpt (the Java action class code) above sets to hold value returned from a query of all Division entity stored in the database.

Finally, the resulted value is converted to a something else (alas, I need to see more of it) representable as JSON string. I achieved this with helps from XStream library and Jettison library.

4. The final step is to sent back the JSON String to the client. This is most trivial. The only problem was to determine how the resulted string is returned back from the server. In my case, the result String looks like this.

{”list”:{”arya199.entity.Division”:[{"id":1,"name":"Sales Department"},{"id":2,"name":"Accounting Department"}]}}

If this notation looks alien to you, better head to JSON for a proper explanation. However, as I want to populate my select element with these data, here’s how I retrieved the meaningful data from the returned String (also shown in the first code excerpt of this article).

var divisionList = (data.list);$('#divisionSelect').loadSelect(divisionList["arya199.entity.Division"]);

The first line ‘list’ is obviously refer to the same word ‘list’ as shown in the result, and it is. As we could see from the first code excerpt (the JavaScript one), the whole JSON String is returned and stored in a variable called data, and JSON treats this variable as any other object, therefore, calling data.list would yield {”arya199.entity.Division”:[{"..."}]}.

The second line then obtain the array value of data.list["arya199.entity.Division"] and passed it to a function that populates the select element with values obtained from this array.

i.e.

data.list["arya199.entity.Division"][0].name

would yield the first name element which according to this case, a string valued “Sales Department.”

document.doc / 18

Page 19: Ajax Struts2 Jquery

http://stackoverflow.com/questions/510843/ajax-validations-in-struts-2

If you want to use AJAX to do some server-side validation (and you'r using JQuery) this should at least get you started:

function validate(fieldName) {    $.get('/validation.php',          {'value' : fieldName.value, 'name' : fieldName.name},          function(data, textStatus) {                   if(data) {                           fieldName.style.class = 'validFormInput';                   } else {                           fieldName.style.class = 'invalidFormInput';                   }           }) }

document.doc / 19