JBoss Portals and AJAX - Part 1

Exclusive offer: get 50% off this eBook here
JBoss Portal Server Development

JBoss Portal Server Development — Save 50%

Create dynamic, feature-rich, and robust enterprise portal applications

€18.99    €9.50
by Ramanujam Rao | January 2009 | Java Open Source Web Development

Dynamic, attractive, and rich interfaces have always helped in creating compelling web applications. However, in recent years, the popularity and support for asynchronous browser-to-server communication, combined with the strong client-side capabilities of JavaScript and XML, have resulted in exciting user interfaces with unprecedented functionality. In this article by Ramanujam Rao, we will see that how AJAX (Asynchronous JavaScript and XML), as the rich user interface design is commonly called, has gained wide acceptability in traditional web applications, and portals are no exception to this.

JBoss portal blends the dynamism and rich functionality offered by AJAX with its strong portal architecture to provide users with choices for developing highly-functional portal applications. The latest portlet specification, JSR-286, provides an easy and intuitive approach to implementing asynchronous calls that was not possible in JSR-168. In the first part of this article, we will discuss the limitations of the current specification and walk through an example portlet to understand how AJAX can enhance portlets. The next part will talk about AJAX support for markup.

Rich user interfaces and AJAX

Rich user interfaces can be achieved by using a combination of dynamic HTML elements such as HTML and JavaScript. However, the scope of such an interface is limited to client-side behavior and has minimal functional implications due to the lack of server-side interactions. The power of AJAX is in its capability to provide even richer interface by supplementing its dynamic user interface with powerful functionality through seamless server-side invocation power. AJAX allows individual user interface components to communicate with the server and exchange data without the need for refreshing the whole screen. This is achieved using a process called Web Remoting. Web remoting, or the process of communicating between a browser and a server, can be performed in multiple ways. The popular approaches that are supported by today's browsers are IFrames and XMLHttpRequest. Dynamic HTML can be complemented with either of these methods to generate AJAX functionality.

Asynchronous JavaScript and XML or AJAX

Asynchronous communication between the client and the server forms the backbone of AJAX. Although an asynchronous request-response method can provide significant value in the development of rich functionality by itself, the results are lot more pronounced when used in conjunction with other functional standards such as CSS, DOM, JavaScript, and so on. The predominant popularity of AJAX stems from such usage.

Client-server communication can be achieved either by using IFrames, or by using the supported JavaScript function called XMLHttpRequest(). Due to certain limitations of IFrames, XMLHttpRequest has gained a lot more acceptance. While IFrame can also be an effective option for implementing AJAX-based solutions, in this article, we will focus largely on an XMLHttpRequest-based implementation. The primary advantage of using AJAX-based interfaces is that the update of content occurs without page refreshes. A typical AJAX implementation using XMLHttpRequest happens as described in the following steps:

  1. An action on the client side, whether this is a mouse click or a timed refresh, triggers a client event
  2. An XMLHttpRequest object is created and configured
  3. The XMLHttpRequest object makes a call
  4. The request is processed by a server-side component
  5. The component returns an XML (or an equivalent) document containing the result
  6. The XMLHttpRequest object calls the callback() function and processes the result
  7. The HTML DOM is updated with any resulting values

The following simplified image illustrates the high-level steps involved in an AJAX request flow. The portal client page gets served to the client browser, where the execution of JavaScript functions takes place.

JBoss Portals and AJAX - Part 1

The following example illustrates the initialization of the request object and its basic use:

if (window.XMLHttpRequest) // Object of the current window {
// for non-IE browsers
request = new XMLHttpRequest();
}
else if (window.ActiveXObject){
// For IE
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.onreadystatechange = function()
{
// do something to process response
};
if (request.readyState == 4){
// everything received, OK. Do something now..
} else {
// wait for the response to come to ready state
}

In subsequent sections, we will modify our sample portal application by adding AJAX functionality to one of the portlets.

AJAX in JBoss portal

AJAX has gained tremendous popularity in the traditional web application development world due to the richness and agility that it brings to user interfaces. Portals, such as JBoss portal, can also gain significantly from AJAX, in terms of implementation of both behavior and functionality.

Refreshing the page content tends to be a time-consuming and resource-intensive process. Every request that a user makes to the server, either by clicking on submissions or links, results in the portal calling doView() and a series of methods for each portlet on the page, one at a time, before aggregating the results and sending the response back to the browser. Using AJAX allows for simultaneous submissions of request in their own independent threads of execution, resulting in an asynchronous and parallel execution. The portal page refresh overhead is now only as long as the time consumed by the slowest portlet.

The response times observed by the user improve dramatically, while at the same time allowing more functionality on pages. Architecturally, vertical independent stacks of execution facilitate cleaner and more modular designs and implementations.

AJAX can be implemented in JBoss portal in the following two ways:

  1. Using in-built support for asynchronous portal behavior by using configurations
  2. Writing custom behavior in portlets and page content by using AJAX libraries

The in-built support for asynchronous behavior comprises of support for both markup and content. The markup support is in layouts and renderers, while the content is supported through configurable drag-drop and partial page refresh behavior. Almost all of the AJAX behavior supported by JBoss portal relates to asynchronous communication between the client and the portal servers. The only exception is the drag-drop behavior, which is largely view functionality.

As far as the custom development within a portlet is concerned, the options are innumerable. A portlet can be developed using many advanced frameworks that are available as either commercial or open source products. For example, user interface features such as drag-and-drops, grids, accordion selects, pull-down menus, content refresh, and so on can be implemented by using third-party libraries including Scriptaculous, JQuery, and DOJO, which have gained a strong following among developers, even on traditional applications and non-portal platforms.

In the next few sections, we will walk through an example of AJAX-enabled portlets using one of these libraries, developed on the JBoss portal platform. However, before we go into the implementation, let's step back and understand the limitations that the current portlet specification– JSR-286–addresses, facilitating easy development of AJAX portlets.

JSR-168 AJAX limitations

Before we look at the features and options provided by the new specification, let's look at how traditional JSR-168 portlets functioned. As shown in the following figure, the "Action" request invoked the processAction method on the server, which implemented controller logic to route it to the correct view. The "Render" request then invokes the render method to serve the content page to the browser.

JBoss Portals and AJAX - Part 1

However, when the portlet uses AJAX and needs to makes an asynchronous call, it has to use ActionURL. This in turn follows the standard processing when processAction processes the request and the render method creates the user interface. However, now when the user interface is sent back, the portal injects some other markup and recreates the entire portal page. Hence, instead of refreshing a snippet of user interface, we end up refreshing the whole page.

The issues with JSR-168 and AJAX can be broadly summarized as follows:

  • ActionURL and RenderURL point to a portal, and not to a portlet. When we point to a portal, the result is a complete portal page, even if the portlet generates only a snippet.
  • As per the specification, the user interface rendered by the portlet is supposed to be aggregated with some other markup and served back to the browser. When more than only the necessary data and markup is sent back, the JavaScript code on the client side that makes the asynchronous call cannot process the request.
  • Asynchronous calls are made through XMLHttpRequest, which is designed to consume and process the complete response from the portlet. With the portal processing the request in between, XMLHttpRequest cannot consume the original response for processing.

This defeats the purpose and value of using asynchronous calls to the server, and we end up with traditional full page refreshes.

There were obviously a few workarounds to this. The most common practice was to serve the request from outside of the portal container into the web container. The idea is that the AJAX call can still be made to ActionURL, but the render function copies or shares its context with a traditional Java servlet in the web container of the application server. The AJAX call can now make a direct request to the servlet and get an asynchronous response from the servlet with no interference from the portal.

JBoss Portals and AJAX - Part 1

There was a need for a better solution, and one that was incorporated as part of the specification. JSR-286, the latest portlet specification, addresses these problems.

JBoss Portal Server Development Create dynamic, feature-rich, and robust enterprise portal applications
Published: January 2009
eBook Price: €18.99
Book Price: €30.99
See more
Select your format and quantity:

JSR-286 and AJAX

Among the set of features that the new portlet specification JSR-286 introduces to make things easier for AJAX implementations, are the options to directly communicate with the portlet through shared render parameters and resource serving.

Referring back to the workaround option in JSR-168, the new specification provides a standard for setting and receiving render parameters, and we no longer have to deal with manual copying OF context and parameters.

To set the render parameter directly to the response, all we have to do is this:

public class AssetPortlet extends GenericPortlet {
public void processAction(ActionRequest request,
ActionResponse response) {
response.setRenderParameter("rate", "4.5");
}
...
}

To receive render parameters in the portlet directly from the view, we can say:

public class AssetPortlet extends GenericPortlet {
public void render(RenderRequest request, RenderResponse response)
{
String rate = request.getParameter("rate");
...
}
...
}

Similarly, the resource servicing option allows us to directly invoke the portlet from the portlet user interface, as follows:

ResourceURL resourceURL = renderResponse.createResourceURL()
<form action="<%= resourceURL %> method="POST">
...
</form>

Using ResourceURL invokes a new life cycle method called serveResource() on the server, as follows:

public void serveResource(ResourceRequest req, ResourceResponse resp)
throws PortletException, IOException
{
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
writer.print("<p> <b>Response Markup </b>");
writer.close();
}

So, now when we use ResourceURL instead of ActionURL, the implementation of the asynchronous requests appears as follows:

JBoss Portals and AJAX - Part 1

Hence, we can conclude that the following approaches are available for implementing a portlet user interface:

  • For a traditional, JSR-168 based implementation, ActionURL and RenderURL are still options, although very limited ones, for asynchronous call implementations
  • For an AJAX implementation and asynchronous request-response, the ResourceURL option offered by JSR-286, is the best.

JBoss 2.7.0 offers full support for the JSR-286 Portlet 2.0 specification, allowing us to implement robust AJAX-based applications without any workarounds.

With this background, let's dive right into developing a portlet for our "MyCompany" portal page using AJAX support. In subsequent sections, we will discuss the configuration and other in-built AJAX support provided by the JBoss portal server.

 

Developing an AJAX portlet

Let us enhance our sample application, the "MyCompany" portal, and implement AJAX functionality in one of the portlets, using asynchronous server calls and dynamic HTML.

We will build a simple asset allocation calculator which asks for the user's age and returns an asset allocation mix of stocks and bonds based on a simple age-based logic on the server side. The user interface will submit the request asynchronously to a portlet on the server, which will then process it and return a markup that will only refresh a segment of the page.

We will also use some special user interface DHTML effects to demonstrate the effective combination of asynchronous calls with a rich user interface.

The front-end

We will create a new portlet called "AJAXPortlet" in the "MyPortal" project, and position it in the center column below our current preferences portlet that was created earlier.

The myportal-object.xml shows the following entry:

<deployments>
...
<deployment>
<if-exists>overwrite</if-exists>
<parent-ref>mycompany</parent-ref>
<page>
<page-name>default</page-name>
<window>
<window-name>MyCompany AJAX Portlet</window-name>
<instance-ref>AJAXPortletInstance</instance-ref>
<region>center</region>
<height>2</height>
</window>
...
</page>
</deployment>
</deployment>

Let's add our form to the JSP:

<!--AJAX submission via form
Actual post takes place in Javascript function -->
<form method='post'
id="assetform"
name="assetcalc"
action=""
onsubmit="ajaxSubmit('<%= renderResponse.
createResourceURL() %>','testdiv',
Form.serialize(this),true); return false;">
<p>Your Age: <input type="text" name="age"/> <br><br>
<input id="page" type="hidden" name="page" value="asset"/>
<input id="submit" type="submit" name="Submit"/>
</form>

As we can see, the form has an onSubmit option to delegate submission to a JavaScript function. We are also using ResourceURL, generated from renderResponse.createResourceURL(), to submit our form. This allows us to talk directly to the portlet instead of to the portal.testdiv demarcates the location of the result.

Although we are using the direct API here for illustrative purposes, we can use the Portlet 2.0 tag library provided by JBoss portal in our JSP, in which case the following taglib declaration needs to be added: <%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

The ResourceURL looks like this:

/portal/portal/mycompany/default/MyCompany+AJAX+Portlet?
action=b&cacheability=PAGE

The cacheability=PAGE parameter indicates that we want the URL to contain the state of the complete page, including values such as PortletURLs, and so on.

Now, let's add some JavaScript code to process the form. It is useful to note that for an AJAX implementation, we rely on JavaScript functions to carry out our submissions and then track responses from the server asynchronously. Although we can write the JavaScript code ourselves, using existing popular libraries gives us a lot more efficiency and a broader feature set. We will use scriptaculous.js for the effects and prototype.js for asynchronous calls. These are available as standard in the headers of JBoss portal. Hence, we can use them without worrying about adding the library files along with the code. Our AJAX code includes asynchronous calls, and the special effects appear as follows:

<script type="text/javascript">
// AJAX call using Prototype.js and Scriptaculous for effects
function ajaxSubmit(url,target,params,effects)
{
new Ajax.Updater(target, url, {method: 'GET', asynchronous:true, parameters:params});
if(effects){
new Effect.BlindDown(document.getElementById(target));
new Effect.Highlight(document.getElementById(target),
{startcolor: '#0066CC', endcolor: '#ffffff', restorecolor:
'#FFCC99'});
}
}
</script>

Here, the Ajax.Updater function takes the ResourceURL, which is the target div for the results, and the parameters entered in the form, to make an asynchronous call to the server. If the effect is enabled, which it is in our example, when the server responds back with a markup, the JavaScript code will slide down, create space, and display the output, while highlighting the information in three colors for emphasis.

We are all set on the client side. Now let's go back and create our portlet.

The server-side portlet

Our JSP invokes an instance of AJAXPortlet which appears as follows:

public class AJAXPortlet extends GenericPortlet
{
// async requests and responses are processed here
public void serveResource(ResourceRequest req, ResourceResponse resp) throws PortletException, IOException
{
resp.setContentType("text/html");
PrintWriter writer = resp.getWriter();
String age = req.getParameter("age");
if (age == null || age.equals("")){
writer.print("<P> Sorry, Please enter valid age between 10 and 100! ");
}
else {
String bond = age;
int stock = 100 - Integer.parseInt(age);
writer.print("<P> The recommended asset allocation for your age is: ");
writer.print("<p> <b>Stocks: </b>" + stock + "% <b> Bonds: </b>" + bond + "%");
}

writer.close();
}
// parent page delivery
public void render(RenderRequest renderRequest, RenderResponse
renderResponse) throws PortletException, IOException
{
PortletContext context = getPortletContext();
PortletRequestDispatcher rd = context.getRequestDispatcher("/WEB-INF/jsp/ajax_calc.jsp");
rd.include(renderRequest, renderResponse);
}
}

Let's look at this a bit more closely. The first method, serveResource, gets invoked when the JSP JavaScript performs a submission. We make a quick calculation, open a PrintWriter and write our output markup to it. The output of the PrintWriter goes directly back to the JavaScript call which then parses the information and displays it in the requested format. We also perform a quick validation of the input data to demonstrate how efficient it is to validate data by using AJAX.

Hence, using this single method, we have achieved asynchronous communication between a window on a client browser and a portlet.

The render method follows the traditional approach of serving the portlet window when the page first loads. All we do here is to point it to the JSP page that houses our AJAX calls.

Deployment

Once we build and deploy the portlet, and the home pages loaded, it looks like this:

 

Let's enter some age as data in the field, and then submit the form.

JBoss Portals and AJAX - Part 1

Once we enter the data and click on Submit Query, we should see the result showing up in the same page in a newly opened area below the portlet, and with some visual effects.

JBoss Portals and AJAX - Part 1

We can also see validation in action by entering either nothing or a number greater than 100. The server reinterprets the data and responds back with an error message, as shown below:

JBoss Portals and AJAX - Part 1

JBoss Portal Server Development Create dynamic, feature-rich, and robust enterprise portal applications
Published: January 2009
eBook Price: €18.99
Book Price: €30.99
See more
Select your format and quantity:

About the Author :


Ramanujam Rao

Ramanujam Rao is a software engineer, architect, and trainer specializing in building large-scale enterprise applications. He has over 13 years of experience in designing and developing complex web architectures, including portals, and helps enterprises build scalable, distributed applications on the JEE platform.

He writes frequently on enterprise architecture and actively consults in field of information technology management, including technology platforms, technology strategy and application delivery.

He has a B.S. in Electrical Engineering, an M.S. in Computer Science, and an MBA from Ohio State University. He currently lives and works in Columbus, OH, USA.

Contact Ramanujam Rao

Books From Packt

Building Websites with Joomla! 1.5
Building Websites with Joomla! 1.5

RESTful PHP Web Services
RESTful PHP Web Services

Learning Website Development with Django
Learning Website Development with Django

OpenCms 7 Development
OpenCms 7 Development

Liferay Portal Enterprise Intranets
Liferay Portal Enterprise Intranets

Alfresco Enterprise Content Management Implementation
Alfresco Enterprise Content Management Implementation

Tapestry 5: Building Web Applications
Tapestry 5: Building Web Applications

Building Powerful and Robust Websites with Drupal 6
Building Powerful and Robust Websites with Drupal 6

Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software