Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Build a Responsive ZK Web App With Fancy URLs

DZone's Guide to

Build a Responsive ZK Web App With Fancy URLs

In this post, we'll go over how to use this web development framework to create a cross-platform web application. Read on for more!

· Web Dev Zone ·
Free Resource

Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.

Introduction

We all know Java from the old days. We'd write full Java applications with Swing and our worst case scenario was that some users used a low pixel screen like 800x600. That time passed long ago; we have all different type screens now, from mobile phones to very big monitors and even TVs are used as computer screens.

The developing of a UI also changed from normal desktop applications to web applications. With this change, JavaScript and CSS are now the basic languages to know if you want to create a web app.

These two changes merge together when you consider developing a web app that is usable for all screens. From the smallest screen to the biggest TV, and the application needs to be simple enough but at the same time allow the user to see all the details they need.

There are so many frameworks on the market, you can’t know them all. Here, I’d like to show you my favorite GUI framework, ZK. The reason why it’s my favorite framework is that I actually keep developing in Java, with a minimal knowledge of CSS and JavaScript which I don’t need to know when developing non-web applications. And ZK allows me to do so! (Note: of course, if you wish to create your own custom components or change the normal behavior of components, this could require some knowledge of JavaScript.)

What to Expect in This Article

In this post, I want to show an example of how you can develop a fully responsive web application with Fancy URLs using the ZK framework

The advantage of ZK is that you can keep developing like you did with Swing (for those who really want that) or use an advanced technique with zul pages and layout your page in XML, and bind it to a Controller or ViewModel (MVC or MVVM). Now, the example in this article was created in MVVM because, personally, I find it a revolutionary pattern with a very strong implementation from ZK on the backend.

While ZK has a lot of options to go fully responsive, I want to show the @media implementation, and also on how we can set this up in an easy way.

Setting Up Fancy URLs

First of all, you need to know that web pages are reusable and we can add zul pages to other zul pages (once or multiple times).

We create our own filter, capture all requests, and forward them to the same index page.

This will look like:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    String path = req.getRequestURI().substring(req.getContextPath().length());
    if (!(path.equals("/")
            || path.startsWith("/img")
            || path.startsWith("/css")
            || path.startsWith("/js")
            || path.startsWith("/zkau")
            || path.startsWith("/zkwm")
            || path.startsWith("/index")
            || path.contains(".zul")
            || path.contains("html")
            || path.contains("j_spring_security_check"))) {
        request.getRequestDispatcher(getPath(path, req)).forward(request, response);
    } else {
        chain.doFilter(request, response); // Goes to default servlet.
    }
}

We will ignore some default calls from ZK, as well as some static resources like the image folder or our index page. All the other requests we will forward to our index page and we set some attributes in the request so we can retrieve the page the user asked for.

Of course, the example is a Spring Boot example so we also need to register this filter as the last filter in the chain.

Main Screen

So, let’s check out our main screen.

First of all, we need to declare our ViewModel. 

Now, as a good practice, I give the id of the ViewModel a very distinctive name. The reason is that most people will just use the id, 'VM.' We can do that too, as creating multiple ids with the same name is not prohibited but it’s better to make them unique. This VM will be accessible through the whole scope of the window tag.

We start with a normal border layout in this setup.

capture

In code, this should look like this :

<?xml version="1.0" encoding="UTF-8"?>
<?page title="spring boot" contentType="text/html;charset=UTF-8" 
id="mainframe" docType="html" ?>
<zk xmlns="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/zul.xsd">
    <window border="normal" height="100%" 
            viewModel="@id('indexVM') @init('be.chillworld.vm.IndexVM')">
        <style>
            .z-center-body, .z-west-body, .z-window, .z-window-content {
                padding:0px;
            }
        </style>
        <borderlayout>
            <north visible="@load(not indexVM.mobile)">
                <if test="@load(not indexVM.mobile)">
                   <apply template="menu"/>
                </if>
            </north>
            <east>
            </east>
            <south>
                <div>
                    <if test="@load(not indexVM.mobile)">
                        <label value="Tip"/>
                    </if>
                    <if test="@load(indexVM.mobile)">
                        <label value="This is the mobile footer"/>
                    </if>
                </div>
            </south>
            <west width="140px" visible="@load(indexVM.mobile)" 
                  splittable="true" collapsible="true" open="false">
                <if test="@load(indexVM.mobile)">
                    <apply template="menu"/>
                </if>
            </west>
            <center id="center" border="normal">
                <div>
                <apply templateURI="@load(indexVM.url)" height="100%" style="overflow:auto" />
                </div>
            </center>
        </borderlayout>
        <template name="menu">
            <menubar autodrop="true" orient="@load(indexVM.mobile?'vertical':'horizontal')">
                <menuitem label="Home" onClick="alert(self.label)" />
                <menu label="Contact us">
                    <menupopup>
                        <menuitem label="Mail" onClick="alert(self.label)" />
                        <menuitem label="Phone" onClick="alert(self.label)" />
                    </menupopup>
                </menu>
            </menubar>
        </template>
    </window>
</zk>

ZK has a component <if> which works with shadow components. For the North part, we add, <if>.

Here we ask the ViewModel to return us the result of the method  isMobile(). We use EL expressions in the zul we are testing if it’s not mobile. This means, if the getter return is false, this part isn't rendered in the DOM returned to the client.

For the East part, we add, <if >. For the footer, we do exactly the same thing, but we put it all in the South area.

If you look carefully, you will notice that we add a <div> around the two <if> tags. This is because in each section there can be only one child tag. That child can contain more children tags.

The Center part is where the magic happens, and we alter the part what needs to be shown with the apply tag.

Main Screen ViewModel

Let’s start with explaining what a ViewModel is.

It’s actually no more than a basic POJO. You don’t need to implement or extend any Class or Interface.

The expressions in the zul page resolve to methods declared in your ViewModel.

As I said earlier, we need a method isMobile() in our ViewModel, and if you look closer at the zul page you will see that we need also a second getter: getUrl().

So let’s start with creating this class.

First, we need to retrieve the attribute that we set in the filter, the one that points to the current page.

@Init
public void init(@QueryParam("page") String queryParam) {
   url = (String) Executions.getCurrent().getAttribute("page") + ".zul";
}

Zk makes it easy with some annotations. The @Init annotation means that this method will be triggered by initializing.The @QueryParam will retrieve the attribute we set in the request.
So the only thing we need to do is to hold that page into a global variable.

Of course, we need a getter for that variable :

public String getUrl() {
    if (url == null) {
        return null;
    }
    return URL_PREFIX + url;
}

Here we implement some kind of null check because we don’t want the user to see some error when the attribute is null. Returning null will result in not initializing the center part.

The next step is implementing some abstract responsiveness for our whole application :

@MatchMedia("all and (max-width: 500px)")
public void handleMax500() {
    switchTemplate(MOBILE);
}

@MatchMedia("all and (min-width: 501px)")
public void handleMin500() {
    switchTemplate(DESKTOP);
}

public void switchTemplate(String newTemplate) {
    if (template == null || !newTemplate.equals(template)) {
        this.template = newTemplate;
        BindUtils.postNotifyChange(null, null, this, "template");
        BindUtils.postNotifyChange(null, null, this, "mobile");
    }
}

public String getTemplate() {
    return template;
}

The @MatchMedia annotations will act like the @media CSS annotations. This triggers the method if the method matches the query set in the annotation. The query is the same query as you use in the CSS @media selector.

@MatchMedia("all and (max-width: 500px)") 

In this example, this means all media and screens have a maximum width of 500px. Important note: the method is only triggered when you come from a no query match to a query match. This means, if you are at 200px width and change to 300px width => the method is NOT triggered. We also provide a getter for the template variable, the usage for that will be explained later on.

With BindUtils.postNotifyChange, we notify the binder that the property is changed. The binder is the glue between the view and the ViewModel.  In other words, the binder will set our view in the correct state and only for that specific property.

As the last part, we needed also a boolean getter to know if we are acting mobile or not :

public boolean isMobile() {
    return MOBILE.equals(template);
}

Pretty straightforward here.

Now, this ViewModel is finished.

The Actual Page

Now it’s time for the final bit of work.

Let’s create a zul page and a ViewModel so we can actually see that this example works.

<div viewModel="@id('vm') @init('be.chillworld.vm.template.TemplateVM')">
    <apply template="@load(indexVM.template)"/>
    <template name="mobile">
        <apply templateURI="~./zul/webpages/common/grid_mobile.zul"/>
    </template>
    <template name="desktop">
        <apply templateURI="~./zul/webpages/common/grid_desktop.zul"/>
    </template>
</div>

Again, we initialize a ViewModel, and this time we will call the id, vm. Now we need to define two different templates. We have a template for the mobile part and a template for the desktop part. As you can see, again we just apply another page to this. It’s not needed, but I do like to have the two separated, just a personal preference. And before (or after, doesn’t matter) the two templates we add a third apply.

Here is our second bit of magic. Because the indexVM is still here and active, as we are in the scope of the window, we can call the template getter of the indexVM. That will return which template we would like to use and the “apply “ will render that template into the browser.

The grid_mobile.zul :

<grid  model="@init(vm.items)">
    <columns>
        <column width="40px" />
        <column label="Name" sort="auto" align="center" hflex="1"/>
    </columns>
    <rows>
        <template name="model" var="item">
            <row>
                <detail>
                    <vlayout>
                        <div>
                            <label value="Brand:" />
                            <label value="${item.brand}"/>
                        </div>
                        <div>
                            <label value="Quantity:" />
                            <label value="${item.quantity}"/>
                        </div>
                        <div>
                            <label value="Price:" />
                             <label value="${item.price}"/>
                        </div>
                    </vlayout>
                </detail>
                <label value="${item.name}" />
            </row>
        </template>
    </rows>
</grid>

And the grid_desktop.zul :

<grid  model="@init(vm.items)">
    <columns>
        <column label="Name" sort="auto" align="center"/>
        <column label="Brand" sort="auto" align="center"/>
        <column label="Quantity" sort="auto" align="center"/>
        <column label="Price" sort="auto" align="center"/>
    </columns>
    <rows>
        <template name="model" var="item">
            <row>             
                <label value="${item.name}" />
                <label value="${item.brand}"/>
                <label value="${item.quantity}"/>
                <label value="${item.price}"/>                  
            </row>
        </template>
    </rows>
</grid>

The last part that I need to show is a basic POJO, the last ViewModel. Normally there can be a lot more logic in there like actions, but, in this example, we just need to return a Collection <Item>.  ZK will autocast all collections to a grid or listbox to a ListModelList<>, but it's better to create your own final ListModelList in the ViewModel. There are two reasons for that:

  1. Each notification of our Collection will trigger a new auto-casting to ListModelList. By having one declared in our zul we avoid doing that.

  2. ListModelList is actually smart. Inserting or deleting any item from the collection will be reflected in the GUI directly. Changing a bean in the collection will not. If you need to show completely new items after a search, just clear the ListModelList and fill it back up with the new collection of beans. 

public class TemplateVM {

    private final ListModelList<Item> items = new ListModelList<>();

    @Init
    public void init() {
        items.add(new Item(20, "Oat Latte Macchiato", "Starbucks", 5));
        items.add(new Item(21, "Almond Latte Macchiato", "Starbucks", 6));
        items.add(new Item(21.5, "Coconut Latte Macchiato", "Starbucks", 7));
        items.add(new Item(22, "Latte Macchiato", "Starbucks", 8));
        items.add(new Item(23, "Caffè Americano", "Starbucks", 9));
        items.add(new Item(23.5, "Caffè Latte", "Starbucks", 4));
        items.add(new Item(24, "Caffè Mocha", "Starbucks", 3));
        items.add(new Item(25, "Cappuccino", "Starbucks", 2));
    }

    public ListModelList<Item> getItems() {
        return items;
    }
}

Because we have one ViewModel for the two templates, switching the templates will not interfere with our ViewModel's state. In other words, if our ViewModel contains any selectedItems or some text already typed, changing templates will result in seeing that into the other template as well.

Now let's show the output.

Desktop vs mobile :

desktopmobile

Playtime

Now it’s up to you.

First of all, you can download or clone the GitHub repository of my example.

Then run the Spring Boot application (goal:spring-boot:run) or with NetBeans, a nbactions.xml provided. The page is: http://localhost:8080/template

You can test the pages with every browser on any device. I tested it on an iPhone 5, Honor 8, and IE. For IE, just reduce your window to see the changes, for phones just rotate your device 90° and you will also see the template change.

Extra Information

I also need feedback for future articles, so if you would be so kind to:

  • Star the GitHub repository if you like my article.

  • Contact me with question/concerns/remarks/ideas on future articles

  • Also, I’m active on the ZK Forum so any questions on ZK you could share there too.

Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.

Topics:
zk framework ,zkoss ,web dev ,web application development

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}