13.07.2015 Views

The MVC-Web Design Pattern - Ralph F. Grove, Jr. - James Madison ...

The MVC-Web Design Pattern - Ralph F. Grove, Jr. - James Madison ...

The MVC-Web Design Pattern - Ralph F. Grove, Jr. - James Madison ...

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

model and then the view may query the model toobtain information that it needs to present. <strong>The</strong>controller component responds to user actions viathe user interface. It is responsible for passingtransactions to the model for execution. Controllersexist in a one-to-one correspondence with views.<strong>The</strong> hierarchy of views is therefore also replicatedamong the corresponding controllers. When acontroller receives input, it yields to its activesubcontrollers first, so that input is processed at thelowest levels of the controller hierarchy first.User input and output devices form an implicitfourth component of the <strong>MVC</strong> pattern. <strong>The</strong>Smalltalk system was based on a graphical displayand standard user input devices, primarily akeyboard and mouse. User menus were alsoconsidered to be a type of virtual device thattransmitted input to the controller hierarchy just asthe keyboard or mouse did. Though menus wereimplemented in the GUI, they were not consideredas view components.<strong>The</strong> primary benefit of the <strong>MVC</strong> design patternis separation of concerns and the resultingmodularity. <strong>The</strong> design isolates user interfacepresentation from user input handling, and isolatesboth of these from application state and transactionprocessing. This makes it possible to modify orreplace one component without needing to modify oreven understand the others. It also facilitatesextensibility by making it possible to add aview/controller pair for a new interface medium, orto add new functionality to the model independentlyof the other components.3 <strong>MVC</strong> IN WEB FRAMEWORKSASP .Net <strong>MVC</strong> 2 is the latest version of theMicrosoft web development framework (Esposito,2010). It adds the <strong>MVC</strong> design architecture to earlierversions of ASP .Net based on <strong>Web</strong> Forms. <strong>The</strong>ASP .Net <strong>MVC</strong> 2 framework uses a single handlerfor HTTP requests that determines and instantiatesan appropriate controller for each request.Controllers are responsible for handling incomingrequests, orchestrating transaction processing by themodel, preparing data for the subsequent viewelement, and activating that view element togenerate the response. A controller class can includemultiple actions that respond to different types ofrequests, each action being a unique public methodof the class. Views are defined in ASP files, whichare HTML templates with server-side scripts thatcan generate dynamic content. Each view receivesinformation from the controller that activated it,either as native objects or as view-model objects,which are unique compilations of data from themodel, each designed for a specific view. <strong>The</strong> modelcomponent is intended to contain application logicand database access. A differentiation is madebetween view models, which are data structuresintended to convey information to a specific viewelement, and application models, which are domainentities and related transactions that operate onthem. <strong>The</strong> model component also provides objectrelationalmapping, which hides the details of howapplication domain objects are mapped to databasetables.Rails is a web application framework developedfor use with the Ruby programming languages(Thomas and Hansson, 2007). HTTP requests arehandled in Rails through a central router that directsrequests to the appropriate ActionController classand method within the controller component.ActionController objects are responsible for filteringrequest parameters, for orchestrating transactions byinvoking methods of appropriate model elements,and for arranging the appropriate view response.ActionControllers also arrange for view elements tohave access to data from the model. <strong>The</strong> controllerelements are also responsible for web sessionmanagement, including cookie management. <strong>The</strong>user interface (view component) is presentedthrough dynamic document templates that arestandard HTML documents with embedded Rubyscripts, similar to ASP, PHP, JSP, etc. Viewelements can access the model component asnecessary to obtain data for presentation. <strong>The</strong> Railsmodel component includes elements that encapsulateapplication logic and transaction processing(ActiveModel), and an object relational mappingscheme (ActiveRecord) that associates each databasetable with a model element. <strong>The</strong> model also includesActiveResource elements that provide access toexternal resources.<strong>The</strong> Apache Struts 2 framework is based on Java2 Enterprise Edition (J2EE) and Java Server Pages(JSP) technology. Struts2 view components are JSPdocuments with embedded tags that provide avariety of functionality, including flow of control(iteration, conditionals), access to Java Beans(model components), and streamlined HTML Formsconstruction. Controller components of a Struts2web application are embodied in actions, which are


Java classes. An action can respond to user inputfrom one or more JSPs. <strong>The</strong> primary responsibilitiesof each action are to validate user input and toorchestrate transaction processing by invokingappropriate model operations. Actions are definedand configured through an XML configuration fileor through the Java annotation mechanism. Thisconfiguration information also controls the flow of aweb application by determining what view followseach action, depending upon the outcome of theaction. A central part of Struts2 is the Value Stack,where information flowing between view andcontroller is stored and converted as needed. Thiseliminates much of the detail involved in handlingHTTP request parameters and in providinginformation for JSPs to display.All three of these web frameworks are consistentwith the <strong>MVC</strong> pattern in that user interfacecomponents (View) are separated from applicationlogic (Model) and control functions (Controller).<strong>The</strong>y differ from the original <strong>MVC</strong> pattern in severalrespects, however. No inherent view->model dependency(Observer pattern): <strong>The</strong> model component inweb applications does not notify viewelements of changes to the model. Rather, thecontroller determines view behavior,depending on the outcome of modeltransaction processing. No 1-1 view-controller correspondence: In theoriginal <strong>MVC</strong>, each view element has aunique controller element that is defined forthat view element alone. <strong>The</strong> Front Controller pattern: All threeframeworks use this pattern, in which a singlecontroller element is responsible for routingincoming HTTP requests, based upon therequested URL and configuration data. <strong>The</strong> controller specifies view dynamics: <strong>The</strong>controller decides which view follows eachcontroller action, based upon the actionoutcome. This amounts to what is essentially aview=>controller dependency. Controller elements are responsible for datavalidation: Transaction parameter validation isessentially a model function. Validation logiccan be pushed into the model component, butthe responsibility for executing the validationfunction is still with the controller. <strong>The</strong> model is not clearly defined: All of theframeworks lack a clear definition of theModel component. It is assumed to involveapplication logic and data management, butthere is no clear structure to define the modelor to cleanly separate it from the controller.Model classes are instantiated on demand:Rather than a persistent model component asenvisioned in the original <strong>MVC</strong>, the webframeworks instantiate model objects asneeded to handle transactions and toencapsulate domain entities. <strong>The</strong> database ordata persistence layer of the application can bea persistent model component, however.<strong>The</strong>se changes to the <strong>MVC</strong> pattern reflect thefundamental nature of the client-serverarchitectural style underlying the <strong>Web</strong>. <strong>The</strong> viewplatform (client) is physically separated from theother components, and so the view componenthas become less closely tied to the controller andmodel in structure and operation. At the sametime, the view has taken on some of the modelresponsibility in order to provide a moreresponsive user interface. <strong>The</strong> addedresponsibility of the controller (front controllerfunctions and view sequencing) are necessarybecause of the need to explicitly manage theflow of control inherent in the user experience.4 <strong>MVC</strong>-WEB DESIGN PATTERN<strong>The</strong> <strong>MVC</strong>-<strong>Web</strong> design pattern described in thissection is a model for how the <strong>MVC</strong> pattern is nowbeing interpreted in web application frameworks.<strong>MVC</strong>-<strong>Web</strong> reflects the evolutionary changes thathave occurred in the <strong>MVC</strong> design pattern as it hasbeen implemented in web frameworks.<strong>The</strong> <strong>MVC</strong>-<strong>Web</strong> model component is generallyresponsible for maintaining the application state. Itsresponsibilities include: Data persistence: maintain a database or anabstract database interface Transaction processing: execute applicationlogic that operates on the application state External interface: manage interactions withexternal agents, such as web services orlegacy systems Query handling: provide information to viewand controller elements in response toqueries.<strong>The</strong> <strong>MVC</strong>-<strong>Web</strong> view component presents a userinterface, including data presentation and inputdevices. Its responsibilities include:


Information retrieval and display: presentinformation to the user; query the model asnecessary to obtain information to bedisplayedUser input: present input forms and controlsthat allow the user to interact with theapplicationClient-side dynamic behavior: provide aninteractive client-side experience for the user(using JavaScript, Ajax, or other means); Thismay include input completion, inputvalidation or other implementations ofapplication-specific rules or functions that areotherwise a responsibility of the modelcomponent.<strong>The</strong> <strong>MVC</strong>-<strong>Web</strong> controller component has threeprimary responsibilities. Front controller: receive incoming requestsand route them to the appropriate handler Action handlers: receive request parameters;validate request parameter syntax (this mayrepeat validation done by view elements);orchestrate request handling by invokingappropriate model elements Control flow: invoke the appropriate viewelement as a response to the request beingprocessed, depending upon the outcome ofthe action invoked.Components of the <strong>MVC</strong>-<strong>Web</strong> pattern interact inthe following ways. Model-view: View elements may query themodel to obtain information to be displayedto the user Model-controller: Controller action elementscall on model elements to carry out requestedtransactions. Model functions can includeexecuting application logic, updating thedatabase, or invoking services of externalagents. Controller elements may request datafrom the model to be passed to viewelements. Controller-view: Controller elements respondto requests originating with view elements.<strong>The</strong> controller also determines which viewelement will be presented to the user inresponse to a request. Controller elementsmay prepare information for use by viewelements.This version of <strong>MVC</strong> differs from the original(Smalltalk) version in several important ways:<strong>The</strong> Observer pattern is not used to inform theview and controller of model updates. <strong>The</strong>controller has a more prominent role insteadin propagating updates.<strong>The</strong>re is no 1-1 correspondence between viewand controller elements. <strong>The</strong> relationship ismany-many instead.<strong>The</strong> controller must be able to route requestsfrom multiple view elements (FrontController pattern) and to manage the flow ofthe application in response. <strong>The</strong> controllermay pass information from model to view aspart of this function.Some application logic (e.g., for validation orcompletion of input data) can be present inthe view and controller components. Thismuddies the separation of concerns, butimproves efficiency of the application byproviding faster response to users.This <strong>MVC</strong>-<strong>Web</strong> pattern is intended to reflect thecurrent implementation of <strong>MVC</strong> in web applicationframeworks. <strong>The</strong> pattern is not necessarily stable,however. Evolution of the <strong>MVC</strong>-<strong>Web</strong> patterncontinues, for example in Ajax-based user interfacesthat are becoming richer and more responsive. Suchchanges may further cloud the boundaries between<strong>MVC</strong>-<strong>Web</strong> components and reduce the degree ofmodularity that the pattern provides.REFERENCESBarrett, R., Delany, S., 2004, open<strong>MVC</strong>: A NonproprietaryComponent-based Framework for <strong>Web</strong>Applications, WWW2004.Chun, L., Yanhua, W., Hanhong, L., 2003, A Novel <strong>Web</strong>Application Frame Developed by <strong>MVC</strong>, SoftwareEngineering Notes, 28(2).Esposito, D., 2010. Programming Microsoft ASP.NET<strong>MVC</strong>, Microsoft Press.Fowler, M., 2003. <strong>Pattern</strong>s of Enterprise ApplicationArchitecture, Addison-Wesley, Boston.Gamma, E., Helm, R., Johnson, R., Vlissides, J.,1995.<strong>Design</strong> <strong>Pattern</strong>s, Addison Wesley, Reading, MA.Goldberg, A., Robson, D., 1985. Smalltalk-80 : thelanguage and its implementation, Addison-Wesley.Krasner, G.E., Pope, S.T., 1988. A Cookbook for Usingthe Model-View Controller User Interface Paradigm inSmalltalk-80. Journal of Object-OrientedProgramming, 1(3), 26-49.Mahmoud, Q., 2003. Servlets and JSP Pages BestPractices, http://www.oracle.com/technetwork/articles/javase/servlets-jsp-140445.html.Thomas, D., Hansson, D.H., 2007. Agile <strong>Web</strong>Development with Rails. <strong>The</strong> Pragmatic Bookshelf.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!