jdbbc2.0

Upload: agupta3304

Post on 06-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 jdbbc2.0

    1/18

    What is runtime polymorphism in Java?

    Polymorphism is the capability of an action or method to do different things based on the

    object that it is acting upon. In other words, polymorphism allows you define one interface

    and have multiple implementation. This is one of the basic principles of object orientedprogramming.

    The method overriding is an example of runtime polymorphism. You can have a method in

    subclass overrides the method in its super classes with the same name and signature. Java

    virtual machine determines the proper method to call at the runtime, not at the compile time.

    Let's take a look at the following example:

    class Animal {

    void whoAmI() {

    System.out.println("I am a generic Animal.");}

    }

    class Dog extends Animal {

    void whoAmI() {

    System.out.println("I am a Dog.");

    }

    }

    class Cow extends Animal {

    void whoAmI() {

    System.out.println("I am a Cow.");

    }

    }

    class Snake extends Animal {void whoAmI() {

    System.out.println("I am a Snake.");

    }

    }

    class RuntimePolymorphismDemo {

    public static void main(String[] args) {

    Animal ref1 = new Animal();

    Animal ref2 = new Dog();

    Animal ref3 = new Cow();

    Animal ref4 = new Snake();

    ref1.whoAmI();

    ref2.whoAmI();

    ref3.whoAmI();

    ref4.whoAmI();

    }

    }

    The output is

    I am a generic Animal.

    I am a Dog.

    I am a Cow.

    I am a Snake.

  • 8/3/2019 jdbbc2.0

    2/18

    The primary usage of polymorphism in industry (object-oriented programmingtheory) is the ability

    ofobjectsbelonging to different types to respond tomethod,field, orpropertycalls of the same

    name, each one according to an appropriate type-specific behavior.

    The programmer (and the program) does not have to know the exact type of the object in advance,

    and so the exact behavior is determined atrun-time(this is calledlate bindingordynamic binding).Polymorphism is only concerned with the application of specificimplementationsto aninterfaceor a

    more generic base class. Method overloading refers to methods that have the same name but

    different signatures inside the same class. Method overriding is where a subclass replaces the

    implementation of one or more of its parent's methods. Neither method overloading nor method

    overriding are by themselves implementations of polymorphism

    The purpose of polymorphism is to implement a style of programming called message-passing in the

    literature[citation needed]

    , in which objects of various types define a common interface of operations for

    users. In strongly typed languages, polymorphism usually means that type A somehow derives from

    type B, or type C implements an interface that represents type B. In weakly typed languages types

    are implicitly polymorphic.

    http://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Object-oriented_programminghttp://en.wikipedia.org/wiki/Object_%28computer_science%29http://en.wikipedia.org/wiki/Object_%28computer_science%29http://en.wikipedia.org/wiki/Object_%28computer_science%29http://en.wikipedia.org/wiki/Method_%28computer_science%29http://en.wikipedia.org/wiki/Method_%28computer_science%29http://en.wikipedia.org/wiki/Method_%28computer_science%29http://en.wikipedia.org/wiki/Field_%28computer_science%29http://en.wikipedia.org/wiki/Field_%28computer_science%29http://en.wikipedia.org/wiki/Field_%28computer_science%29http://en.wikipedia.org/wiki/Property_%28computer_science%29http://en.wikipedia.org/wiki/Property_%28computer_science%29http://en.wikipedia.org/wiki/Property_%28computer_science%29http://en.wikipedia.org/wiki/Run_time_%28program_lifecycle_phase%29http://en.wikipedia.org/wiki/Run_time_%28program_lifecycle_phase%29http://en.wikipedia.org/wiki/Run_time_%28program_lifecycle_phase%29http://en.wikipedia.org/wiki/Late_bindinghttp://en.wikipedia.org/wiki/Late_bindinghttp://en.wikipedia.org/wiki/Late_bindinghttp://en.wikipedia.org/wiki/Dynamic_dispatchhttp://en.wikipedia.org/wiki/Dynamic_dispatchhttp://en.wikipedia.org/wiki/Dynamic_dispatchhttp://en.wikipedia.org/wiki/Implementationhttp://en.wikipedia.org/wiki/Implementationhttp://en.wikipedia.org/wiki/Implementationhttp://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29http://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29http://en.wikipedia.org/wiki/Wikipedia:Citation_neededhttp://en.wikipedia.org/wiki/Wikipedia:Citation_neededhttp://en.wikipedia.org/wiki/Wikipedia:Citation_neededhttp://en.wikipedia.org/wiki/Wikipedia:Citation_neededhttp://en.wikipedia.org/wiki/Interface_%28object-oriented_programming%29http://en.wikipedia.org/wiki/Implementationhttp://en.wikipedia.org/wiki/Dynamic_dispatchhttp://en.wikipedia.org/wiki/Late_bindinghttp://en.wikipedia.org/wiki/Run_time_%28program_lifecycle_phase%29http://en.wikipedia.org/wiki/Property_%28computer_science%29http://en.wikipedia.org/wiki/Field_%28computer_science%29http://en.wikipedia.org/wiki/Method_%28computer_science%29http://en.wikipedia.org/wiki/Object_%28computer_science%29http://en.wikipedia.org/wiki/Object-oriented_programming
  • 8/3/2019 jdbbc2.0

    3/18

    Interfaces

    There are a number of situations in software engineering when it is important for disparate

    groups of programmers to agree to a "contract" that spells out how their software interacts.

    Each group should be able to write their code without any knowledge of how the othergroup's code is written. Generally speaking, interfaces are such contracts.

    For example, imagine a futuristic society where computer-controlled robotic cars transport

    passengers through city streets without a human operator. Automobile manufacturers write

    software (Java, of course) that operates the automobilestop, start, accelerate, turn left, and

    so forth. Another industrial group, electronic guidance instrument manufacturers, make

    computer systems that receive GPS (Global Positioning System) position data and wireless

    transmission of traffic conditions and use that information to drive the car.

    The auto manufacturers must publish an industry-standard interface that spells out in detail

    what methods can be invoked to make the car move (any car, from any manufacturer). Theguidance manufacturers can then write software that invokes the methods described in the

    interface to command the car. Neither industrial group needs to know how the other group's

    software is implemented. In fact, each group considers its software highly proprietary and

    reserves the right to modify it at any time, as long as it continues to adhere to the published

    interface.

    Interfaces in Java

    In the Java programming language, an interface is a reference type, similar to a class, that can

    contain only constants, method signatures, and nested types. There are no method bodies.Interfaces cannot be instantiatedthey can only be implementedby classes or extendedby

    other interfaces. Extension is discussed later in this lesson.

    Defining an interface is similar to creating a new class:

    public interface OperateCar {

    // constant declarations, if any

    // method signatures

    int turn(Direction direction, // An enum with values RIGHT, LEFT

    double radius, double startSpeed, double endSpeed);int changeLanes(Direction direction, double startSpeed, double

    endSpeed);

    int signalTurn(Direction direction, boolean signalOn);

    int getRadarFront(double distanceToCar, double speedOfCar);

    int getRadarRear(double distanceToCar, double speedOfCar);

    ......

    // more method signatures

    }

    Note that the method signatures have no braces and are terminated with a semicolon.

    To use an interface, you write a class that implements the interface. When an instantiable

    class implements an interface, it provides a method body for each of the methods declared in

    the interface. For example,

  • 8/3/2019 jdbbc2.0

    4/18

    public class OperateBMW760i implements OperateCar {

    // the OperateCar method signatures, with implementation --

    // for example:

    int signalTurn(Direction direction, boolean signalOn) {

    //code to turn BMW's LEFT turn indicator lights on

    //code to turn BMW's LEFT turn indicator lights off//code to turn BMW's RIGHT turn indicator lights on

    //code to turn BMW's RIGHT turn indicator lights off

    }

    // other members, as needed -- for example, helper classes

    // not visible to clients of the interface

    }

    In the robotic car example above, it is the automobile manufacturers who will implement the

    interface. Chevrolet's implementation will be substantially different from that of Toyota, of

    course, but both manufacturers will adhere to the same interface. The guidance

    manufacturers, who are the clients of the interface, will build systems that use GPS data on a

    car's location, digital street maps, and traffic data to drive the car. In so doing, the guidance

    systems will invoke the interface methods: turn, change lanes, brake, accelerate, and so forth.

    Interfaces as APIs

    The robotic car example shows an interface being used as an industry standard Application

    Programming Interface (API). APIs are also common in commercial software products.

    Typically, a company sells a software package that contains complex methods that another

    company wants to use in its own software product. An example would be a package of digital

    image processing methods that are sold to companies making end-user graphics programs.The image processing company writes its classes to implement an interface, which it makes

    public to its customers. The graphics company then invokes the image processing methods

    using the signatures and return types defined in the interface. While the image processing

    company's API is made public (to its customers), its implementation of the API is kept as a

    closely guarded secretin fact, it may revise the implementation at a later date as long as it

    continues to implement the original interface that its customers have relied on.

    Interfaces and Multiple Inheritance

    Interfaces have another very important role in the Java programming language. Interfaces are

    not part of the class hierarchy, although they work in combination with classes. The Javaprogramming language does not permit multiple inheritance (inheritance is discussed later in

    this lesson), but interfaces provide an alternative.

    In Java, a class can inherit from only one class but it can implement more than one interface.

    Therefore, objects can have multiple types: the type of their own class and the types of all the

    interfaces that they implement. This means that if a variable is declared to be the type of an

    interface, its value can reference any object that is instantiated from any class that

    implements the interface. This is discussed later in this lesson, in the section titled "Using an

    Interface as a Type."

  • 8/3/2019 jdbbc2.0

    5/18

    Defining an Interface

    An interface declaration consists of modifiers, the keyword interface, the interface name, acomma-separated list of parent interfaces (if any), and the interface body. For example:

    public interface GroupedInterface extends Interface1,

    Interface2, Interface3 {

    // constant declarations

    double E = 2.718282; // base of natural logarithms

    // method signatures

    void doSomething (int i, double x);

    int doSomethingElse(String s);

    }

    The public access specifier indicates that the interface can be used by any class in any

    package. If you do not specify that the interface is public, your interface will be accessible

    only to classes defined in the same package as the interface.

    An interface can extend other interfaces, just as a class can extend or subclass another class.

    However, whereas a class can extend only one other class, an interface can extend any

    number of interfaces. The interface declaration includes a comma-separated list of all the

    interfaces that it extends.

    The Interface Body

    The interface body contains method declarations for all the methods included in the interface.

    A method declaration within an interface is followed by a semicolon, but no braces, because

    an interface does not provide implementations for the methods declared within it. All

    methods declared in an interface are implicitly public, so the public modifier can be omitted.

    An interface can contain constant declarations in addition to method declarations. All

    constant values defined in an interface are implicitly public, static, and final. Once

    again, these modifiers can be omitted.

    Abstraction in Java allows the user to hide non-essential details relevant to user.

    -- It allows only to show the essential features of the object to the end user.-- In other sense we can say it deals with the outside view of an object (interface).

  • 8/3/2019 jdbbc2.0

    6/18

    Abstract Classes versus Interfaces

    Unlike interfaces, abstract classes can contain fields that are not static and final, and they

    can contain implemented methods. Such abstract classes are similar to interfaces, except that

    they provide a partial implementation, leaving it to subclasses to complete the

    implementation. If an abstract class contains only abstract method declarations, it should bedeclared as an interface instead.

    Multiple interfaces can be implemented by classes anywhere in the class hierarchy, whether

    or not they are related to one another in any way. Think ofComparable or Cloneable, forexample.

    By comparison, abstract classes are most commonly subclassed to share pieces of

    implementation. A single abstract class is subclassed by similar classes that have a lot in

    common (the implemented parts of the abstract class), but also have some differences (the

    abstract methods).

    ) synchronized keyword in java provides locking which ensures mutual exclusive access of shared resource andprevent data race.2) synchronized keyword also prevent reordering of code statement by compiler which can cause subtleconcurrent issue if we don't use synchronized or volatile keyword.3) synchronized keyword involve locking and unlocking. before entering into synchronized method or blockthread needs to acquire the lock at this point it reads data from main memory than cache and when it releasethe lock it flushes write operation into main memory which eliminates memory inconsistency errors.

    The Java programming language provides two basic synchronization idioms: synchronized

    methods and synchronized statements.

    To make a method synchronized, simply add the synchronized keyword to its declaration:

    public class SynchronizedCounter

    {private int c = 0;

    public synchronized void increment()

    {

    c++;

    }

    public synchronized void decrement()

    {

    c--;

    }

    public synchronized int value()

    {

    return c;

    }

    }

    If count is an instance of SynchronizedCounter, then making these methods synchronized has

    two effects:

    * First, it is not possible for two invocations of synchronized methods on the same object to

    interleave. When one thread is executing a synchronized method for an object, all other

    threads that invoke synchronized methods for the same object block (suspend execution)until the first thread is done with the object.

  • 8/3/2019 jdbbc2.0

    7/18

    * Second, when a synchronized method exits, it automatically establishes a happens-before

    relationship with any subsequent invocation of a synchronized method for the same object.

    This guarantees that changes to the state of the object are visible to all threads.

    Simply put, a threadis a program's path of execution. Most programs written today run as asingle thread, causing problems when multiple events or actions need to occur at the same

    time. Let's say, for example, a program is not capable of drawing pictures while reading

    keystrokes. The program must give its full attention to the keyboard input lacking the ability

    to handle more than one event at a time. The ideal solution to this problem is the seamless

    execution of two or more sections of a program at the same time. Threads allows us to do

    this.

    Multithreaded applications deliver their potent power by running many threads concurrently

    within a single program. From a logical point of view, multithreading means multiple lines of

    a single program can be executed at the same time, however, it is not the same as starting a

    program twice and saying that there are multiple lines of a program being executed at the

    same time. In this case, the operating system is treating the programs as two separate and

    distinct processes. Under Unix, forking a process creates a child process with a different

    address space for both code and data. However, fork() creates a lot of overhead for theoperating system, making it a very CPU-intensive operation. By starting a thread instead, an

    efficient path of execution is created while still sharing the original data area from the parent.

    The idea of sharing the data area is very beneficial, but brings up some areas of concern that

    we'll discuss later.

    A threadis a thread of execution in a program. The Java Virtual Machine allows an

    application to have multiple threads of execution running concurrently.

    Every thread has a priority. Threads with higher priority are executed in preference to threads

    with lower priority. Each thread may or may not also be marked as a daemon. When code

    running in some thread creates a new Thread object, the new thread has its priority initially

    set equal to the priority of the creating thread, and is a daemon thread if and only if the

    creating thread is a daemon.

    When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which

    typically calls the method named main of some designated class). The Java Virtual Machine

    continues to execute threads until either of the following occurs:

    The exit method of class Runtime has been called and the security manager haspermitted the exit operation to take place.

    All threads that are not daemon threads have died, either by returning from the call tothe run method or by throwing an exception that propagates beyond the run method.

    There are two ways to create a new thread of execution. One is to declare a class to be a

    subclass ofThread. This subclass should override the run method of class Thread. An

    instance of the subclass can then be allocated and started. For example, a thread that

    computes primes larger than a stated value could be written as follows:

    class PrimeThread extends Thread {

    http://forums.techarena.in/newreply.php?do=newreply&p=4035050
  • 8/3/2019 jdbbc2.0

    8/18

    long minPrime;

    PrimeThread(long minPrime) {

    this.minPrime = minPrime;

    }

    public void run() {

    // compute primes larger than minPrime. . .

    }

    }

    The following code would then create a thread and start it running:

    PrimeThread p = new PrimeThread(143);

    p.start();

    The other way to create a thread is to declare a class that implements the Runnable interface.

    That class then implements the run method. An instance of the class can then be allocated,

    passed as an argument when creating Thread, and started. The same example in this other

    style looks like the following:

    class PrimeRun implements Runnable {

    long minPrime;

    PrimeRun(long minPrime) {

    this.minPrime = minPrime;

    }

    public void run() {

    // compute primes larger than minPrime

    . . .

    }

    }

    The following code would then create a thread and start it running:

    PrimeRun p = new PrimeRun(143);

    new Thread(p).start();

    Servlet Life Cycle

    The life cycle of a servlet is controlled by the container in which the servlet has been

    deployed. When a request is mapped to a servlet, the container performs the following steps.

    1. If an instance of the servlet does not exist, the Web containera. Loads the servlet class.b. Creates an instance of the servlet class.

  • 8/3/2019 jdbbc2.0

    9/18

    c. Initializes the servlet instance by calling the init method. Initialization is covered inInitializing a Servlet.

    2. Invokes the servicemethod, passing a request and response object. Service methods arediscussed in the sectionWriting Service Methods.

    If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's

    destroy method. Finalization is discussed inFinalizing a Servlet.

    Handling Servlet Life-Cycle Events

    You can monitor and react to events in a servlet's life cycle by defining listener objects whose

    methods get invoked when life cycle events occur. To use these listener objects, you must

    define the listener class and specify the listener class.

    Defining The Listener Class

    You define a listener class as an implementation of a listener interface.Table 10-3lists the

    events that can be monitored and the corresponding interface that must be implemented.

    When a listener method is invoked, it is passed an event that contains information appropriate

    to the event. For example, the methods in the HttpSessionListener interface are passed an

    HttpSessionEvent, which contains an HttpSession.

    Difference between ServletContext andServletConfig

    What the difference between ServletContext and ServletConfig apart from the fact that

    Context gives environmental details and Config abt the initialisation params?? Another

    other substantial diff??

    I have mentioned some tips regarding ServletContext and ServletConfig. okey Do well

    ServletContext Defines a set of methods that a servlet uses to communicate with its servlet

    container.

    ServletConfig is a servlet configuration object used by a servlet container used to pass

    information to a servlet during initialization. All of its initialization parameters can ONLY be

    set in deployment descriptor.

    The ServletContext object is contained within the ServletConfig object, which the Web

    server provides the servlet when the servlet is initialized.

    You can specify param-value pairs for ServletContext object in tags in

    web.xml file.

    The ServletConfig parameters are specified for a particular servlet and are unknown to other

    servlets.

    The ServletContext parameters are specified for an entire application outside of any particularservlet and are available to all the servlets within that application.

    http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets6.html#82013http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets6.html#82013http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets7.html#74749http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets7.html#74749http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets7.html#74749http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets12.html#71764http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets12.html#71764http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets12.html#71764http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets4.html#76892http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets4.html#76892http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets4.html#76892http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets4.html#76892http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets12.html#71764http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets7.html#74749http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets6.html#82013
  • 8/3/2019 jdbbc2.0

    10/18

    Murugesa pandian

    Just to add more clearity...

    ServletContext has a APPLICATION SCOPE .. [GLOBALLY ACCESSIBLE ACROSS

    THE PAGES]

    where as

    ServletContext has a SESSION SCOPE.. [LOCAL SCOPE......which is mostly used for

    intialising purpose].

    ServletConfig :

    One ServletConfig per servlet Used to pass deploy-time info to servlet and configured in deployment

    descriptor Used to access ServletContext Within servlet element in DD:

    InitParamTest

    InitParamTest

    test.InitParamTest

    test parameter

    mynameDummyValue

    getServletConfig.getInitParameter(myname); Available to only to the servlet which has init-param configured

    ServletContext:

    One per webapp If webapp is distributed, one per JVM Used to access webapp parameters configured in deployment descriptor Application bulletin-board Use to get server info Within web-app element of DD

    myname

    DummyValue

  • 8/3/2019 jdbbc2.0

    11/18

    MVC Overview

    Flexibility in large component based systems raise questions on how to organize a project for

    easy development and maintenance while protecting your data and reputation, especially

    from new developers and unwitting users. The answer is in using the Model, View, Control

    (MVC) architecture. An architecture such as MVC is a design pattern that describes arecurring problem and its solution where the solution is never exactly the same for every

    recurrence.

    To use theModel-View-ControllerMVC paradigm effectively you must understand the

    division of labor within the MVC triad. You also must understand how the three parts of the

    triad communicate with each other and with other active views and controllers; the sharing of

    a single mouse, keybord and display screen among several applications demands

    communication and cooperation. To make the best use of the MVC paradigm you need also

    to learn about the available subclasses of View and Controller which provide ready made

    starting points for your applications.

    In the MVC design pattern , application flow is mediated by a central controller. The

    controller delegates requests to an appropriate handler. The controller is the means by which

    the user interacts with the web application. The controller is responsible for the input to the

    model. A pure GUI controller accepts input from the user and instructs the model and

    viewport to perform action based on that input. If an invalid input is sent to the controller

    from the view, the model informs the controller to direct the view that error occurred and to

    tell it to try again.

    A web application controller can be thought of as specialised view since it has a visual

    aspect. It would be actually be one or more HTML forms in a web application and thereforethe model can also dictate what the controller should display as input. The controller would

    produce HTML to allow the user input a query to the web application. The controller would

    add the necessary parameterisation of the individual form element so that the Servlet can

    observe the input. This is different from a GUI, actually back-to-front, where the controller is

    waiting and acting on event-driven input from mouse or graphics tablet.

    The controller adapts the request to the model. The model represents, or encapsulates, an

    application's business logic or state. It captures not only the state of a process or system, but

    also how the system works. It notifies any observer when any of the data has changed. The

    model would execute the database query for example.

    Control is then usually forwarded back through the controller to the appropriate view. The

    view is responsible for the output of the model. A pure GUI view attaches to a model and

    renders its contents to the display surface. In addition, when the model changes, the viewport

    automatically redraws the affected part of the image to reflect those changes. A web

    application view just transforms the state of the model into readable HTML. The forwarding

    can be implemented by a lookup in a mapping in either a database or a file. This provides a

    loose coupling between the model and the view, which can make an application much easier

    to write and maintain.

  • 8/3/2019 jdbbc2.0

    12/18

    By dividing the web application into a Model, View, and Controller we can, therefore,

    separate the presentation from the business logic. If the MVC architecture is designed purely,

    then a Model can have multiple views and controllers. Also note that the model does notnecessarily have to be a Java Servlet. In fact a single Java Servlet can offer multiple models.

    The Java Servlet is where you would place security login, user authentication and database

    pooling for example. After all these latter have nothing to do with the business logic of the

    web application or the presentation.

    MVC in Java Server Pages

    Now that we have a convenient architucture to separate the view, how can we leverage that?

    Java Server Pages (JSP) becomes more interesting because the HTML content can be

    separated from the Java business objects. JSP can also make use of Java Beans. The business

    logic could be placed inside Java Beans. If the design is architected correctly, a Web

    Designer could work with HTML on the JSP site without interfering with the Java developer.

    The Model/View/Controller architecture also works with JSP. In fact it makes the initial

    implementation a little easier to write. The controller object is master Servlet. Every request

    goes through the controller who retrieves the necessary model object. The model may interact

    with other business entities such as databases orEnterprise Java Beans (EJB). The model

    object sends the output results back to the controller. The controller takes the results and

    places it inside the web browser session and forwards a redirect request to a particular Java

    Server Page. The JSP, in the case, is the view.

  • 8/3/2019 jdbbc2.0

    13/18

    The controller has to bind a model and a view, but it could be any model and associated anyview. Therein lies the flexibility and perhaps an insight to developing a very advanced

    dynamic controller that associates models to a view.

    The prior sections have concentrated on their being one controller, one model, and one view.

    In practice, multiple controllers may exist - but only one controls a section of the application

    at a time. For example, the administrator's functions may be controlled by one controller and

    the main logic controlled by another. Since only one controller can be in control at a given

    time, they must communicate. There may also be multiple models - but the controller takes

    the simplified view representation and maps it to the models appropriately and also translates

    that response back to the view. The view never needs to know how the logic is implemented.

    The case for separating presentation and logic

    Decoupling data presentation and the program implementation becomes beneficial since a

    change to one does not affect the other. This implies that both can be developed separately

    from the other: a division of labor. The look and feel of the web application, the fonts, the

    colours and the layout can be revised without having to change any Java code. As it should

    be. Similarly if the business logic in the application changes, for instance to improve

    performance and reliability, then this should not cause change in the presentation.

    A model-view-controller based web application written with only Java Servlets would give

    this decoupling. If the presentation changed then the Java code that generates the HTML, the

    presentation, in the view object only has to change.

  • 8/3/2019 jdbbc2.0

    14/18

    Similarly if the business logic changed then only the model object has to change. A web

    application built with MVC and Java Server Pages would be slightly easier if the business

    logic is contained only in Java Beans. The presentation (JSP) should only access these beans

    through custom tag libraries. This means that the Java Beans did not have Java code that

    wrote HTML. Your beans would only concern themselves with the business logic and not the

    presentation. The JSP would get the data from the Beans and then display the presentation(the "view"). Decoupling is therefore easy. A change to the implementation only necessitates

    changes to the Java Beans. A change to the presentation only concern changes to the relevant

    Java Server Page. With Java Server Pages a web designer who knows nothing about Java can

    concentrate on the HTML layout, look and feel. While a Java developer can concentrate on

    the Java Beans and the core logic of the web application.

    Structure

    The following diagram represents the Model-View-Controller pattern:

    Participants & Responsibilities

    The MVC architecture has its roots in Smalltalk, where it was originally applied to map the

    traditional input, processing, and output tasks to the graphical user interaction model.

    However, it is straightforward to map these concepts into the domain of multi-tier enterprise

    applications.

    Model - The model represents enterprise data and the business rules that govern access toand updates of this data. Often the model serves as a software approximation to a real-

    world process, so simple real-world modeling techniques apply when defining the model.

    View-The view renders the contents of a model. It accesses enterprise data through themodel and specifies how that data should be presented. It is the view's responsibility to

  • 8/3/2019 jdbbc2.0

    15/18

    maintain consistency in its presentation when the model changes. This can be achieved by

    using a push model, where the view registers itself with the model for change notifications,

    or a pull model, where the view is responsible for calling the model when it needs to retrieve

    the most current data.

    Controller - The controller translates interactions with the view into actions to be performedby the model. In a stand-alone GUI client, user interactions could be button clicks or menuselections, whereas in a Web application, they appear as GET and POST HTTP requests. The

    actions performed by the model include activating business processes or changing the state

    of the model. Based on the user interactions and the outcome of the model actions, the

    controller responds by selecting an appropriate view.

  • 8/3/2019 jdbbc2.0

    16/18

    ontents

    -What Is Model-View-Controller (MVC)?

    -Interaction Between MVC Components

    -Modifying the MVC Design

    -Using the Modified MVC-Issues With Application Design

    -Common Swing Component Listeners

    -Conclusion

    -For More Information

    What Is Model-View-Controller (MVC)?

    If you've programmed with graphical user interface (GUI) libraries in the past 10 years or so,

    you have likely come across the model-view-controller (MVC) design. MVC was first

    introduced byTrygve Reenskaug, a Smalltalk developer at the Xerox Palo Alto Research

    Center in 1979, and helps to decouple data access and business logic from the manner in

    which it is displayed to the user. More precisely, MVC can be broken down into three

    elements:

    Model - The model represents data and the rules that govern access to and updates ofthis data. In enterprise software, a model often serves as a software approximation of

    a real-world process.

    View - The view renders the contents of a model. It specifies exactly how the modeldata should be presented. If the model data changes, the view must update its

    presentation as needed. This can be achieved by using apush model, in which the

    view registers itself with the model for change notifications, or apull model, in whichthe view is responsible for calling the model when it needs to retrieve the most current

    data.

    Controller - The controller translates the user's interactions with the view into actionsthat the model will perform. In a stand-alone GUI client, user interactions could be

    button clicks or menu selections, whereas in an enterprise web application, they

    appear as GET and POST HTTP requests. Depending on the context, a controller may

    also select a new view -- for example, a web page of results -- to present back to the

    user.

    Sun BluePrints Catalog

    http://www.oracle.com/technetwork/articles/javase/index-142890.html#1http://www.oracle.com/technetwork/articles/javase/index-142890.html#1http://www.oracle.com/technetwork/articles/javase/index-142890.html#1http://www.oracle.com/technetwork/articles/javase/index-142890.html#2http://www.oracle.com/technetwork/articles/javase/index-142890.html#2http://www.oracle.com/technetwork/articles/javase/index-142890.html#2http://www.oracle.com/technetwork/articles/javase/index-142890.html#3http://www.oracle.com/technetwork/articles/javase/index-142890.html#3http://www.oracle.com/technetwork/articles/javase/index-142890.html#3http://www.oracle.com/technetwork/articles/javase/index-142890.html#4http://www.oracle.com/technetwork/articles/javase/index-142890.html#4http://www.oracle.com/technetwork/articles/javase/index-142890.html#4http://www.oracle.com/technetwork/articles/javase/index-142890.html#5http://www.oracle.com/technetwork/articles/javase/index-142890.html#5http://www.oracle.com/technetwork/articles/javase/index-142890.html#5http://www.oracle.com/technetwork/articles/javase/index-142890.html#6http://www.oracle.com/technetwork/articles/javase/index-142890.html#6http://www.oracle.com/technetwork/articles/javase/index-142890.html#6http://www.oracle.com/technetwork/articles/javase/index-142890.html#7http://www.oracle.com/technetwork/articles/javase/index-142890.html#7http://www.oracle.com/technetwork/articles/javase/index-142890.html#7http://www.oracle.com/technetwork/articles/javase/index-142890.html#8http://www.oracle.com/technetwork/articles/javase/index-142890.html#8http://www.oracle.com/technetwork/articles/javase/index-142890.html#8http://en.wikipedia.org/wiki/Trygve_Reenskaughttp://en.wikipedia.org/wiki/Trygve_Reenskaughttp://en.wikipedia.org/wiki/Trygve_Reenskaughttp://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/app-arch/app-arch2.htmlhttp://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/app-arch/app-arch2.htmlhttp://java.sun.com/blueprints/guidelines/designing_enterprise_applications_2e/app-arch/app-arch2.htmlhttp://en.wikipedia.org/wiki/Trygve_Reenskaughttp://www.oracle.com/technetwork/articles/javase/index-142890.html#8http://www.oracle.com/technetwork/articles/javase/index-142890.html#7http://www.oracle.com/technetwork/articles/javase/index-142890.html#6http://www.oracle.com/technetwork/articles/javase/index-142890.html#5http://www.oracle.com/technetwork/articles/javase/index-142890.html#4http://www.oracle.com/technetwork/articles/javase/index-142890.html#3http://www.oracle.com/technetwork/articles/javase/index-142890.html#2http://www.oracle.com/technetwork/articles/javase/index-142890.html#1
  • 8/3/2019 jdbbc2.0

    17/18

    Figure1.A Common MVC Implementation

    Interaction Between MVC Components

    This section will take a closer look at one way to implement Figure 1 in the context of anapplication in theJava Platform, Standard Edition 6(Java SE 6). Once the model, view, and

    controller objects are instantiated, the following occurs:

    1. The view registers as a listener on the model. Any changes to the underlying data ofthe model immediately result in a broadcast change notification, which the view

    receives. This is an example of the push model described earlier. Note that the model

    is not aware of the view or the controller -- it simply broadcasts change notifications

    to all interested listeners.

    2. The controller is bound to the view. This typically means that any user actions that areperformed on the view will invoke a registered listener method in the controller class.

    3. The controller is given a reference to the underlying model.Once a user interacts with the view, the following actions occur:

    1. The view recognizes that a GUI action -- for example, pushing a button or dragging ascroll bar -- has occurred, using a listener method that is registered to be called when

    such an action occurs.

    2. The view calls the appropriate method on the controller.3. The controller accesses the model, possibly updating it in a way appropriate to the

    user's action.

    4. If the model has been altered, it notifies interested listeners, such as the view, of thechange. In some architectures, the controller may also be responsible for updating theview. This is common in Java technology-based enterprise applications.

    http://www.oracle.com/technetwork/java/javase/overview/index.htmlhttp://www.oracle.com/technetwork/java/javase/overview/index.htmlhttp://www.oracle.com/technetwork/java/javase/overview/index.htmlhttp://www.oracle.com/technetwork/java/javase/overview/index.html
  • 8/3/2019 jdbbc2.0

    18/18