November 27, 2014
Hot Topics:

Ajax with the ZK Framework

  • June 1, 2006
  • By Michael Klaene
  • Send Email »
  • More Articles »

Evolution of Web Applications

The web browser has become a primary vehicle for delivering business applications to users. There are several benefits to delivering software through the web, including easy administration and simplified accessibility. For all these benefits, however, web applications typically exhibit limited functionality when compared to thick client software. Not only is usability diminished, developing these web applications is often more complex than writing for the desktop, mainly due to the stateless nature of HTTP. Not long after the advent of the web, developers began seeking ways to make their web sites mimic the look and responsiveness of desktop applications. This was often be a dangerous proposition because doing so typically required complex client side programming with JavaScript. Recently, the promise of Ajax technology has given web developers new hope. This article will introduce the open-source Ajax framework known as ZK that allows Java developers to create rich web applications.

Ajax (Asynchronous JavaScript and XML) technology relies on asynchronous communication between client and server to provide users with a dynamic and responsive interface. In traditional Java Servlet-based web applications, a page's entire content is sent via a request to the server where a response is generated and returned. When the client receives this response, the complete page is rendered back to the user. This is the case even if a specific request is relevant to only a small portion of the page. In this scenario, given the amount of processing involved from request to response, contact with the server is kept to a minimum. With Ajax, several light weight requests are continuously sent to the server and responses to those requests cause a partial rendering of the page's model. Server requests are more frequent in nature, but they also tend to be smaller and less expensive. Developing Ajax applications can be a costly enterprise if it means adding significant amounts of JavaScript code. Client script can be difficult to write and maintain, largely due to the fact that different browsers support different implementations of JavaScript and these issues must be addressed by the developer.

ZK Framework Overview

ZK is an AJAX-based web framework from the Potix Corporation. ZK is open-source, licensed under the GPL (GNU Public License). ZK's AJAX engine consists of both client and server components that communicate with one another. ZK provides two sets of user interface components. One set of components is based upon XUL, or the XML User Interface Language. The second set utilizes XHTML. ZK provides an XML-based markup language called ZUML for adding components to a page. Though ZK's Ajax engine makes considerable use of JavaScript, it is important to note that the complexity of implementing Ajax is concealed from the developer. Client side events send data to the server where the developer can handle them with Java code. ZK provides a simplified programming model, similar in many respects to programming with Java Swing. In the Model-View-Controller architecture, ZK addresses the 'View' portion of an application. Developers are free to use technologies such as Enterprise JavaBeans and object-relational frameworks such as Hibernate in conjunction with ZK. It is even possible to incorporate ZK into applications that use view technologies such as JavaServer Pages and JavaServer Faces.

In the remainder of this article, we will take a brief look at ZK in action. The sample application presented here is by no means a comprehensive demonstration of ZK's features. Hopefully, it will encourage you to explore the framework yourself in greater detail.

ZK in Action

The sample application allows university students to create a schedule of courses. There are several domain objects used to represent data used by the application:

Java ClassDescription
CourseSubject offered at university
RoomRoom on university campus
FacultyInstructor at university
AvailableCourseCourse that student may schedule
StudentStudent at university
StudentCourseCourse in student's schedule

An AvailableCourse is an aggregate of Course, Room, and Faculty. It represents a specific course offering for the current semester. A StudentCourse links a Student instance with a particular AvailableCourse. A collection of StudentCourse objects will comprise a student's schedule. I used the NetBeans IDE to develop this sample application. In addition to the domain classes mentioned above, I created a simple Data Access Object in Dao.java that event handlers can use to access sample data. You can download this sample application, including the source code and .war file, here. All .jar files necessary for building ZK applications are included in the ZK distribution. After adding these libraries to your project, you will need to modify the web.xml configuration file to add Servlet mappings that allow ZK to process requests. The ZK download includes a demo application and the easiest way to get started on a new application is to copy its web.xml file and customize as necessary.


Start Page

As mentioned earlier, ZK provides two different component sets, XUL or XHTML. You can actually use both in the same page using XML namespaces. This application will utilize XUL components. ZUML (ZK User Interface Markup Language) is used to specify page components. With ZUML, you can arrange the layout of components on a page, modify attributes for these components, and wire component events to event handlers. It is also possible to handle events directly in the page using the <zscript> element. Zscript lets developers embed Java code in a page, similar to Java scriptlets in JavaServer Pages. Of course, the more robust option is to handle events inside Java classes but we will take a look at both options.

Index.zul contains all the components used in the sample application. You have the option to break up the interface into smaller, reusable files and include them in the main page as you might do with the include directive in JavaServer Pages. The <window> component is a top level component that will normally encapsulate several components on a given page. Like all components, you can modify a window's attributes to modify its appearance and name event handlers. A convenient way to handle component events is to extend the component class. This 'use' attribute in ZUML enables you to specify a custom subclass to represent the component. As an example, the main window in index.zul uses the Java class MainWindow which can be found in the 'web' package:

  <window id="winMain" use="web.MainWindow" border="normal" 
             width="800px" height="500px">
     ...
  <window>

MainWindow can access child components as well as handle window events. For example, by overriding the onCreate Window event, we have the opportunity to customize the title according to the student accessing the application:

    public void onCreate()  {
        //Personalize the window for the current user...
        Student currentStudent = this.getDao().getStudent(this.getDao().getCurrentStudentId());
        this.setTitle("Welcome " + currentStudent.getFname() + " " +
                currentStudent.getLname() + ", This is the Student Enrollment Application.");
    }

As it turns out, the MainWindow class is a convenient place to handle other component events as well. Really any Java class can be used to respond to user actions. The screenshot below shows the page tab where most user interaction takes place. This tab panel consists of a tree component that displays course offerings, a list representing the student's current schedule, and a label that displays the total credit hours for a schedule. In the spirit of a rich client application, students add courses to their schedules by selecting a course from a tree node and dragging it onto the schedule list. This is just one of many examples in which ZK can provide functionality that a typical web application cannot. All of it accomplished too, I might add, with very little code.

Create schedule through drag and drop

Some components defined in index.zul markup file are static in nature. For example, the <html> component is a special component that allows you to add HTML to a page:

     <html>
         <attribute name="content"><![CDATA[
            <br/>
            <h3>Adding a course to your schedule</h3>
            <p>To add a course to your schedule, locate an available course on the left.
            <br>
            Then, drag it onto your schedule.
            </p>
            <br/>
         ]]></attribute>
      </html>  

Other components, such as the tree component shown below, will generate its content dynamically. It uses some helpful attributes that ZK provides to iterate through a Java Collection as well as EL expressions. When the component is first loaded, the tree will loop through a collection of Course objects and display one node for each course name that the university offers. Then, when the user expands a node, an event handler,showAvailableCourses, in class MainWindow executes and generates a node representing all available courses that a user may add to his or her schedule.

     <tree height="300px" width="150px" style="background-color: white">
         <treechildren> 
              <treeitem open="false" forEach="${winMain.dao.courseList}" 
                    onOpen="winMain.showAvailableCourses(self)"  id="${each.id}"> 
                 <treerow> 
                     <treecell label="${each.name}"/>  
                 </treerow> 
                 <treechildren> 

                          <!--Content will be dynamically added in user event handler!-->

                 </treechildren> 
              </treeitem> 
         </treechildren> 
     </tree>

Explore the MainWindow code and the index.zul file. Examine how the .zul page wires component events to event handler methods in the Java class. I think you will find this an intuitive programming model, one that most web developers should find refreshing.





Page 1 of 2



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.


Rocket Fuel