DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Build Self-Hosted RSS Feed Reader Using Spring Boot and Redis
  • Introduction to Spring Boot and JDBCTemplate: JDBC Template
  • How to Use Bootstrap to Build Beautiful Angular Apps
  • Manage Microservices With Docker Compose

Trending

  • Java Virtual Threads and Scaling
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • A Modern Stack for Building Scalable Systems
  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  1. DZone
  2. Coding
  3. Frameworks
  4. Build a Responsive ZK Web App With Fancy URLs

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!

By 
Filip Cossaer user avatar
Filip Cossaer
·
Mar. 01, 18 · Tutorial
Likes (11)
Comment
Save
Tweet
Share
14.8K Views

Join the DZone community and get the full member experience.

Join For Free

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 :

desktop mobile

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.

mobile app Spring Framework Template Spring Boot Database IT Build (game engine)

Opinions expressed by DZone contributors are their own.

Related

  • How To Build Self-Hosted RSS Feed Reader Using Spring Boot and Redis
  • Introduction to Spring Boot and JDBCTemplate: JDBC Template
  • How to Use Bootstrap to Build Beautiful Angular Apps
  • Manage Microservices With Docker Compose

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!