Mar 24, 2009
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 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> <action name="addDivision" method="addDivision" class="arya199.action.EmployeeAction"> <result-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.
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.
Mar 23, 2009
-
The Wrestler (2008) - Randy “The Ram” Robinson is a professional wrestler way past his prime. Twenty years to be exact. And for a profession that requires dexterity and rather high pain endurance, twenty years past your prime isn’t really somewhere you want to be. The old age has surely taken its toll for the Ram. Having only known [...] »
Movies
Mar 18, 2009
-
Kanji Disassembled #8: ‘Green’ - Before I met my wife, when I was asked about “what is your favorite color?” I’d stared blankly at a point approximately an inch in front of my brow for a fraction of second before answering which of course, forgo the definition of a “favorite” in the first place. And my answer is always between [...] »
Mar 17, 2009
-
Struts 2 Select UI Tag Problem - Today, I’ve got a problem that manages to puzzled me for a good part of two hours with Struts 2 select UI tag behavior. This is the code responsible for the said puzzlement. <s:select name="employee.division" list="allDivisions" listKey="id" listValue="name" headerKey="-1" headerValue="-- Select Division --"/> Any seasoned Struts 2 programmers could tell by a glance what the [...] »
Mar 11, 2009
-
Kanji Disassembled #7: ‘Kanji’ - This week’s Kanji Disassembled is about the word ‘Kanji’ itself. As everyone who has the exposure to the Japanese language should be aware of, Kanji is a writing system adopted from China. When or how, doesn’t really matter, unless you’re a historian (and I’m not one), but one fact remains intact, somehow during the inception [...] »
Mar 04, 2009
-
Kanji Disassembled #6: ‘Cardinal Points’ - Whoever said that video games are only for kids needs to gets a reality check. Nowadays, if we talk about games (objects) or gamers (subjects), perhaps kudos to this cute little thing called Wii from Nintendo, we usually divides the discussion topic into two. Are you casual? Or are you hardcore? While it is true [...] »
Mar 03, 2009
-
Quarantine (2008) - Granted, making film in the manner used here in “Quarantine” is nothing entirely new. Back in 2002, “The Blair Witch Project” making a lot of fuss among the movie goers. At the time, though, I was still somewhat on the outside of this circle, looking in and truth be told, I never saw that film. [...] »
Movies
Feb 27, 2009
-
Struts 2 Custom Template - Abstract: Struts 2 Framework uses a specialized tags on its JSP file to generate its View page. The Framework processed these tags (UI tags) using template mechanism and these templates are written in FreeMarker language and every copy of Struts 2 Framework are shipped with a default template. This article shows that the Framework’s default [...] »
Feb 25, 2009
-
Kanji Disassembled #5: ‘Love’ - This week’s kanji is one of the very first kanji I memorized and learned to write in a perfection. And I never forget about it and about how and whence the strokes of this kanji went. It’s a kanji for “love” 愛 (Jap. あい|Ai). From top to bottom, the kanji would goes like this, “finger” [...] »
Feb 21, 2009
-
Righteous Kill (2008) - I had fond memories of “Heat”. I’m still too young when I saw it for the first time, back in 1996, and I had seen the film without any subtitles, added to the fact that I have yet developed a deeper affection toward films as half as I have right now but I was drawn [...] »
Movies



