Getting Started With Spring MVC - Developing the MVC components

December 2009

In the world of networked applications, thin clients (also known as web applications) are more in demand than thick clients. Due to this demand, every language is providing frameworks that try to make web-application development simpler. The simplicity is not provided just through setting up the basic application structure or generating boiler plate code. These frameworks are trying to provide simplicity through plug-ability of the frameworks i.e. the components of different frameworks could be brought together without much difficulty.

Among such frameworks, Spring Framework is one of the most used. With its support to multiple Data Access frameworks/libraries and light-weight IoC container makes it suitable for scenarios where one would like mix-and-match multiple frameworks, a different one for each layer. This aspect of Spring Framework becomes more suitable for development of web-applications where the UI does not need to know with which framework it is dealing for business process or data access. The component of the Spring Framework stack that caters to the web UI is Spring MVC. In this discussion, we will focus on the basics of Spring MVC. First section will deal with the terms and terminologies related with Spring MVC and MVC. The second section will detail the steps for developing components of a web-application using Spring MVC. That is the agenda for this discussion.

Spring MVC

Spring MVC, as the name suggests, is a framework based on Model (M), View (V), Controller (C) pattern. Currently there are more than seven well known web-application frameworks that implement MVC pattern. Then what are the features of Spring MVC that sets it apart from other frameworks? The two main features are:

  1. Pluggable View technology
  2. Injection of services into controllers

The former provides a way to use different UI frameworks instead of Spring MVC’s UI library and the latter removes the need to develop a new way to access functionality of business layer.

  1. Pluggable View technology
    Various View technologies are available in the market (including Tiles, Velocity, etc) with which Spring MVC can quite easily be integrated. In other words, JSP is not the only template engine supported. The pluggable feature is not limited to the templating technologies. By using common configuration functionality, other frameworks such as JSF can be integrated with Spring MVC applications. Thus, it is possible to mix-and-match different View technologies by using Spring MVC.
  2. Injection of Services into Controllers
    This feature comes into picture when the Spring Framework is used to implement the business layer. Using the IoC capabilities of Spring Framework, the business layer services and/or objects can be injected into the Controller without explicitly setting up the call to the service or mirroring the business layer objects in controller. This helps in reduction of code duplication between Web UI/process layer and business process layer.

The next important aspect of Spring MVC is its components. They are:

  1. Model (M)
  2. View (V)
  3. Controller (C)

Model deals with the data that the application has to present, View contains the logic to present the data and Controller takes care of the flow of navigation and application logic. Following are the details.

  1. Model
    Model is an object that holds the data to be displayed. It can be any Java object – from simple POJO to any type of Collection object. It can also be a combination of both – an instance of POJO to hold the detailed data and a collection object to hold all the instances of the POJO which, in reality, is most commonly used Model in Spring MVC. Also, the framework has its own way to hold the data. It holds the data using the Model object that is an instance of org.springframework.ui.ModelMap. Internally, whichever collection class object is used, the framework maps it to the ModelMap class.
  2. View
    In MVC, it is the View that presents the data to the user. Spring MVC, just as many other JEE frameworks, uses a combination of JSP and tag libraries to implement View. Apart from using JSP, many kinds of View technologies like Tiles, Velocity, and Jasper Reports can be plugged into the Framework. The main class behind this plug ability is the org.springframework.web.servlet.View. The View class achieves the plug-in functionality by presenting the View as Logical View instead of actual/physical View. Physical view corresponds to the page developed using any of the templating technologies. The Logical View corresponds to the name of the View to be used. The name is then mapped to the actual View in the configuration file. One important point to remember about how Spring MVC uses Logical View is that Logical View and Model are treated as one entity named Model And View represented by org.springframework.web.servlet.ModelAndView class.
  3. Controller
    The flow of application and navigation is directed by the controller. It also processes the user input and transforms it into the Model. In Spring MVC, controllers are developed either by extending the out-of-the-box Controller classes or implementing the Controller interface. Following comes under the former category
    • SimpleFormController
    • AbstractController
    • AbstractCommandController
    • CancellableFormController
    • AbstractCommandController
    • MultiActionController
    • ParameterizableViewController
    • ServletForwardingController
    • ServletWrappingController
    • UrlFilenameViewController

    Of these most commonly used are AbstractController, AbstractCommandController, SimpleFormController and CancellableFormController.

That wraps up this section. Let us move onto the next section – steps for developing an application using Spring MVC.

Developing Applications using Spring MVC – Step-by-Step

To develop an application using Spring MVC, there are three main steps:

  1. Develop the Model
  2. Implement the Controller
  3. Create the View

Among the above steps, the last step tells the framework how the components developed in the initial steps will interact with it and amongst them. Here are the details.

Develop the Model

As discussed in the previous section, any Java object can be used as Model. The object to be used depends upon the requirements. If a set of data that contains a single value per item (e.g. a set of strings representing names or a set of floats representing scores/marks etc) then inbuilt objects such as String along with Collection objects such as List or ArrayList can suffice as Model. An example of such a Model is as follows:

List<String> strList = new List<String>();

Here List of strings containing names is the Model as it has data to be displayed to the user or the data that can be modified by the user through View. However, if the data to be displayed has multiple values per item (such as details of multiple logged-in users) then a combination of POJO (Plain Old Java Object) with inbuilt Collection objects needs to be used as Model. For example, to display a table containing username, logged-in time and duration, the approach will be to have a POJO to hold the details of the logged-in user and place all the instances of the POJO within a Collection object. Following statements depict the same:

User user = new User("a01", "12:30", "1");
List<User> userList =new List<User>();

The user instance contains details of a user having user id as a01. Then it is added to an instance of List. This combination of List and POJO becomes the Model. Important point to keep in mind is that the approaches discussed here for implementing Model cut across all the MVC implementations i.e. these approaches are applicable to all the frameworks that implement MVC pattern. Next step is to implement the Controller.

Implement the Controller

Controller, as discussed before, can be developed either by implementing the IController interface or by extending any one of the provided Controller classes. To develop Controller using the first approach, one will have to implement org.springframework.web.servlet.mvc.Controller.Controller interface. This interface has only one method – handleRequest.  It accepts two arguments – request of type HttpServletRequest and response of type HttpServletResponse. The return type is ModelAndView. For example, a Controller that passes on the list of names to the View, will be as shown below:

public class HelloWorldController implements Controller { 
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
List<String> strList = new List<String>();
ModelAndView modelAndView = new ModelAndView("hello_world");
modelAndView.addObject("list", strList);
return modelAndView;

In the above example, a list of names is created and passed onto the View by adding it to the ModelAndView instance using addObject method. The addObject accepts two parameters – the key by which the object can be later retrieved and the object itself. Even though, developing Controller by implementing IController interface provides fine grained control over Controller’s functionality, it has one major drawback. To have functionalities such as session handling, one will have to provide one’s own implementation. This is where the second approach comes into picture. One can extend any of the pre-built controllers provided by the framework and get most of the basic functionalities out-of-the-box. The second approach will be discussed in detail in the future parts of this series. Next let us move towards the next step – creating the views.

Creating the View

Among the components of MVC, the presentation of data (how user sees) is the sole responsibility of the View. Spring MVC, true to its goal, provides flexibility in creation of Views too. One can use either of the following approaches – using JSP or plugging in other templating frameworks.  If one uses JSP for developing the View, Spring MVC has its own set of JSP taglibs to make interaction with the Controller and Model components easier. Some of the tags are <form>, <errors>, etc. One point to keep in mind is that for each of the form element of HTML, there is a corresponding taglib element. Also if one wants to use the standard taglibs such as JSTL, they can be used without any extra configuration. The following example depicts the use of JSP with JSTL to display a simple page to the user.

<c:forEach items="${requestScope.list}"
User #<c:out value="${status.count}" /> is
<c:out value="${currentName}" /> <br />

The above example uses JSTL to display the list of user first names passed on by the Controller. Similarly, other templating engines (like Velocity) can be plugged in to develop the View. How this can be achieved will be explained in future.


With this we come to the end of this discussion on developing Spring MVC components. The steps to configure the components developed in this discussion will be covered in the next part of this series.


If you have read this article you may be interested to view :

You've been reading an excerpt of:

Spring Persistence with Hibernate

Explore Title