CSC/ECE 517 Fall 2012/ch1 1w20 pp

From Expertiza_Wiki
Jump to navigation Jump to search

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.

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

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 (EJB), 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 ActionFormbeans. 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.

Advantages and disadvantages of MVC pattern

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.

Examples

Spring framework

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

  • Model classes

‎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;
 }
 }

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;
 }
}

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

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

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)

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.


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
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

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>

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)