CSC/ECE 517 Fall 2012/ch1 1w20 pp: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
No edit summary
 
(81 intermediate revisions by 2 users not shown)
Line 2: Line 2:
A common feature of today’s web applications is to retrieve data from a data store and display it for the user. The system stores the updates in the data store when the user changes the data. The flow of information between the data store and the user interface might compel the computer programmer to tie these two pieces together to reduce the amount of coding.  This approach has significant problems. User interface logic tends to change more frequently than business logic, especially in Web-based applications. If user interface code and business logic are combined in a single object, you have to modify an object containing business logic every time you change the user interface. Also, in most cases, the application displays the same data in different ways. Tight coupling between the presentation and business logic would mean that the same code is repeated at multiple places. This reduces the maintainability and flexibility of the application.
A common feature of today’s web applications is to retrieve data from a data store and display it for the user. The system stores the updates in the data store when the user changes the data. The flow of information between the data store and the user interface might compel the computer programmer to tie these two pieces together to reduce the amount of coding.  This approach has significant problems. User interface logic tends to change more frequently than business logic, especially in Web-based applications. If user interface code and business logic are combined in a single object, you have to modify an object containing business logic every time you change the user interface. Also, in most cases, the application displays the same data in different ways. Tight coupling between the presentation and business logic would mean that the same code is repeated at multiple places. This reduces the maintainability and flexibility of the application.


The '''Model-View-Controller (MVC)''' pattern separates the modeling of the business logic, the presentation, and the actions based on user input into three separate classes:
The '''Model-View-Controller '''[http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller MVC] pattern separates the modeling of the business logic, the presentation, and the actions based on user input into three separate classes:


* '''Model''': The model manages the behavior and data of the application domain. It responds to requests for the user interface(view), and responds to instructions from the controller to change state.
  * '''Model''': The model manages the behavior and data of the application domain. It responds to requests for the user interface(view),and responds to instructions from the controller to change state.
  * '''View''': The view refers to the user interface and manages the display of information
  * '''Controller''': The controller interprets the inputs from the user, informing the model and/or the view to change appropriately.


* '''View:''' The view refers to the user interface and manages the display of information
==History==
The invention of MVC is attributed to [http://en.wikipedia.org/wiki/Trygve_Reenskaug Trygve Reenskaug], who was working at Xerox PARC at the time. The 80's saw the first implementations of the MVC framework in the form of smalltalks-80. MVC, which was a key feature of the language [http://en.wikipedia.org/wiki/Smalltalk Smalltalk] was designed for desktop applications with the main concern being the separation of the presentation from the domain model.
 
[[File:Mvc-structure-generic.gif]]
 
 
 
 
In a classic MVC model, the view is supposed to learn by observing the relevant model as the View and Controller are transparent to each other. The view updates itself through observing the relevant model. Therefore the model needs to implement the observer pattern. Controller handles the user inputs and delegates the user actions to method calls in the models.                                                                     
 
A complete screen can be understood as a collection of widgets - each widget element consisting of its own View and Controller object.
 
==Previous research in MVC==
 
The MVC framework is a well-established design pattern that is widely used for applications with a user interface component.  Several papers describe applications of the MVC framework for Web application development.  For example, GuangChun et al. (13) describe an approach whereby the model component is a JavaBean, the View is created using Java Server Pages (JSPs), and the Controller is created using a Java servlet.  Leff and Rayfield (14) describe an MVC Web application that provides flexibility in how the application is partitioned between the client and the server.  Sauter et. al (15) describe an MVC application that adapts to multiple client devices, including computers, printers, and handheld devices.
 
A number of proprietary Web-oriented technologies have been developed using MVC, including [http://struts.apache.org/ Struts] and [http://mav.sourceforge.net/ Maverick].  Barrett and Delany (16) describe a non-proprietary MVC framework using XML and XSLTs. 
 
The consensus among most authors is that the MVC framework provides significant advantages for Web based applications:  less coupling, higher cohesion, easier maintenance, and enhanced scalability.  Selfa et. al (17) state that MVC provides an added advantage for systems with a database component because it allows the same information to be presented in a variety of different formats by utilizing different information views.  (It should be noted that the system developed by Selfa et. al was developed using ASP.NET, which uses a separate controller for each of the views in the Web site.  This is a deviation from the standard MVC architecture, which prescribes a single controller for all views.)  None of this work substantiates the advantages of the MVC architecture using specific comparisons between MVC and non-MVC Web applications that systematically identify the advantages and disadvantages of each approach. 


* '''Controller:''' The controller interprets the inputs from the user, informing the model and/or the view to change appropriately.


==History==
The invention of MVC is attributed to Trygve Reenskaug, who was working at Xerox PARC at the time. The 80s decade saw the first implementations of the MVC framework in the form of smalltalks-80. MVC, which was a key feature of the language (Smalltalk) was designed for desktop applications with the main concern being the separation of the presentation from the domain model.


==MVC pattern in web application development==
==MVC pattern in web application development==
The classical MVC concept is more suited for desktop applications than typical web applications. In desktop applications you have a direct connect between UI components and the responsible controller or presenter. In web applications the HTML for a complete screen is sent to the browser. The user actions in the UI  are sent to the web server in the form of a request. This request has to be interpreted and normally the new or updated screen has to be sent to the browser again.
The HTML for the complete screen can be understood as a set of widgets (or subviews). For example it can contain a "main menu", a "news list", a "basket" etc. The web server always needs to generate the complete view with all its subviews.
[[File:mvc-web.jpg]] 
A MVC Framework for web applications therefore normally works this way:
*The request that is sent from the browser to the web server goes to a front controller, which then builds a request object and starts processing the request.
*This is followed by “dispatching” .The Controller objects call the action methods that belong to the current request and are responsible to return the correct response. This can be roughly summarized as:
1. The controller loads/modifies model objects
2. It then passes the model to a view
3. Next it calls the view "render()" method to get the response.
*Normally the view that is returned to the browser consist of a hierarchy of subviews and/or widgets


==Web frameworks using MVC pattern==
==Web frameworks using MVC pattern==
Recently MVC has become a very popular strategy for building websites. There are quite a few programming languages for which the MVC-Web framework is now available.
[http://struts.apache.org/ Struts] for Java, [http://en.wikipedia.org/wiki/Maypole_framework Maypole] for Perl and [http://rubyonrails.org/ Rails] for Ruby are some to name a few.
===[http://rubyonrails.org/ Ruby on Rails]===
Ruby on Rails is an open source full-stack web application framework for the Ruby programming language.
'''Model ( [http://api.rubyonrails.org/classes/ActiveRecord/Base.html ActiveRecord] ) :'''
Maintains the relationship between Object and Database and handles validation, association, transactions, and more.
This subsystem is implemented in ActiveRecord library which provides an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables, and so on.
'''View ( [http://api.rubyonrails.org/classes/ActionView/Base.html ActionView] )'''
A presentation of data in a particular format, triggered by a controller's decision to present the data. They are script based templating systems like [http://en.wikipedia.org/wiki/JavaServer_Pages JSP], [http://en.wikipedia.org/wiki/Active_Server_Pages ASP], [http://en.wikipedia.org/wiki/PHP PHP] and very easy to integrate with [http://en.wikipedia.org/wiki/Ajax_(programming) AJAX] technology.
This subsystem is implemented in ActionView library which is an Embedded Ruby (ERb) based system for defining presentation templates for data presentation. Every Web connection to a Rails application results in the displaying of a view.
'''Controller ( [http://api.rubyonrails.org/classes/ActionController/Base.html ActionController] ):'''
The facility within the application that directs traffic, on the one hand querying the models for specific data, and on the other hand organizing that data into a form that fits the needs of a given view.
This subsystem is implemented in ActionController which is a data broker sitting between ActiveRecord (the database interface) and ActionView (the presentation engine).
===[http://jakarta.apache.org/struts/index.html Struts framework]===
Struts is a set of Java classes and JSP tag libraries that uses a model-view-controller (MVC) design pattern to provide a framework for developing Web applications. Struts is an open source subproject of the Apache Software Foundation's Jakarta project.
'''Model:'''
The [http://en.wikipedia.org/wiki/Enterprise_JavaBeans Enterprise JavaBeans], [http://en.wikipedia.org/wiki/Java_Data_Objects Java Data Objects(JDO)] and [http://en.wikipedia.org/wiki/JavaBeans JavaBeans] can be use as a model. Struts frame work doesn't limit you to one particular model implementation.
'''View:'''
The View portion of a Struts-based application is most often constructed using JavaServer Pages (JSP) technology. The framework includes a set of custom tag libraries that facilitate creating user interfaces that are fully internationalized and interact gracefully with ActionForm beans. ActionForms capture and validate whatever input is required by the application.
'''Controller:'''
The primary component of the Controller in the framework is a servlet of class ActionServlet. This servlet is configured by defining a set of [http://struts.apache.org/1.x/apidocs/org/apache/struts/action/ActionMapping.html ActionMappings]. An ActionMapping defines a path that is matched against the request URI of the incoming request and usually specifies the fully qualified class name of an Action class.
==Examples==
===[http://en.wikipedia.org/wiki/Spring_Framework '''Spring framework''']===
The Spring Framework is an open source application framework and Inversion of Control container for the Java platform.
The example is a page displaying a car list.
[[File:Spring-mv.jpg]]
Model classes: Car and Brand
Manager class: to obtain a list of Cars
Controller class: will use the list method from the Manager
View (JSP): display the car list
* '''Model classes'''
The Brand class serves as a Model class and has the information for id, name and country for the brand.
'''‎WEB-INF/src/springmvc/model/Brand.java'''
  package springmvc.model;
  public class Brand {
  private Long id;
  private String name;
  private String country;
  public String getCountry() {
  return country;
  }
  public void setCountry(String country) {
  this.country = country;
  }
  public Long getId() {
  return id;
  }
  public void setId(Long id) {
  this.id = id;
  }
  public String getName() {
  return name;
  }
  public void setName(String name) {
  this.name = name;
  }
  }
The Car class is another Model which has information for the brand, model and price of the car.
'''WEB-INF/src/springmvc/model/Car.java'''
package springmvc.model;
import java.math.BigDecimal;
public class Car {
  private Long id;
  private Brand brand;
  private String model;
  private BigDecimal price;
  public Long getId() {
  return id;
  }
  public void setId(Long id) {
  this.id = id;
  }
  public Brand getBrand() {
  return brand;
  }
  public void setBrand(Brand brand) {
  this.brand = brand;
  }
  public String getModel() {
  return model;
  }
  public void setModel(String model) {
  this.model = model;
  }
  public BigDecimal getPrice() {
  return price;
  }
  public void setPrice(BigDecimal price) {
  this.price = price;
  }
}
The CarManager contains the list of Cars.
'''WEB-INF/src/springmvc/service/CarManager.java'''
  package springmvc.service;
  import java.math.BigDecimal;
  import java.util.LinkedList;
  import java.util.List;
  import springmvc.model.Brand;
  import springmvc.model.Car;
public class CarManager {
  private static List<Car> carList;
  static {
    Brand brand1 = new Brand();
    brand1.setId((long)1);
    brand1.setName("Mercedes");
    brand1.setCountry("Germany");
    Brand brand2 = new Brand();
    brand2.setId((long)2);
    brand2.setName("Peugeot");
    brand2.setCountry("France");
    Car car1 = new Car();
    car1.setId((long)1);
    car1.setBrand(brand1);
    car1.setModel("SL 500");
    car1.setPrice(new BigDecimal(40000));
    Car car2 = new Car();
    car2.setId((long)2);
    car2.setBrand(brand2);
    car2.setModel("607");
    car2.setPrice(new BigDecimal(35000));
    carList = new LinkedList<Car>();
    carList.add(car1);
    carList.add(car2);
    }
    public List<Car> getCarList() {
    return carList;
    }
}
'''In 'WEB-INF/springmvc-servlet.xml', we declare a new URL:'''


<bean name="/list_cars.html" class="springmvc.web.CarListController"/>
* '''Controller'''
The CarListController will use the list method from the CarManager.
'''WEB-INF/src/springmvc/web/CarListController.java'''
package springmvc.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import springmvc.service.CarManager;
public class CarListController implements Controller {
  public ModelAndView handleRequest(HttpServletRequest arg0,
  HttpServletResponse arg1) throws Exception {
  CarManager carManager = new CarManager();
  ModelAndView modelAndView = new ModelAndView("carList");
  modelAndView.addObject("carList", carManager.getCarList());
  return modelAndView;
  }
}
* '''View'''
This displays the list of cars along with the brand, model and price.
'''jsp/carList.jsp'''
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
  <body>
    <c:forEach items="${carList}" var="car">
    ${car.brand.name} ${car.model}: ${car.price}
    </c:forEach>
  </body>
</html>
===[http://en.wikipedia.org/wiki/JavaServer_Faces Java Server Faces(JSF)]===
[http://en.wikipedia.org/wiki/JavaServer_Faces JSF] is a UI component based Java Web application framework. JSF is serverbased, e.g. the JSF UI components and their state are represented on the server with a defined life-cycle of the UI components. JSF is part of the Java EE standard.
A JSF application run in a standard web container, for example Tomcat or Jetty.
A JSF application consists of web pages with JSF UI components. A JSF application requires also some configuration files ("faces-config.xml" and web.xml).
The faces-config.xml defines:
Managed Bean - the data elements of the JSF application (managed beans and backing beans) Represents a Java class which will be created dynamically during runtime of the JSF application. It can be defined for which scope the bean is valid (Session, Request, Application or none).
the navigation between web pages
data validators - Used to check the validity of UI input
data converters -Used to translate between UI and model
Managed beans are simple Java objects (POJO's) which are declared in "faces-config.xml" and can be used in an JSF application. For example you can define a Java object "Person". Once you define the object in faces-config.xml you can use the attributes of Person in your JSF UI components, e.g. by binding the value "firstName" of this object to an JSF input field.
JSF uses the Unified Expression Language (EL) to bind UI components to object attributes or methods.
JSF is based on the following configuration files:
*'''web.xml - General web application configuration file'''
You must specify in web.xml that a "FacesServlet" is responsible for handling JSF applications. "FacesServlet" is the central controller for the JSF application. "FacesServlet" receives all requests for the JSF application and initializes the JSF components before the JSP is displayed.
*'''faces-config.xml - Contains the configuration of the JSF application.'''
"faces-config.xml" allows to configure the application, managed beans, convertors, validators, and navigation.
* '''Model'''
This is the model class that returns the celsius or fahrenheit temperature.
package jsf.first.model;
public class TemperatureConvertor {
  private double celsius;
  private double fahrenheit;
  private boolean initial= true;
 
public double getCelsius() {
  return celsius;
  }
public void setCelsius(double celsius) {
  this.celsius = celsius;
  }
public double getFahrenheit() {
  return fahrenheit;
  }
 
public boolean getInitial(){
  return initial;
  }
 
public String reset (){
  initial = true;
  fahrenheit =0;
  celsius = 0;
  return "reset";
}
public String celsiusToFahrenheit(){
  initial = false;
  fahrenheit = (celsius *9 / 5) +32;
  return "calculated";
}
}
* '''View'''
This JSP page is the view for the application and allows the user to get the celsius or fahrenheit temperature.
'''Convertor.jsp'''
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f"  uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h"  uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Celsius to Fahrenheit Convertor</title>
</head>
<body>
<f:view>
  <h:form>
  <h:panelGrid columns="2">
    <h:outputLabel value="Celsius"></h:outputLabel>
    <h:inputText  value="#{temperatureConvertor.celsius}"></h:inputText>
  </h:panelGrid>
    <h:commandButton action="#{temperatureConvertor.celsiusToFahrenheit}" value="Calculate"></h:commandButton>
    <h:commandButton action="#{temperatureConvertor.reset}" value="Reset"></h:commandButton>
    <h:messages layout="table"></h:messages>
  </h:form>
  <h:panelGroup rendered="#{temperatureConvertor.initial!=true}">
  <h:outputLabel value="Fahrenheit "></h:outputLabel>
  <h:outputLabel value="#{temperatureConvertor.fahrenheit}"></h:outputLabel>
  </h:panelGroup>
</f:view>
</body>
</html>
==Conclusion==
The startup costs for MVC architectures can be high.  Newcomers to the Java-based MVC will initially face the challenge of assembling a compatible set of tag and other libraries needed for the current versions of servlet and JSP technologies.  There are also subtle but important differences in the syntax used in configuration files and tags that occur with each version of servlets, JSPs, and tag libraries.  Once these are understood, development using MVC requires writing the controller or setting up controller configuration files in Struts or JSF. 
If you create a customized (non-Struts or JSF) MVC environment, you must train your developers in the nuances of your environment.  An advantage to using Struts or JSF over a custom MVC environment is that you can hire programmers with prior experience in these technologies.  (Other MVC frameworks exist beyond Struts and JSF, including Ruby on Rails or Tapestry.  However, the issues involved with any pre-built MVC framework, are similar to those identified for Struts and JSF.)
After the startup costs of learning how to configure, program, and design with a selected MVC framework are realized, development time in an MVC versus a non-MVC environment is likely to be similar for small projects.  For larger projects, we anticipate MVC will be faster because the application will be more loosely coupled, have higher cohesion, and minimize intra and inter-crosscutting.  We believe a large MVC site will be more easily maintained and modified over time than a large site developed using non-MVC approaches. 


==Advantages and disadvantages of MVC pattern==
==='''Advantages of MVC pattern'''===
==='''Advantages of MVC pattern'''===


Line 24: Line 381:
* You can more easily migrate legacy programs, because the view is separate from the model and the control and can be tailored to platform and user category.
* You can more easily migrate legacy programs, because the view is separate from the model and the control and can be tailored to platform and user category.
* Isolation of business logic from the user interface
* Isolation of business logic from the user interface
* Ease of keeping code DRY
* Ease of keeping code [http://en.wikipedia.org/wiki/Don't_repeat_yourself DRY]
* Making it clear where different types of code belong for easier maintenance
* Making it clear where different types of code belong for easier maintenance
* Since MVC separates the application into the model, view and controller components, it increases the maintainability of the application
* Since MVC separates the application into the model, view and controller components, it increases the maintainability of the application
Line 35: Line 392:


* Using MVC initially can feel a bit restrictive.
* Using MVC initially can feel a bit restrictive.
* MVC pattern introduces new levels of indirection and therefore increases the complexity of the solution.
* It also increases the event-driven nature of the user-interface code, which can become more difficult to debug.
* Developers cannot completely ignore the view of the model even if they are decoupled. If the model undergoes frequent changes, the views could be flooded with update requests.Views like graphical displays may take some time to render. As a result, the view may fall behind update requests as frequent updates may increase the cost significantly.
==References==
<references/>
1. [http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html  http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html]


==Examples==
2. [http://en.wikipedia.org/wiki/Web_application_framework Web Application Frameworks]
 
3. [http://en.wikipedia.org/wiki/Model-view-controller Model-View-Controller(MVC)]
 
4. [http://rubyonrails.org/ Ruby on Rails]
 
5. [http://www.typo3-media.com/blog/mvc-mvp-typo3-introduction.html MVC: "Introduction and History" ]
 
6. [http://jakarta.apache.org/struts/index.html Struts framework]
 
7. [http://www.careerride.com/MVC-disadvantages.aspx http://www.careerride.com/MVC-disadvantages.aspx]
 
8. [http://en.wikipedia.org/wiki/Ruby_on_Rails http://en.wikipedia.org/wiki/Ruby_on_Rails ]
 
9. [http://en.wikipedia.org/wiki/Spring_Framework http://en.wikipedia.org/wiki/Spring_Framework]


10. [http://www.springsource.org/ Spring framework]


11. [http://www.javaserverfaces.org/ Java Server Faces(JSF)]


==References==
12. [http://www.oracle.com/technetwork/articles/javase/index-142890.html http://www.oracle.com/technetwork/articles/javase/index-142890.html]
<references/>
1. [http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html]


2. [http://en.wikipedia.org/wiki/Web_application_framework http://en.wikipedia.org/wiki/Web_application_framework]
13. GuangChun, L., WangYanhua, Xianliang, L, and Hanhong. A Novel Web Application Frame Developed by MVC. Software Engineering Notes. 2003, 
Vol. 28, 2.


3. [http://en.wikipedia.org/wiki/Model-view-controller http://en.wikipedia.org/wiki/Model-view-controller]
14. Leff, A. and Rayfield, J.T. Web-Application Development Using the Model/View/Controller Design Pattern. IEEE XPlore. 2001.


4. [http://rubyonrails.org/ http://rubyonrails.org/]
15. Sauter, P., Vogler, G., Specht, G., and Flor, T. A Model-View-Controller extension for pervasive multi-client user interfaces. Pers Ubiquit Comput. October, 2004.


5. [http://www.typo3-media.com/blog/mvc-mvp-typo3-introduction.html http://www.typo3-media.com/blog/mvc-mvp-typo3-introduction.html]
16. openMVC: A Non-proprietary Component-based Framework for Web Applications. Barrett, R. and Delany, S.J. New York : ACM, WWW 2004.


6. [http://jakarta.apache.org/struts/index.html http://jakarta.apache.org/struts/index.html]
17. A Database and Web Application Based on MVC Architecture. Selfa, D.M., Carrillo, M., and Rocio Boone, M. Puebla, Mexico : IEEE, IEEE Int. Conf. on Electronics, Communications, and Computers (CONIELECOMP 2006).

Latest revision as of 00:27, 20 September 2012

Introduction

A common feature of today’s web applications is to retrieve data from a data store and display it for the user. The system stores the updates in the data store when the user changes the data. The flow of information between the data store and the user interface might compel the computer programmer to tie these two pieces together to reduce the amount of coding. This approach has significant problems. User interface logic tends to change more frequently than business logic, especially in Web-based applications. If user interface code and business logic are combined in a single object, you have to modify an object containing business logic every time you change the user interface. Also, in most cases, the application displays the same data in different ways. Tight coupling between the presentation and business logic would mean that the same code is repeated at multiple places. This reduces the maintainability and flexibility of the application.

The Model-View-Controller MVC pattern separates the modeling of the business logic, the presentation, and the actions based on user input into three separate classes:

 * Model: The model manages the behavior and data of the application domain. It responds to requests for the user interface(view),and responds to instructions from the controller to change state.
 * View: The view refers to the user interface and manages the display of information
 * Controller: The controller interprets the inputs from the user, informing the model and/or the view to change appropriately.

History

The invention of MVC is attributed to Trygve Reenskaug, who was working at Xerox PARC at the time. The 80's saw the first implementations of the MVC framework in the form of smalltalks-80. MVC, which was a key feature of the language Smalltalk was designed for desktop applications with the main concern being the separation of the presentation from the domain model.



In a classic MVC model, the view is supposed to learn by observing the relevant model as the View and Controller are transparent to each other. The view updates itself through observing the relevant model. Therefore the model needs to implement the observer pattern. Controller handles the user inputs and delegates the user actions to method calls in the models.

A complete screen can be understood as a collection of widgets - each widget element consisting of its own View and Controller object.

Previous research in MVC

The MVC framework is a well-established design pattern that is widely used for applications with a user interface component. Several papers describe applications of the MVC framework for Web application development. For example, GuangChun et al. (13) describe an approach whereby the model component is a JavaBean, the View is created using Java Server Pages (JSPs), and the Controller is created using a Java servlet. Leff and Rayfield (14) describe an MVC Web application that provides flexibility in how the application is partitioned between the client and the server. Sauter et. al (15) describe an MVC application that adapts to multiple client devices, including computers, printers, and handheld devices.

A number of proprietary Web-oriented technologies have been developed using MVC, including Struts and Maverick. Barrett and Delany (16) describe a non-proprietary MVC framework using XML and XSLTs.

The consensus among most authors is that the MVC framework provides significant advantages for Web based applications: less coupling, higher cohesion, easier maintenance, and enhanced scalability. Selfa et. al (17) state that MVC provides an added advantage for systems with a database component because it allows the same information to be presented in a variety of different formats by utilizing different information views. (It should be noted that the system developed by Selfa et. al was developed using ASP.NET, which uses a separate controller for each of the views in the Web site. This is a deviation from the standard MVC architecture, which prescribes a single controller for all views.) None of this work substantiates the advantages of the MVC architecture using specific comparisons between MVC and non-MVC Web applications that systematically identify the advantages and disadvantages of each approach.


MVC pattern in web application development

The classical MVC concept is more suited for desktop applications than typical web applications. In desktop applications you have a direct connect between UI components and the responsible controller or presenter. In web applications the HTML for a complete screen is sent to the browser. The user actions in the UI are sent to the web server in the form of a request. This request has to be interpreted and normally the new or updated screen has to be sent to the browser again. The HTML for the complete screen can be understood as a set of widgets (or subviews). For example it can contain a "main menu", a "news list", a "basket" etc. The web server always needs to generate the complete view with all its subviews.



A MVC Framework for web applications therefore normally works this way:

  • The request that is sent from the browser to the web server goes to a front controller, which then builds a request object and starts processing the request.
  • This is followed by “dispatching” .The Controller objects call the action methods that belong to the current request and are responsible to return the correct response. This can be roughly summarized as:
1. The controller loads/modifies model objects
2. It then passes the model to a view
3. Next it calls the view "render()" method to get the response.
  • Normally the view that is returned to the browser consist of a hierarchy of subviews and/or widgets

Web frameworks using MVC pattern

Recently MVC has become a very popular strategy for building websites. There are quite a few programming languages for which the MVC-Web framework is now available. Struts for Java, Maypole for Perl and Rails for Ruby are some to name a few.

Ruby on Rails

Ruby on Rails is an open source full-stack web application framework for the Ruby programming language.

Model ( ActiveRecord ) : Maintains the relationship between Object and Database and handles validation, association, transactions, and more. This subsystem is implemented in ActiveRecord library which provides an interface and binding between the tables in a relational database and the Ruby program code that manipulates database records. Ruby method names are automatically generated from the field names of database tables, and so on.

View ( ActionView ) A presentation of data in a particular format, triggered by a controller's decision to present the data. They are script based templating systems like JSP, ASP, PHP and very easy to integrate with AJAX technology. This subsystem is implemented in ActionView library which is an Embedded Ruby (ERb) based system for defining presentation templates for data presentation. Every Web connection to a Rails application results in the displaying of a view.

Controller ( ActionController ): The facility within the application that directs traffic, on the one hand querying the models for specific data, and on the other hand organizing that data into a form that fits the needs of a given view. This subsystem is implemented in ActionController which is a data broker sitting between ActiveRecord (the database interface) and ActionView (the presentation engine).

Struts framework

Struts is a set of Java classes and JSP tag libraries that uses a model-view-controller (MVC) design pattern to provide a framework for developing Web applications. Struts is an open source subproject of the Apache Software Foundation's Jakarta project.

Model: The Enterprise JavaBeans, Java Data Objects(JDO) and JavaBeans can be use as a model. Struts frame work doesn't limit you to one particular model implementation.

View: The View portion of a Struts-based application is most often constructed using JavaServer Pages (JSP) technology. The framework includes a set of custom tag libraries that facilitate creating user interfaces that are fully internationalized and interact gracefully with ActionForm beans. ActionForms capture and validate whatever input is required by the application.

Controller: The primary component of the Controller in the framework is a servlet of class ActionServlet. This servlet is configured by defining a set of ActionMappings. An ActionMapping defines a path that is matched against the request URI of the incoming request and usually specifies the fully qualified class name of an Action class.

Examples

Spring framework

The Spring Framework is an open source application framework and Inversion of Control container for the Java platform.

The example is a page displaying a car list.

Model classes: Car and Brand Manager class: to obtain a list of Cars Controller class: will use the list method from the Manager View (JSP): display the car list

  • Model classes

The Brand class serves as a Model class and has the information for id, name and country for the brand.

‎WEB-INF/src/springmvc/model/Brand.java

 package springmvc.model;
 public class Brand {
 private Long id;
 private String name;
 private String country;

 public String getCountry() {
  return country;
 }
 public void setCountry(String country) {
  this.country = country;
 }
 public Long getId() {
  return id;
 }
 public void setId(Long id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 }

The Car class is another Model which has information for the brand, model and price of the car.

WEB-INF/src/springmvc/model/Car.java

package springmvc.model;
import java.math.BigDecimal;

public class Car {
 private Long id;
 private Brand brand;
 private String model;
 private BigDecimal price;

 public Long getId() {
  return id;
 }
 public void setId(Long id) {
  this.id = id;
 }
 public Brand getBrand() {
  return brand;
 }
 public void setBrand(Brand brand) {
  this.brand = brand;
 }
 public String getModel() {
  return model;
 }
 public void setModel(String model) {
  this.model = model;
 }
 public BigDecimal getPrice() {
  return price;
 }
 public void setPrice(BigDecimal price) {
  this.price = price;
 }
}

The CarManager contains the list of Cars.

WEB-INF/src/springmvc/service/CarManager.java

 package springmvc.service;

 import java.math.BigDecimal;
 import java.util.LinkedList;
 import java.util.List;
 import springmvc.model.Brand;
 import springmvc.model.Car;

public class CarManager {

 private static List<Car> carList;

  static {
   Brand brand1 = new Brand();
   brand1.setId((long)1);
   brand1.setName("Mercedes");
   brand1.setCountry("Germany");		

   Brand brand2 = new Brand();
   brand2.setId((long)2);
   brand2.setName("Peugeot");
   brand2.setCountry("France");		

   Car car1 = new Car();
   car1.setId((long)1);
   car1.setBrand(brand1);
   car1.setModel("SL 500");
   car1.setPrice(new BigDecimal(40000));

   Car car2 = new Car();
   car2.setId((long)2); 
   car2.setBrand(brand2);
   car2.setModel("607");
   car2.setPrice(new BigDecimal(35000));

   carList = new LinkedList<Car>();
   carList.add(car1);
   carList.add(car2);		
   }

   public List<Car> getCarList() {
    return carList;
   }	
}

In 'WEB-INF/springmvc-servlet.xml', we declare a new URL:

<bean name="/list_cars.html" class="springmvc.web.CarListController"/>
  • Controller

The CarListController will use the list method from the CarManager.

WEB-INF/src/springmvc/web/CarListController.java

package springmvc.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import springmvc.service.CarManager;

public class CarListController implements Controller {

 public ModelAndView handleRequest(HttpServletRequest arg0,
  HttpServletResponse arg1) throws Exception {

 CarManager carManager = new CarManager();

 ModelAndView modelAndView = new ModelAndView("carList");
 modelAndView.addObject("carList", carManager.getCarList());

 return modelAndView;
 }
}
  • View

This displays the list of cars along with the brand, model and price.

jsp/carList.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
 <body>
   <c:forEach items="${carList}" var="car">
    ${car.brand.name} ${car.model}: ${car.price}
   </c:forEach>
 </body>
</html>

Java Server Faces(JSF)

JSF is a UI component based Java Web application framework. JSF is serverbased, e.g. the JSF UI components and their state are represented on the server with a defined life-cycle of the UI components. JSF is part of the Java EE standard.

A JSF application run in a standard web container, for example Tomcat or Jetty.

A JSF application consists of web pages with JSF UI components. A JSF application requires also some configuration files ("faces-config.xml" and web.xml).

The faces-config.xml defines:

Managed Bean - the data elements of the JSF application (managed beans and backing beans) Represents a Java class which will be created dynamically during runtime of the JSF application. It can be defined for which scope the bean is valid (Session, Request, Application or none).

the navigation between web pages

data validators - Used to check the validity of UI input

data converters -Used to translate between UI and model

Managed beans are simple Java objects (POJO's) which are declared in "faces-config.xml" and can be used in an JSF application. For example you can define a Java object "Person". Once you define the object in faces-config.xml you can use the attributes of Person in your JSF UI components, e.g. by binding the value "firstName" of this object to an JSF input field.

JSF uses the Unified Expression Language (EL) to bind UI components to object attributes or methods.

JSF is based on the following configuration files:

  • web.xml - General web application configuration file

You must specify in web.xml that a "FacesServlet" is responsible for handling JSF applications. "FacesServlet" is the central controller for the JSF application. "FacesServlet" receives all requests for the JSF application and initializes the JSF components before the JSP is displayed.

  • faces-config.xml - Contains the configuration of the JSF application.

"faces-config.xml" allows to configure the application, managed beans, convertors, validators, and navigation.

  • Model

This is the model class that returns the celsius or fahrenheit temperature.

package jsf.first.model;
public class TemperatureConvertor {
 private double celsius; 
 private double fahrenheit;
 private boolean initial= true; 
 
public double getCelsius() {
 return celsius;
 }
public void setCelsius(double celsius) {
 this.celsius = celsius;
 }
public double getFahrenheit() {
 return fahrenheit;
 }
 
public boolean getInitial(){
 return initial;
 }
 
public String reset (){
 initial = true;
  fahrenheit =0;
  celsius = 0; 
  return "reset";
}
public String celsiusToFahrenheit(){
 initial = false; 
 fahrenheit = (celsius *9 / 5) +32;
 return "calculated";
} 
} 
  • View

This JSP page is the view for the application and allows the user to get the celsius or fahrenheit temperature.

Convertor.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="f"  uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h"  uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Celsius to Fahrenheit Convertor</title>
</head>
<body>
<f:view>
 <h:form>
  <h:panelGrid columns="2">
   <h:outputLabel value="Celsius"></h:outputLabel>
   <h:inputText  value="#{temperatureConvertor.celsius}"></h:inputText>
  </h:panelGrid>
   <h:commandButton action="#{temperatureConvertor.celsiusToFahrenheit}" value="Calculate"></h:commandButton>
   <h:commandButton action="#{temperatureConvertor.reset}" value="Reset"></h:commandButton>
   <h:messages layout="table"></h:messages>
 </h:form>
 <h:panelGroup rendered="#{temperatureConvertor.initial!=true}">
 <h:outputLabel value="Fahrenheit "></h:outputLabel>
 <h:outputLabel value="#{temperatureConvertor.fahrenheit}"></h:outputLabel>
 </h:panelGroup>
</f:view>
</body>
</html>

Conclusion

The startup costs for MVC architectures can be high. Newcomers to the Java-based MVC will initially face the challenge of assembling a compatible set of tag and other libraries needed for the current versions of servlet and JSP technologies. There are also subtle but important differences in the syntax used in configuration files and tags that occur with each version of servlets, JSPs, and tag libraries. Once these are understood, development using MVC requires writing the controller or setting up controller configuration files in Struts or JSF.

If you create a customized (non-Struts or JSF) MVC environment, you must train your developers in the nuances of your environment. An advantage to using Struts or JSF over a custom MVC environment is that you can hire programmers with prior experience in these technologies. (Other MVC frameworks exist beyond Struts and JSF, including Ruby on Rails or Tapestry. However, the issues involved with any pre-built MVC framework, are similar to those identified for Struts and JSF.)

After the startup costs of learning how to configure, program, and design with a selected MVC framework are realized, development time in an MVC versus a non-MVC environment is likely to be similar for small projects. For larger projects, we anticipate MVC will be faster because the application will be more loosely coupled, have higher cohesion, and minimize intra and inter-crosscutting. We believe a large MVC site will be more easily maintained and modified over time than a large site developed using non-MVC approaches.

Advantages of MVC pattern

  • You can distribute development effort to some extent, so that implementation changes in one part of the Web application do not require changes to another. The developers responsible for writing the business logic can work independently of the developers responsible for the flow of control, and Web-page designers can work independently of the developers.
  • You can more easily migrate legacy programs, because the view is separate from the model and the control and can be tailored to platform and user category.
  • Isolation of business logic from the user interface
  • Ease of keeping code DRY
  • Making it clear where different types of code belong for easier maintenance
  • Since MVC separates the application into the model, view and controller components, it increases the maintainability of the application
  • Testing is easier since the components are independent.
  • Multiple views can reuse the same model objects, thus facilitating code reusability.
  • MVC architecture helps in developing loosely coupled systems
  • The modularity of MVC enables easier changes to the user interface.

Disadvantages of MVC pattern

  • Using MVC initially can feel a bit restrictive.
  • MVC pattern introduces new levels of indirection and therefore increases the complexity of the solution.
  • It also increases the event-driven nature of the user-interface code, which can become more difficult to debug.
  • Developers cannot completely ignore the view of the model even if they are decoupled. If the model undergoes frequent changes, the views could be flooded with update requests.Views like graphical displays may take some time to render. As a result, the view may fall behind update requests as frequent updates may increase the cost significantly.

References

<references/> 1. http://heim.ifi.uio.no/~trygver/themes/mvc/mvc-index.html

2. Web Application Frameworks

3. Model-View-Controller(MVC)

4. Ruby on Rails

5. MVC: "Introduction and History"

6. Struts framework

7. http://www.careerride.com/MVC-disadvantages.aspx

8. http://en.wikipedia.org/wiki/Ruby_on_Rails

9. http://en.wikipedia.org/wiki/Spring_Framework

10. Spring framework

11. Java Server Faces(JSF)

12. http://www.oracle.com/technetwork/articles/javase/index-142890.html

13. GuangChun, L., WangYanhua, Xianliang, L, and Hanhong. A Novel Web Application Frame Developed by MVC. Software Engineering Notes. 2003, Vol. 28, 2.

14. Leff, A. and Rayfield, J.T. Web-Application Development Using the Model/View/Controller Design Pattern. IEEE XPlore. 2001.

15. Sauter, P., Vogler, G., Specht, G., and Flor, T. A Model-View-Controller extension for pervasive multi-client user interfaces. Pers Ubiquit Comput. October, 2004.

16. openMVC: A Non-proprietary Component-based Framework for Web Applications. Barrett, R. and Delany, S.J. New York : ACM, WWW 2004.

17. A Database and Web Application Based on MVC Architecture. Selfa, D.M., Carrillo, M., and Rocio Boone, M. Puebla, Mexico : IEEE, IEEE Int. Conf. on Electronics, Communications, and Computers (CONIELECOMP 2006).