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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
  1. DZone
  2. Coding
  3. Frameworks
  4. Rich Web Applications With Spring MVC

Rich Web Applications With Spring MVC

How to develop rich web apps using Spring web MVB and the ZK UI framework with a useful demo.

Tendy Su user avatar by
Tendy Su
·
Nov. 26, 15 · Opinion
Like (11)
Save
Tweet
Share
10.47K Views

Join the DZone community and get the full member experience.

Join For Free

The Spring web MVC framework is a well-known web model-view-controller architecture that provides solutions for RESTFul web sites or for URL routing system purposes. To develop a rich web application, the most popular pattern in the Java world recently has been to choose Spring MVC and jQuery, or other JavaScript UI frameworks, such as AngularJS and React.

Today, we are going to share our idea of using a new approach, in which we can apply the power of Spring MVC to communicate with ZK UI framework seamlessly between client and server channels, and let ZK framework handle the routine tasks, such as HTML DOM update, browser compatibility, and JavaScript code debugging. In the following demo, we will guide you through the steps of using both the power of ZK and Spring MVC in the same world.

Architecture Overview

The figure below depicts the Ajax update workflow for ZK and Spring MVC. The left panel is the same as the ZK architecture workflow, which handles everything concerning client side updates, and the right panel is similar to the Spring MVC architecture workflow. We have designated the white area (circle) as a ZK Spring MVC extension, representing the possibilities of using ZK and Spring MVC together.

Screen Shot 2015-11-12 at 4.31.56 PM
As you can see from above, step 6a is the normal Spring MVC method to handle the response data, and we have injected ZK lifecycle to 6b to allow developers to manipulate ZK components there.

To-do Management Demo (CRUD)

The following demonstrates leveraging Spring MVC controller with ZK UI components to develop a To-do management system with CRUD operations in Java code.

Required Configuration

Versions:

  • Spring MVC: 3.1 or later
  • ZK CE: 8.0.1.FL.20151113 or later
  • ZK PE and EE: (Optional)

web.xml

<!-- Spring MVC configuration -->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
<!-- ZK configuration omitted (as same as usual)-->

springmvc-servlet.xml

<!-- Setup the ZK SpringMVC extension -->
<context:annotation-config/>
<bean class="org.zkoss.zkspringmvc.config.ZKWebMvcConfigurerAdapter"/>

<!-- Demo classes -->
<context:component-scan base-package="org.zkoss.zkspringmvc.demo" />

<!-- Use ZKUrlBasedViewResolver and ZKView instead -->
<bean id="viewResolver" class="org.zkoss.zkspringmvc.ZKUrlBasedViewResolver">
    <property name="viewClass" value="org.zkoss.zkspringmvc.ZKView"/>
    <property name="prefix" value="/WEB-INF/" />
    <property name="suffix" value="" />
</bean>

Defining a Controller

We provided a few new annotations for developer to use.

  • @ZKSelector:[ElementType.PARAMETER] a way to query ZK component or input value with ZK CSS-like Selector
  • @ZKVariable:[ElementType.PARAMETER] a way to evaluate ZK variable (such as EL variable in ZK scope)

TodoController.java

The controller we used is a Spring MVC controller and we have declared some @RequestMapping to handle the request with ZK components.

@Controller
@RequestMapping("/mvc/todos")
@SessionAttributes("todoList")
public class TodoController {

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(ModelMap model) {
        ListModelList<Todo> todoList = new ListModelList<Todo>();
        todoList.add(new Todo("Wakeup early"));
        todoList.add(new Todo("Booking a restaurant"));
        todoList.add(new Todo("Visit Jobs' office"));
        model.addAttribute(todoList);

        return "forward:list";
    }

    @RequestMapping(value = "/finish", method = RequestMethod.POST)
    public String finish(@ZKVariable("self.value") Todo todo) {
        todo.setDone(!todo.isDone());
        return ZKModelAndView.SELF; // meaning the view is handled by ZK way.
    }

    @RequestMapping(value = "/list", method = {RequestMethod.GET,RequestMethod.POST})
    public String list() {
        return "mvc/list.zul";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String add(
            @ModelAttribute("todoList") ListModelList<Todo> todoList,
            @ZKSelector("#message") String message) {
        todoList.add(new Todo(message));
        return "forward:list";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edit(
            @ModelAttribute("todoList") ListModelList<Todo> todoList,
            @ZKSelector("#status") Label status,
            @ZKSelector("#message") Textbox message,
            @ZKSelector("#submit") Button submit) {

        // get the current selected item
        Todo editTodo = todoList.getSelection().iterator().next();
        message.setValue(editTodo.getMessage());

        status.setValue("Edit:");

        submit.setLabel("Update");
        submit.setClientDataAttribute("springmvc-action", "update"); // change to mapping to '/update'

        return ZKModelAndView.SELF;
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(
            @ModelAttribute("todoList") ListModelList<Todo> todoList,
            @ZKSelector("#status") Label status,
            @ZKSelector("#message") String message,
            @ZKSelector("#submit") Button submit) {

        Todo editTodo = todoList.getSelection().iterator().next();
        editTodo.setMessage(message);

        status.setValue("Add:");

        submit.setLabel("Add new Todo");
        submit.setClientDataAttribute("springmvc-action", "add");

        //save to model
        todoList.update(editTodo);

        return "forward:list";
    }
}

Java Bean (POJO)

Todo.java

public class Todo {
    private String message;
    private boolean done;
    //omitted getter and setter
}

Preparing a View

The ZK View can be a Zul, Xhtml, html, or combined with JSP.
In this demo we have chosen a Zul page with the built-in ZK components, and specified the namespace declaration within line 1 in the list.zul file.

  • xmlns:ca=”client/attribute”: a pure html data attribute that is used to declare the action of SpringMVC in this case, such as “ca:data-springmvc-action=’edit'” and “ca:data-springmvc-trigger=’onSelect'”
  • list.zul

    <zk xmlns:ca="client/attribute">
        <vlayout>
            <listbox id="list" model="${todoList}" ca:data-springmvc-action="edit"
                ca:data-springmvc-trigger="onSelect">
                <listhead>
                    <listheader label="Message"/>
                </listhead>
                <template name="model">
                    <listitem>
                        <listcell>
                            <checkbox label="${each.message}" checked="${each.done}" value="${each}"
                            ca:data-springmvc-action="finish" ca:data-springmvc-trigger="onCheck"/>
                        </listcell>
                    </listitem>
                </template>
    
            <div>
                <label id="status" value="Add:"/>
                <grid>
                    <columns>
                        <column label="Message"/>
                    </columns>
                    <rows>
                        <row>
                            <textbox id="message" cols="40"/>
                        </row>
                        <row>
                            <button id="submit" label="Add new Todo"
                                    ca:data-springmvc-action="add"/>
                        </row>
                    </rows>
                </grid>
            </div>
        </vlayout>
    </zk>

    Now, you can run the code above with Tomcat or Jetty server to visit the page

    Further Questions

    1. Q: Can we use ZK MVVM with Spring MVC approach? A: Yes, it is possible with this version.
    2. Q: Can we use ZK MVVM validator mechanism with Spring MVC approach? A: Yes, it is possible with this version.
    3. Q: Can we use HTML or XHTML as a view with ZK SpringMVC approach? A: Yes, ZK 8 version allows you to do this.
    4. Q: Can we invoke SpringMVC action from a JavaScript API? A: Yes, you can use it via “zMvc.send()” JavaScript function.
    5. Q: Can we use Spring MVC controller with ZK composer or ZK MVVM ViewModel mechanism together? A: Yes, it is possible. You can use Spring MVC controller to update the big area, and inside the big area, you can still use ZK Composer or ZK MVVM ViewModel to control the micro update.
    6. Q: Where’s the use of Form Submit to get data in ZK SpringMVC approach? A: In the ZK world, you don’t need to use Form Submit to receive data on the server side, as you can get all the data from ZK component directly on the server.

    Downloads

    The whole demo project can be found at Github.

    Spring Framework application

    Published at DZone with permission of Tendy Su. See the original article here.

    Opinions expressed by DZone contributors are their own.

    Popular on DZone

    • Why Every Fintech Company Needs DevOps
    • Key Considerations When Implementing Virtual Kubernetes Clusters
    • PostgreSQL: Bulk Loading Data With Node.js and Sequelize
    • Top Five Tools for AI-based Test Automation

    Comments

    Partner Resources

    X

    ABOUT US

    • About DZone
    • Send feedback
    • Careers
    • Sitemap

    ADVERTISE

    • Advertise with DZone

    CONTRIBUTE ON DZONE

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

    LEGAL

    • Terms of Service
    • Privacy Policy

    CONTACT US

    • 600 Park Offices Drive
    • Suite 300
    • Durham, NC 27709
    • support@dzone.com
    • +1 (919) 678-0300

    Let's be friends: