Introduction

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 with a rich web application, the most popular pattern in the Java world recently is to choose Spring MVC + 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


    
        springmvc
        org.springframework.web.servlet.DispatcherServlet
        
        1
    
    
        springmvc
        /
    

springmvc-servlet.xml

    
    <context:annotation-config/>
    <bean class="org.zkoss.zkspringmvc.config.ZKWebMvcConfigurerAdapter"/>
    
    
    <context:component-scan base-package="org.zkoss.zkspringmvc.demo" />

    
    
        <property name="viewClass" value="org.zkoss.zkspringmvc.ZKView"/>
        <property name="prefix" value="/WEB-INF/" />
        <property name="suffix" value="" />
    

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

	
		<listbox id="list" model="${todoList}" ca:data-springmvc-action="edit"
			ca:data-springmvc-trigger="onSelect">
			
				<listheader label="Message"/>
			
			
				
					
						<checkbox label="${each.message}" checked="${each.done}" value="${each}" 
						ca:data-springmvc-action="finish" ca:data-springmvc-trigger="onCheck"/>
<label id=”status” value=”Add:”/> <column label=”Message”/> <textbox id=”message” cols=”40″/> <button id=”submit” label=”Add new Todo” ca:data-springmvc-action=”add”/>
	

Now, you can run the code above with Tomcat or Jetty server to visit the page “http://localhost:8080/zkspringmvc-demo/mvc/todos/” and view the demo.

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 on Github project

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

15 Responses to “Rich Web Application with Spring MVC CRUD Demo”

  1. Admilson Cossa says:

    Very good! 1000 likes!

  2. Trong Dinh says:

    My maven seems not able to find zkspringmvc. (Could not find artifact org.zkoss.zkspringmvc:zkspringmvc:jar:1.0-SNAPSHOT). Where is zkspringmvc located?

  3. Admilson Cossa says:

    Hi Trong Dinh, it ‘s not available in maven repository yet. You can use the jar file in the github’s released zip
    https://github.com/jumperchen/zkspringmvc-demo/releases

  4. Jumper Chen says:

    Hi, we just uploaded it to the zk eval repository here – http://mavensync.zkoss.org/eval/org/zkoss/zkspringmvc/zkspringmvc/1.0-SNAPSHOT-Eval/

    You can add the repository into your pom.xml file as follows.

    <repositories>
    <repository>
    <id>ZK PE/EE Evaluation</id>
    <url>http://mavensync.zkoss.org/eval/</url>
    </repository>
    </repositories>

    And then change the version of zkspringmvc to 1.0-SNAPSHOT-Eval

  5. […] the previous post, we have explored the benefits of combining ZK with Spring MVC. In essence, applying the power of […]

  6. zang says:

    It’s real good, but i have something not understand,can you give me some
    advice. the technology is you creat or not ? and i’m rookie.
    Thank you if you can help me

  7. ace says:

    will you make another demo with springboot or javaconfig?

  8. Jumper Chen says:

    @ace,
    Yes, we will consider it.

  9. […] the previous two articles Rich Web Application with Spring MVC CRUD Demo and  Rich Web Application with Spring MVC CRUD Demo – Part II, we’ve explored the […]

  10. ace says:

    Thank you, Jumper Chen

  11. jhanaaron says:

    Why does my program in use @ZKSelector ( “# submit”) Button submit is null get it ?
    Can you help me? thank you.

  12. suman says:

    Components can be accessed only in event listeners Error.help

  13. Wenning Hsu says:

    @jhanaaron

    The problem was caused by the expiry date of zkspringmvc, and it has bean updated. Please clone the repository again. Thanks.

  14. Wenning Hsu says:

    @suman

    I’ve replied to the other article you’ve commented for the same exception, thanks!

Leave a Reply