AJAX Using Java
AJAX Using Java
Java
APTECH LIMITED
Contact E-mail: [email protected]
Second Edition - 2014
Dear Learner,
We congratulate you on your decision to pursue an Aptech Worldwide course.
Aptech Ltd. designs its courses using a sound instructional design model from conceptualization
to execution, incorporating the following key aspects:
The content outlines are developed by including additional topics that are required for the
completion of the domain and for the logical development of the competencies identified.
Evaluation strategy and scheme is developed for the subject. The topics are arranged/organized
in a meaningful sequence.
The detailed instructional material Training aids, Learner material, reference material, project
guidelines, etc.- are then developed. Rigorous quality checks are conducted at every stage.
Assessment of learning
The learning is assessed through different modes tests, assignments & projects. The
assessment system is designed to evaluate the level of knowledge & skills as defined by the
learning objectives.
*TAG Technology & Academics Group comprises of members from Aptech Ltd., professors from
reputed Academic Institutions, Senior Managers from Industry, Technical gurus from Software
Majors & representatives from regulatory organizations/forums.
Technology heads of Aptech Ltd. meet on a monthly basis to share and evaluate the technology
trends. The group interfaces with the representatives of the TAG thrice a year to review and
validate the technology and academic directions and endeavors of Aptech Ltd.
Industry Recruitment Profile Survey - The Industry Recruitment Profile Survey was conducted
across 1581 companies in August/September 2000, representing the Software, Manufacturing,
Process Industry, Insurance, Finance & Service Sectors.
1
Scanning the
user system
and needs
assessment
Evaluation of
Instructional
Processes and
Material
Need Analysis
and design of
curriculum
Design and
development of
instructional
material
Assessment
of learning
Strategies for
delivery of
instructions
Preface
A new breed of Web applications are emerging recently that have better, faster and more user-friendly
interfaces, almost as good as typical desktop interfaces. These Web applications do not need page
reloading unlike traditional Web applications. These Web applications use AJAX extensively.
AJAX is not a new programming language, rather it is a new technique of doing same old things. It is
a combination of JavaScript and XML. Besides these two technologies, several other technologies like
Java, .NET and a host of open source technologies are used to get the AJAX effect in a traditional Web
application.
This book starts with an overview of a typical AJAXified Web application. It then familiarizes you with
various AJAX features, technologies, toolkits and frameworks used in these new breed of Web applications.
This book is the result of a concentrated effort of the Design Team, which is continuously striving to bring
you the best and the latest in Information Technology. The process of design has been a part of the ISO
9001 certification for Aptech-IT Division, Education Support Services. As part of Aptechs quality drive,
this team does intensive research and curriculum enrichment to keep it in line with industry trends.
We will be glad to receive your suggestions.
Design Team
Table of Contents
Sessions
1.
Introduction to AJAX
2.
22
3.
46
4.
jMaki - I
65
5.
jMaki - II
98
6.
122
1
Module -
Introduction to AJAX
Welcome to the module, Introduction to AJAX.
Asynchronous JavaScript and XML (AJAX) refers to a group of Web
technologies. AJAX provides Web applications with rich user interface
(UI), similar to desktop applications, and improves their response time as
well. Reduced request-response time of Web applications makes the Web
applications highly responsive.
In this module, you will learn about:
Asynchronous JavaScript and XML
Document Object Model
Module
1
Introduction to AJAX
Concepts
Module
Introduction to AJAX
Web developers all over the world adapted to this trend of using disparate technologies. However, Jesse
James Garrett was the first to talk about them. In his article, Ajax: A New Approach to Web Applications,
Garrett listed the various technologies involved, discussed their roles and explained how they worked
together. Garrett named this group of technologies as Asynchronous JavaScript and XML (AJAX). Garretts
article marked the birth of AJAX.
3 of 154
Concepts
The aim to overcome the conventional Web applications drawbacks forced Web developers to look for
alternative Web development methods. Developers overcame the drawbacks using technologies like
JavaScript, XML, DOM, CSS, and so on.
Module
Introduction to AJAX
JavaScript
JavaScript facilitates the creation of XMLHttpRequest objects. XMLHttpRequest objects
facilitate asynchronous communication between the client and the server. Asynchronous
communication permits the user to continue interacting with the Web page on the client-side while
the XMLHttpRequest object retrieves data from the server. Thus, the user does not experience a
page refresh.
XML
The server-side components process the client request and send a corresponding response back to
the client. The response contains the data requested by the client. This data is sent to the client in
XML format.
DOM
DOM performs dual role in AJAX. Firstly, DOM allows you to parse the XML response received from
the server and extract the data from it. Secondly, it allows you to access the Web pages DOM tree
to add or update existing nodes with new data received from the server. In other words, DOM
facilitates the update of a Web page.
CSS
Concepts
4 of 154
Module
Introduction to AJAX
Figure 1.4 shows the various steps involved in processing the AJAX request and getting the response from
the server.
Step 1
The input text box is associated to an event handler with the help of the onkeyup event. Thus,
every time the user types a digit in the text box, the onkeyup event occurs. Every time the onkeyup
event occurs, an event handler is invoked.
Step 2
The event handler is a JavaScript function that creates an XMLHttpRequest object and configures
it using the open() method. The open() method specifies the HTTP method (GET or POST),
the URL of the server-side component that processes the request, and the mode (synchronous
or asynchronous) of communication. Note that the credit card number is included as a request
parameter in the HTTP request.
Step 3
The send() method of the XMLHttpRequest object is then invoked. This establishes a connection
with the server-side component such as a servlet or a JSP page. In this case, this component is a
servlet. Therefore, the servlet whose URI is mapped to ValidateCCN is executed.
5 of 154
Concepts
Module
Introduction to AJAX
Step 4
The processing of AJAX begins. The servlet first retrieves the credit card number from the request
object. This number is then sent to a credit card validator Web service. This service verifies the
credit card number and accordingly intimates the servlet.
Step 5
The servlet then generates an XML response. This XML response is an XML document containing
the element ccnumber with the text Valid or Invalid in it. If the credit card number is valid, the
text Valid is enclosed in the ccnumber element. This XML response is sent to the client.
Step 6
After the client receives the XML response, a callback function is called. The callback function is
usually specified in step 2 while configuring the XMLHttpRequest object. The XML response sent
by the server is accessible through the responseXML property of the XMLHttpRequest object.
Step 7
The callback function displays a message on the Web page about the validity of credit card number.
This is achieved by reserving a div element specifically for displaying such a message. The callback
function retrieves this div element using DOM API and sets its innerHTML property to display the
message.
Knowledge Check 1
1.
Which of the following statements about the evolution of AJAX are true?
(A)
(B)
(C)
(D)
Concepts
(E)
6 of 154
The c+lick, wait and refresh model was slow and hampered user interactivity to some
limit.
Conventional Web applications, while communicating with the Web server, rendered the
Web page useless.
Refreshing the entire page to display request results, added to higher request-response
latency.
Synchronous communication provided fast responses but fared badly when it came to
providing rich user interactivity.
Asynchronous communication is slower but less complicated than synchronous
communication.
(A)
A, B, and C
(C)
B, C, and D
(B)
C, D, and E
(D)
B, D, and E
Module
2.
Introduction to AJAX
Which of the following statements about the working of AJAX are true?
(A)
The callback function is specified in the responseXML property with the help of the
send() method of XMLHttpRequest object.
A client event on the Web page invokes an event handler that updates the Web page
instantaneously.
The callback function is called only after successful receipt of XML response from the
server.
The XMLHttpRequest objects send() method invokes the server-side component that
processes the AJAX request.
The callback function uses DOM to display data on a Web page.
(B)
(C)
(D)
(E)
(A)
A, B, and C
(C)
B, C, and D
(B)
C, D, and E
(D)
B, D, and E
Consider the Example.html file shown in figure 1.5. It has six lines of code. html is the main tag. It has
two sub tags, title and body respectively. title contains text while body consists of a sub tag, h1. Again, h1
contains text. Using these observations a tree structure can be created as shown in figure 1.5.
7 of 154
Concepts
DOM represents HTML or XML document as a collection of objects referred as nodes. Based on how these
objects are placed in the document, DOM connects each of these nodes creating a tree like structure.
DOM classifies every node as a specific type of node. For example, tags are classified as element nodes
where as text within the tags is classified as text nodes.
Module
Introduction to AJAX
getElementById(id)
The getElementById() method searches for and returns the element whose id is specified as
the input parameter.
Concepts
Syntax:
getElementByID(id)
where,
id - value of the id attribute of an element in an HTML document
8 of 154
Module
Introduction to AJAX
The code snippet when added to Example.html results in the following output:
Hello World 1!
Hello World 2!
Hello World 3!
Hello World 4!
getElementsByTagName(name)
The getElementsByTagName() method searches for and returns all such elements whose name
matches to the one specified as the input parameter. It returns the entire list of elements in the
form of an array.
Syntax:
getElementsByTagName(name)
where,
name name of a tag in an HTML document
x = document.getElementsByTagName(p);
Concepts
<script type=text/javascript>
document.write(x[i].innerHTML);
document.write(<br />);
}
</script>
9 of 154
Module
Introduction to AJAX
The code snippet when added to Example.html results in the following output:
Hello World 1!
Hello World 2!
Hello World 3!
Hello World 4!
Hello World 1!
Hello World 2!
Hello World 3!
Hello World 4!
appendChild(node)
The appendChild() method appends the node specified as input parameter to the tree structure.
Syntax:
appendChild(node)
where,
Code Snippet:
<script type=text/javascript>
x = document.getElementsByTagName(p);
x[0].appendChild(x[3].childNodes[1]);
</script>
The code snippet when added to Example.html results in the following output:
Hello World 1! World 4!
Hello World 2!
Concepts
Hello World 3!
Hello
removeChild(node)
The removeChild() method removes the node specified as input parameter from the tree
structure.
10 of 154
Module
Introduction to AJAX
Syntax:
removeChild(node)
where,
node the exact node that needs to be removed
x = document.getElementsByTagName(p);
x[2].removeChild(x[2].childNodes[1]);
</script>
The code snippet when added to Example.html results in the following output:
Hello World 1!
Hello World 2!
Hello
Hello World 4!
innerHTML
The innerHTML property provides access to the content of an element. Therefore, you can use this
property to retrieve or update the text in an element.
The code shows the use of the innerHTML property.
Code Snippet:
<script type=text/javascript>
x = document.getElementById(one);
Concepts
document.write(x.innerHTML);
</script>
11 of 154
Module
Introduction to AJAX
The code snippet when added to Example.html results in the following output:
Hello World 1!
Hello World 2!
Hello World 3!
Hello World 4!
Hello World 1!
nodeName
The nodeName property provides access to the name of the current node. It is used to display the
name of the current node.
The code shows the use of the nodeName property.
Code Snippet:
<script type=text/javascript>
x = document.getElementById(one);
document.write(x.nodeName);
</script>
The code snippet when added to Example.html results in the following output:
Hello World 1!
Hello World 2!
Hello World 3!
Hello World 4!
P
nodeValue
The nodeValue property can be used to display a nodes content. The nodeValue property when
used with text nodes returns the nodes content. The nodeValue property when used with element
nodes returns the value null.
Concepts
x = document.getElementById(one);
document.write(x.nodeValue);
</script>
12 of 154
Module
Introduction to AJAX
The code snippet when added to Example.html results in the following output.
Hello World 1!
Hello World 2!
Hello World 3!
Hello World 4!
null
The p node has null value. However, it does have two child nodes: a text node and another element
node.
parentNode
The parentNode property provides access to the parent node of the current node.
Code Snippet:
<script type=text/javascript>
x = document.getElementById(one);
document.write(x.parentNode.nodeName);
</script>
The code snippet when added to Example.html results in the following output:
Hello World 1!
Hello World 2!
Hello World 3!
Hello World 4!
BODY
childNodes
The childNodes property provides access to all the child nodes of the given node. You can access
the child nodes by using prefixes. For example, childNodes[1] will return the second child node
of the current node.
The code shows the use of the childNodes property.
Concepts
Code Snippet:
<script type=text/javascript>
x = document.getElementsByTagName(p);
document.write(x[2].childNodes[0].nodeValue);
</script>
13 of 154
Module
Introduction to AJAX
The code snippet when added to Example.html results in the following output:
Hello World 1!
Hello World 2!
Hello World 3!
Hello World 4!
Hello
length
The length property returns the number of nodes present in a node list. The
getElementsByTagName() method returns a list of all the nodes having a specific tag name.
The length property returns the total number of nodes present in the list.
The code shows the use of the length property.
Code Snippet:
<script type=text/javascript>
x = document.getElementsByTagName(p);
document.write(x.length);
</script>
The code snippet when added to Example.html (as shown in the image) results in the following
output:
Hello World 1!
Hello World 2!
Hello World 3!
Hello World 4!
Concepts
XML Document Object Model (XML DOM) allows you to access and manipulate XML documents using
methods similar to that of HTML DOM.
14 of 154
Module
Introduction to AJAX
getElementsByTagName(name)
The getElementsByTagName() method searches for and returns elements whose name matches
with the input parameter.
Syntax
getElementsByTagName(name)
where,
name name of a tag in an XML document
Concepts
xmlDoc.async = false;
15 of 154
Module
Introduction to AJAX
xmlDoc.load(Student.xml);
x = xmlDoc.getElementsByTagName(name);
document.write(x[i].childNodes[0].nodeValue);
document.write(<br />);
}
</script>
In accordance with the XML content shown on screen, the script generates the following result:
Ashley Andrews
Ashley Mathias
Ashley Waters
appendChild(node)
The appendChild() method appends the node specified as input parameter to the tree structure.
Syntax
appendChild(node)
where,
xmlDoc.async = false;
xmlDoc.load(Student.xml);
x = xmlDoc.getElementsByTagName(name);
Concepts
x[0].appendChild(x[1].childNodes[0]);
document.write(x[0].childNodes[0].nodeValue);
document.write(x[0].childNodes[1].nodeValue);
</script>
16 of 154
Module
Introduction to AJAX
removeChild(node)
The removeChild() method removes the node specified as input parameter from the tree
structure.
Syntax
removeChild(node)
where,
node the exact node that needs to be removed
xmlDoc.async = false;
xmlDoc.load(Student.xml);
x = xmlDoc.getElementsByTagName(name);
x[0].removeChild(x[1].childNodes[0]);
document.write(x[0].childNodes[0].nodeValue);
</script>
In accordance with the XML content shown on screen, the script generates the following result:
A Runtime Error has occurred.
Do you wish to Debug?
Line: 8
Error: The parameter Node is not a child of this Node.
Yes or No?
Concepts
Note - Unlike HTML DOM, XML DOM does not support the getElementByID() method.
17 of 154
Module
Introduction to AJAX
nodeName
The nodeName property provides access to the name of the current node. It is widely used to
display the name of the current node.
The code shows the use of the nodeName property.
Code Snippet:
<script type=text/javascript>
xmlDoc.async = false;
xmlDoc.load(Student.xml);
x = xmlDoc.getElementsByTagName(name);
document.write(x[0].nodeName);
</script>
In accordance with the XML content shown on screen, the script generates the following result:
name
nodeValue
The nodeValue property can be used to display a nodes value. Not all nodes have values. For
example, an element node could either have a text node or another element node as its child node.
In either case, the element node will always have a value of null.
The code shows the use of the nodeValue property.
Code Snippet:
Concepts
<script type=text/javascript>
xmlDoc.async = false;
xmlDoc.load(Student.xml);
x = xmlDoc.getElementsByTagName(name);
document.write(x[2].childNodes[0].nodeValue);
</script>
In accordance with the XML content shown on screen, the script generates the following result:
18 of 154
Module
Introduction to AJAX
Ashley Waters
parentNode
The parentNode property provides access to the parent node of the current node. You can use the
parentNode property to access or gain control of the current nodes parent.
The code shows the use of the parentNode property.
Code Snippet:
<script type=text/javascript>
xmlDoc.async = false;
xmlDoc.load(Student.xml);
x = xmlDoc.getElementsByTagName(name);
y = x[0];
document.write(y.parentNode.nodeName);
</script>
In accordance with the XML content shown on screen, the script generates the following result:
record
childNodes
The childNodes property provides access to all the child nodes of the given element. It returns
a list of all the child nodes present. You can access the various child nodes using prefixes. For
example, the second child node is accessed using expression childNodes[1].
The code shows thw use of the childNodes property.
Code Snippet:
<script type=text/javascript>
xmlDoc.async = false;
xmlDoc.load(Student.xml);
x = xmlDoc.getElementsByTagName(name);
Concepts
document.write(x[2].childNodes[0].nodeValue);
</script>
In accordance with the XML content shown on screen, the script generates the following result:
Ashley Waters
19 of 154
Module
Introduction to AJAX
length
The length property returns the number of nodes present in a node list. The
getElementsByTagName() method returns a list of all the nodes having a specific tag name. The
length property returns the total number of nodes present in the list.
The code shows the use of the length property.
Code Snippet:
<script type=text/javascript>
xmlDoc.async = false;
xmlDoc.load(Student.xml);
x = xmlDoc.getElementsByTagName(name);
document.write(x[i].childNodes[0].nodeValue);
}
</script>
In accordance with the XML content shown on screen, the script generates the following result:
Ashley AndrewsAshley MathiasAshley Waters
attributes
The attributes property returns a list containing the specified nodes attributes. If the specified
node is not an element, this property returns NULL.
The code shows the use of the attributes property.
Code Snippet:
<script type=text/javascript>
xmlDoc.async = false;
Concepts
xmlDoc.load(Student.xml);
x = xmlDoc.getElementsByTagName(record)[0].attributes;
attri = x.getNamedItem(id);
document.write(attri.value);
</script>
20 of 154
Module
Introduction to AJAX
In accordance with the XML content shown on screen, the script generates the following result:
1
Knowledge Check 2
1.
A, B, and C
(C)
B, C, and E
(B)
C, D, and E
(D)
A, D, and E
Concepts
21 of 154
Module
Introduction to AJAX
Summary
In the module, Introduction to AJAX, you learnt about:
Concepts
The Document Object Model is a platform and language-independent standard for representing
HTML and XML documents. It creates tree-like structures of objects present in HTML or XML documents. It then classifies these objects as nodes. Each node has properties. Using these properties
and some methods you can update HTML documents and extract data from XML documents.
22 of 154
Module -
Module
2
Using Dojo Toolkit
Explain Dojo.
Explain the steps to create a button widget using the Dojo toolkit.
Quality
Dojo widgets use the combination of CSS, DOM, and JavaScript to create a rich User Interface (UI).
Therefore, these widgets deliver same output quality across all browsers.
Performance
Dojo provides tools to handle high-traffic sites. Using Dojo, you can manage big projects without
making any change in the code. Dojo also helps in the creation of a custom toolkit that can provide
performance similar to the actual toolkit.
Community
Dojo is an open source community, and hence many organizations and individuals contribute in
improving it. The goal of the toolkit is to be as simple as possible so that the end users can use it
with ease.
Concepts
2.1.2
Features of Dojo
The five main features of Dojo that help in designing AJAX-based applications are:
Widget
Dojo provides many widgets such as menus, trees, tabs, tool tips, date selector, time selector, and
so on for designing Web pages. You can create Dojo widgets by using JavaScript, HTML, and CSS
style declarations.
24 of 154
Module
Asynchronous communication
AJAX applications send and receive data from a server asynchronously by using the XMLHttpRequest object. However, you have to write a lot of JavaScript code to implement this functionality.
Dojo provides an abstract wrapper method called dojo.xhrGet() that allows you to exchange
data asynchronously using minimal code.
Packaging System
The packaging system in Dojo allows you to list the packages that need to be imported for the application. Thus, there is no need to include a script tag for every script file that is to be loaded. The
packaging system ensures that the required package is loaded using the dojo.require() function.
Code Simplification
Dojo provides wrappers that encapsulate all the functionality required to send and receive AJAX
requests. Dojo also handles cross browser incompatibility issues.
Reusable Code
Dojo supports reusability of code. In other words, you can use dojo code of one application in
another application. Such reusability of code allows you to add new functionalities to existing applications with minimal effort.
Portable Tools
Dojo provides several widgets for Web page authors and designers. You can add new functionalities
to existing Web pages by using Dojo widgets. A page author need not learn additional programming
language to use the Dojo widgets.
25 of 154
Concepts
Module
2
Using Dojo Toolkit
Note - Disadvantage of Dojo is that a developer has to depend on the browser support for the Dojo. In
Concepts
26 of 154
Module
In Programmatic model, the widget class, style, and id are passed as parameters to the constructor.
The btnExit variable will refer to the instantiated widget. The first parameter refers to the Button class
that is used by Dijit to initialize the Button widgets properties. The second parameter shows the label
of the button. The third parameter uses the dijit.byId() function to refer the Exit button by its id
name.
Figure 2.2 shows the creation of a Button widget declaratively and programmatically.
Concepts
27 of 154
Module
2
Using Dojo Toolkit
Figure 2.4 shows the steps to set up and load Dojo in a Web page.
Concepts
The Dojo Widget library, also known as Dijit, contains several widgets for designing Web pages. The
most commonly used widget is a button. Figure 2.5 shows the code to create a Button widget with the
caption Hello Dojo!
Module
To create a Button widget, you first load the Button widget module by using the dojo.require()
function. In the body section of the HTML document, you create a Button widget by using the button tag.
The dojoType attribute instructs Dojo about the type of the widget to be displayed.
In Dojo, you connect an event handler to a widget through a script tag. Note that the script tag is
written within the button tag. Additionally, the type attribute of the script tag uses dojo/method
to indicate that the script is a method. This method is bound to the onclick event using the event
attribute. Therefore, when the button is clicked, an alert message is displayed on the page.
29 of 154
Concepts
Module
Knowledge Check 1
1.
2.
(A)
A, B, and C
(C)
B, C, and E
(B)
C, D, and E
(D)
A, C, and D
Which of the following statements about Dojo architecture and its working are false?
(A)
(B)
(C)
(D)
(E)
3.
Dojo provides a set of three layered libraries namely, the packaging system, the event
system and the language utilities layer.
Dojo fails to overcome compatibility issues across major browsers.
Dojos programming model allows you to create widgets using tags.
The Dojo programming model can be used only declaratively.
The Dojo code is divided into logical units called modules.
(A)
A, B, and C
(C)
B, C, and E
(B)
B and D
(D)
A and C
Which of the following code snippet will create a Dojo button widget with the caption Close?
(A)
Concepts
<body class=tundra>
<button dojoType=dijit.form.Button>Close</button>
</body>
30 of 154
Module
(B)
(C)
</body>
<script type=text/javascript src=./dojo/dojo.js>
dojo.require(dijit.form.Button);
</script>
...
<body class=tundra>
<button dojoType=dojo.form.Button>Close</button>
(D)
</body>
<script type=text/javascript src=./dojo/dojo.js>
dojo.require(dijit.Button);
</script>
...
<body class=tundra>
<button dojoType=dijit.button>Close</button>
</body>
Explain Dijit.
31 of 154
Concepts
In the last lesson, Dojo Widget Library, you will learn to:
Module
2
Using Dojo Toolkit
Based on the context, you use the term Dijit for a single Dojo widget or the term Dijits for the all
the widgets in the toolkit.
Some of the widget libraries available include CheckBox, RadioButton, ComboBox, TextBox, TextArea,
ValidationTextBox, and so on.
Concepts
32 of 154
Module
AccordionContainer
The AccordionContainer layout displays multiple panes. You can click a panes title to pull up or pull
down the panes. Only one complete pane is visible at a time.
BorderContainer
The BorderContainer layout divides the container into top, left, bottom, right, and center sections.
The layout also provides optional splitter controls to allow users to adjust the dimensions. For example, this layout can be used to reserve the top 100 pixels of the screen for title and navigation,
and the rest for the displaying some other content.
ContentPane
The ContentPane layout resembles an internal frame, but contains additional design features. A
ContentPane is the most basic layout container that is placed inside the layout container.
33 of 154
Concepts
Module
SplitContainer
The SplitContainer layout splits the children into many sections. You can adjust the size of each
section.
StackContainer
The StackContainer layout has multiple children, but shows only one child at a time. This container
can be used for slide shows, allowing the user to display one pane at a time.
TabContainer
The TabContainer layout resembles a tabbed folder. To display the content of a particular tab, you
click the corresponding tab title.
Concepts
Button is the most important and widely used form element. The look-and-feel of a Dojo button is far
better than an HTML button. You can display text or an icon on the button. You can display an image on
the button by using the img tag within the button tag. Like HTML buttons, the Dojo button automatically
resizes itself to fit the caption.
34 of 154
Module
Radio buttons are used when there is a list of two or more options and you want to allow the users to
select only one option from the list of options. Note that you import the CheckBox and RadioButton
classes by using dijit.form.*. The name attribute defines a common name, group1, for all the radio
buttons. The label tag displays a label for the radio button.
35 of 154
Concepts
Check boxes are used when you want to allow a user to select zero or more options from a set of options.
Dojo check boxes are similar to HTML check boxes, but the former provides more styling options. To
render a selected check box, you can set the value of the checked attribute as checked. The value
attribute returns the value of the selected check box.
Module
2
Using Dojo Toolkit
Figure 2.10 shows the creation of check box and radio button using dijit.
Concepts
2.2.6
Dojo combo box is a combination of a drop-down list and a single-line text box. A user can display the
list by clicking the drop-down arrow. As the user moves the pointer over the list, each option under the
pointer is highlighted. If the user selects an option from the list, the current selection is replaced with the
selected option.
You create a combo box widget by using the select and option tags as shown in the image, The
dojoType attribute uses the value digit.form.FilteringSelect.
36 of 154
Module
The autocomplete attribute is set to false, which forces the user to write the entire text in the combo
box to confirm its availability in the options provided.
Figure 2.11 shows the creation of AutoCompleter Combo box using dijit.
Dialog box is a rectangular GUI window that either requests or provides information to the user. Dojo
provides the digit.Dialog class to create a dialog box.
37 of 154
Concepts
Module
2
Using Dojo Toolkit
Concepts
Dojo provides a function named dojo.xhrGet() to send and receive data asynchronously. The image
shows the code to send an AJAX request using Dojo. Note that the script tag is enclosed within the
button tag and bound to the onclick event. This ensures that the script is executed on the click of the
Dojo button.
38 of 154
Module
url
The url attribute specifies the name of the server-side component such as a JSP page or a servlet
that will process the AJAX request. Here, the servlet named DataServlet acts as the server-side
component.
handleAs
The handleAs attribute specifies the MIME type such as text, json, javascript, and xml. Here, the
MIME type used is xml, as the DataServlet will send an XML response.
load
error
The error attribute specifies the name of the callback function that will be executed in case an error is encountered while processing the request. Here, the loginError() function will be called.
39 of 154
Concepts
The load attribute specifies the name of the callback function that will be executed after successful receipt of response. Here, the loginCallback() function will be called.
Module
Concepts
Server-side Code
Figure 2.15 shows the doGet() method of DataServlet. This method will process the AJAX
request and send an XML response back to the client.
40 of 154
Module
First, the content type of the response is set to text/xml indicating that the response will contain
XML data. Next, an instance of PrintWriter is created to write data to the response. Then, you
retrieve the value of request parameter named nameParam and store it in a variable, param.
Finally, you write the XML data to enclose the value of variable param in the name element.
Figure 2.15 shows the implementation of the doGet() method at the server-side.
Concepts
41 of 154
Module
Knowledge Check 2
1.
2.
Dijit is a widget system that can be used to build good GUIs using minimal JavaScript code.
(B)
(C)
The AccordionContainer layout consists of panes that are pulled up or down by clicking
the pane title.
(D)
The StackContainer layout has multiple children, but shows only one child at a time.
(E)
(A)
A, B, and C
(C)
B, C, and E
(B)
C, D, and E
(D)
A, C, and D
Which one of the following code snippets will create two radio buttons with the labels Graduate and
Post Graduate respectively?
<script type=text/javascript src=./dojo/dojo.js>
dojo.require(dijit.RadioButton); </script>
<body class=tundra>
(A)
(B)
Concepts
42 of 154
Module
(C)
(D)
3.
Consider a scenario where you want to send the value of a Dojo widget, named bookname,
asynchronously. A callback function named bookCallback will process the XML response sent by
servlet, BookServlet. Which one of the following code snippets will allow you to achieve this?
dojo.xhrGet({
url: BookServlet,
(A)
handleAs: text,
load: bookCallback,
content: {param: dojo.byId(bookname).value}
});
dojo.xhrGet({
url: BookServlet,
handleAs: xml,
load: bookCallback,
Concepts
(B)
43 of 154
Module
2
Using Dojo Toolkit
dojo.xhrGet({
url: BookServlet,
(C)
handleAs: xml,
load: bookCallback,
content: {param: dojo.byId(bookname).value}
});
dojo.xhrGet({
url: BookServlet.java,
type: javascript,
(D)
load: bookCallback,
content: {param: dojo.byId(bookname).value}
Concepts
});
44 of 154
Module
Summary
In the module, Using Dojo Toolkit, you learnt about:
Dojo Toolkit
Dojo is an open source JavaScript toolkit for developing AJAX-based applications. The benefits of
using Dojo toolkit include code simplification, and reusability of code. The Dojo programming model follows object-oriented approach. Dojo toolkit includes the modules Dojo, Dijit, Dojox, and Util.
Concepts
Dojo Widget Library (Dijit) is a widget system that enables quick and easy development of Web
pages. Dijit provides several layouts that determine the placement of widgets on a Web page.
Some of the widgets available in Dijit are CheckBox, RadioButton, ComboBox, TextBox, DialogBox,
and so on. Dojo supports asynchronous mode of communication by sending AJAX-based requests
to a server.
45 of 154
Module -
Module
JSON objects are typed whereas XML objects are untyped. JSON supports data types such as
string, number, array and boolean, whereas XML supports only the string data type.
JSON code is native to JavaScript code. It is readily accessible to JavaScript code. However, XML
code needs to be parsed and assigned to variables using tedious DOM operations.
Object
An object is a collection of unordered name/value pairs. A JSON object is represented by {}.
Object Member
A JSON object member consists of a name/value pair, which is a combination of string and value.
Members are separated by using commas. Object name and its value in a name/value pair are
separated by a colon.
Array
A JSON array consists of elements or values that are separated by commas.
47 of 154
Concepts
3
Module
Value
A JSON value can be a string, a number, a boolean, an object, null or an array.
String
A JSON string consists of Unicode characters except double quotes (), backslash (\), or control
characters. A JSON string is enclosed within double quotes.
The code snippet represents the personal details of Jack Daniels in JSON notation using JSON
elements.
Code Snippet:
{
fullname: Jack Daniels,
company: JSON Consulting,
age : 20,
email: [
{type: work, value: [email protected]},
{type: home, value: [email protected]}
],
contactno: [
{type: work, value: 123456},
{type: fax, value: 345678},
{type: mobile, value: 9987651111}
],
addresses: [
{type: work, format: us,
Concepts
48 of 154
Module
The code snippet creates an object named employee. It contains two attributes or name/value pairs,
name and age. The values are Samson and 20. Samson is a string but age is a number. You can access the
attributes name and age by writing employee.name and employee.age.
Note - There is no limit to JSON object nesting.
Array elements
You can access and modify an array element by using an index that is zero(0)- based. You can access attribute of an array element as array_name[index].attribute. If multiple name/value pairs are
present instead of single attribute, these will be enclosed in {}.
49 of 154
Concepts
3
Module
Concepts
In the code snippet, the fullname : Jack Daniels is an example of name/value pair or an object
member. The email, contactno and addresses are example of arrays that consist of name/value
pairs separated by commas. Each array holds its elements as JSON objects in []. Each array element
holds its name/value pairs within {}, email[0] represents first element, and so on. Jack Daniels is
a String and 20 is a number.
50 of 154
Module
The client converts the string data into a JavaScript object by using the statement, eval((+request.
responseText+)).
2.
The client can access and modify properties of the converted JavaScript object.
The server finds an appropriate parser depending on the programming language of the server-side
program. For example, if the server application is written using JSP/servlets, the server uses a parser
from the org.json package.
2.
The parser interprets JSON text into a language that the server understands.
51 of 154
Concepts
The server uses the following steps to processes the JSON text received from the client:
3
Module
2.
JavaScripts eval() method is invoked to convert the JSON text into a JSON object.
3.
Concepts
52 of 154
Module
To send a JSON object as part of a client request, convert the JSON object into a string data by using
toJSONString(), and then use GET or POST method with XMLHttpRequest object.
GET request method allows transferring of JSON data from client to server, but it compromises security
of data. Besides, it does not allow you to send large amount of data. If you want to send large amount of
confidential data, you should use the POST request method.
Server can generate JSON data and send it to client as part of response text.
53 of 154
Concepts
3
Module
2.
3.
4.
Knowledge Check 1
1.
Concepts
Description
2.
Element
(1)
Object
(B)
(2)
Object Member
(C)
(3)
Array
(4)
String
(E)
(5)
Value
(A)
(C)
(B)
(D)
Can you match the receiving methods for JSON data with descriptions?
(A)
(B)
54 of 154
Description
Executes only JSON text
Safest and parses only JSON text
(1)
(2)
Receiving Methods
Assignment
Callback
Module
3.
(C)
(3)
Parse
(D)
(4)
parseJSON()
(E)
(5)
eval()
(A)
(C)
(B)
(D)
Which of the following code snippet will send JSON data to client?
JSONObject jsonObject = new JSONObject();
(A)
(B)
(C)
jsonObject.toString();
JSONObject jsonObject = new JSONObject();
Concepts
55 of 154
3
Module
Concepts
Features that make DWR more useful compared to similar products are:
Integration with popular frameworks: DWR library supports Spring, Hibernate, Struts and JSF
frameworks.
56 of 154
Module
Reverse AJAX: DWR allows the server to connect with clients and send updated data to clients
asynchronously.
Java Servlet: Processes client requests and sends responses back to the client. DWR contains a
runtime library that helps the servlet to process requests and responses.
JavaScript code: Runs in the client application. It can dynamically update the Web page with the
help of a JavaScript library that is part of the DWR architecture.
Figure 3.8 shows the components of DWR.
In DWR-based AJAX applications, the DWR servlet dynamically generates JavaScipt classes for each
exposed server-side Java class.
The workflow of DWR can be summarized as:
1.
DWR dynamically generates the client-side JavaScript code, called stub. The stub handles remote
communication between browser and server.
57 of 154
Concepts
3
Module
2.
The JavaScript code at the client-side routes calls to the server-side methods through the stub. The
DWR servlet receives the client requests and calls the appropriate server-side methods.
3.
DWR converts the data types of method parameters, received from the client application, to Java
data types.
4.
DWR converts the data types of return values, from the server-side methods, to JavaScript data
types. Since data types of Java and JavaScript are different, conversion of the data types is
required.
5.
DWR asynchronously invokes the client-side callback methods by using the XMLHttpRequest object
and sends the server response from the servlet to the callback function.
Note - Present version of DWR supports only limited data types for conversion between Java and
Concepts
Declare a callback function in the client-side code. The callback function handles responses from the
server.
58 of 154
Module
2.
Register the callback function with the server. To register the callback function, you need to pass an
additional parameter when calling the remote methods. After making an asynchronous request, the
client can carry out other tasks. When the server completes synchronous processing of the client
request, the server invokes the callback function to pass the response data.
The code snippet shows how to declare a callback function in JavaScript- based client and register it with
server.
Code Snippet:
//Declare callback function in client-side
function handleGetName(str){
alert(str);
}
//Server-side Java Class that will be remotely accessed by browser
public class Student{
public String getName(String name) {...}
}
// Invoke remotely getName() from client-side and
// register callback function getName()
StudentJavaScript.getName(42, handleGetName);
59 of 154
Concepts
In code snippet, the handleGetName() is declared as callback function. The server-side Java class,
Student, is exposed to client application. DWR generates JavaScript class, StudentJavaScript, from
this class. Client calls the getName() method of the remote Student class by using the generated
JavaScript class. It also registers callback method, handleGetName(), with the server by passing it as
argument to getName().
3
Module
Modify web.xml
The DWR servlet in an AJAX application processes requests and responses. You must add mapping
for DWR servlet in the web.xml file, located in /WEB-INF of the Web application.
The tag <servlet-name> indicates a DWR servlet named dwr-invoker. The tag <servletclass> indicates actual class name of the DWR servlet. The DWR servlet is located in the package,
org.directwebremoting.servlet. The initial parameters in tag <init-param> indicate that
DWR servlet can be in debug mode. Finally, the <servlet-mapping> tag maps the servlet to the
url pattern /dwr/*.
Concepts
Configure DWR
Add one more XML file, called dwr.xml in same folder with WEB-INF/web.xml. The file is DWR
configuration file.
60 of 154
Module
In the code snippet, dwr.xml determines which Java classes DWR can convert to JavaScript classes.
A dwr.dtd is declared at the beginning. The tag <create> generates a JavaScript class Student
from Student class defined in tag <param>.
Figure 3.12 shows the dwr.xml configuration file.
Client-Side JavaScript
You must include the JavaScript files engine.js and util.js in the client-side application. These
files are part of the DWR JavaScript library. The engine.js file provides core DWR functionalities.
The util.js file provides DWR utilities. The file Student.js is the generated JavaScript file.
Concepts
61 of 154
3
Module
Knowledge Check 2
1.
Which of the following statements with respect to DWR architecture are true?
(A)
(B)
(C)
(D)
(E)
2.
(A)
A and B
(C)
B and D
(B)
D and E
(D)
C and E
Which of the following code snippet correctly handles asynchronous AJAX calls?
(A)
function handleGetName(str){
alert(str);
}
public class Student{
Concepts
62 of 154
Module
(B)
(C)
JavaScript.getName(42, handleGetName);
function handleGetName(str){
alert(str);
}
public class Student{
public String getName(String name) {...}
}
(D)
Student.getName(42, handleGetName);
function handleGetName(str){
alert(str);
}
public class Student{
public String getName(String name) {...}
}
(C)
(D)
Description
Allows bidirectional communication between
client and server
Exchanges XML information in distributed
system
Exchanges XML messages using HTTP/HTTPS
Based on Java technology
(E)
(A)
(B)
(1)
DWR
(2)
XML-RPC
(3)
JSON-RPC
(4)
(5)
Technology
SOAP
JSON-RPC
(A)
(C)
(B)
(D)
Concepts
3.
63 of 154
3
Module
Summary
In the module, JSON and DWR, you learnt about:
JSON
JSON is a subset of JavaScript language that is used for interchanging of data between a browser
and the server. It is easier to manipulate as compared to XML.
DWR
Concepts
DWR is an AJAX framework that can generate JavaScript code from Java classes. It is based on Java
technology. A client browser can access remote Java classes that runs in the Web server by invoking the generated JavaScript functions. You can decide which Java classes will be accessible to the
client browser by configuring DWR.
64 of 154
Module -
jMaki - I
Welcome to the module, jMaki - I. This module introduces you to jMaki
and its features. jMaki is a light weight client-server framework that helps
easy development of JavaScript-based AJAX Web applications.
In this module, you will learn about:
jMaki Architecture
jMaki Widgets
Module
4
jMaki - I
4.1.1 Origin
jMaki is an open source, light weight client-server framework. jMaki originated in Kumamoto, Japan. The
letter j in jMaki represents JavaScript technology and Maki, which is a Japanese word, means to wrap.
In other words, jMaki means JavaScript wrappers.
jMaki is used for creating AJAX applications by integrating JavaScript technology into the applications.
jMaki allows you to include styles and templates, widget model, and client services, such as event
handling, in a client application. For server applications, jMaki provides server runtime component and a
generic proxy, named XMLHttpProxy. XMLHttpProxy enables the server applications to interact with
external Web services outside the application domain. JMaki provides access to widgets from various
toolkits as a JSP taglib or as a JSF component.
Concepts
Module
jMaki - I
modules. The advantages of this framework are that its sections are independently configurable, and
it is easy to learn.
4.1.2 Features
The main aim of jMaki is to enable communication between client-side JavaScript and the multiple server
technologies. Some of the features of jMaki are:
Concepts
jMaki describes tree, table, and menu structures using JavaScript Object Notation (JSON) format.
The consistent programming model helps in standardization of data and event model by jMaki. This
enables the widgets from various toolkits to work with the same set of data.
67 of 154
Module
jMaki - I
It hides low level widget details by providing default values for widgets.
It references a widget in JSP page by adding appropriate tag library and including appropriate
widget tag.
It uses JSF architecture for handling inputs and validating user inputs by wrapping the widgets as
JSF components.
It requires no prior knowledge in DOM, CSS and JavaScript technology. However, you will need to
use JavaScript code to implement widget functionalities.
Concepts
Module
jMaki - I
jMaki Layouts
jMaki provides different layouts to help reduce efforts and time required to create/design the
layout of a Web page. jMaki uses HTML and CSS to create these layouts. You can easily customize
these layouts.
Concepts
jMaki widget model provides a component model for reusable JavaScript components. The
structure of Widgets is based on HTML, CSS, and JavaScript. jMaki stores widget descriptions in
widget.json format.
69 of 154
Module
jMaki - I
Figure 4.3 shows the client-side components of jMaki framework.
XMLHttpProxy
Concepts
XMLHttpProxy allows widgets to access JSON or other external services, such as Flickr image
searches. Direct Communication takes place between the widgets and the services.
70 of 154
Module
jMaki - I
jMaki applications can range from simple applications containing few widgets to complex applications
containing multiple jMaki widgets.
71 of 154
Concepts
Module
jMaki - I
resources
The resources directory contains all the resources used by a jMaki application.
jmaki.js
The jmaki.js is a JavaScript file that contains code for loading jMaki widgets and functions for widget communication. It is present in the resources directory.
config.json
Concepts
The config.json file contains theme information, extension mapping information and glue mapping
information for wiring widgets.
jmaki-comp.jar
The jmaki-comp.jar file that contains the server runtime code is present in the /WEB-INF/lib directory.
hello
The hello is a widget and its resources are present in the /resources/hello directory. A widget is a
directory comprising component.css, component.js, and component.htm file.
72 of 154
Module
jMaki - I
glue.js
The glue.js file glues widgets together. It is used for registering and defining widget event listener,
publishing events to a topic and subscribing to a topic.
Knowledge Check 1
1.
Can you match the client and server side components with their descriptions?
Description
2.
Components
(A)
(1)
(B)
(2)
jMaki Layouts
(C)
(3)
(D)
(4)
XMLHttpProxy
(E)
(5)
(A)
(C)
(B)
(D)
Which of the following statements describing the features of jMaki are true?
(A) AJAX components are wrapped as a JSP tags or JSF components.
(B)
(C)
(A)
A, B, and C
(C)
B, D, and E
(B)
A, D, and E
(D)
C, D, and E
Concepts
(E)
73 of 154
Module
3.
jMaki - I
Which of the following statements describing the advantages of using jMaki and application structure
of jMaki are false?
(A) The config.json file glues the widgets together.
(B)
(C)
(D) The jMaki.js is a JavaScript file containing the code for loading jMaki widgets.
(E)
(A)
A and B
(C)
B and D
(B)
D and E
(D)
C and E
Concepts
A jMaki widget is a reusable parameterized component. jMaki ensures that proper parameters are passed
to a widget code to initialize the widget in a page.
The name of a widget maps to a directory. In other words, a jMaki widget is a directory or a package
where the widget resides. The directories are separated using dot notation. The directory which makes
a widget comprises of three core resource files. They are:
component.css
This file defines the CSS styles for a widget when it is displayed. It contains the code controlling the
appearance of the widget. It is optional.
74 of 154
Module
jMaki - I
The CSS file contains the code defining the appearance of the widget.
component.js
This file defines the behavior of the widget. It contains code for wrapping of widgets, handling of
widget events initiated by the user and interaction with AJAX. It is mandatory to have this file.
The code displays the content of a component.js file.
Code Snippet:
jmaki.namespace(jmaki.widgets.hello);
jmaki.widgets.hello.Widget = function(wargs) {
//widget code
In the code snippet the widget is placed in a jmaki.widgets.hello namespace and is called a
widget by appending the term Widget to it. The term Widget represents the constructor which is
passed the widget argument. The jMaki server-side component will look in the same widgets directory for a directory named hello containing the subdirectory, foo. If the directory is found then it
will look for component.js and component.htm file under jmaki/widgets/hello. If the directory
is not found then the server side component will look under the resources directory for the widget
and its resources.
75 of 154
Concepts
Module
jMaki - I
component.htm
This file defines the default HTML template that will be used by the rendering mechanism to display
the widget in the page. In other words, it specifies the page layout for the widget. jMaki ensures
that the HTML template is displayed with unique and instance specific parameters. It is mandatory
to have this file.
The code displays the content of component.htm file.
Code Snippet:
<div id=${uuid} >
</div>
The markup that is included in the page is an instance of this widget. The code displays a template
of a simple <div> element with a unique id. The ${uuid} is replaced when jMaki processes the
template before the page is displayed.
Concepts
Both client and server interactions are needed for displaying jMaki widgets. The sequence for the
interactions are:
1.
The jMaki widget defined in a JSP page along with the taglibs is interpreted.
2.
The jMaki server-side components provide the correct HTML content along with their links to
component.css file that is rendered to the page.
3.
The jMaki server-side runtime component provides the content from the template file (component.
htm) containing unique identifier of the widget to the page.
4.
The jMaki bootstrapper script present in the jmaki.js file is rendered first to create a global object
named jMaki. The object contains the properties and functions for registering, loading and supporting
jMaki widgets.
5.
Once the widgets template has been rendered, addWidget() function of jMaki object creates and
registers the widget with the jMaki bootstrapper.
76 of 154
Module
jMaki - I
6.
When the onload event of the page is fired, the registered widgets are initialized by the jmaki
bootstrapper.
7.
4.2.4 Layout
HTML pages are rendered by the browser based on the document type. The document type tells the
browser to render the page strictly or transitionally in accordance with XHTML or CSS guidelines.
The CSS layout provided by jMaki uses XHTML transitional doctype as it follows XML syntax rules. jMaki
uses CSS to define the layout of the page. To define the layout, you have to choose the layout and include
the CSS file in the link tag.
77 of 154
Concepts
Module
4
jMaki - I
The code snippet demonstrates how to use layout by specifying the .css filename in the link tag.
Code snippet:
<link rel=stylesheet href=jmaki-standard.css
type=text/css></link>
Layout
Description
Standard
Standard No Sidebars
Standard with Footer
Centered
Right Sidebar
Two Row Right Sidebar Contains two rows on the left side and a right sidebar
Table 4.1: Layouts and Templates Provided by jMaki
Note - You can design your own layout by following the naming conventions in the CSS styles.
4.2.5 Style
A style sheet helps to improve the appearance of the Web pages in a Web application. The Library Level
Styles and Widget Level Styles are two style types that can be applied to a Web application.
The Library Level Styles are applied to all the widgets in a given library. To define a library style for a given
library, you have to use the style property when defining a widget type in the widget.json file. While
defining the style you can specify the absolute or relative path of the style filename. The relative path
is relative to the location of the widget where they are defined. The resources property specifies the
directory containing the resources used in the Web application such as image files.
Concepts
Widget Level Styles define the style and layout for a given widget. The component.css file contains the
style definition for a given widget. The default colors and size for a specific widget are specified in the
style definition. Widget Level styles override Library Level Styles. The style specified in component.css
is applied after a library level style has been applied.
78 of 154
Module
jMaki - I
4.2.6 Theme
Themes are CSS styles and describe the color palette and typography used in a Web application. Themes
do not change the layout or the structure of the documents.
The config.json file contains the definition of themes. Themes are applied in a Web application once all
the widgets have been loaded and initialized. Themes override all the CSS properties defined for a page
including the library level and widget level CSS files.
You can specify a theme by including the relative or absolute path of the theme file in the theme property
of the config.json file.
The code snippet demonstrates how to declare theme in config.json file.
Code Snippet:
{
config: {
theme: /resources/css/themes/orange/theme.css,
version: .9
}
}
The code in code snippet specifies the theme file name, theme.css, in the theme property.
Description
jmakiFont
jmakiFontHover
body
header
jmakiShadow
Concepts
Style Name
79 of 154
Module
jMaki - I
The structure of the document is described in the layout and is applied first to a page.
2.
The Library Level Style containing the layout definition is applied and thus overrides the layout.
3.
The Widget Level Style defining the style and layout for a given widget is applied. It overrides the
library and layout styles.
4.
The theme describing the typography and color used in an application overrides all the other styles.
This style is applied after the page and widgets have been loaded.
Widget resources such as component.js and component.htm files are added to the application
under the resources directory.
Custom jMaki widget tag is added to the page that refers the widgets and sets the widget
attributes to default value. The tag represents a JSP handler. It also adds the tag library
declaration.
For example, on adding a Dojo table widget, the component.js and component.htm files are added
in the resources/dojo directory. Next, the Dojo widget code is added to the resources/lib
directory of the application. Finally, the tag library is declared and ajax tag is used to add the widget.
Once a widget has been dropped onto a page, the IDE uses the name and value attribute to initialize
the widget.
The code demonstrates adding of the tag library declaration and ajax tag to the page.
Code Snippet:
<%@ taglib prefix=a uri=http://jmaki/v1.0/jsp %>
Concepts
...
<a:widget name=dojo.table
args={columns: { title : Title, author: Author, bookId: BookID,
price: Price}}
80 of 154
Module
jMaki - I
value={rows:[
[JavaScript by Dummies, Alex John,A101, 450],
[Ajax with Java, Jean Thomas,A102, 650]
]} />
The name attribute specifies the widget name. Dot notation specifies the directory structure containing
the widgets resource files. The args attribute contains the column description whereas the value
attribute contains the values for each column. The structure of the table has been separated from the
data. The jMaki widgets accept data in JSON format and the data is provided using the value attribute.
Attribute
id
name
style
Description
value
args
service
Referring to the data in a bean by using an expression language (EL) expression in the tags value
attribute
Referring to the data provided by a JSP page or servlet using the widgets service attribute
All the data needs to be passed to jMaki widgets in JSON format. In other words, data from a bean needs
to be converted into JSON format. Data conversion is performed using JSON APIs.
81 of 154
Concepts
jMaki widgets can be populated with data. There are three ways by which data can be loaded onto a
widget. They are:
Module
jMaki - I
Three steps to be followed for adding data into a widget using EL expression are: creation of a bean class
that represent a single object, conversion of the data into JSON format, loading of the data from the bean
into a widget.
Concepts
82 of 154
Module
jMaki - I
Concepts
Figure 4.8 demonstrates the code that converts data into JSON format.
83 of 154
Module
jMaki - I
ArrayList bookList = new ArrayList() - Creates an instance of ArrayList class named booklist.
Book bookObj = new Book(201, Who Moved My Cheese, Alfred John, 450) - Creates an
instance of the Book class and initializes its data members (id, name, author, and price) by calling
the parameterized constructor.
bookList.add(bookObj) - Invokes the add() method of the ArrayList class to store an instance
of the Book class in the ArrayList object.
return booklist - Returns the ArrayList object to the calling method.
public JSONArray displayBookData() throws Exception - Defines a method that will convert the
book data to JSON format.
JSONArray booksArray = new JSONArray() - Declares a JSON array.
ArrayList bookList = (ArrayList)addBooks() - Invokes the addbooks() method and stores the
ArrayList object returned from the method in an ArrayList object.
while(i.hasNext()) - Loops through the iterator using the hasNext() method.
Book bookData = (Book)itr.next() - Obtains the object stored in the ArrayList class. Converts the
object to Book type by explicitly casting the record.
book.put(bookData.getBookID()) - Obtains the ID of the book and stores it in a JSON array.
booksArray.put(book) - Converts the data into JSON format.
return booksArray - Returns the JSON array containing the book data in JSON format.
Concepts
84 of 154
Module
jMaki - I
scope=session
class=simpleBookjMaki.Boo-
Uses the useBean tag to access the property of the bean, ApplicationBean.
<a:widget name=dojo.table
Adds a widget, Dojo table, to the Web page. The widget name is specified using the name attribute
of the widget tag.
value={columns:
],
Creates the column data as the displayBookData() method does not create the column data.
JSONObject API uses HashMap which inserts data in any order. To maintain insertion order, the
column data is entered directly in the tag.
rows:${bookBean.bookData}
Obtains the row data by referencing the method from the rows attribute. The displayBookData()
method returns the row data in JSON format.
Flickr
Flickr widget is used for creating captcha, word art and for searching images easily.
Widget
Name
Topic Name
Type
Description
Returns a boolean value of true or false
depending on whether there is a match
Subscribes to the flickr Search listener
captcha
/flickr/captcha
publish
search
/flickr/search
subscribe
85 of 154
Concepts
Table 4.4 list some of the tools created using Flicker widget
Module
jMaki - I
Google
Google widgets are used for creating a map, mappopup and search.
Table 4.5 lists some of the tools created using Google widget.
Widget
Name
args
map
centerLat, centerLon
mappopup
height, width
search
centerPoint
Description
Sets the latitude and longitude
of the map to a default value
of
37.4041960114344
and
-122.008194923401 respectively
Sets the height and width of the
map popup to a default value of
320 and 500 respectively
Sets the point to the center of the
map at the default location of Santa
Clara, CA
Yahoo
Yahoo widgets are used for creating a button, calendar, map, menu, rgbslider and so on.
Table 4.6 lists some of the tools created using Yahoo widgets.
Concepts
Widget
Name
Topic Name
Type
Description
publish
On selection of a date,
onSelect will publish to
its topic name an object
with id and value
When the button is
clicked or changed, both
publish to their topic
name an object with id
and value. onChange
is sent from checkbox
buttons.
When the map is
zoomed or clicked both
publishes to their topic
name an object with id
and value
calendar
/yahoo/calendar/
onSelect
button
/ y a h o o / b u t t o n / publish
onClick,
/yahoo/
button/onChange
map
/yahoo/map/onClick,
publish
/yahoo/map/
onChangeZoom
Module
4.2.13
jMaki - I
jMaki Widgets
Each jMaki widget present in different toolkits has the same data model. But this does not mean that
the widgets present in different toolkits support the same functionality. Some toolkits support a more
complicated structure than the other toolkit. For example, jMakis menu widget cannot have child menus
whereas Yahoos menu widget can have child menus. If you pass the same data to jMakis menu widget
as you would pass to Yahoos menu widget, it will ignore some of the data.
Concepts
In this model the expanded property for child trees have been by default set to false. In the image
the title property specifies the label that will appear on each node. The url property specifies
the page whose content will be displayed when the user clicks on that node.
87 of 154
Module
jMaki - I
Figure 4.11 shows the creation of a tree.
Concepts
88 of 154
Module
jMaki - I
title that will appear on each tab and the url specifies the page that will be loaded in the area.
Figure 4.13 shows the creation of tabbed views.
4.2.15 Glue
In jMaki, events are handled by Glue. Glue is a feature that allows JavaScript components to talk to each
other by using the publish/subscribe mechanism. Components that generate events are called publishers
and components that consume the generated events are called subscribers. The publish/subscribe
mechanism helps in asynchronous communication.
Concepts
When an event takes place on a publisher widget, the widget notifies the topic of the event to the
consumers, also called listeners. If a widget is interested in the event, the widget can subscribe to the
topic by registering itself with the topic. Topic of an event is a string that associates the publisher of the
event with the subscriber of the event.
89 of 154
Module
jMaki - I
Topic Name
A topic name is a string that starts with a forward slash (/), followed by jMaki library toolkit and by
the widget name. For example, /jMaki/table is a topic name. The default topic name can be overridden.
Concepts
Commands
The consumer widgets contain event handlers. The event handlers perform a set of common operations known as commands, on the widgets. The command name is appended at the end of the
topic name. For example, /jMaki/table/onSelect. Here, onSelect is the command name.
Payloads
Payload represents the data that a widget publishes to the topic. When a widget publishes a topic,
it specifies the topic name and the payload.
90 of 154
Module
jMaki - I
The action approach associates the action property of a widget with the event handler code within
the widget. When a widget is initialized, the event topic is associated with the event handler.
The code demonstrates the use of action property of Yahoo button for publishing an event.
Code Snippet:
<a:widget name=yahoo.button
value=
{label : Select Second Row,
action : {topic : /table/select, message: {targetId: add}}}/>
The action property of the button widget publishes the command /select to the topic, /table.
The payload published to the topic is targetId: add. The targetId attribute specifies the id of
the element the action will affect.
The code demonstrates the use of the subscribe method for consuming the published event.
Code Snippet:
<a:widget name=yahoo.dataTable
subscribe=[/table, /mytable]
value={columns : [
{ label : Title, id : title},
{ label :Author, id : author},
{ label :ISBN, id : ISBN},
{ label :Description, id : description},
],
rows : [
{ title : Gone With the Wind,
author : Scarlette O Hara,
isbn : 103,
description: A Must Read Book
},
Concepts
{ id : add,
title : Learn Java,
author : John Lewis,
91 of 154
Module
jMaki - I
isbn : 102,
description: Good Book on Java
}
..
]
} />
There are a set of properties that are common to all the widgets and one of them is id. The id
property is used to identify an item such as a tab, a table row, or a tree node.
The select event of the Yahoo button widget has the payload published as targetId: add.
Thus, the second row of Yahoo datatable is targeted as it has the id value set to add.
Figure 4.15 shows the output of the code.
Concepts
Sometimes, the action to be performed in response to an event is not simple or straight forward. For
example, in response to an event, you may need to retrieve data from a database and then use the data
to update another table. In such cases, the programmatic approach of Glue should be used, which is also
based on publish/ subscribe mechanism.
To use the programmatic approach of Glue mechanism, you need to write code in the glue.js file.
jMaki framework loads the glue.js file, other glue files included in the config.json file and makes the
glue code available to the entire application.
92 of 154
Module
jMaki - I
In the code snippet, the glue listener is added to jmaki.listeners object. The code maps the
/jmaki/editor/onSave topic to the event handler, editorListener.
The args parameter overwrites the default topic name by passing the value myeditor. The subscribe method in the glue.js file should match the new topic name, and hence should have the
following code:
jmaki.subscribe(/myeditor, jmaki.listener.editorListener);
93 of 154
Concepts
Module
jMaki - I
The code demonstrates how to handle the notification.
Code Snippet:
jmaki.listener.editorListener = function (args) {
var content = args.value;
var contented = args.id;
if (typeof content != undefined) {
//send the data back to the server
jmaki.doAjax ({ method: POST, url: Service.jsp,
content: {message: contentValue },
callback: function(_req) {
value = eval(req.responseText);
//error handling code
}
});
}
}
Every time the save operation is performed, the editor widget publishes to a topic. The handler receives the widget value through args. The listener processes the received data and after processing, returns the result to the caller.
Knowledge Check 2
1.
Can you identify the code that demonstrates the use of action property for publishing an event?
<a:name=yahoo.button
(A)
value=
{label : Select Second Row,
Concepts
(B)
value=
{label : Select Second Row,
action : {message: {targetId: add}}}/>
94 of 154
Module
jMaki - I
<a:widget name=yahoo.button
(C)
value=
{label : Select Second Row,
action : {topic : /table/select, message: {targetId: add}}}/>
<a:widget name=yahoo.button
(D)
column=
{row : Select Second Row,
message : {topic : /table/select, action: {targetId: add}}}/>
2.
Which of the statements describing the characteristics of the widget model are true?
(A) Widget name maps to a directory.
(B)
(C)
3.
(A)
A, C, and D
(C)
B, D, and E
(B)
B, C, and D
(D)
C, D, and E
(C)
(D)
jMaki object containing properties and functions registers, loads and supports jMaki
widgets.
(E)
Registered widgets are initialized and the rendered page is available for event processing.
(A)
A, B, C, D, E
(C)
E, D, C, B, A
(B)
C, A, D, B, E
(D)
D, A, C, B, E
Concepts
(B)
95 of 154
Module
4.
jMaki - I
Which of the following statements about layout, style, and theme of jMaki widgets are true?
(A) Left and Right Sidebars layout contains only fixed left and right sidebars.
(B)
(C)
Theme describes the color palette and typography used in a Web application.
Widget Level Styles defines the style and layout for a given library.
A and C
(C)
B and C
(B)
C and D
(D)
D and E
Concepts
(A)
96 of 154
Module
jMaki - I
Summary
In the module, jMaki - I, you learnt about:
jMaki Architecture
jMaki is a lightweight client-server framework used for creating AJAX applications. It wraps the
functionality of JavaScript technology. The main aim of jMaki is to use JavaScript on the client machine enabling it to communicate with different server technologies such as JSP, JSF and PHP. jMaki
Architecture comprises of client and server components.
jMaki Widgets
Concepts
A widget is a reusable parameterized component. The three core resource files for a widget are
component.css, component.js and component.htm, files that define the style of the widget,
the behavior of the widget and the default HTML template for rendering the widget on the page.
97 of 154
Module -
jMaki - II
Welcome to the module, jMaki - II. This module introduces the concept of
data models in jMaki mashups. The dData model pages include the formal
specification of specifies the data expected by the widgets. The mashup
is a wWeb site that combines content from various other wWeb sites into
one convenient, easy-to-use portal.
In this module, you will learn about:
Data Models
Mashups
Module
jMaki - II
Data models are standard for widgets, such as combo boxes, menus, trees, tables, and so on,
across toolkits.
Data model of a widget can be used in any toolkit without changing the format of the data. When
you want to use a widget in another toolkit, the widget wrappers convert the jMaki data model as
per the data requirement of the new toolkit.
Data model of a widget includes publishers and subscribers. These allow and simplify dynamic
update and communication between widgets.
Data models across the various widgets have similar properties and events. If you learn one data
model, most of the information of the data model will be applicable for other data models too.
Concepts
99 of 154
Module
5
jMaki - II
Note - This standardization of data and event model helps in simplifying the programming model for
Data Model
jMaki Menu
Yahoo Menu, jMaki Menu, jMaki Tab Menu, jMaki Accordion Menu
jMaki Table
Yahoo Datatable, Dojo Table
jMaki Tree
Yahoo Tree, Dojo Tree
jMaki Combobox Dojo Combobox
jMaki Multiview jMaki Dynamic Container, Dojo Accordion, Dojo Tabbedview, Yahoo
Tabbedview
jMaki Fisheye
Dojo Fisheye
jMaki Drawer
Dojo Drawer
jMaki Map
Yahoo Map, Google Map
Table 5.1: Widgets Supporting Data Models
Concepts
There are a set of properties which are common among the different data models. They are:
id Indicates the identifier of items such as table row, tree node, tab, and so on.
label Indicates the title of items such as table column, tree node, tab, and so on.
href Indicates that the string will act as a hyperlink. Clicking the link will navigate to the
specified url.
include Indicates that the content from the specified url will be included in the page.
100 of 154
Module
jMaki - II
Properties
Figure 5.3 shows syntax.
101 of 154
Concepts
The label property specifies the text to be displayed for a specific item.
Module
5
jMaki - II
Subscribe/Publish
There are two subscribe events:
select It selects a given item with the value provided in the payload.
setValues It specifies the payload value which is passed to the Combobox widget. This value is
onSelect It is published when the user selects an item from the Combobox widget.
Concepts
102 of 154
Module
jMaki - II
When a user clicks the Yahoo button, the button publishes a topic to add content in the Combobox.
You have to add a listener to the topic, /mysettopic, in the glue.js file. The jmaki.publish API
sends the hard coded data to the topic /dojo/combobox. The Dojo Combobox widget subscribes
the topic and adds rows of data to the Combobox and displays it in the Web page.
Properties
The rows in a table must be an array of objects which are mapped to the column names. You can
provide the column names as a property of the args attribute. You can also pass to the widget as
a service or value, the row and column values by combining it into a single object. The row id is
implicitly assigned on a given row if not provided.
Figure 5.5 shows the syntax.
Subscribe/Publish
yy
addRow This event appends the payload value passed to the widget at the end of the
yy
addRows This event adds to the table the payload value passed to the widget and applies
yy
table.
103 of 154
Concepts
Module
jMaki - II
The publish event available is:
yy
Concepts
},
{ title :A Light Load ,
author : Radford,
104 of 154
Module
jMaki - II
isbn : 4414,
description: Good Book
}
]
});
});
When a user clicks the Yahoo button, the button publishes a topic to add content rows. You have to
add a listener to the topic, /mytopic, in the glue.js file. The jmaki.publish API sends the hard
coded data to the topic /table. The Yahoo table widget subscribes the topic and adds two rows
of data to the table and displays it in the Web page.
Properties
The outer menu property identifies the labels of the menu bar.
The publish argument is overridden by the topic property for an item identified by a label.
The message property specifies the message that will displayed on the menu.
The disabled property indicates if an item in the menu is disabled or not.
Concepts
105 of 154
Module
jMaki - II
Subscribe/Publish
Only one event is available for the Menu data model that publishes the message.
yy
Concepts
106 of 154
Module
jMaki - II
The attributes, value and service pass data to the menu widget wrapper. You can use the value
attribute when the data is located in the static page. The value attribute is assigned to the JSON
representation of the data described in the menu data model. The menu creates links for two Web
sites.
Properties
The tree property specifies the node in the tree data structure. The outer tree property specifies
the root of the tree.
The expanded property specifies if the children under this node will be initially visible or not.
The children property has an array of tree sub elements representing the child nodes of the
current node. If a node exists, and a click action is performed on the node, the action property
raises an event to be published. If the node has children, they are expanded.
The action and children properties are not permitted for the same node.
Concepts
107 of 154
Module
jMaki - II
Subscribe/Publish
Some of the subscribe events are:
yy
addNodes This event will add a sub tree of nodes under the node with the specified
targetId.
yy
expandNodes This event will expand the node with the specified targetId and its parent
nodes.
yy
Concepts
var node = {
label : Encyclopaedia ,
expanded : true,
children : [
108 of 154
Module
jMaki - II
{label : Culture},
{label : Science}
]
};
jmaki.publish(/dojo/tree/addNodes, {value : node});
});
When a user clicks the Yahoo button, the button publishes a topic to add a tree node. You have to
add a listener to the topic, /mytopic, in the glue.js file. The jmaki.publish API sends the hard
coded data to the topic /dojo/tree. The Dojo tree widget subscribes the topic and add a node
to the tree and displays it in the Web page. The code adds a node Encyclopaedia the Dojo tree
widget and the child elements, Culture and Science, are then added to the Encyclopaedia node.
Properties
The content property specifies the static content to be displayed in a row when the widget is
rendered.
The include property specifies the page to be included in the pane.
The action property allows the users to specify the message to publish and the topic to publish
to. If no topic is specified then the default topic is used that was specified by the publish property
on the tag.
Concepts
109 of 154
Module
jMaki - II
Subscribe/Publish
The different subscribe events are:
yy
yy
yy
setContent This event sets the content of the pane to the value specified in the value
yy
setInclude This event sets the URL of the page that will be included in the pane.
property.
The code not only sets the content of the dojo drawer with the value Welcome to Aptechs Ajax
Course and displays the value when an event occurs such as clicking of a button.
Concepts
The Multi View data model is useful for all tabbed view widgets, accordion widgets, and jMaki dynamic
container.
Properties
An iframe is a frame inside a Web page that is not dependent on the sides of the Web page window.
The iframe property represents if the content is loaded into the iframes.
The lazyLoad property when set to true loads the content once the pane have been selected.
110 of 154
Module
jMaki - II
The content property specifies the static content to be displayed in a tab when the widget is
rendered.
The include property specifies the page to be loaded in the tab. This is done using the container.
Figure 5.13 shows the syntax.
Subscribe/Publish
The different subscribe events are:
yy
select This event selects a tab whose id have been specified in the targetId property.
yy
setContent This event sets the contents of a tab whose id have been specified in the
targetId property.
yy
setInclude This event sets the include URL of a tab whose id have been specified in the
targetId property.
Concepts
111 of 154
Module
5
jMaki - II
Knowledge Check 1
1.
Can you match the description with the appropriate subscribe / publish events?
Description
(A)
(1)
removeNode
(B)
(2)
removeChildren
(C)
(3)
expandNodes
(4)
clear
(5)
addNodes
(D)
(E)
2.
Subscribe/Publish Event
(A)
(C)
(B)
(D)
Which of the following options describing the use and purpose of data models are true?
(A) The data model does not maintain consistency across the different types of widgets.
(B)
(C)
(D) jMaki has a standard data model for only Google widgets.
(E)
(C)
B, C, and E
(B)
A, D, and E
(D)
C, D, and E
Concepts
(A)
112 of 154
Module
jMaki - II
5.2.1 Characteristics
Consider a Web site housingmaps.com that provides real estate information from the craglist.org Web
site. The information is provided through clickable pushpins on interactive Google maps. When users
click the pushpins, they can view the exact location of apartments that are available for sale or rent.
Users can view content of both Google maps and craiglist.org in housingmaps.com. Thus, users need not
toggle back and forth between the sites, Google map and cariglist.org.
Concepts
When services or content from various Web sites are combined in a single Web site, it is known as mashup.
Unlike open source software, mashups typically function through APIs, which facilitate communication
between technologies. Figure 5.14 information on Google map.
113 of 154
Module
5
jMaki - II
5.2.2 Components
A mashup application consists of three different components. The three components are: API/content
providers, the mashup site, and the clients Web browser.
The content provider is the data source. Data is retrieved by using APIs and different Web protocols. The
Web protocols include Really Simple Syndication (RSS), Representational State Transfer (REST), and Web
Service.
The mashup site uses data from different data sources.
The clients Web browser is the GUI of the mashup.
A mashup requires multiple input sources. The input sources will have an XML based output stream.
The mashup uses these XML outputs as input, and consolidates them together. After combining the data
streams, the mashup usually generates its own output, and displays a combination of the original inputs.
Concepts
Client side logic includes code embedded in the mashup Web pages, the scripting API libraries, or the
applets referenced by the Web pages. Mashups created by using the client-side logic are termed as
Rich Internet Applications (RIAs). An example of client-side technology is Google Maps API that can be
accessed through client-side JavaScript. Figure 5.15 shows the implementation of Mashups.
Module
jMaki - II
1.
2.
The client sends a request in the form of XmlHttpRequest object to the server in the mashup site.
3.
A Web component (servlets) receives a client request and invokes a method on the Java classes in
mashup site. The Java classes contain the code that helps to connect and interact with the other
Web sites in the mashup.
4.
The server sends a request to the other Web sites in the mashup that provides the required service.
5.
The other Web sites in the mashup site receives the request, processes the request, and returns the
data to the server.
6.
The server receives the response and transforms it to an appropriate data format which the client
understands. It also caches the response which can be used for future request processing.
7.
The Web component in the mashup site returns the response to the client.
8.
A callback function in the XmlHttpRequest updates the page on the client side. This is achieved
by manipulating the Document Object Model (DOM) that represents the page.
115 of 154
Concepts
Module
5
jMaki - II
Concepts
The client browser requests a Web server in the mashup site for a Web page.
2.
The server on the mashup site makes the JavaScript library available by loading the page into the
client.
3.
Actions in the Web page invoke a JavaScript function. The function generates a <script> element
that links to the mashup site.
4.
As per the request in the <script> element, appropriate requests are made to the Web sites in a
mashup site to load the script.
5.
A local callback in the browser executes with a JavaScript Object Notation (JSON) and loads the script.
6.
A callback function in the XmlHttpRequest updates the page on the client side. This is achieved
by manipulating the DOM that represents the page.
It provides an easy access to the other mashup Web sites due to use of the Java EE and Java SE
platforms libraries.
116 of 154
Module
jMaki - II
The server-side mashups proxy acts as a buffer between the client and other Web sites to take
care of the problems, and displays appropriate error messages.
It manipulates the content by either sending data to the client in smaller chunks or sending only
the portion of the data that the client needs.
It may slow down the performance because of delay in receiving the response. This is so because
a request and response move from the browser to the server side proxy, and then from the server
side proxy back to the mashup server. Thus, before arriving at the client, the response makes
same two network hops in reverse order.
Security
It is required to check whether the service requires a user login or some other authentication
mechanism. Also check if the service hides the identity of the malicious user who uses the service
illegally.
Response format
In a server side mashup, the response format that the service returns needs to be determined. The
different response formats a service can return are XML, JSON, HTML, plain text, RSS/ATOM, and
GData.
Results caching
It is required to check whether the data retrieved can be cached to be used by clients or is it
required to be stored on the server.
117 of 154
Concepts
Module
5
jMaki - II
Response modification
It is required to check whether there is a need to modify the response before it is sent to the client.
It is easy to implement. It includes the JavaScript library in the Web page of the site that needs to
be in a mashup. Then to use the functions in the library, provide the appropriate code in the Web
page.
It improves the performance because a request and response object moves directly from the
browser to the mashup server and from server back to the browser.
It reduces the processing load on the server by passing the service request and response object
between client and mashup server without including the proxy server.
It does not require installation of any custom plug in for its implementation.
Concepts
It has no buffer like server-side styles has to protect the client from problems occurring in other
Web sites.
It needs to handle the data of any size and format returned by the Web sites, because the data
returned is not formatted and manipulated.
It has constraints on making many asynchronous calls to various data sources at the same time.
118 of 154
Module
jMaki - II
Security
It is required to check whether the client has access to the content and service for a mashup. Also,
the unintended users should be restricted to access the site and data.
Performance
It is required to check whether the other Web sites from mashup does not delay the response and
frustrate the user.
Stability
It is required to check whether the services functions the same way as expected and remains the
same way in future also.
Caching
It is required to check whether the data retrieved can be cached to be used by multiple clients.
Thus, it will reduce the number of calls to the mashup sites.
Knowledge Check 2
1.
Which of the following statements describing the mashup architecture are true?
(B)
A mashup is a Web site that combines content from various other Web sites.
(C)
Concepts
(D) Mashups can be implemented using only server side content technologies.
(E)
119 of 154
Module
2.
5
jMaki - II
(A)
A, B, and C
(C)
B, C, and E
(B)
A, B, and E
(D)
C, D, and E
Which of the following statements stating the advantages of client side mashups are false?
(A) It reduces the processing load on the server.
(B)
(C)
(D)
It improves the performance because a request and response object communicates directly
between the browser and the mashup server.
(E)
(C)
A and D
(B)
C and E
(D)
D and E
Concepts
(A)
120 of 154
Module
jMaki - II
Summary
In this module, jMaki - II, you learnt about:
Data Models
The data model specifies the formal specification of the data expected by the widgets. The data
models are defined for the various types of widgets such as menus, trees, tables, tabbed views and
so on.
Mashups
Concepts
A mashup is a Web site that combines the content from various other Web sites into one convenient, easy-to-use portal. A mashup application consists of API/content providers, the mashup site,
and the clients Web browser. The mashups have two different styles - server side mashups and
client side mashups.
121 of 154
Module -
Module
Concepts
If you use AJAX based applications, you can notify users about existence of the username as soon as the
username textbox looses focus.
123 of 154
Module
6
AJAX with Struts and JSF
Figure 6.1 shows the registration page in a Web application with and without using AJAX.
To enable AJAX in Struts applications, you need to perform the following steps:
1.
Bind a GUI component, such as a textbox in a JSP page, to an appropriate event handler.
2.
3.
4.
Define a Struts Action class to accept data, forward the data to a model class and send the response
back to the JSP page.
5.
Define a model class that will process the data. For example, you can verify the existence of a
124 of 154
Module
Update the JSP page such as account registration page to display information received.
Concepts
Figure 6.2 shows the JavaScript code that retrieves the value of the textbox.
125 of 154
Module
6
AJAX with Struts and JSF
Concepts
Step 1
The variable, xmlRequest holds a reference to the XML request object.
Step 2
The if-else block creates the XML request object based on the browser type. If the Web page runs
126 of 154
Module
on Internet Explorer, the xmlRequest variable is initialized to Microsoft.XMLHTTP. For all other
browsers, the xmlRequest variable is initialized to XMLHttpRequest.
Step 3
The URL is constructed. The URL comprises of following four parts:
yy
yy
yy
yy
Step 4
The xmlRequest variables onreadystatechange property is set to the processResponse()
function. Every time the state of the XML request object changes, the processResponse() function is executed.
Step 5
Three arguments are passed to the open() method. The three arguments are:
yy
GET indicates that request should be sent by using the HTTP GET method
yy
yy
Concepts
127 of 154
Module
6
AJAX with Struts and JSF
Concepts
The name variable stores the value of the request parameter named username.
2.
An instance of the model class, User, is created. The validateUsername() method checks for
existence of the users name and returns an XML fragment containing a true or a false value.
3.
The response instance writes back the XML fragment on the client application. You must set the
content-type of the response to application/xml to send an XML response.
128 of 154
Module
Concepts
Figure 6.5 demonstrates the code for the User model class.
129 of 154
Module
6
AJAX with Struts and JSF
Step 1
The processResponse() function first checks the current values of the properties readyState
and status. If the values of these properties are 4 and 200 respectively, it means that the function
has received the response from the server successfully.
Concepts
Step 2
The function then retrieves all the elements having the name exists from the received XML response and stores the elements in a node variable. The text value of the first exists element is
retrieved by accessing the first child node of the node variable. The value is stored in the flag variable. The nodeValue property is used to access the element value.
130 of 154
Module
Step 3
The message element is retrieved and the color of the element is changed to red. This element, in
the JSP page, is a div element. The div element displays messages to the user.
Step 4
If the exists element contains the text true, the if block is executed and message elements
innerHTML property is set to display the message Username already exists. Otherwise, the
innerHTML property is set to null.
Knowledge Check 1
1.
Which of the following statements about AJAX and Web frameworks are true?
(A) Struts and JSF use servlets to send HTTP requests.
(B)
(C)
Web frameworks like Struts and JSF provide an abstraction layer above the servlet API.
A, C, and D
(C)
B, D, and E
(B)
B, C, and D
(D)
C, D, and E
Can you match the steps to enable AJAX in Struts applications with their corresponding descriptions?
Description
Step
(1)
Step 1
(B)
(2)
Step 4
(C)
(3)
Step 3
(D)
(4)
Step 2
(E)
(5)
Step 5
Concepts
2.
Web frameworks like Struts and JSF improve the response time of Web applications.
131 of 154
Module
3.
6
AJAX with Struts and JSF
(A)
(C)
(B)
(D)
Consider a scenario where you have to use XMLHttpRequest object named xhrObject to send
asynchronously the value of the textfield, orderID, to Action class named OrderAction. You process
the response using orderResponse() function. Which one of the following code snippets will help
you to achieve this?
var context = <%=request.getContextPath()%>;
var actionURL = context +
orderId= + orderID.value;
(A)
xhrObject.onreadystatechange = orderResponse;
xhrObject.open(GET, actionURL, true);
xhrObject.send(null);
var context = <%=request.getContextPath()%>;
var actionURL = context +
/OrderAction.do?orderId=
(B)
+ orderID.value;
xhrObject.open(GET, actionURL, true);
xhrObject.send(null);
var context = <%=request.getContextPath()%>;
var actionURL = context +
/OrderAction.do?orderId=
+ orderID.value;
Concepts
(C)
xhrObject.onreadystatechange = orderResponse;
xhrObject.open(GET, actionURL, true);
xhrObject.send(null);
132 of 154
Module
(D)
xhrObject.onreadystatechange = orderResponse;
xhrObject.open(GET, actionURL, false);
xhrObject.send(null);
You can use AJAX in JSF applications to send and receive data asynchronously. There are several
approaches to include AJAX functionality in JSF applications. The easiest approach is to include the AJAX
JavaScript code in JSF pages and use a servlet or a phase listener to process the AJAX request. However,
this requires the page author to have sound knowledge of JavaScript. JSF provides the option of creating
custom components. All the JavaScript code can be included in the custom component. The page author
only needs to know how to use the custom component in the page.
133 of 154
Concepts
JSF is a component UI framework. It provides a rich set of UI components, validators and converters to
create Web applications. However, JSF also follows the click-wait-refresh cycle. In other words, JSF pages
do not allow you to interact with the page until the response is received from the server.
Module
6
AJAX with Struts and JSF
UI Component Class contains the core logic of the component. This class is derived from either
UIInput to create an input component, UIOutput to display static text, or UICommand class to
create an event-based component.
Renderer Class contains the code to render the markup of the component. Usually, most simple
custom components include the rendering code in the UI Component class itself.
UI Component Tag Class is the tag handler class and associates the custom tag with the
component and renderer classes.
Tag Library Descriptor File describes the usage of custom component in JSP pages and
associates the tag in JSP page with the UI Component tag class.
Concepts
Module
The class is derived from UIOutput class. This is because the component will display static text only.
The code to write text or markup is included in the encodeBegin() method. In this case, you write
the current date and time to the response. The class overrides the getFamily() method. This method
returns a string identifying the family of a component. However, here the method returns null.
After the component class is defined, you configure it in the faces-config.xml file as shown in figure
6.8. The component-type element assigns a name to the component and component-class element
specifies the fully qualified class name.
Figure 6.8 shows the definition of component class and its configuration in the faces-config.xml.
Note - The methods encodeEnd() and encodeChildren() are also used for rendering the
component. The encodeEnd() method renders the ending tag. Some tags include child tags as well.
The encodeChildren() method renders these child tags.
For simple components, all the rendering code is included in the encodeBegin() method. For
complex components, you create a subclass of Renderer class and override the encode methods in
the subclass.
135 of 154
Concepts
Module
6
AJAX with Struts and JSF
The next step in creating custom component is to create a tag library descriptor file as shown in figure
6.10. Some of the important XML elements of this file are:
uri specifies the path of tag library descriptor file; in this case, the file is located in the tlds
folder of WEB-INF folder.
tag-class specifies the fully qualified class name of the tag handler class.
136 of 154
Module
name assigns a short name to the tag handler class; in the JSP page, the tag is referred using
the name CustomLabelTag.
Concepts
137 of 154
Module
6
AJAX with Struts and JSF
Concepts
The custom component is created in the JSF page using a custom tag, stockItem, as shown in the
image. Note that value attribute is used to pass the stock symbol to the server.
138 of 154
Module
Step 1
Figure 6.13 shows the code of a custom UIInput component named StockUI derived from UIInput. The StockUI class overrides the encodeBegin() method to render the markup of the
component.
Concepts
First, you create an instance of ResponseWriter class. This instance is used to render the markup, of the component, on the client.
139 of 154
Module
6
AJAX with Struts and JSF
Figure 6.13 shows the code of the StockUI component.
Step 2
Here, you create a textfield named stockSymbol to accept a symbol from the user. The custom
tag has a value attribute to specify stock symbol. If this attribute is set, you retrieve its value using
the getValue() method and assign it to the value attribute of the textfield.
Concepts
Figure 6.14 shows the code to accept a symbol from the user.
Step 3
Here, you create a submit button with the caption Enter Stock Symbol. On clicking this button,
the stock symbol entered in the stockSymbol textfield is sent as part of an HTTP POST request.
140 of 154
Module
Step 4
JSF maintains a request map that contains all the values sent in a HTTP POST request. In this step,
you retrieve the value of the stock symbol from this map and compare it with orcl. If a match is
found, the stock price $1000.00 is displayed; else the stock price $0.00 is displayed.
Concepts
Figure 6.16 shows the code to compare the value of the stock symbol with orc1.
141 of 154
Module
6
AJAX with Struts and JSF
The StockUI class must override the decode() method as well. Figure 6.17 shows the code of decode()
method.
The decode() method is used to process the request data. JSF maintains the request data in a Map
instance. You retrieve this map using the getRequestParameterMap() method. Then, you use the
get() method to retrieve the value of request parameter named stockSymbol. Then, you set the
submitted value of the component to the value submitted by the user. This completes the creation of
custom component, StockUI. Therefore, you configure it in faces-config.xml file as shown in the
image.
Note that the encodeBegin() method rendered a textfield named stockSymbol. The user enters a
stock symbol in this field and then clicks the submit button. This causes the textfield data to be sent as
part of an HTTP POST request.
Figure 6.17 shows the code for the decode() method.
Concepts
142 of 154
Module
Concepts
143 of 154
Module
6
AJAX with Struts and JSF
Concepts
144 of 154
Module
Figure 6.20 shows the code for the StockUI component to process the request by a phase listener.
Step 1
Step 2
In step 2, you write the code to render a textfield named stockSymbol and set its value attribute to
the value specified in the custom tag.
Step 3
In step 3, now you render a simple button instead of a submit button. Additionally, you bind the
145 of 154
Concepts
In step 1, now you also render a script tag. This tag writes the code in AJAXScript.js to the
client. The AJAXScript.js file contains code to send the stock symbol, asynchronously to the
server, and display the stock price.
Module
6
AJAX with Struts and JSF
function, sendAJAXRequest() to the buttons onclick event. Note that the sendAJAXRequest() is defined in AJAXScript.js file.
Step 4
In step 4, now you just render a div tag. The div tag will be used to display the price of the stock
symbol entered by the user.
Concepts
146 of 154
Module
Concepts
In JSF applications, an AJAX request from custom component is processed using a phase listener. Figure
6.23 shows the StockPhaseListener class implementing the PhaseListener interface. The class
provides definitions for the interface methods afterPhase(), beforePhase(), and getPhaseId().
147 of 154
Module
6
AJAX with Struts and JSF
afterPhase
The afterPhase() method is invoked after the processing of a particular phase is completed. In
this method, you store the view identifier of the incoming request in variable viewId. If the variable viewId contains the text, Ajax, the processing of AJAX request is started by calling the processAjaxRequest() method. Note that this method is not defined yet.
Concepts
beforePhase
The beforePhase() method is invoked before the processing of a particular phase is started. In
this case, the method body is empty because the phase listener processes the request in the afterPhase() method.
getPhaseId
The getPhaseId() method identifies the phase for which the phase listener must process the
request. In this case, the phase listener will process the AJAX request in the RESTORE_VIEW phase.
148 of 154
Module
In Step 1, you use an ExternalContext instance to store a reference to the current HTTP request
in the variable, request. Next, the value of request parameter named value is stored in the variable value.
Step 2
In Step 2, you use the ExternalContext instance to store a reference to the response. Next,
you set the content type of the response to application/xml and create an instance of
PrintWriter class.
149 of 154
Concepts
Module
6
AJAX with Struts and JSF
Step 3
In Step 3, you send the stock price to StockUI component by writing an XML response using the
writer instance. Finally, you invoke the responseComplete() method to end the current request processing life cycle and return control to the StockUI component.
Concepts
150 of 154
Module
Knowledge Check 2
Can you match the files and/or classes required to create custom component with their corresponding
descriptions?
(A)
(B)
(C)
(D)
(E)
2.
(1)
(2)
(3)
File/Class
UI Component
faces-config.xml
Tag Class
(4)
Renderer
(5)
(A)
(C)
(B)
(D)
Can you arrange the code to create a custom UIOutput component named Message to display a
message Good Day!.
(A)
(B)
(C)
(D)
(E)
Description
Renders the components markup.
Describes the usage of the custom tag.
Contains core logic of the custom
component.
Specifies the name of the custom component
and renderer.
Associates the custom tag, component and
the renderer.
ex.printStackTrace();
}
try {
ResponseWriter w = c.getResponseWriter();
(A)
D, B, E, A, C
(C)
B, E, D, A, C
(B)
A, B, C, D, E
(D)
C, B, E, A, D
Concepts
1.
151 of 154
Module
3.
6
AJAX with Struts and JSF
Which one of the following encodeBegin() method can be used to create a custom UIInput
component to render a textfield named orderID?
public void encodeBegin(FacesContext context) {
try {
ResponseWriter writer = context.getResponseWriter();
writer.write(<input type=text );
(A)
writer.write( name=orderID>);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void encodeBegin(FacesContext context) {
try {
ResponseWriter writer = context.getResponseWriter();
writer.write(<input type=button );
(B)
writer.write( name=orderID>);
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void encodeBegin() {
try {
ResponseWriter writer = getContext().getResponseWriter();
writer.write(<input type=text );
(C)
writer.write( name=orderID>);
} catch (IOException ex) {
ex.printStackTrace();
Concepts
}
}
152 of 154
Module
(D)
writer.write( name=orderID>);
} catch (IOException ex) {
ex.printStackTrace();
}
Concepts
153 of 154
Module
6
AJAX with Struts and JSF
Summary
In the module, AJAX with Struts and JSF, you learnt about:
Concepts
The lesson, AJAX in JSF Applications, explained the basic concept of custom components. The lesson described the procedure to create custom UIOutput and UIInput components. At the end,
the lesson explained how to add AJAX functionality to custom UIInput component and process
the AJAX request using a phase listener.
154 of 154
Module 1
Knowledge Check 1
1.
(A)
2.
(B)
Knowledge Check 2
1.
(C)
Module 2
Knowledge Check 1
1.
(D)
2.
(B)
3.
(A)
Knowledge Check 2
1.
(D)
2.
(B)
3.
(C)
Module 3
Knowledge Check 1
1.
(A)
2.
(B)
3.
(A)
1.
(B)
2.
(A)
3.
(C)
Concepts
Knowledge Check 2
1 of 2
Module 4
Knowledge Check 1
1.
(A)
2.
(B)
3.
(A)
Knowledge Check 2
1.
(C)
2.
(A)
3.
(B)
4.
(C)
Module 5
1.
(D)
2.
(C)
Knowledge Check 2
1.
(B)
2.
(B)
Module 6
Concepts
Knowledge Check 1
1.
(B)
2.
(C)
3.
(C)
Knowledge Check 2
1.
(B)
2.
(A)
3.
(A)
2 of 2