Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Create Rich Web applications using Spring MVC?

In this tutorial, we are going to take a look at how to develop Web applications that are very rich in nature. To do so, we are going to make use of Spring web MVC and the ZK UI framework. We shall also illustrate this with a small demo

If you are into developing web applications, you’d know that Spring happens to be a very popular framework and is also the most obvious choice for many a developer. However, Spring is also mostly combined with jQuery or several other known JavaScript-based frameworks, such as the likes of React or AngularJS.

Here, we shall take an entirely different approach, but also achieve the same thing. We shall make use of the Spring MVC and allow it to communicate with the ZK UI framework, i.e. through the channels that exist between the client and the server. As a result, the ZK UI can take care of basic tasks, such as browser compatibility, HTML DOM update, JavaScript code debugging, etc.

The steps that follow in the article will guide you through the entire process of how you can implement what you are seeking. Also, just before that, we shall take a look at what the Spring and ZK UI framework is all about.

What is the Spring web framework?

Spring basically happens to be an application framework and also a container meant for Java. It belongs to the open source community and hence is supported at all times. Almost all Java applications can make use of the framework’s core features, but requires extensions when they pertain to applications running atop Java Enterprise Editions.

As such, Spring does not follow any particular model of programming, among the numerous that are there. However, it is still very popular among developers of the Java community.

What is MVC?

MVC is elaborated as model-view-controller and is nothing but a basic architecture that allows the implementation of user interfaces. Here, a software application is basically divided into three different parts, which also remain interconnected. However, it also separates the internal information from the manner in which such information is presented and accepted.

MVC has always been popularly used for the development of graphical interfaces for users in desktop computing software. However, at present, a majority of the Web applications are designed using this method.

What is Spring MVC?

Spring framework is a big framework which can cover the entire enterprise application development. It has all components to develop a complex enterprise application. Spring MVC is the web part of spring's framework. It provides different functionalities to build rich and robust web applications. The MVC architecture of spring framework is designed to support re-usable and highly configurable components. It helps to configure logic and functionality of all the components of the web application. Spring MVC also supports to integrate with other popular web frameworks like JSF, Structs, and Hibernate etc. So spring MVC is highly flexible and configurable to use with any other technology platform.

Spring MVC work flow

Now, we know about the spring MVC model and the MVC architecture. Let us now check the work flow that happens in a spring MVC framework.

  • Step 1: The web client send a request for resource to a web application.
  • Step 2: The request is received by the spring front controller. Spring front controller is a servlet which intercepts the incoming request and find out the handler mapping to forward it.
  • Step 3: The handler mapping is the actual bridge between the controller object and the front end request. In the configuration file, keeps all the details. So the mapping technique checks the configuration file and detects the controller object which is supposed to handle the request.
  • Step 4: In the next step, the dispatcher servlet (with the help of handler adapters) dispatch the incoming request to the controller object.
  • Step 5: The controller is the actual request processor; It processes the client request and returns response in the form of ModelAndView object to the front controller.
  • Step 6: After getting the result back, the front controller resolves the actual view in the form of JSP, HTML, and JSF etc. with the help of View Resolver object.
  • Step 7: In the final step, the view part, which contains the result is rendered back as a view to the client.

Figure 1. Spring MVC request-response model

What is ZK UI?

ZK happens to be an open source framework meant for Ajax web applications and also allows for the creation of graphical interfaces for Web applications. The code has been primarily written in Java and developers can create applications with even very little or basic programming knowledge.

ZK architecture

In ZK architecture, the application runs on the server. The application can access all types of resources including backend, UI, listeners and then update the user interface. And all these activities are performed on the server itself. The synchronization between browser and server is taken care automatically by the ZK architecture. The server can access full Java technology stakes and hence it is very helpful to develop any Java based application.

Figure 2. ZK architecture

Demo of To-do Management with CRUD

Now that we have has a very basic introduction of everything that we’ll make use of in our demo, we shall now go ahead with the code. Here, we basically make use of the Spring MVC controller, along with ZK UI, in order to create a to-do management system with CRUD operations. We shall do the work in Java.

What are the requirements?

We shall need the following to construct our demo –

  • Spring MVC 3.1 or higher
  • ZK CE 8.0.1.FL.20151113 or higher
  • ZK PE and EE, although these are optional.

Configuring Spring MVC

This listing is for the configuration of Spring MVC.

Listing 1. Configuring Spring MVC (Web.xml)

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

Setting up of ZK Spring MVC extension

The following listed code demonstrates the setup for the ZK Spring MVC extension.

Listing 2. Setup of ZK Spring MVC (sprngmvc-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

Here are a few annotations that have been provided for developers and can be used.

  • @ZKSelector:[TypeofElement.Parameter] is a means to query ZK part or an input value with ZK CSS-like Selector.
  • @ZKVariable:[TypeofElement.Parameter] is a method to find ZK Variable. For eg. EL VARIABLE IN ZK scope.

ControllerToDo.java

We then make use of a Spring MVC controller and have also declared certain @RequestMapping in order to handle the request with ZK components.

Listing 3. ControllerToDo.java code

@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("Rising early"));
        TodoList.add(new Todo("Booking of a restaurant for breakfast"));
        TodoList.add(new Todo("Visit technical 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) {
        // getting the currently 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");
        //saving to the model
        TodoList.update(editTodo);
        return "forward:list";
    }
}

Java Bean (POJO)

Listing 4. ToDo.java

public class ToDo {
    private String mesage;
    private boolean done;
    //omitting the getter and setter
}

Preparation of the output

View using ZK can be of many types such as html, xhtml, zul, or even combined with JSP. For this demon, we have made use of a Zul page that has built-in ZK components. We have also specified the declaration of the namespace within the very first line in the list.zul program.

Listing 5. 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, this demo code can be run on a server, i.e. Jetty or Apache Tomcat. Following is the output screen as shown below.

Figure 3. Output screen

Conclusion

Spring MVC is a very popular enterprise level framework. It supports all the layers from front end to middle tier and back end. It is highly configurable and flexible. It can also be extended to increase its functionality. One of the biggest advantages is that you need not use all the components while using the spring framework. You can use only those components which are required for your application development. In this article we have put more stress on the front end part.

The above tutorial shows a very simple method that demonstrates the creation of rich web applications using the Spring MVC framework and ZK UI. While this one of the most common approach followed by developers, it certainly does the task at hand. Here, we have started with the very basics and then moved onto a demonstration of a very simple To-Do list. We hope this will help you learn about how to create web applications using Spring MVC.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login