Integrating ZK with Other Frameworks

Exclusive offer: get 50% off this eBook here
ZK Developer's Guide

ZK Developer's Guide — Save 50%

Developing responsive user interfaces for web applications using Ajax, XUL, and the open source ZK rich web client development framework

$23.99    $12.00
by Jurgen Schumacher Markus Stäuble | April 2009 | AJAX Java Open Source Web Development

ZK is a great framework but the focus is on the GUI so other frameworks may be needed. This article by Hans-Jurgen Schumacher and Markus Staeuble discusses the integration of ZK with other frameworks. One of the most important frameworks is Spring. This is very often used together with Hibernate. As we will see, it is very easy to integrate ZK with other frameworks. Once it was difficult to use captchas but in the latest ZK versions, ZK supports captchas natively.

Integration with the Spring Framework

Spring is one of the most complete lightweight containers, which provides centralized, automated configuration, and wiring of your application objects. It improves your application's testability and scalability by allowing software components to be first developed and tested in isolation, then scaled up for deployment in any environment. This approach is called the POJO (Plain Old Java Object) approach and is gaining popularity because of its flexibility.

So, with all these advantages, it's no wonder that Spring is one of the most used frameworks. Spring provides many nice features: however, it works mainly in the back end. Here ZK may provide support in the view layer. The benefit from this pairing is the flexible and maturity of Spring together with the easy and speed of ZK. Specify a Java class in the use attribute of a window ZUL page and the world of Spring will be yours. A sample ZUL looks like:

<?xml version="1.0" encoding="UTF-8"?>
<p:window xmlns:p="http://www.zkoss.org/2005/zul"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.zkoss.org/2005/zul
http://www.zkoss.org/2005/zul "
border="normal" title="Hello!"
use="com.myfoo.myapp.HelloController">

Thank you for using our Hello World Application.
</p:window>

The HelloController points directly to a Java class where you can use Spring features easily.

Normally, if a Java Controller is used for a ZUL page it becomes necessary sooner or later to call a Spring bean. Usually in Spring you would use the applicationContext like:

ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
UserDAO userDAO = (UserDAO) ctx.getBean("userDAO");

Then the userDAO is usable for any further access. In ZK there is a helper class SpringUtil. It wrapps the applicationContext and simplifies the code to:

UserDAO userDAO = (UserDAO) SpringUtil.getBean("userDAO");

Pretty easy, isn't it? Let us examine an example.

Assume we have a small web application that gets flight data from a flight table. The web.xml file looks like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>IRT-FLIGHTSAMPLE</display-name>

<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>
hibernateFilter
</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext-jdbc.xml
,classpath:applicationContext-dao.xml
,classpath:applicationContext-service.xml
,classpath:applicationContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

<session-config>
<!-- Default to 30 minute session timeouts -->
<session-timeout>30</session-timeout>
</session-config>

<mime-mapping>
<extension>xsd</extension>
<mime-type>text/xml</mime-type>
</mime-mapping>

<servlet>
<description>
<![CDATA[The servlet loads the DSP pages.]]>
</description>
<servlet-name>dspLoader</servlet-name>
<servlet-class>
org.zkoss.web.servlet.dsp.InterpreterServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>dspLoader</servlet-name>
<url-pattern>*.dsp</url-pattern>
</servlet-mapping>

<!-- ZK -->
<listener>
<description>
Used to cleanup when a session is destroyed
</description>
<display-name>ZK Session Cleaner</display-name>
<listener-class>
org.zkoss.zk.ui.http.HttpSessionListener
</listener-class>
</listener>
<servlet>
<description>ZK loader for ZUML pages</description>
<servlet-name>zkLoader</servlet-name>
<servlet-class>
org.zkoss.zk.ui.http.DHtmlLayoutServlet
</servlet-class>
<!-- Must. Specifies URI of the update engine
(DHtmlUpdateServlet).
It must be the same as <url-pattern> for the update
engine.
-->
<init-param>
<param-name>update-uri</param-name>
<param-value>/zkau</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.zul</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.zhtml</url-pattern>
</servlet-mapping>
<servlet>
<description>The asynchronous update engine for ZK
</description>
<servlet-name>auEngine</servlet-name>
<servlet-class>
org.zkoss.zk.au.http.DHtmlUpdateServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>auEngine</servlet-name>
<url-pattern>/zkau/*</url-pattern>
</servlet-mapping>

<welcome-file-list id="WelcomeFileList">
<welcome-file>index.zul</welcome-file>
</welcome-file-list>

</web-app>

Furthermore let's have a small ZUL page that has the interface to retrieve and show flight data:

<?xml version="1.0" encoding="UTF-8"?>
<p:window xmlns:p="http://www.zkoss.org/2005/zul"
xmlns:h="http://www.w3.org/1999/xhtml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.zkoss.org/2005/zul
http://www.zkoss.org/2005/zul "
id="query" use="com.myfoo.controller.SampleController">

<p:grid>
<p:rows>
<p:row>
Airline Code:
<p:textbox id="airlinecode"/>
</p:row>
<p:row>
Flightnumber:
<p:textbox id="flightnumber"/>
</p:row>
<p:row>
Flightdate:
<p:datebox id="flightdate"/>
</p:row>
<p:row>
<p:button label="Search" id="search"/>
<p:separator width="5px"/>
</p:row>
</p:rows>
</p:grid>

<p:listbox width="100%" id="resultlist" mold="paging" rows="21"
style="font-size: x-small;">
<p:listhead sizable="true">
<p:listheader label="Airline Code" sort="auto"
style="font-size: x-small;"/>
<p:listheader label="Flightnumber" sort="auto"
style="font-size: x-small;"/>
<p:listheader label="Flightdate" sort="auto"
style="font-size: x-small;"/>
<p:listheader label="Destination" sort="auto"
style="font-size: x-small;"/>
</p:listhead>
</p:listbox>
</p:window>

As you can see, the use attribute of the ZUL page is the link to the SampleController. The SampleController handles and controls the objects. Let's have a short look at the SampleController sample code:

public class SampleController extends Window {

private Listbox resultlist;
private Textbox airlinecode;
private Textbox flightnumber;
private Datebox flightdate;
private Button search;
/**
* Initialize the page
*/
public void onCreate() {
// Components
resultlist = (Listbox)
this.getPage().getFellow("query").getFellow("resultlist");
airlinecode = (Textbox)
this.getPage().getFellow("query").getFellow("airlinecode");
flightnumber = (Textbox)
this.getPage().getFellow("query").getFellow("flightnumber");
flightdate = (Datebox)
this.getPage().getFellow("query").getFellow("flightdate");
search = (Button)
this.getPage().getFellow("query").getFellow("search");
search.addEventListener("onClick", new EventListener() {

public void onEvent(Event event) throws Exception {
performSearch();
}
});
}
/**
* Execute the search and fill the list
*/
private void performSearch() {
//(1) List<Flight> flightlist = ((FlightService)
SpringUtil.getBean("flightService")).
getFlightBySearch(airlinecode.getValue(),
flightnumber.getValue(),
flightdate.getValue(),"");
resultlist.getItems().clear();
for (Flight aFlightlist : flightlist) {
// add flights to list
}
}
}
/* (1)-shows the integration of the Spring Bean*/

Just for completion the context file for Spring is listed here with the bean that is called.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

<bean id="txProxyTemplate" abstract="true"
class="org.springframework.transaction.
interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="add*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>

<bean id="flightService" parent="txProxyTemplate">
<property name="target">
<bean class="com.myfoo.services.impl.FlightServiceImpl">
<property name="flightDAO">
<ref bean="flightDao"/>
</property>
</bean>
</property>
</bean>

</beans>

In short we have learned how to use Spring with ZK and about the configurations. We have seen that the integration is quite smooth and also powerful.

ZK Developer's Guide Developing responsive user interfaces for web applications using Ajax, XUL, and the open source ZK rich web client development framework
Published: March 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

Hibernate

Well, Hibernate has really nothing to do with a view layer so why are we talking here about this issue?

Normally, Hibernate is used along with Spring to take care of the database transactions. In the Spring sample the section above in we have also shown the integration of Hibernate to do the mapping and DAO handling. However, unfortunately there is a downer. Hibernate has a different session management. Unlike the ZK multi-threaded environment, Hibernate handles all data accessing operations in one session. To solve this problem the creators of ZK developed their own ZK listener for Hibernate.

This listener has to be configured in the zk.xml:

<listener>
<description>Hibernate thread session context
handler</description>
<listener-class>
org.zkoss.zkplus.hibernate.HibernateSessionContextListener
</listener-class>
</listener>

The <listener> copies the sessionMap to the event thread's ThreadLocal variable whenever a new event thread is initiated. So whenever you call getCurrentSession() in Hibernate the same sessionMap is referenced.

Pay attention of this issue and then Hibernate can be used as described in the Hibernate documentation.

JasperReport

JasperReport is an open-source reporting engine. It can generate print-quality output like PDF, HTML, and RTF. Because there is no communication between the ZK layer and the JasperReport module the integration is quite easy. Just generate the reports (or graphs or PDFs) with JasperReport and show them with ZK tools. A graphic may be loaded dynamically or a PDF can be shown by opening the link.

To use JasperReport use the Java Controller for a ZUL page and use statements like:

jasperReport = JasperCompileManager.compileReport(
"reports/zkbook_demo.jrxml");
jasperPrint = JasperFillManager.fillReport(
jasperReport, new HashMap(), new JREmptyDataSource());
JasperExportManager.exportReportToPdfFile(
jasperPrint, "reports/zkbook.pdf");

There is nothing more to configure.

ZK Mobile

Mobile devices have become more and more popular. There are some tools in the market to create mobile websites. ZK also supports the mobile device market with a special ZK Mobile solution. This ZK Mobile client has to be installed into the mobile device and should be made to run as a thin client to interact with a ZK server. However, the solution isn't perfect because the user has to install software on his or her device even if he or she wishes to access only a single website. But the installation process on mobile devices can be automated so it's not that big an issue.

ZK Mobile features 10 out-of-the-box components:

  • listbox
  • listitem
  • textbox
  • image
  • label
  • command
  • datebox
  • decimalbox
  • intbox
  • frame

Also, the way of developing ZK applications is similar in ZK Mobile. After the installation of the ZK Mobile client (easy with zkmob.jad) any URL pointing to a ZK application may be called. See the following sample picture:

ZK Developer’s Guide

Instead of using the extension *.zul the extension *.mil is used for pages. MIL stands for Mobile Interactive Language. We need a Loader to interpret the ZUL pages and one will also be needed for MIL pages.

The web.xml modifications are:

<servlet-mapping>
<servlet-name>zkLoader</servlet-name>
<url-pattern>*.mil</url-pattern>
</servlet-mapping>

<mime-mapping>
<extension>jad</extension>
<mime-type>text/vnd.sun.j2me.app-descriptor</mime-type>
</mime-mapping>

<welcome-file-list>
<welcome-file>index.mil</welcome-file>
</welcome-file-list>

To use ZK Mobile it is necessary to use at least version 3.0.0 of the ZK framework.

ZK JSP Tags Library

ZK as an AJAX framework has its own interpreting and rendering technology. In some cases, however, the developer would like to use JSP pages and add some ZK features. Maybe there is a large application with hundreds of JSP pages that can't migrate so easily. For this purpose ZK provides the ZK JSP tags library.

Actually the ZK JSP tags library consists of two files:

  • zuljsp.jar
  • zuljsp.tld

Declare the namespace in the JSP files and start using ZK via tags. Check this sample.jsp:

<%@ taglib uri="http://www.zkoss.org/2005/zul/jsp" prefix="j" %>
<j:page zscriptLanguage="java">
<h3>JSP Tag Demo</h3>
<j:window title="jsp demo" border="normal" width="650px">
<j:button label="Click Me">
<j:attribute name="onClick">{
Messagebox.show("It works.", "Information",
Messagebox.OK, Messagebox.INFORMATION);
}
</j:attribute>
</j:button>
<j:vbox id="demo"/>
</j:window>
</j:page>

ZK JSF Components

To enable features from JSF like Validator and ValueBinding the ZK JSF Components wrap ZK components.

Similarly to with the JSP components, just declare the name space and start using the components, that is:

<%@ taglib uri="http://www.zkoss.org/jsf/zul" prefix="z"%>

The sample code from the JSP section will look like:

<HTML>
<HEAD>
<title>JSF Component Demo</title>
</HEAD>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://www.zkoss.org/jsf/zul" prefix="z"%>
<f:view>
<z:page>
<z:window title="jsf demo" border="normal">
<z:button label="Click Me">
<z:attribute name="onClick">{
Messagebox.show("It works.", "Information", Messagebox.OK, Messagebox.INFORMATION);
}</z:attribute>
</z:button>
<z:vbox id="demo"/>
</z:window>
</z:page>
</f:view>
</body>
</HTML>

Binding to a Backing Bean

With the EditableValueHolder implementation a component can bind values to and from a backing bean. The input ZK components implement the EditableValueHolder interface and the following table shows the list of components with the, class of binding target and the attribute of the ZK component that will be set in wrapping.

ZK JSF Component

Class of Binding

Attribute of ZK Component

Bandbox

String

value

Calendar

Date

value

Checkbox

Boolean

checked

Combobox

String

value

Datebox

Date

text

Decimalbox

BigDecimal

text

Doublebox

Double

text

Intbox

Integer

text

Listbox

StringString[] (multiple selection)

Binding on selection

Radiogroup

String

Binding on selection

Slider

Integer

curpos

Timebox

Date

text

Textbox

String

value

Tree

StringString[] (multiple selection)

Binding on selection

ValueBinding of a component

The binding follows typical JSF style. See the following code snippet:

<z:window z:title="ValueBinding Demo" width="650px" >
<z:textbox id="demotextbox"
f:value="#{ValueBindingBean.text}" /><br/>
<z:intbox id="demointbox"
f:value="#{ValueBindingBean.number}" /><br/>
<z:datebox id="demodatebox" format="dd/MM/yyyy"
f:value="#{ValueBindingBean.date}" />
<br/>
<z:listbox id="demolistbox"
f:value="#{ValueBindingBean.selection}">
<z:listitem value="2" label="Text 2" />
<z:listitem value="3" label="Text 3" />
<z:listitem value="4" label="Text 4" />
<z:listitem value="5" label="Text 5" />
<z:listitem value="6" label="Text 6" />
</z:listbox>
<h:commandButton id="submit" action="#{ValueBindingBean.doSubmit}"
value="Submit" />
</z:window>

Summary

We started this article with advantages and disadvantages. Then we saw how to integrate ZK with the Spring Framework and also why it is useful to do so. We then moved on to Hibernate and JasperReport. Then we had a quick brush with ZK Mobile, ZK JSP tags library, and ZK JSF components.

ZK Developer's Guide Developing responsive user interfaces for web applications using Ajax, XUL, and the open source ZK rich web client development framework
Published: March 2008
eBook Price: $23.99
Book Price: $39.99
See more
Select your format and quantity:

About the Author :


Jurgen Schumacher

Hans-Jurgen Schumacher studied mathematics at the University of Karlsruhe, Germany. Since 17 years he is working as a Software Developer and Architect. Right now he is in the position of a Senior Architect for J2EE. One of his special fields are GUIs for web applications as well as Improvements in the Software Build process.

Markus Stäuble

Markus Stäuble is currently working as CTO at namics (deutschland) gmbh. He has a Master degree in Computer Science. He started programming with Java in the year 1999. After that he has earned much experience in building enterprise java systems, especially web applications. He has a deep knowledge of the java platform and the tools and frameworks around Java.

Books From Packt

 

  PHP and script.aculo.us Web 2.0 Application Interfaces
PHP and script.aculo.us Web 2.0 Application Interfaces

WordPress Plugin Development: Beginner's Guide
WordPress Plugin Development: Beginner's Guide

Drupal 6 JavaScript and jQuery
Drupal 6 JavaScript and jQuery

Seam 2.x Web Development
Seam 2.x Web Development

Grails 1.1 Web Application Development
Grails 1.1 Web Application Development

Drools JBoss Rules 5.0 Developer's Guide
Drools JBoss Rules 5.0 Developer's Guide

Django 1.0 Website Development
Django 1.0 Website Development

Learning jQuery 1.3
Learning jQuery 1.3

 

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