Implement the org.zkoss.zk.ui.Richlet interface

All richlets must implement the org.zkoss.zk.ui.Richlet interface. To minimize the effects of implementing all methods, can extend the org.zkoss.zk.ui.GenericRichlet class instead. Then, when the specified URL is requested, the service method is called, and you can create the user interface then.

package org.zkoss.zkdemo;

import org.zkoss.zk.ui.Page;
import org.zkoss.zk.ui.GenericRichlet;
import org.zkoss.zk.ui.event.*;
import org.zkoss.zul.*;

public class TestRichlet extends GenericRichlet {
    //Richlet//    
    public void service(Page page) {    
        page.setTitle("Richlet Test");        

        final Window w = new Window("Richlet Test", "normal", false);        
        new Label("Hello World!").setParent(w);        
        final Label l = new Label();        
        l.setParent(w);        

        final Button b = new Button("Change");        
        b.addEventListener(Events.ON_CLICK,        
            new EventListener() {            
                int count;                
                public void onEvent(Event evt) {                
                    l.setValue("" + ++count);                    
                }                
            });            
        b.setParent(w);        

        w.setPage(page);        
    }    
}

Like servlets, you can implement the init and destroy methods to initialize and to destroy the richlet when it is loaded. Like servlet, a richlet is loaded once and serves all requests for the URL it is associated with.

One Richlet per URL

Like servlets, a richlet is created and shared for the same URL. In other words, the richlet (at least the service method) must be thread-safe. On the other hands, components are not shareable. Each desktop has an independent set of components. Therefore, it is generally not a good idea to store components as a data member of a richlet.

There are many ways to solve this issue. A typical one is to use another class for holding the components for each desktop, as illustrated below.

class MyApp { //one per desktop
    Window _main;    
    MyApp(Page page) {    
        _main = new Window();        
        _main.setPage(page);        
    }    
}

class MyRichlet extends GenericRichlet {

    public void service(Page page) {    
        new MyApp(page); //create and forget        
    }    
}