MVC as usual!

I have three windows that show details of a customer (object),
such as the customer's name, phone number and address details.
The windows (view classes) communicates with a controller that modifies the customer object.
All the three windows (view classes) communicates with the same static controller.
Now, if the controller modifies a customer's object , I want all the three windows
to be updated.
That is, if I change to the next window I want to see the newly update customer
details there too.
I know there are many ways, including cheap ways.
But I want to know the correct way of doing so.
I have checked java's event model.
The EventObject and the EventListener.
In this case the textfield of each window must be the listeners for the controller,
and the conroller as an EventObject, which to me sound strange.
Because JTextField's are already event objects themselves, and my solution is the opposite way added additionaly.
That means, the JTextField would be a EventListener and an EventObject.
(Of course I have to subclass JTextField in order to implement this).
Unfortunately I have not provided my code , because it is all too big and
will just be confusing.
The principal idea is what I wish to know!
Now what could your solution be to this, surely this is a very common thing,
hope you can help!
Thanks!

You might want to take a look at Observer pattern and StateListener and related classes from Swing. Register your Views as Observers (Listeners) for your Model and notify listeners as Model gets updated.
Denis Krukovsky
http://dotuseful.sourceforge.net/

Similar Messages

  • Custom Tag and CFC : Nate Weiss

    Hi,
    being a beginner I'm trying with some marginal degree of
    success to understand CFC's and Custome Tags.
    In the CFMX7 W.A.C.K. There is an example shopping cart. This
    start off as a basic affair then expands into more object based
    principles using a custom tag add products to the cart
    (ShoppingCart.cfc) and later on the same page uses a custome Tag to
    display the cart items, calling it once for each item to display.
    I am using the MVC structure under Fusebox 4, so this method
    of using the same template, (reloading etc) is alien to me as with
    MVC you usually have the data type intructions in different files
    (anyway, I digress)
    Now that I have the thing adding products and generally
    working with my "shop", I thought about having a "special offer"
    facility. With these "Hot Deals" being stored in another database
    table, with their productID and new price.
    However, obviously the shopping cart needs to be made aware
    of this. With I would have thought an extra variable in the array
    telling the custom tag to retrieve the special price and the
    product information using a diufferent inner join query to normal.
    I have attemtped this by adding an additional URL parameter
    thus /..../HSOP/Y ("Has Special Offer Price" being set to "Y")
    When this reloads the page the CFC invoke is set thus
    <CFIF IsDefined("URL.HSOP") AND #URL.HSOP# EQ "Y">
    <CFINVOKE
    COMPONENT="#SESSION.MyShoppingCart#"
    METHOD="Add"
    MERCHID="#URL.AddMerchID#"
    SOPH="Y">
    <cfelse>
    This successfully passes
    Add(SOPH = Y, MERCHID = xxxx)
    to the CFC. However I get this error......,
    ..................Element SOPH is undefined in ARGUMENTS.
    the CFC simpley isnt adding the new variable to the array...
    I think... it wont do a CFDump so there is no way of telling
    <CFFUNCTION
    NAME="Add"
    HINT="Adds an item to the shopping cart">
    <!--- Three Arguments: MerchID, Quantity and SOPH (flag
    to state if there is a special price) --->
    <CFARGUMENT NAME="MerchID" TYPE="numeric"
    REQUIRED="Yes">
    <CFARGUMENT NAME="Quantity" TYPE="numeric" REQUIRED="No"
    DEFAULT="1">
    <CFARGUMENT NAME="SOPH" type="string">
    <!--- Get structure that represents this item in cart,
    --->
    <!--- then set its quantity to the specified quantity
    --->
    <CFSET CartItem = GetCartItem(MerchID)>
    <CFSET CartItem.Quantity = CartItem.Quantity +
    Arguments.Quantity>
    <CFSET CartItem.SOPH = Arguments.SOPH>
    </CFFUNCTION>
    I cant see why this wouldn't create the variable
    "CartItem.SOPH" and set it to "Y" as passed to it.
    I notice the CFC performs an iteration of sorts to put the
    cart items into an array. But I'm afraid I cant fathom what this
    problem might be.
    Any ideas. I have attached the whole CFC code (post editing
    by me)
    MAny thanks and Happy new Year

    Hi,
    As for me, I am testing the related pdf-417 barcode scanner these days. Do you have any ideas about it? Or any good suggestion? I am totally a green hand on barcode field. Any suggestion will be appreciated. Thanks in advance.
    Best regards,
    Arron

  • MVC model in Web systems and applications

    MVC model in Web systems and applications
    Object-oriented design model is experience, MVC idea is a user interface for the original. This article discusses how the major application areas in the new Web design patterns and the use of MVC framework. The article first introduced the concept of design patterns and characteristics, and MVC architecture design concepts and analysis of the MVC framework contains several key models. Based on the characteristics of Web applications on how to use patterns and MVC framework made some design ideas.??
    1. Introduction
    1.1 design model
    Object-oriented technology and the emergence of software applications has greatly enhanced the trusted and software quality. Object-oriented programming than previous models to various programming simple and efficient, but the object-oriented design methodology than the previous design methods to complex and much more skill, a good design should be both on the issue of gender, but also to take full account of the problems and needs sufficient interoperability. In the past 10 years, people in the object-oriented technology and the practical application of research to explore certain issues in relation to the creation of a number of good solutions, the so-called object-oriented design patterns. Object-oriented technology is one of the purposes of enhancing the software trusted, and to design model, design programmes in important positions from a deeper sense of meaning and essence embodies trusted. There are many people in the design model definition, which cited Christopher Alexander is the largest design model definition : Each design model is a tripartite rule, which expresses a contextual environment (Context), a problem and a solution. Design models generally following basic elements : model name, the purpose solution effect 1995-1998 code and related design models. There are several classifications design patterns can be divided into a model based on the purpose (Creational), structural type (Structural) and the type of behaviour (Behavioral) three. It is mainly used in the creation of a model-based object model-based structure to deal primarily with the category or combination of objects, used to describe behavior-based model is the main target for the category or how stress and how to allocate responsibilities. Design patterns can be divided into categories based on the scope and target mode model type model dealing with the relationship between the categories and sub-categories, these relations through the establishment of succession in Translation moment to be finalized, are static. Model is targeted at addressing the relationship between the moment of change these relations in the operation, more dynamic. Model features : through the experience acquired in a structured format to write down, avoid encountering the same problems on the first design, exist in different abstract level, in continuous improvement, can be trusted artificial product for the design and best practice in the world to be combined to address larger issues.
    1.2 MVC framework
    MVC was first used in a user interface Smalltalk-80 China. M representative models Model, representatives maps View V, C representatives controller Controller. MVC trusted code with the aim of increasing the rate of data reduction expressed, the data describing the operation and application coupled degrees. Also makes software Keweihuxing, restorative, expansionary, flexibility and packaging of greatly enhanced. Single-user applications are usually incident-driven user interface to the organizational structure. Staff development tool with an interface painting of a user interface interface code based on user input and then prepare to implement the corresponding moves, many interactive development environment encouraged to do so, because it emphasizes first and then a functional interface. Some software design model is the strategy that will be fixed before the code into the regular system of the final. Result is that the procedures and organizations around the user interface elements in the user interface elements of those moves, data storage, applications and functions of the code is used to indicate the way intertwined. In single-user system code structure can be so, because the system will not demand frequent changes. But for a large system such as large Web systems, or e-commerce systems to be applied. Model by incorporating data from a variety of access and control data can be separated to improve distributed system design. MVC design pattern is composed of three parts. Model is the application object, no user interface. Type in the screen showing that it represents the flow of data users. Controller user interface definition response to user input, the users responsible for the action against the Model into operation. Model View data updated to reflect the adoption of data changes.
    2. MVC design pattern,
    An MVC framework for the design of the system includes many models, but with MVC is most closely related to the following three models : Observer, Cambridge and Strategy.
    2.1 Observer models
    MVC through the use of purchase / notification form and the separation of the Model View. View to ensure that their content accurately reflected Model and state. Once Model content changes, there must be a mechanism to allow notification to the relevant Model View, View can be made relevant at the appropriate time updating of data. This design is also more general problems can be solved, the target separation, making a change to the target audience affect others, which targets those who do not know the details of the object being affected. This is described as Observer in the design model. Model type : Observer model is the object-oriented model, it is behaviour-based model. Model purposes : definition of hierarchical dependence relations between objects, or when a target value of the state change, all its dependent relationship with the object are notified and automatically updated. There are a variety of data may show a way, in different ways and may also show. When a way through a changed data, then the other should be able to show immediately that the data change and do accordingly.
    Effect :
    1. Abstract coupling. I only know that it has a target audience of some observers, the observers met each abstract Observer category simple interface, does not know their specific affiliation categories. This makes the coupling between goals and observers smallest and abstract.
    2. Support radio communications. Needless to notify designated observers goals, how to deal with the observer informed decisions.
    3. Possible accidents updated. We update logic, avoiding mistakes updated.
    2.2 Faculty model
    MVC is an important feature of View can nest. Nest can be used for any type of combination of local maps available, but also management of type nest. This thinking reflects the type and mix of components will be equal treatment design. This object-oriented design ideas in the area of Cambridge has been described as a design model. Model types : Cambridge model is the object-oriented model, it is also the structure type model. Model purpose : to target portfolio into tree structures to express "part-whole" level structure. Prepared for the use and combination of individual target audiences with the use of consistency.
    Effect :
    1. Definition of a target portfolio includes simple objects and the structure of the category level. Simple objects may be complex combinations of objects, and can be targeted portfolio mix. This customer-code used in the target areas can use simple combinations target.
    2. Simplify customer-code. Needless to know their customers - a mix of target audiences is a simple target or can use these items in a consistent manner.
    3. Easier to add new types of components. New components can easily be changed to a combination of customer-targeted codes.
    2.3 Strategy model
    Another important characteristic is the MVC can not change the View of changes View response to user input. This often requires a change in response to the logic of the system is very important. MVC to respond to the logic involved in the Controller. Controller of a category level structure could easily change to the original Controller appropriate, a new Controller. View Controller son used to achieve a specific example of such a response strategy. To achieve different response strategy, as long as examples of the use of different types of replacement will Controller. Also in the running time by changing the View Controller for users to change View of response strategies. This View-Controller relationship was described as an example of Strategy design pattern. Model types : Strategy model is the object-oriented model, it is behaviour-based model. Model purposes : definition of a series of algorithms, and their packaging, and ensure that they can replace each other, making algorithms can independently use its customer-change.
    Effect :
    1. Strategy category levels for Context definition of the relevant algorithms can be trusted or behaviour.
    2. Alternative methods of succession. If the direct successor Context, with different acts will be added Context act, the realization of which would algorithm mixed up with Context, Context hard to preserve and expand, but can not dynamically changing algorithms. Will be enclosed in a separate Strategy category algorithms to enable algorithm independent Context change easily cut over expansion.
    3. Can provide the same acts different date.
    4. Strategy-must understand what customers between different.
    5. Context and Strategy communications between costs.
    6. An increase in the number of targets.
    3. MVC in Web application system
    Now some of the distributed systems such as Web-based B2B e-commerce system, suitable for use MVC framework. Through analysis from the perspective of high-level applications can be a target divided into three categories. Category is shown for the target audience consists of a group of commercial rules and data, there is a category that is receiving requests to control commercial target to complete the request. These applications often need to change is shown, such as web style, color, but also need to demonstrate the contents of the display. And the business rules and data to be relatively stable. Therefore, said that the frequent need to change the View objects that the business rules and data model to be relatively stable target, and that the control of the Controller is the most stable. When the system is usually issued after the View objects by artists, designers or HTML/JSP system managers to manage. Controller target applications development personnel from the development and implementation of rules for commercial and business development personnel from the target data, database managers and experts in the field of common completed. Show in Web?? or customers - control logic can be Servlet or JSP, dynamically generated Html. Generally used Servlet better than using JSP. JSP will be better with the Html code of separate codes for page designers and developers of separation efficiency. Servlet and JSP can complete all complete functions, actually JSP eventually converted into a Servlet. And control of the target system exists in every level, the coordination of cross-layer moves. Contain business rules and data objects exist in the EJB layer (EJB-centred model) or Web?? (Web-centred model).
    3.1 View in the Web application system
    View of the system shows that it fully exist in Web??. General by JSP, Java Bean and Custom Tag. JSP can generate dynamic web content using Java Custom Tag easier Bean, but it can show the logic of packaging, and more conducive to modular trusted. Some well-designed in a number of JSP Custom Tag can even be used in different system duplication. Model for control of JSP and Java Bean objects. JSP through Java Bean objects to retrieve the data model, the Model and Controller object is responsible for updating the data on Java Bean. In general, can we devise all possible screen that users can see all the elements of the system. Based on these elements, to identify the public part of passive components and dynamics. Can consider the use of templates means to separate the content generated JSP public, also need to change their generation Html or JSP from a JSP templates to dynamically introduce these different parts (include methods). Another issue to consider is screen option, when dealing with End users request template automatically available to show that the concern that users must know what is the screen components. So can consider all screens on the definition of a centralized document, such as a document or text document java. Taking into account the possibility of changes in future document definition screens, the best use of text documents such as a XML document, so future changes to the recompilation. According to the URL and user input parameters to shine upon the results of a screen, of course, likely to be made on the basis of the outcome of the implementation of actions to choose different results screen. Therefore, the need for a request for matching resources with document (XML), if a URL request several different results, it must specify in the document need to control the flow (a controller object), as well as the corresponding screen different flows.
    3.2 Model in the Web application system
    Model objects represent business rules and business data exist in EJB layer and Web??. In J2EE norms, the system needs some data stored in the database, such as user account information (account model), the company's data (company model), some not recorded in the database. If a user browsing the current catalogue (catalog model), the contents of his shopping (shopping cart model). Which one of these models exist in the data according to their life cycle and scope to decide. In Web?? a HttpSession and ServletContext and Java Bean objects to store data in the EJB layer is a data storage and logic EJB to. Web?? the Java Bean objects stored in the model layer model of the EJB object data copy. Because there are many different EJB tier model targets, so Web?? through a ModelManager to control the EJB layer object model in ModelManger background model can be used for packaging methods. In the EJB layer and the rules have all the data into EJB model is inappropriate. If the database can visit the Dao object model into objects. Dao can be encapsulated and the specific details of the database in the world, if we can write a different table, a number of databases, or even multiple databases. If the orders can be a model for OrderDAO, it may have to deal with Order table, table and OrderItemLines OrderStatus table. Value can also consider the use of targets. Value can be a target of securing long-range targets, because every time the remote object attributes could be a long-range redeployment process will consume network resources. EJB objects in the distance can be used instead target. In the distance, one-time items to be targeted instead of the value of all attributes.
    3.3 Controller in Web application system
    Coordination with the Model View Controller object to the request of users into the system to identify incidents. In Web?? generally a MainServlet (or Main.jsp), and receiving all requests, it can use screen flow management devices (ScreenFlowManger) decided next screen. There is a general request processors RequestProcessor contains all requests are needed to be done to deal with logic, such as the request translated into system events (RequestToEvent). Acting processors usually also includes a request for ClientControlWebImpl, it is logical to deal with the EJB layer in Web?? Acting. In EJB layer, a layer for EJB tier Web ClientController provide the CD visit. Another StateMachine used to create and delete ejb handle Web?? sent to the incident. Controller Another important function is synchronous View and Model data. ModelManger contained in a ModelUpdateManger, it puts events into a Model System assembly that all the needs of synchronous Model, and then notify Listeners do synchronous operation.
    4. Concluding remarks
    In recent years, with the Internet technology development and the emergence of new business models, the Web is based on a large number of applications. On how to design these systems architecture, and gradually there has been some convergence of opinion, the most important point is that its structure should be rational in the open. Demand than ever faster development of technology and design concepts, systems for the future, the cost of upgrading the smallest, research software systems architecture still very useful and necessary.

    Bravo. And your point is?

  • Can anyone solve this simple MVC problem with ArrayCollection

    I have very simple application trying to understand how to apply MVC without any framework. There are quite a few exemples on the net but most do not deal with complex data.
    here is my application with 4 files: MVCtest.mxml, MyController.as, MyModel.as and MyComponent.as
    first the Model MyModel.as
    package model
    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.events.IEventDispatcher;
    import mx.collections.ArrayCollection;
    [Event(name="ArrayColChanged", type="flash.events.Event")]
    [Bindable]
    public class MyModel extends EventDispatcher
      private static var instance:MyModel;
      public static const ARRAYCOL_CHANGED:String = "ArrayColChanged";
      private var _myArrayCol:ArrayCollection;
      public function MyModel(target:IEventDispatcher=null)
       super(target);
       instance = this;
      public static function getInstance():MyModel
       if(instance == null)
        instance = new MyModel();
       return instance;
      public function get myArrayCol():ArrayCollection
       return _myArrayCol;
      public function set myArrayCol(value:ArrayCollection):void
       _myArrayCol = new ArrayCollection(value.source);
       dispatchEvent(new Event(ARRAYCOL_CHANGED));
    then the controller: MyController.as
    package controller
    import components.MyComponent;
    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.events.IEventDispatcher;
    import model.MyModel;
    import mx.collections.ArrayCollection;
    import mx.controls.Alert;
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.rpc.remoting.RemoteObject;
    public class MyController extends EventDispatcher
      [Bindable]
      public var view:MVCtest;
      [Bindable]
      public var componentView:MyComponent;
      private var _model:MyModel = MyModel.getInstance();
      public function MyController(target:IEventDispatcher=null)
       super(target);
       _model.addEventListener("ArrayColChanged", onArrayColChange);
      public function initialise(event:Event):void
       getData();
      public function getData():void
       var dataRO:RemoteObject = new RemoteObject;
       dataRO.endpoint = "gateway.php";
       dataRO.source = "MytestdbService";
       dataRO.destination = "MytestdbService";
       dataRO.addEventListener(ResultEvent.RESULT, dataROResultHandler);
       dataRO.addEventListener(FaultEvent.FAULT, dataROFaultHandler);
       dataRO.getAllMytestdb();   
      public function dataROResultHandler(event:ResultEvent):void
       _model.myArrayCol = new ArrayCollection((event.result).source);
      public function dataROFaultHandler(event:FaultEvent):void
       Alert.show(event.fault.toString());
      public function onArrayColChange(event:Event):void
       componentView.myDataGrid.dataProvider = _model.myArrayCol;
    This is the main application: MVCtest.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
          xmlns:s="library://ns.adobe.com/flex/spark"
          xmlns:mx="library://ns.adobe.com/flex/mx"
          xmlns:controller="controller.*"
          xmlns:components="components.*"
          width="600" height="600"
          creationComplete="control.initialise(event)">
    <fx:Declarations>
      <controller:MyController id="control" view = "{this}"/>
    </fx:Declarations>
    <fx:Script>
      <![CDATA[
       import model.MyModel;
       import valueObjects.MyVOorDTO;
       [Bindable]
       private var _model:MyModel = MyModel.getInstance();
      ]]>
    </fx:Script>
    <s:VGroup paddingTop="10" paddingLeft="10" paddingRight="10" paddingBottom="10">
      <s:Label fontSize="20" fontWeight="bold" text="MVC Test with components"
         verticalAlign="middle"/>
      <components:MyComponent/>
    </s:VGroup>
    </s:Application>
    And this is the component: MyComponent.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
       xmlns:s="library://ns.adobe.com/flex/spark"
       xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300">
    <s:layout>
      <s:VerticalLayout paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10"/>
    </s:layout>
    <fx:Declarations>
      <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Label fontSize="16" fontWeight="bold" text="My Component " verticalAlign="bottom"/>
    <s:DataGrid id="myDataGrid" width="100%" height="100%" requestedRowCount="4">
      <s:columns>
       <s:ArrayList>
        <s:GridColumn dataField="mystring" headerText="String"></s:GridColumn>
        <s:GridColumn dataField="myinteger" headerText="Integer"></s:GridColumn>
        <s:GridColumn dataField="myreal" headerText="Real"></s:GridColumn>
        <s:GridColumn dataField="mydate" headerText="Date"></s:GridColumn>
       </s:ArrayList>
      </s:columns>
    </s:DataGrid>
    </s:Group>
    Here is the code to generate the database:
    CREATE DATABASE mytest;
    CREATE TABLE myTestDB
          myid INT UNSIGNED NOT NULL AUTO_INCREMENT,
          mystring CHAR(15) NOT NULL,
          myinteger INT NOT NULL,
          myreal DECIMAL(6,2) NOT NULL,
          mydate DATE NOT NULL,
          PRIMARY KEY(myid)
    ) ENGINE = InnoDB;
    INSERT INTO myTestDB (mystring, myinteger, myreal, mydate) VALUES ('Test', 123, 45.67, '2012-01-01'), ('Practice', 890, 12.34, '2012-02-01'), ('Assay', 567, 78.90, '2011-10-01'), ('Trial', 111, 22.22, '2009-09-09'), ('Experiment', 333, 44.44, '1999-04-15'), ('Challenge', 555, 66.66, '2012-12-21');
    And finally here is the PHP script.
    <?php
    class myVOorDTO
      var $_explicitType = "valueObjects.myVOorDTO";
      public $myid;
      public $mystring;
      public $myinteger;
      public $myreal;
      public $mydate;
      public function __construct()
        $this->myid = 0;
        $this->mystring = "";
        $this->myinteger = 0;
        $this->myreal = 0.0;
        $this->mydate = date("c");
    class MytestdbService
      var $username = "yourusername";
      var $password = "yourpassword";
      var $server = "yourserver";
      var $port = "yourport";
      var $databasename = "mytest";
      var $tablename = "mytestdb";
      var $connection;
      public function __construct()
        $this->connection = mysqli_connect(
        $this->server, $this->username, $this->password, $this->databasename, $this->port);
    * Returns all the rows from the table.
    * @return myVOorDTO
      public function getAllMytestdb()
        $query = "SELECT * from $this->tablename";
        $result = mysqli_query($this->connection, $query);
        $results = array();
        while ($obj = mysqli_fetch_assoc($result))
          $row = new myVOorDTO();
          $row->myid = $obj['myid'] + 0;
          $row->mystring = $obj['mystring'];
          $row->myinteger = $obj['myinteger'] + 0;
          $row->myreal = $obj['myreal'] + 0.0;
          $row->mydate = new Datetime($obj['mydate']);
          array_push($results, $row);
        return $results;
    ?>
    My understanding as to what is going on is: (1) on creation complete the application launch the initialise() function of the controller (2) this function starts the remoteObject which get the data (3) once the results arrive the resultHandler store the data into the ArrayCollection of the model ***this does not work*** (4) even if part 3 did not work, the setter of the ArrayCollection in the model send an event that it has been changed (5) the controller receive this event and assigns the ArrayCollection of the model as the dataprovider for the datagrid in the compoent.
    Of course, since the ArrayCollection is null, the application gives an error as the dataProvider for the datagrid is null.
    What is missing in this application to make it work properly? I believe this is an example that could help a lot of people.
    Even if I change the setter in the model to _myArrayCol = ObjectUtil.copy(value) as ArrayCollection; it still does not work.
    Also, it seems that the remoteObject does not return a typed object (i.e. myVOorDTO) but rather generic objects. I am usually able to make this works but in this particular application I have not managed to do it. Again what's missing?
    Thanks for any help with this!

    Calendar c = GregorianCalendar.getInstance();
    c.set(Calendar.YEAR,2000);
    System.out.println(c.getActualMaximum(Calendar.WEEK_OF_YEAR));
    c.set(Calendar.YEAR,2001);
    System.out.println(c.getActualMaximum(Calendar.WEEK_OF_YEAR));But it says that 2000 has 53 weeks and 2001 has 52.

  • When to use MVC in BSP??

    Hi,
    I am new to BSP. I would like to know in which cases we will go for MVC architecture and when to use Page with flow logic.
    Also, plz let me know in what areas of BSP we shuld be strong if we need to handle a real time project.
    Very soon, I may be involved in BSP project.
    Plz understand my situation and guide me.
    Thanks,
    Ravindra.

    >I would like to know in which cases we will go for MVC architecture and when to use Page with flow logic.
    There is really no reason why you wouldn't stick entirely with MVC.  Other technologies, such as WebDynpro, only allow MVC designs.  MVC really is a way of designing applications as much as it is a technology.
    I would say that 90%+ of everything that I write is MVC.  I rarely use Pages with Flow Logic.  Usually I only use pages if I am quickly building a test app to try out an idea or test a new BSP extension element.  All of my production applications are MVC! 
    But even within an App that is MVC you still mix in some flow logic pages.  I might have a frame within my application that just displays some static information (or maybe just a redirect page). If these are really simple (no event handling) or static, I might create those as pages with flow logic just to save a little time.

  • Help on getting started with Spring MVC, WebFlow; Where can it be applied ?

    I'm an individual programmer, developer and I see a huge demand (at the corporate level) for the frameworks: Spring, Spring MVC, webflow, and Hibernate. Popular today: Spring MVC, webflow, GWT.
    I've been going through the tutorials, and the technology looks awesome ! What I would like to know, is.. It's used in corporate sites, why not for smaller sites. How can I apply these frameworks in building websites ?
    I can't imaging doing any kind of serious website building without a modern CMS or Portal framework (whether in Java/php-opensource), And yes, MVC gives you the validation and authentication hooks to be used.
    The spring framework, with it's extensive scope, is a bit overwhelming, and implies that there could be a significant amount of architecture, design and planning time needed before starting implementation on a project
    All the demo's on Spring, cover some elementary, contrived example.
    If I learn these technologies (and I'm well on my way), how do I put them into practice, and in what context (no pun intented) do I use them ? I don't want to rebuild a CMS system, but I'd like to employ these frameworks effectively.

    user1944443 wrote:
    The spring framework, with it's extensive scope, is a bit overwhelming, and implies that there could be a significant amount of architecture, design and planning time needed before starting implementation on a projectYes, usually there is. Unless you're using the frameworks to build a home page for your kittens. Then you usually don't need to put that much effort into it.
    All the demo's on Spring, cover some elementary, contrived example.I'm sure you realize that they have to. There's no "follow these examples and you'll become a competent programmer" method of learning invented yet and frameworks usually need to document the basic cases extensively.
    If I learn these technologies (and I'm well on my way), how do I put them into practice, and in what context (no pun intented) do I use them ? I don't want to rebuild a CMS system, but I'd like to employ these frameworks effectively.You'll just need to come up with a project you'll be interested in finishing or at least developing for a while.
    I'm not sure whether I managed to answer your question or not, but if anything was left unclear, just ask.

  • MVC - Organizing models and managing GUI windows

    I'm having difficulty organizing my MVC models and basically controlling the whole application in general. My application works, but all the controlling logic is being dumped into the main class (Main.java). Here's a simple example of the problem I'm having:
    Objectives
    1) Display a list of Companies; i.e. Sun, Microsoft, Adobe, etc. (JFrame with a JList)
    2) The user select a Company and it pops up a new dialog with a list of Employees. (JDialog with a JList)
    Here are the classes I came up with:
    Models:
    1) CompanyListModel
    2) EmployeeListModel
    Listeners:
    1) CompanyListener
    Views:
    1) CompanyListFrame
    2) EmployeeListDialog
    Domain Objects:
    1) Company
    2) Employee
    And then there's the main application class. To implement the above objective, I've been using my main class to control the GUI.
    Here's an example of how I've implemented it.
    public class Main implements CompanyListener {
        /** Creates a new instance of Main */
        public Main() {
            CompanyListModel companyModel = new CompanyListModel();
            companyModel.addCompanyListener(this);
            CompanyListFrame gui = new CompanyListFrame(companyModel);
        // A company was selected.  Open a new dialog and display the employees
        public void companySelected(CompanyModel companyModel) {
            Company company = companyModel.getCompany();
            EmployeeListModel employeeModel = new EmployeeListModel(company));
            EmployeeListDialog = new EmployeeListDialog(employeeModel);
        public static void main(String[] args) {
            new Main();
    }My program is similiar design wise to the above, but contains many more classes. I'm still using my main class to control GUI logic (popping up new windows and creating models, etc). Thus, my main class implements like 5 different listeners. I'm sure this is a really poor design choice, I just don't know how else to implement it.
    I should not nest models... correct? I was thinking about nesting the models, i.e. CompanyListModel contains an EmployeeListModel, but then the CompanyListModel will need to spawn the EmployeeListDialog when a Company is selected, right? Thus, I'd be mixing the view with the model.
    Please provide some advice! :( Thanks!

    I'm sorry, I read your reply about 3 times and I've
    spent the last 20 minutes trying to implement it.
    I'm just not sure how the controllers are involved.
    Could you possibly provide source code for the
    controllers (and any part of the models / views that
    communicate with the controller)?No source code. Read about the MVC pattern.
    I feel like this is a wasted effort. I'm the sole
    entry level programmer at my company and I have only
    one year real wold experience . I work with about 10
    other senior level (microsoft) programmers and none
    of them code in this fashion. All of our
    applications are desktop applications using C#,
    C/C++, or scripting languages.What's a wasted effort? You posting a question? Me posting a response? You writing Java? You trying to think about how to do this properly?
    So why are you using Java if you're in a Microsoft shop? How's this working out with your co-workers?
    I feel like if I worked on a project with one of
    them, they would criticize me for using MVC and
    "complicating" such a simple issue.That's usually because Microsoft likes tying a particular text box to a column in a table. If you change the textbox value you change the database. Nice and easy, right?
    In trying to implement this solution, my workspace
    now has a huge load of classes for something so
    simple:
    Company
    CompanyFrame
    CompanyListController
    CompanyListListener
    CompanyListModel
    CompanyListPanel
    Employee
    EmployeeListDialog
    EmployeeListModel
    EmployeeListPanel
    Main
    11 classes and I left out the Emp Controller and
    Listener to simplify the example. The more classes
    that you have, the slower the application startup
    time. Moving the Views to JPanels as you suggested
    seemed smart but it wound up making it more
    difficult. I'm using NetBeans and Matisse and I
    don't believe you can use another JPanel class in the
    GUI editor unless you make it a bean.
    Traditionally, I would have implemented as follows.
    I would have completed it in 5 minutes and it would
    be much easier to understand what's going on:
    Company
    CompanyFrame - contains a list of companies
    Employee
    EmployeeListDialog - contains a list of employees
    Main
    Of course doing it this way I'd be mixing data with
    the view, but is that always a bad thing or is it
    only bad for large scale applications? Should MVC
    not be used for small modules like this?For small modules that are nothing more the CRUD operations, it might be that a simpler approach is fine. (PS - CRUD stands for Create/Read/Update/Delete, standard relational operations on tables. I'm not commenting on you or your code.)
    It only becomes a problem when that "simple" CRUD application decides to branch into something bigger. The approach of mingling view and data can become problematic then.
    It's still possible to have a clean application for small apps. I think most Microsoft programmers do it that way because the wizards and stuff they're used only allow it to be done that way.
    The reasons why I'm going away from my old "academic"
    programming practices is:
    1) I want to become a better programmer of course!Kudos to you. At least you're still thinking about it.
    2) There's alot of database queries in this
    application so I wanted to separate that from the GUI
    as much as possible. Thus, each model knows how to
    query the database and it's all done on separate
    threads.That's good motivation, too.
    I'd really like to do this right. If you could
    provide source that would be great. Also, are there
    any good books on desktop GUI development geared
    towards Java (or even C#)?I don't write for the desktop, so I'm not much help.
    I already purchased the e-book Desktop Java Live,
    which is great but they don't go into detail about
    MVC and instead use Model-Presenter which has been
    retired (according to Fowlers website). I found that
    section fairly confusing so I figured I'd start with
    MVC since it's more widespread (?).If you're reading Martin Fowler you're doing well.
    Thank you.I'm sorry that I'm not more helpful.
    %

  • Which is more in line with MVC architecture with Struts?

    Hello all
    When using the MVC Model 2 architecture, the JSP's are the view, servlets the control, and the beans are the model. If we say that a control method should represent a specific use case, then in theory, you should be able to call the control method from any interface to request that a specific use case be performed, whether it be over a simple socket connection receiving bytes, or using HTTP.
    However, when using jsp's/servlets, if thr servlet is the control, then it means that the interface must make the request using HTTP and contain a request/response object. But supposing you wanted to change the interface to request the same use case, but makes an http request but supplying XML (instead of several request parameters) which contains the request data, you cannot then simply use the same servlet use-case.
    So what is the solution? If you write another servlet to handle the different request format (XML) it copies a lot of the control code from the other servlet which is a bit messy. Or, would it be correct to write a seperate Controller class (standard Java class), which would contain a set of related use cases, and are called by the servlet. Each use case (which would be a method call in the controller class), would take in its parameter list the exact type and data it needs to complete the use case. In this case the servlets are simply pulling data from the HttpRequest object, converting them to the correct java type to be passed to the controller class you create.
    This introduces an extra layer; the servlet now sits between the request interface and control. It means that the control methods can be called from any type of interface, but is it the right way of doing things, and how would the new control objects be held in the servlet?
    Please could someone give their opinion on which they think is the best way of architecting this?
    Many thanks,
    Shaun.

    Shaun,
    I'm going through the same issues as I try to build my own MVC framework. Struts is useful, but does not cover everything. If you're interested, I've found that the book "Core J2EE Patterns - Best Practices and Design Strategies" by Alur, Crupi and Malks is very helpful. It contains design patterns for all the various tiers. It does not describe a framework, just a set of patterns from which you can pick and choose.
    In the example you describe, one of the applicable patterns is the "Session Facade" which is basically a high-level business interface. The goal is to hide the complexity of the entire business API from the client. The book recommends each facade to correspond to a related set of use cases. e.g. methods in one facade could include OpenAccount, CloseAccount, GetBalance etc. Implementation would be Java classes.
    This facade should be independent of the request protocol and could be used for HTTP, by a Java application, by a web service etc. Usually the facade classes would be located close to the business objects to minimize network delay and traffic.
    In your example, the controller servlet (Struts Action) would invoke services from the Session Facade.
    You're right about this introducing an extra layer. Depending on your present and future needs, you can end up with others such as abstracting the persistence layer. The trade-off is between up-front effort and future flexibility.
    You ask how to reference the new objects. In my case, the initialization servlet calls a factory class method to get references to the facades. These references are stored in an application-specific object that is added as a ServletContext attribute for use by other controller servlets.
    I know this doesn't fully answer your question, but hopefully it helps a little.

  • MVC in Purchase orders display

    Hi friends,
       i would <b>like to work purchase orders display scenario using MVC. if any body done this please let me know which CLASS</b> i need to use while i will create controller.
    thanks in advance,
    cheers,
    Kannan.

    Nothing special to creating the method.  You just create a normal global class in the ABAP workbench.  The only special thing you should do is make your class inherit from CL_BSP_MODEL. 
    Unlike Views and Controllers, there is no integrated creation or visibility to the model in the workbench. 
    Generally in the coding of your Controller (usually DO_REQUEST or DO_INIT) you create the link to the model class in code:
    if me->model is initial.
        me->model ?= create_model( model_id = 'SO'
                                   class_name = 'ZCL_ES_BSP_M_SE16' ).
    endif.

  • Can i use Custom Tags for Database retrieval (as per MVC pattern)?

    In our project we are dealing with database, and i've used the Cutom Tags for database retrieval (as per the Article from Mr Faisal Khan) and it is working fine. But i have a doubt if it affects the performance in any way . I wanted to know if its recommendable to use Custom Tags for the DB retrieval as per MVC Pattern or shall i create a intermediate bean and then call the bean in custom tag.
    Thanks
    Prakash

    Putting database code in your JSPs certainly couples your view to the database. That's usually not good.
    If it's a simple app, it might be justified.
    When you start having lots of pages and complex business logic it becomes less attractive. - MOD

  • Fundamentals: Custom Nodes vs Methods and Controller in MVC

    I have a couple quick questions that I'd consider somewhat fundamental that I should have a better grasp this far along in development...
    - First of all, what do you guys/gals consider the best way to structure your JavaFX classes. I almost always create custom nodes (XCustomNodes usually... from JFXtras) representing certain "panels" filled with content (buttons, labels, text, etc). I realize you could also create a separate class/method to simply return HBoxes, VBoxes, Groups, etc. So... thoughts?
    - Second, I see all these articles/posts saying ghat JavaFX is a perfect MVC language. I agree for the most part, but what would you consider the Controller? Aren't the View and Controller pretty well married together in JFX? Separating the Controller into its own entity seems like it'd be more work than help.
    Just trying to extend my knowledge reach... Thanks in advance!

    evnafets
    Thank you!!!
    While I do not understand how to do this:(though I understand principle of it... the misunderstanding is the whole problem)
    To make this example work all in one file, you have to make RemindTask2 an
    inner class of Reminder (which is already an inner class)
    I do not always understand packages....and doing what you suggested, in forming the packages, and sorting the classes, will help me understand the structure better...plus get me in the norm of always creating packages !
    So what I'm going to do right now is go tear my code down into various packages
    and source files.....however...if you or anyone else could explain/show example
    of how to do what you said(for inner classes, not packages...understand packages) , it would be appreciated.
    This fundamental inner class creation is obviously a major bump right now...and creating the packages and linking the classes will be easy, because I understand how to do it when I already have functional classes created.
    I do not always understand class/method creation/implementation..such as here.
    (IE: can create network apps/gui apps of simple nature....but this easy ol' thing has been driving me nuts.)
    Creating those classes however,,,,even if not the most efficient way is something
    needed for my basic Java knowledge.
    Thank you,,,,VERY GOOD project/training is going to come from this !!
    Really, thank you in any case...if you do not have the time(100% understand) please lmk, will just give you your duke award.
    AEWSOME

  • Jboss with mvc/uix gives errors

    I made a jheadstart application. This works perfectly with ias , now i want to try it on jboss , i followed the howto.
    jboss tries to load the mvc servicefile
    <?xml version='1.0' encoding='windows-1252'?>
    <service name="startService" class="oracle.cle.process.Service"
    initial="HOMEPAGE">
    <seedinfo name="debugMarlinPage" value="true"/>
    <globalinfo name="groupAccessDataObject"/>
    <!--
    Process Group: HomePage
    Description: HomePage pagina
    -->
    <processgroup name="HOMEPAGE" class="oracle.cle.process.DisplayGroup"
    initial="DisplayHomePage" end="true">
    <process name="DisplayHomePage"
    class="oracle.jheadstart.process.CreateUIXPage" end="true">
    <argument type="String" value="/uix/HomePage.uix"/>
    </process>
    </processgroup>
    </service>
    error
    2003-06-17 15:04:48,057 ERROR [STDERR] null
    2003-06-17 15:04:48,057 ERROR [STDERR] oracle.cle.exception.CLEException
    2003-06-17 15:04:48,057 ERROR [STDERR]      at oracle.cle.util.xml.XMLUtil.saxParse(XMLUtil.java:114)
    2003-06-17 15:04:48,057 ERROR [STDERR]      at oracle.cle.process.Service.loadFromXML(Service.java:360)
    2003-06-17 15:04:48,057 ERROR [STDERR]      at oracle.cle.process.Service.<init>(Service.java:225)
    2003-06-17 15:04:48,057 ERROR [STDERR]      at oracle.cle.process.Service.<init>(Service.java:178)
    2003-06-17 15:04:48,057 ERROR [STDERR] Failed Loading Service from XML file...
    2003-06-17 15:04:48,057 ERROR [STDERR] Service could not be instantiated...
    2003-06-17 15:04:48,057 ERROR [STDERR] Check your service definition (XML) file: startService.xml
    it there something missing

    I'm guessing that these errors:
    2003-06-17 15:22:46,120 INFO [org.jboss.web.localhost.Engine] UIX could not find the filesystem location of the stylesheet cache. Usually, this indicates that
    you are running in an environment that does not support the automatic discovery of writable directories; if so, you'll need to configure UIX to give it an explicit
    filesystem path and URL.
    2003-06-17 15:22:46,120 ERROR [org.jboss.web.localhost.Engine]
    oracle.cabo.share.config.DirectoryUnavailableException: contextPath is null
    are caused by the fact that jboss doesn't explode the
    uix install zip. uix needs access to the local file
    system to store images and style sheets. try unzipping
    the zip file and make uix is configured properly to
    use that directory. see the uix developers guide
    in jdev help for configuration issues

  • Role of backing beans in MVC design

    Hello,
    yet another JSF/MVC question. In short, I would like to know what the role of the backing beans are in an MVC design with JSF. The most simple answer would be that they are just the Controllers. But that doesn't seem enough.
    Suppose I have an application model, call it Ma, which is just an interface that represents a use case in Java. Ma doesn't know anything about a view or controller, it is just domain logic with application-specific state and behavior added. Now,
    - my backing bean uses Ma as its Model, acting as a true Controller by delegating requests to it
    - my backing bean also adds view-specific state (show/hide stuff and it also returns a List<SelectItem> for example) that I can't put on Ma, so it also acts as a view model Mv
    So, I could argue that I have an Mv-V-C design, where the backing bean is both C and Mv. My user interface V only queries Mv for its state.
    Usually I read that V and C are considered to be very tightly coupled, so then I would have an Ma-V-C design with the backing bean being C and part of V.
    Is it just a question of terminology or point of view, expressing the same idea twice?

    The way I think about it is that there are multiple layers of MVC.This kind of refers to my point-of-view question. So let's try two of them.
    The view itself can be thought of as containing MVC elements.When only looking at JSF (presentation layer) we have:
    - Model: backing beans (view model Mv)
    - View: view root and JSPs (query backing beans for state)
    - Controller: Faces servlet (dispatches requests to backing beans)
    In my "enterprise" quality applications, I will have three distinct layers.Taking a step back, let's look at the application layer (your "control layer", application logic behind interface) and the presentation layer.
    Then:
    - Model: application model Ma in application layer
    - View: backing bean (associated with UI components)
    - Controller: backing bean (dispatches requests to Ma)
    Agree?
    It's interesting that you call my application layer "control layer" since it seems more like a model to me, especiallly when you say:
    The control layer consists of business logic interfaces and their implementations.This said, the objects in this application layer do have some controller functionality as they orchestrate the interactions with the underlying domain model, just llike the backing beans do with the application model. So maybe you can take another step back and consider these application logic interfaces as the View and Controller for the underlying domain model. That is: in a layered MVC design every M can become the VC for an underlying (more general) layer?
    And I have seen this taken to extremes.Perhaps that's what I'm doing here :)

  • Musings: MVC Front Controller/Command and Controller Strategy

    Hi,
    I am currently taking my first shot at implementing the Front Controller pattern, the Command and Controller Strategy flavor, in Java. When applying the pattern, my chosen point of focus is achieving as much isolation as possible of Client-specific implementation details from the rest of the framework (Web-based framework Clients, Swing-based framework Clients, queueing-based framework Clients, etc.) However, I am running into a lot of (apparent?) inconsistencies when it comes to CCS discussions "out there", so I have a feeling that perhaps I have misunderstood the Front Controller/Command and Controller Strategy pattern. Maybe the MVC gurus out there would have some thoughts on the matter.
    My issues:
    1.) Some CCS discussions seem to assign View presentation (sometimes called "dispatch", or "rendering", or "forwarding"?) to an ApplicationController. It seems puzzling to me, since only a concrete FrontController should include any knowledge of a concrete View structure. Shouldn't only a FrontController perform a logical-to-physical resource mapping, thus encapsulating knowledge whether a particular View is a separate, stand-alone Web page or a compound, argument-driven Swing object, and how to "present it" (by either redirecting to a Web page, or bringing a particular Swing object into the foreground)?
    2.) Some CCS discussions seem to introduce Client-specific implementation details at the ApplicationController level, for example "HTTP requests" or "HTTP responses". It seems puzzling to me, since I feel that every part of the framework, except for a concrete FrontController, should be completely independent of the nature of a Client making a request. Instead, I created a generic Request object w/arguments and have a concrete FrontController translate any client-specific details into such a generic Request, before delegating to an ApplicationController.
    3.) In the light of the (2.) above, I am not sure what constitutes a "response" from an ApplicationController back to a FrontController. It seems to me that the only universal "response" is a LogicalViewEnumeration: what View to present once a command has been completed, in many cases a "don't care", or a "show the requestor", or a "show a home page" (not every request has to result in changing a View). Well, perhaps a LogicalViewEnumeration as well as possible View arguments (?).
    4.) In the light of the (3.) above, I suspect that any failures in Request delegation, or Command execution, should be perhaps propagated back to a FrontController by exceptions only, since, say, a WebFrontController might want to show a click-through error page, when a SwingFrontController might prefer to show an error dialog box, a LogicalErrorViewEnumeration might not make sense at all in the context of a particular Client, for example a queueing Client.
    5.) In the light of the (4.) above, there is the question of an appropriate Request interface (into an ApplicationController), an appropriate Response interface (back into a FrontController), as well as an appropriate ViewArguments interface (into a FrontController and later into a View). The problem with generic Requests is that they can be created with nonsensical argument combinations, so shouldn't Requests be abstract and force proper arguments in concrete subclasses, through explicit constructors (in a sense, degenerate Commands)? The problem with Responses and ViewArguments is that... well, I have not found any formal discussion anywhere as to what those should look like. In most samples I have encountered, Responses include Client-specific implementation details, as mentioned in (2.), above.
    6.) Some CCS discussions seem to introduce a Flow Manager at the ApplicationController level. It seems puzzling to me, since the whole point of the Command and Controller Strategy flavor seems to be centralization of business logic execution within self-contained Command objects. Shouldn't Requests get associated with Handlers (objects capable of actually carrying out Requests) and transformed into Commands inside an ApplicationController, thus Commands themselves return appropriate LogicalViewEnumeration back to an ApplicationController, back to a FrontController? Let's consider a ShowMyShippingAddress request coming into the framework: unless such a Request is eventually treated as a Command returning a particular LogicalViewEnumeration, it is suddenly a Flow Manager "acting" as a business logic driver. I guess the question here is: except for a few special cases handled by a particular ApplicationController (authentication, error conditions, default behavior, etc.), should flow management be considered stand-alone, or always delegated to Commands?
    7.) Some CCS discussions seem to include an extra Request argument that specifies an ApplicationController to use (Request.Action="create", Request.Controller="account", Request.Username="me-me-me"), instead of using a Router inside of a FrontController to resolve to a particular ApplicationController through a generic action (Request.Action="createAccount", Request.Username="me-me-me"). I am not sure about the reason for such a design decision: why should a Client or a FrontController be allowed to concern itself with an implementation-level structure of the framework? Wouldn't any framework state -dependent ApplicationController resolution issues be best handled inside a Router, used by a FrontController to resolve [obtain] an appropriate ApplicationController, thus preventing Clients from ever forcing the framework into a possibly inconsistent behavior?
    Any comments appreciated...
    Thanks,
    Gary

    gniemcew wrote:
    1.) Some CCS discussions seem to assign View presentation (sometimes called "dispatch", or "rendering", or "forwarding"?) to an ApplicationController. It seems puzzling to me, since only a concrete FrontController should include any knowledge of a concrete View structure. Shouldn't only a FrontController perform a logical-to-physical resource mapping, thus encapsulating knowledge whether a particular View is a separate, stand-alone Web page or a compound, argument-driven Swing object, and how to "present it" (by either redirecting to a Web page, or bringing a particular Swing object into the foreground)?It is hard to tell without reading the actual discussion, but my guess is that the posters were either conflating or being loose with the distinction between a FrontController and an ApplicationController. The former is (normally) intimately tied to the actual view being used (HTTP, Swing, etc.) whereas the ApplicationController typically is not. Both are involved in dispatch and event processing. The former normally renders a view whereas the latter does not.
    gniemcew wrote:
    2.) Some CCS discussions seem to introduce Client-specific implementation details at the ApplicationController level, for example "HTTP requests" or "HTTP responses". It seems puzzling to me, since I feel that every part of the framework, except for a concrete FrontController, should be completely independent of the nature of a Client making a request. Instead, I created a generic Request object w/arguments and have a concrete FrontController translate any client-specific details into such a generic Request, before delegating to an ApplicationController.Generic is fine. However, you can become generic to the point where your Request and Response interfaces are only acting as "marker" interfaces (think of java.io.Serializable). Writing a truly generic controller is possible, but personally, I have never found the effort justified.
    gniemcew wrote:
    3.) In the light of the (2.) above, I am not sure what constitutes a "response" from an ApplicationController back to a FrontController. It seems to me that the only universal "response" is a LogicalViewEnumeration: what View to present once a command has been completed, in many cases a "don't care", or a "show the requestor", or a "show a home page" (not every request has to result in changing a View). Well, perhaps a LogicalViewEnumeration as well as possible View arguments (?).A given service (if you ascribe to SOA) should be the fundamental unit in your architectural design. A good application controller would be responsible for determining how to dispatch a given Command. Whether a Command pattern is used or whether service methods are invoked directly from your FrontController, the ApplicationController should enforce common service aspects. These include authentication, authorization, auditing, orchestration, validation, logging, error handling, just to name a few.
    The ApplicationController should ideally offload these aspects from a given service. The service would indicate how the aspects are to be applied (e.g., strong authentication required, x role required, fetching of existing process state, etc.) This allows services to be developed more quickly and to have these critical aforementioned aspects developed and tested centrally.
    Your FrontController, in contrast, is responsible for transforming whatever input it is designed to receive (HTTP form data posts, XML-RPC, etc.) and ensure that it honors the contract(s) that the ApplicationController establishes. There are no cut-and-dry decisions though about when a given piece of functionality should be ApplicationController or FrontController. Take error handling. Should I emit just a generic ServiceException or allow the FrontController to decide what to do with a more concrete checked exception? (The FrontController, in any case, should present the error to the user in a manner dictated by the protocol it serves).
    gniemcew wrote:
    4.) In the light of the (3.) above, I suspect that any failures in Request delegation, or Command execution, should be perhaps propagated back to a FrontController by exceptions only, since, say, a WebFrontController might want to show a click-through error page, when a SwingFrontController might prefer to show an error dialog box, a LogicalErrorViewEnumeration might not make sense at all in the context of a particular Client, for example a queueing Client.See above. Yes. However, the ApplicationController could easily 'hide' details about the failure. For example, any number of exceptions being mapped to a generic DataAccessException or even more abstractly to a ServiceFailureException. The ApplicationController could indicate whether the failure was recoverable and/or populate information necessary to speed up production support (e.g., mapping exceptions to error codes and/or providing a primary key in an error audit log table for support to reference). A given FrontController would present that information to the user in the method that makes sense (e.g., error dialog for Swing, error page for HTML, etc.)
    gniemcew wrote:
    5.) In the light of the (4.) above, there is the question of an appropriate Request interface (into an ApplicationController), an appropriate Response interface (back into a FrontController), as well as an appropriate ViewArguments interface (into a FrontController and later into a View). The problem with generic Requests is that they can be created with nonsensical argument combinations, so shouldn't Requests be abstract and force proper arguments in concrete subclasses, through explicit constructors (in a sense, degenerate Commands)? The problem with Responses and ViewArguments is that... well, I have not found any formal discussion anywhere as to what those should look like. In most samples I have encountered, Responses include Client-specific implementation details, as mentioned in (2.), above.See comment on marker interfaces above. Nothing, however, stops you from requiring a certain sub-type in a given service method. You can still pass in the interface and validate the proper type by an assert statement (after all, in the vast majority of situations, the proper service method should get the proper instance of a given Request object). IMO, the FrontController would create the Command instance which would be passed to the ApplicationController which would dispatch and invoke the proper service method. A model response would be received by the FrontController which would then render the appropriate view.
    gniemcew wrote:
    6.) Some CCS discussions seem to introduce a Flow Manager at the ApplicationController level. It seems puzzling to me, since the whole point of the Command and Controller Strategy flavor seems to be centralization of business logic execution within self-contained Command objects. Shouldn't Requests get associated with Handlers (objects capable of actually carrying out Requests) and transformed into Commands inside an ApplicationController, thus Commands themselves return appropriate LogicalViewEnumeration back to an ApplicationController, back to a FrontController? Let's consider a ShowMyShippingAddress request coming into the framework: unless such a Request is eventually treated as a Command returning a particular LogicalViewEnumeration, it is suddenly a Flow Manager "acting" as a business logic driver. I guess the question here is: except for a few special cases handled by a particular ApplicationController (authentication, error conditions, default behavior, etc.), should flow management be considered stand-alone, or always delegated to Commands?There are distinct kinds of flow management. For example, orchestration (or BPM) is properly at either the service or ApplicationController layers. However, determining which view to display is properly at the FrontController layer. The ApplicationController should receive a Command (with a populate Request) and return that Command (with a populated Response). Both the Request and Response are fundamentally model classes (within MVC). The FrontController is responsible for populating the Request and/or Command and rendering the Response and/or Command. Generic error handling is usually centralized for both controllers.
    gniemcew wrote:
    7.) Some CCS discussions seem to include an extra Request argument that specifies an ApplicationController to use (Request.Action="create", Request.Controller="account", Request.Username="me-me-me"), instead of using a Router inside of a FrontController to resolve to a particular ApplicationController through a generic action (Request.Action="createAccount", Request.Username="me-me-me"). I am not sure about the reason for such a design decision: why should a Client or a FrontController be allowed to concern itself with an implementation-level structure of the framework? Wouldn't any framework state -dependent ApplicationController resolution issues be best handled inside a Router, used by a FrontController to resolve [obtain] an appropriate ApplicationController, thus preventing Clients from ever forcing the framework into a possibly inconsistent behavior?I am not 100% sure of what you are getting at here. However, it seems to be the method by which commands are dispatched. They are in effect allowing a FrontController to dictate which of n ApplicationControllers should receive the request. If we allow a FrontController to directly invoke a service method, then the ApplicationController is simply a centralized framework that should always be invoked for each service method (enforced via AOP or some other mechanism). If there is a single, concrete ApplicationController which handles dispatch, then all FrontControllers communicate directly with that instance. It is really just a design decision (probably based on your comfort level with concepts like AOP that allow the ApplicationController to exist solely behind the scenes).
    I might have totally missed your questions, but those are my thoughts on a Monday. Best of luck.
    - Saish

  • Organizing MVC

    Hi, I'm just learning MVC and I have few questions.
    As the class count increases with MVC, how do you usually organize the models, views and controllers in Java packages? I think I'm trying to "tie them together" too much. Also, should I think like that the Models arent actually a part of the MVC at all?
    I have Screens (views) like TitleScreen, OptionsScreen, HelpScreen. They all have an abstract base class Screen that has a Window (which contains all smaller components like buttons etc.). Now I'm gonna have quite many of these screens and I'm wondering if it's practical for each of them to have a separate controller, model and view. Some of them are pretty simple and may have just like few buttons which have some simple actions. Also, if I know that, for example, some controller isn't gonna change, could I make things easier by declaring it as inner class or something. I'm not really trying to achieve any kind of superior flexibility but mainly just a practical division between the view and data.
    Especially the controller part is hardest to think of maybe because of the simplicity of my screens. And I'm not too sure of all it's responsibilities.
    Let's say I want to have a screen that shows a list of Players, and it's possible to create, delete and choose players in it. So as I've understood I should create:
    - TitleScreen (has a Window, which in turn has the List that displays the Players)
    - TitleState (contains the actual player-objects, and some methods to interact with them)
    - TitleController (first things that come into my mind are methods like createPlayer(String), deletePlayer(String), but I think they would fit to TitleState too?)
    How would you design the above classes?
    Another thing I'm confused of is that in some examples I've seen the View has a reference to the model and sometimes it seems to pull data directly from it (using getters) and sometimes it gains them as events. Which one should I prefer?
    Also, how do you usually name the models, views and controllers?
    Thanks a bunch

    Hi, I'm just learning MVC and I have few questions.
    As the class count increases with MVC, how do you
    usually organize the models, views and controllers in
    Java packages? I think I'm trying to "tie them
    together" too much. Also, should I think like that
    the Models arent actually a part of the MVC at all?
    There are two high-level package organization options, neither of which is either correct or incorrect, but rather a matter of preference. After your domain, you can either go tier and then component or vice versa. Here are two examples:
    com.foo.controller.account
    com.foo.controller.invoice
    com.foo.model.account
    com.foo.model.invoice
    com.foo.view.account
    com.foo.view.invoice
    or
    com.foo.account.controller
    com.foo.account.model
    com.foo.account.view
    com.foo.invoice.controller
    com.foo.invoice.model
    com.foo.invoice.view
    I have Screens (views) like TitleScreen,
    OptionsScreen, HelpScreen. They all have an abstract
    base class Screen that has a Window (which contains
    all smaller components like buttons etc.). Now I'm
    gonna have quite many of these screens and I'm
    wondering if it's practical for each of them to have
    a separate controller, model and view. Some of them
    are pretty simple and may have just like few buttons
    which have some simple actions. Also, if I know that,
    for example, some controller isn't gonna change,
    could I make things easier by declaring it as inner
    class or something. I'm not really trying to achieve
    any kind of superior flexibility but mainly just a
    practical division between the view and data.
    There is no reason that a series of common screens, presumably with common functionality offered, could not also have controllers that have common functionality. Either refactor the common controller code to a helper object or an abstract controller super-class.
    What you have stumbled upon is that it is very difficult to separate the view from the controller. The controller's responsibilities are to response to user requests and dispatch model data to the appropriate view. As such, the controller is 'dependent' on both the model and the view. Neither model nor view, however, should be dependent on the controller.
    Within a standard GUI application, any events that you process are candidates for controller code. These include button clicks, menu clicks, etc. Now, you can simply leave these as event listeners or you can refactor them into proper controllers. This would mean that you instantiate a given controller which would be responsible for managing a given view. The methods on the controller would alter the state of the view.
    Especially the controller part is hardest to think of
    maybe because of the simplicity of my screens. And
    I'm not too sure of all it's responsibilities.
    See above. Also note that it is hard to decouple the view and controller. For most GUI applications, you really do not need model-view-controller, you simply need model-delegate, where delegate is a mish-mosh of view and controller responsibilities.
    Let's say I want to have a screen that shows a list
    of Players, and it's possible to create, delete and
    choose players in it. So as I've understood I should
    create:
    - TitleScreen (has a Window, which in turn has the
    List that displays the Players)
    - TitleState (contains the actual player-objects, and
    some methods to interact with them)
    - TitleController (first things that come into my
    mind are methods like createPlayer(String),
    deletePlayer(String), but I think they would fit to
    TitleState too?)
    That is fine. Your controller is delegating a request to the model class. That is normal. It might seem odd the signatures are similar (or wasteful), but to do proper MVC, the view should invoke a controller which will invoke the model which and then finally pass the model result(s) if any to either the same or a different view.
    How would you design the above classes?
    See above.
    Another thing I'm confused of is that in some
    examples I've seen the View has a reference to the
    model and sometimes it seems to pull data directly
    from it (using getters) and sometimes it gains them
    as events. Which one should I prefer?
    It depends on how much decoupling you want. You can have your controllers or your views act as listeners or observers (via the observer-observable pattern). However, the model generally should stand on its own.
    Also, how do you usually name the models, views and
    controllers?
    Personal preference. Remember from above that the package structure itself will give you a clue as to what tier you are in.
    Thanks a bunchYou are welcome.
    - Saish

Maybe you are looking for