+ All Categories
Home > Documents > 1 Solution Jun10

1 Solution Jun10

Date post: 08-Aug-2018
Category:
Upload: vrunda-kapadia
View: 220 times
Download: 0 times
Share this document with a friend

of 20

Transcript
  • 8/22/2019 1 Solution Jun10

    1/20

    PMRC-June 20101-a Write a note on structure of web applications. [10 marks]

    Ans. In the Java EE architecture, web components and static web content files, such as images,are called web resources.

    A web module is the smallest deployable and usable unit of web resources. A Java EE web

    module corresponds to a web application as defined in the Java Servlet specification.In addition to web components and web resources, a web module can contain other files:

    Server-side utility classes, such as shopping carts

    Client-side classes, such as applets and utility classes

    Structure of web module:

    A web module has a specific structure. The top-level directory of a web module is thedocument rootof the application. The document root is where XHTML/HTML pages, client-side classes and archives, and static web resources, such as images, are stored. (Figure 1-1)

    The document root contains a subdirectory named WEB-INF, which can contain the following

    files and directories:

    classes: A directory that contains server-side classes: servlets, enterprise bean class

    files, utility classes, and JavaBeans components

    tags: A directory that contains tag files, which are implementations of tag librarieslib: A directory that contains JAR files that contain enterprise beans, and JAR

    archives of libraries called by server-side classes

    Deployment descriptors, such as web.xml (the web application deployment

    descriptor) and ejb-jar.xml (an EJB deployment descriptor)

    Figure 1-1: Web module structure

    A web module needs a web.xml file if it uses JavaServer Faces technology, if it must specify

    certain kinds of security information, or if you want to override information specified by webcomponent annotations.

    You can also create application-specific subdirectories (that is, package directories) in thedocument root or the WEB-INF/classes/ directory.

    1-b Explain the states in life cycle of midlet. [10 marks]

    Ans. A MIDlet is a MID (Mobile Information Device) Profile application. MIDP applications are

    represented by instances of the javax.microedition.midlet.MIDlet class. MIDlets have a

    specific life cycle, which is reflected in the methods and behavior of the MIDlet class.

    Application Management Software (AMS) is a piece of device-specific software which controls

    the installation, execution, and life cycle of MIDlets. The methods ofMIDlet class allow theAMS to create, start, pause, and destroy a MIDlet.

  • 8/22/2019 1 Solution Jun10

    2/20

    MIDlet States (Pause-Active-Destroyed):

    The states allow the AMS to manage the activities of multiple MIDlets within a runtimeenvironment. It can select which MIDlets are active at a given time by starting and pausingthem individually. The AMS maintains the state of the MIDlet and invokes methods

    (startApp(),pauseApp(),destroyApp() ) on the MIDlet to notify the MIDlet of change

    states. The MIDlet implements these methods to update its internal activities and resource

    usage as directed by the AMS. The MIDlet can initiate some state changes itself and notifies

    the AMS of those state changes by invoking the appropriate methods (notifyPaused(),

    notifyDestroyed()).

    A MIDlet goes through the following states:

    1. When the MIDlet is about to be run, an instance is created. The MIDlets constructoris run, and the MIDlet is in the Paused state.

    2. Next, the MIDlet enters the Active state after the AMS calls startApp().3. While the MIDlet is Active, the AMS can suspend its execution by calling pauseApp().

    This puts the MIDlet back in the Paused state. A MIDlet can place itself in the Paused

    state by calling notifyPaused().

    4. While the MIDlet is in the Paused state, the AMS can call startApp() to put it backinto the Active state.5. The AMS can terminate the execution of the MIDlet by calling destroyApp(), at whichpoint the MIDlet is destroyed and patiently awaits garbage collection. A MIDlet can

    destroy itself by calling notifyDestroyed().

    Figure 1-2: MIDlet life cycle

    resumeRequest():

    A MIDlet in the Paused state can call this method to signal to the AMS that it wants tobecome Active.

    Summary:

    State By calling method Called by

    Paused

    Constructor AMSpauseApp() AMSnotifyPaused() MIDlet

    Active startApp() AMS

    DestroydestroyApp() AMSnotifyDestroyed() MIDlet

    2-a Write note on servlet lifecycle. [10 marks]

    Ans. Servlets follow the life-cycle, which governs the multithreaded environment that Servlets runin and provides an insight to some of the mechanisms available to a developer for sharing

    server-side resources.The Servlets follow a three-phase life namely: (ISD)

  • 8/22/2019 1 Solution Jun10

    3/20

    1. Initialization,2. Service, and3. Destruction.

    This three-phase lifecycle is opposed to the single-phase life-cycle. Among the three phases,the Servlet typically performs only once with initialization and destruction while the service isperformed many times.

    Initialization Phase

    The first phase of the Servlet life-cycle is initialization. It represents the creation andinitialization of resources the Servlet may need in response to service requests. All Servlets

    must implement the javax.servlet.Servlet interface. This interface defines the init()

    method to match the initialization phase of a Servlet life-cycle. As soon as a container loads

    a Servlet, it invokes the init() method prior to servicing any requests.

    Service Phase

    The service phase is the second phase of a Servlet life-cycle. This phase of Servlet life-cycle

    represents all interactions along with requests until the Servlet is destroyed. The Servletinterface matches the service phase of the Servlet life-cycle to the service() method. The

    service() method of a Servlet is invoked once as per the request. Then, it is solely

    responsible for generating the response to that request. The Servlet specification defines theservice() method to take two parameters, which are:

    1. javax.serviet.ServletRequest and2. javax.servlet.ServletResponse object.

    These two objects represent a client's request for the dynamic resource and the Servlet's

    response to the client. By default, a Servlet is multithreaded which means that, typicallyonly one instance of a Servlet is loaded by a Web container at any given time. Initializationof this phase is done only once, and after that, each request is handled concurrently by

    threads executing the Servlet's service() method.

    Destruction PhaseThe destruction phase is the third and final phase of the Servlet life-cycle. The destructionphase of the Servlet life-cycle represents the removal of the Servlet from the Container. In

    this case, the Servlet interface defines the destroy() method to correspond to the

    destruction life-cycle phase. When time comes that a Servlet is about to be removed, a

    container calls the destroy() method.

    At the time of creation of the Servlet for the first time, its init() method is invoked, and

    therefore, init() can be found where you put the one-time setup code. After this, each user

    request results to a thread. This calls the service() method of the previously created

    instance. The service() method then calls doGet(), doPost(), or another doXxx()

    method. However it depends upon the type of HTTP request it receives. Finally, when serverdecides to unload a Servlet, it first calls the Servlets destroy() method.

    The init() Method

    As mentioned earlier, the init() method is called when the Servlet is created for the first

    time. It is not called again for other user request. Therefore, it is used for one-time

    initializations only, just as with the init() method of applets. This Servlet is normally

    created when a user invokes a URL for the first time corresponding to the Servlet, but theServlet is loaded on the server when the container maps the user request to the Servlet, The

    init() method definition looks like this:public void init() throws ServletException{

    // Initialization code...}

    Reading the server-specific initialization parameters is one of the most common tasks thatinit() method performs. For example, the Servlet might need to know different aspects

  • 8/22/2019 1 Solution Jun10

    4/20

    such as database settings, password files, server-specific performance parameters, hit countfiles, or serialized cookie data from previous requests. Initialization parameters let the

    Servlet to deploy (for example the server administrator) and also customize the Servlet.

    The service() Method

    As per the service() method, each time when the server receives a request for a Servlet,

    the server spawns a new thread and calls for service(). The service() method checks the

    HTTP request type (GET, POST, PUT, DELETE) and calls doGet(), doPost(), doPut(),

    doDelete() as appropriate. Here, a GET request results from a normal request for a URL or

    from an HTML form that has no METHOD specified. The POST request results from an HTMLform that specifically lists POST as the METHOD. For example:

    Other HTTP requests are generated only by the custom clients.Now, if you have a Servlet that needs to handle both POST and GET requests identically, you

    may be tempted to override service() directly rather than implementing both doGet() and

    doPost(). However, remember, this is not a good idea. Instead of it, you just have to stick

    to doPost() call doGet() (or vice versa), as shown here:@Overridepublic void doGet(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException){

    // Servlet code}

    @Overridepublic void doPost(HttpServletRequest request, HttpServletResponse response)

    throws ServletException, IOException{

    doGet(request, response);

    }

    The doGet(), doPost(), and doXxx() methods

    During the entire request and response process, most of the time, you only care about GET

    or POST requests. Therefore, you override doGet() and/or doPost(). However, if you want

    to, you can also override doDelete() for DELETE requests, doPut() for PUT, doOptions()

    for OPTIONS, and doTrace() for TRACE.

    The destroy() Method

    In the destroy() method, the server may decide to remove a previously loaded Servlet

    instance, perhaps because it is explicitly asked to do so by the server administrator. It alsomay do it perhaps because the Servlet is sitting idle for a long time. Before it removes a

    previously loaded Servlet instance, it calls the Servlet's destroy() method. This methodgives your Servlet a chance to close database connections, halt background threads, writecookie lists or hit counts to disk, and perform other such cleanup activities.

    2-b Describe model-2 architecture and state its advantages. [10 Marks]

    Ans. The drawbacks in the Model-1 architecture led to the introduction of a new model, calledModel-2. The Model-2 architecture was targeted at overcoming the drawbacks of Model-1and helping developers in design more powerful Web applications. Figure 2-1 shows the

    Model-2 architecture.

    Initially, JSPs were introduced as an alternative to Sevlets, as JSP is more powerful than theServlet. Developers soon realized that JSPs and Servlets can be used together to develop aWeb application. Servlets handle the control flow while JSPs handle the HTML page creation.

    The approach of using JSPs and Servlets together evolved as the Model-2 architecture. Inthis type of design model, the presentation logic is separated from the business logic.

  • 8/22/2019 1 Solution Jun10

    5/20

    Figure 2-1: Model-2 Architecture

    Model-2 architecture is based on the MVC design model. The Model-2 architecture (or MVC)

    contains the following components:Model Represents enterprise data and business rules that specify how data isaccessed and updated. Model is generally implemented by using JavaBeans.

    View Renders the contents of a model. The View component accesses enterprisedata through the Model component and specifies how that data should be presented.The View component is designed by using JSP.Controller Receives HTTP requests. The Controller component receives requestsfrom client, determines the business logic to be performed, and delegates the

    responsibility for producing the next phase of the user interface to an appropriateView component. The Controller has complete control over each View, implying thatany change in the Model component is immediately reflected in all the Views of an

    application. The Controller component is implemented by Servlets.

    So far, Model-2 is the most successful development model used to develop Web applications.It not only overcomes the limitations of the Model-1 architecture, but provides new features

    that have their own advantages, such as:

    Allows use of reusable software components to design the business logic. Therefore,these components can be used in the business logic of other applications.

    Offers great flexibility to the presentation logic, which can be modified withoutaffecting the business logic.Allows each software component to perform a different task, making it easy to designan application by simply embedding these components in the application.

    3-a Write a MIDP application to draw following image as mutable image. [10 Marks]

    Ans. Will be updated soon...

    3-b Write a note on image class, also state the types of images that can be included oncanvas. [10 Marks]

    Ans. Instances of the javax.microedition.lcdui.Image class represent images in MIDP. The

    specification dictates implementations be able to load images files in PNG format. This

    format supports both a transparent color and lossless compression.

    Package: Class definition:javax.microedition.lcdui public class Image

    extends ObjectImage class has no constructors, but the Image class offers a handful of createImage()

  • 8/22/2019 1 Solution Jun10

    6/20

    factory methods for obtaining Image instances.public static Image createImage(String name)

    This attempts to create an Image from the named file, which should be packaged inside theJAR that contains your MIDlet. You must use an absolute pathname or the image file will not

    be found.

    public static Image createImage(byte[] imagedata,int imageoffset, int imagelength)

    This method creates an Image using data in the supplied array. The data starts at the given

    array offset, imageoffset, and is imagelength bytes long.

    public static Image createImage(InputStream stream)

    This creates an Image from an InputStream.

    Types of images

    Images may be mutable or immutable.

    Immutable ImagesThe createImage() methods described previously return immutable Images.

    Mutable Image

    Mutable Images can be modified by calling getGraphics() and using the returned Graphics

    object to draw on the image. If you try to call getGraphics() on an immutable Image, an

    IllegalStateException will be thrown.

    To create a mutable Image, use the following method:public static Image createImage(int width, int height)

    The type of images that can be included on canvas are:1. Immutable Images2. Mutable Images

    4-a What is event handling? Elaborate the types of event handling in J2ME. [10 Marks]

    Ans. An action or occurrence detected by a program is called event. When a user interacts with a

    MIDlet loaded on a mobile information device, some events are generated. For example, if

    the user selects Save from the File menu, the application is notified of this action and

    responds to the generated event.

    There are two MIDP user interface APIs: high-level and low-level. Therefore, there are two

    kinds of events:1. High-level (such as selecting an item from a list) and2. Low-level (such as pressing a key on the device).

    Event handling:Event handling refers to handling or responding to the events. That is providing an action

    (program code) whenever an event occurs.

    Types of event handling in J2ME

    Depending on the event, Event handling can be divided into two groups:1. High-level event handling2. Low-level event handling

    High-level event handling:

    Handling events in the high-level API is based on a listener model. Screen and Canvas

    objects can have listeners for commands. For an object to be a listener, it must implement

    the CommandListener interface.

    You add commands to a displayable object with the addCommand method, and register a

  • 8/22/2019 1 Solution Jun10

    7/20

    listener with the setCommandListener method. Both of these methods are part of the

    Displayable class and they are inherited by Screen and Canvas.

    The CommandListener Interface

    The CommandListener interface is for MIDlets that need to receive high-level events from

    the implementation. This interface has one method that a listener must implement, which isthe commandAction method.public void commandAction(Command c, Displayable d)

    The c parameter is a command object that identifies the command (if any) that has been

    added to Displayable with the addCommand method. The d parameter is the displayable

    where the event occurred.

    Low-level event handling:

    If you use the Canvas class to write applications to access low-level input events or to issue

    graphics calls for drawing to the display, you must handle low-level events. Game

    applications are likely to use the Canvas class because it provides methods to handle game

    actions and key events. The key events are reported with respect to key codes that are

    directly bound to concrete keys on the device.The Canvas class, which is a subclass ofDisplayable, allows the application to register a

    listener for commands, but it requires applications to subclass it first. Also, unlike screens

    that allow the application to define listeners and register them with instances of the Screen

    class, the Canvas class does not allow this because several new listener interfaces need to

    be created with one for each kind of event.

    Key Events

    Every key for which events are reported is assigned a key code. The MIDP defines the

    following key codes in the Canvas class:KEY_NUM0, KEY_NUM1, ..., KEY_NUM9, KEY_STAR, KEY_POUND

    Basically, these are the keys 0..9, *, and #. Other keys might exist on some devices, but for

    portability, applications should use only the standard key codes.

    Game Actions

    If your application needs arrow key and gaming-related events, use game actions instead ofkey codes. MIDP defines the following game actions:

    DOWN

    LEFT

    RIGHT

    FIRE

    GAME_A

    GAME_B

    GAME_CGAME_D

    While each key code is mapped to one game action, a game action can be associated with

    more than one key code. The translation between the two is done with the getKeyCode and

    getGameAction methods.

    Event Delivery Methods

    The following methods are available for handling low-level events.protected void keyPressed(int keyCode)

    protected void keyReleased(int keyCode)

    protected void keyRepeated(int keyCode)

    protected void pointerPressed(int x, int y)

    protected void pointerDragged(int x, int y)protected void pointerReleased(int x, int y)

  • 8/22/2019 1 Solution Jun10

    8/20

    protected void showNotify()protected void hideNotify()

    protected abstract void paint(Graphics g)

    commandAction() method of the CommandListener interface

    5-a Obfuscator [5 Marks]Ans. Why required?

    Because MIDP devices have so little memory, MIDlet suites should be as compact aspossible.

    Purpose:An obfuscator is a useful tool for minimizing the size of MIDlet suite JARs.

    How it does this?

    Obfuscators, originally designed to foil attempts to reverse engineer compiled bytecode,perform any combination of the following functions:

    Renaming classes, member variables, and methods to more compact namesRemoving unused classes, methods, and member variables

    Inserting illegal or questionable data to confuse decompilersExcept for the last point, obfuscators can significantly reduce the size of compiled classes ina MIDlet suite JAR.

    When to use?Obfuscate the classes before they are preverified.

    5-b GameCanvas [5 Marks]

    Ans. The GameCanvas class provides the basis for a game user interface. GameCanvas extendsjavax.microedition.lcdui.Canvas with methods for animation and key state polling.

    GameCanvas offers two main advantages over Canvas.

    1.

    Your application has control over exactly when the display is updated, instead ofhaving to wait for the system software to call paint().

    2. You can control what region of the screen is updated. GameCanvas gives yourapplication very specific control of display updates.

    Using GameCanvas:

    To use GameCanvas, you subclass it. To draw on the screen, you use the Graphics returned

    from getGraphics(). When you want updates to appear on the screen, call

    flushGraphics(), which does not return until the screen is updated. For more specific

    updates, use the method flushGraphics(int x, int y, int width, int height), which

    only updates a region of the screen.

    To subclass GameCanvas, you need to call its protected constructor from your subclasss

    constructor. This constructor accepts a single boolean argument, which indicates whetherthe normal key event mechanism should be suppressed for the GameCanvas instance. The

    normal key event mechanism refers to the callback mechanism of keyPressed(),

    keyReleased(), and keyRepeated().

    Key state polling

    GameCanvas offers an alternative method for responding to key presses, which are expected

    to be the way the user controls the game. Instead of passively waiting for the key event

    callbacks defined in Canvas, GameCanvas offers a method that returns the current state of

    the keys:public int getKeyStates()

    The returned integer uses one bit to represent each of the nine game actions. A one bit

    indicates a key press, while a zero bit indicates no key press. Each of the bits is represented

    by a constant in the GameCanvas class as:

  • 8/22/2019 1 Solution Jun10

    9/20

    GameCanvas Bit Constants Corresponding GameCanvas Action ConstantsUP_PRESSED UPDOWN_PRESSED DOWN

    LEFT_PRESSED LEFTRIGHT_PRESSED RIGHT

    FIRE_PRESSED FIREGAME_A_PRESSED GAME_A

    GAME_B_PRESSED GAME_B

    GAME_C_PRESSED GAME_C

    GAME_D_PRESSED GAME_D

    By grabbing the current state of the keys (a technique called polling), you can respond touser actions within the game loop instead of relying on the event callback methods, which

    run in a different thread.

    5-c CLDC 1.0 and 1.1 [5 Marks]

    Ans. CLDC 1.0 CLDC 1.1

    CLDC 1.0 does not support floating-pointtypes at all. That means there are no floator double primitive types. Thecorresponding wrapper types,

    java.lang.Float and java.lang.Double, havealso been eliminated.

    CLDC 1.1 includes floating-point support, theprimitive types double and float, and thewrapper types Double and Float. Various otherclasses have been modified for floating-point

    support in CLDC 1.1, but the changes areminor.

    The interrupt() method is not present in

    the java.lang.Thread class.

    The interrupt() method is available.

    In the String class valueOf() static

    methods that convert between floating-point primitives and Strings is eliminated.

    The valueOf() method is available.

    StringBuffers append() and insert()

    methods do not include overrides forfloating-point types.

    These methods are available.

    Minimum memory 160 KB. Minimum memory budget has been raised to192 KB, mainly because of the added floatingpoint functionality.

    Weak reference support not present Weak reference support (small subset of theJava SE weak reference classes) hasbeen added

    Not present. New error class, NoClassDefFoundError , has

    been added.

    Methods involving floating point numbershave been removed from Math class.

    As it supports floating point types, includes

    several more methods in java.lang.Math.

    5-d Bluetooth [5 Marks]

    Ans. Bluetooth is a radio connectivity technology designed for creating Personal Area Networks(PANs). It is all about connecting to things that are next to you, wirelessly. Java APIs forBluetooth is an optional API that adds radio PAN connectivity to MIDP applications.

    The Bluetooth radio hardware operates in the 2.45-gigahertz Industrial, Scientific, andMedical (ISM) frequency band, allowing for unlicensed operation worldwide. Bluetoothnetworks are formed ad hoc and dynamically, when Bluetooth-enabled devices come intoproximity of one another. Technically, a Bluetooth network is a piconet, and it can consist of

    one master device and up to seven slave devices. The number of devices supported can beexpanded beyond eight when a master device on one piconet acts as a slave in another,working as a bridge. However, all these hardware and radio protocol details are transparentto the application developer using the Java API for Bluetooth.

    In above Figure, note that a single Bluetooth device can be offering multiple services at the

  • 8/22/2019 1 Solution Jun10

    10/20

    same time. Bluetooth devices can also support both client and server functionalitysimultaneously. On a hardware level, a single master Bluetooth device can synchronize up to

    seven slave devices in a Bluetooth piconet.

    Devices are the discoverable entities in a Bluetooth network. The discovery process is calledan inquiry in Bluetooth lingo. You need to perform an inquiry to discover devices in your PAN

    before finding out what services the devices are offering.

    Each service in a Bluetooth network is uniquely identified by a UUID. Any particular device inthe Bluetooth network can be offering zero or more services. The same service may be

    offered by more than one device in the network. For example, one can easily imagine aprinting service offered by a number of printers in the same room.

    The Bluetooth specification describes a number of interoperability profiles, much like the role

    of the profiles in J2ME, for implementers of Bluetooth devices. These profiles specifyinteroperability standards between different implementations. The Service ApplicationDiscovery Profile (SADP) enables applications running on Bluetooth devices to discover

    services. The Java API for Bluetooth works over this profile to give you the high-level abilityto discover services (with or without having to explicitly discover the devices).

    At the lower level, the actual protocol used for service discovery between devices is called

    the Service Discovery Protocol (SDP).

    Other than the SADP, JSR 82compliant devices must also support the Generic AccessProfile, or GAP (for access to device remotely), and the Serial Port Profile, or SPP (serial port

    emulation for sending and receiving streamed data between devices).

    Figure: Bluetooth device interactions

    6-a What are the frameworks supported by JEE5? [10 Marks]

    Ans. Different frameworks supported by Java EE 5:

    1. Java Server Faces2. Hibernate3. Seam

  • 8/22/2019 1 Solution Jun10

    11/20

    4. Struts5. Spring

    Hibernate

    Figure: The Hibernate architectureHibernate provides a framework for mapping an object-oriented domain model to arelational database. The primary feature of Hibernate is to map JavaBean classes todatabase tables. Hibernate helps in querying and retrieving data from database tables. In

    addition, Hibernate generates the SQL calls and so the developers do not need to provideJava code for handling resultsets. Hibernate ensures that a Web application is portable with

    all SQL supported databases. Hibernate also provides persistence feature for Plain Old JavaObjects (POJOs). Hibernate can be used both standalone Java applications and in Java EEapplications using Servlets or EJB session beans.

    Hibernate is a lightweight Object/Relational mapping (ORM), which is a technique for

    mapping an object model to a relational model. Hibernate handles mapping from Javaclasses to database tables, and provides API for querying and retrieving data from database.This helps to write sophisticated query by using Hibernate Query Language (HQL) thatreduces the time spent in handling data by using SQL and JDBC. It relieves the developer

    from 95 percent of a common data persistence related programming tasks, compared tomanual coding with SQL and the JDBC API.

    The Hibernate architecture

    The Hibernate architecture consists of two technologies Hibernate and Java EE. Hibernatemakes use of the existing Java APIs, including JDBC (Java Database Connectivity), JavaTransaction API (JTA), Java Naming and Directory Interface (JNDI). JDBC loads databasedriver and establish a connection for accessing relational database. It uses all types ofdatabase driver that are supported by Hibernate. JNDI and JTA allow Hibernate to beintegrated with application servers. Figure shows the architecture of Hibernate.

    Hibernate Query Language (HQL)

    HQL is an easy-to-learn and powerful query language designed as an Object-orientedextension to SQL that bridges the gap between the Object-oriented systems and relationaldatabase. The syntax of HQL is very similar to SQL. It has a rich and powerful Object-oriented query language available with the Hibernate object/relational mapping (ORM). The

    term ORM refers to the technique of mapping objects and databases. The data from Object-oriented systems are mapped to relational databases with a SQL-based Schema

  • 8/22/2019 1 Solution Jun10

    12/20

    HQL queries are case-insensitive, but the names of Java classes and properties are case-sensitive. It is used to execute queries against database. Hibernate automatically generates

    the SQL query and executes it, if HQL queries are used in the application. HQL uses classesand properties instead of tables and columns. HQL supports polymorphism and associationsand requires less coding than SQL. It also supports many other SQL statements and

    aggregate functions, such as sum(), max() and clauses, such as group by and order by.

    Struts

    Struts is a Web application framework based on Model-View-Controller (MVC), and is used to

    build high-performance and business-oriented Web applications.

    Struts is an open source framework for creating Java Web applications. Since Struts 2 isbased on the MVC architecture; it separates the business logic code, page design code, and

    navigational code into three different components called model, view, and controller.

    Figure: MVC Pattern in Struts 2

    MVC 2 Design pattern for Struts 2

    The Struts 2 framework follows the MVC 2 design pattern, where model, view, and controller

    components are represented by Action, Result and FilterDispatcher classes,

    respectively. Figure shows the implementation of the MVC pattern by Struts 2 components.

    The steps for the work flow in Struts 2 are as follows:The user sends a request through a user interface provided by the view, which

    further passes this request to the controller represented by FilterDispatcher class

    in Struts 2.

    The controller servlet filter receives the input request coming from the user throughthe interface provided by the view, instantiates an object of the suitable action class,and executes different methods over this object.If the state of model is changed, all the associated views are notified about thechanges. Then the controller selects the new view to be displayed according to theresult code returned by the action class.The view presents the user interface. The view queries about the state of the model

    to show the current data, which is retrieved from the action class.

    Struts 2 Architecture

    Since Struts 2 contains various framework components such as built-in classes, servlets, and

  • 8/22/2019 1 Solution Jun10

    13/20

    Struts tags. All framework components work together in a standard manner. Thearchitecture of Struts 2-based application defines the relationship and interaction between

    these framework components.

    Components of a Struts 2-Based Application

    The architecture of a Struts 2-based application has been shown in Figure. The businesslogic component allows the model layer to store only the state of a Web application. The

    components created in the new group are known as action classes.

    Controller

    The controller receives the requests from users and decides where to send the request. Themain goal of the controller is to map the request URI to an Action class using the mappings

    provided in the Struts-config.xml There is a single Controller Servlet and all requests go

    through this Servlet which is provided by the framework itself.

    The controller component available in Struts 2 framework is the ActionServlet class that

    represents the controller in the MVC design pattern. ActionServlet class implements both

    the front controller and singleton pattern. The front controller pattern allows for a centralized

    access point for presentation-tier request handling, the singleton pattern provides a singleinstance of an object.

    The ActionServlet instance selects and invokes an Action class to perform the requested

    business logic. The action classes do not produce the next page of the user directly; rather itis the duty of the RequestDispatcher class to forward the control to an appropriate JSP

    page. Generally, the Servlet engine uses RequestDispatcher.forward() method of the

    Servlet API to perform this task.

    The Struts-config.xml File

    The Struts-config.xml file contains the transformation and configuration information for

    the Struts application. It provides information regarding various Struts resources, suchasaction, classes, and interceptors.

    Action Classes

    Action classes implement the business logic, or, in other words, they behave as wrappersaround the business logic and interact with the model of the application. They are basicallyresponsible for executing the business service according to user requests.

    ModelModel represents the data objects with the help of JavaBeans. In Struts 2, the model is

    represented by org.apache.struts.action.ActionForm class, which provides the methods

    to get and set data fields with methods to validate the data. The relation between user

    requests, the action class to be invoked, the ActionForm class to be used, and the next

    possible views are defined in the struts-config.xml file using appropriate mappings.

    View

    The view represents a JSP or HTML page. The presentation semantics are encapsulatedwithin a view. There is no business logic available in the view.

    6-b Write a note on web centric approach and EJB centric approach of creating web

    applications. [10 Marks]

    Ans. Four general types of Web applications can be implemented with the J2EE platform:1. Basic HTML,2. HTML with basic JSP pages,3. JSP pages with JavaBeans components, and4. Highly-structured applications that use modular components and enterprise beans.

    The first three types of applications are considered to be Web-centric, whereas the last typeis EJB-centric.

  • 8/22/2019 1 Solution Jun10

    14/20

    Basic HTML

    A web application contains HTML pages to provide static content. Such types of applicationsare considered as basic Web applications. The HTML pages of such Web applications can also

    access various other resources such as images or text files.

    Applications with Basic JSP Pages and Servlets

    In these simple applications, some pages display static HTML content. Where necessary todisplay dynamic content, (for example, content generated using data from a database), aJSP page or servlet should contain code to connect to the database and retrieve the data.

    As the complexity of the application increases, a model that allows for more modularizationof components would be useful.

    Figure: Applications with Basic JSP Pages and Servlets

    Figure : Process Flow of JSP Pages with Modular Components

    Applications with Modular ComponentsWhen developing Web applications with dynamic content and a large degree of userinteraction, you should use JSP pages with JavaBeans components, custom tags, andincluded JSP pages. These three types of components can be used to generate content,

    process requests, and handle the display of personalized content.

  • 8/22/2019 1 Solution Jun10

    15/20

    Figure: Reusable Components in a JSP Page

    Modular Components in a JSP Page

    JSP pages can be created using a variety of components. Used consistently, thesecomponents provide a common look and feel throughout an application.

    Processing Requests with Modular Components

    Processing user requests is another important aspect of Web application behavior that canbe effectively implemented using modular components. Applications that use modularcomponents for request processing will be easier to develop and maintain. Figure depictshow data from a form can be processed in a Web application.

    Figure: Processing a Request with Reusable Components

    Displaying Personalized Content

    The data used to generate the content of this page includes data entered by the user. The

    page can also include other information personalized to the user's needs. After setting up anaccount, the users can be taken directly to a personalized page each time they log into the

    application.

    As web centric application design becomes larger, the level of complexity increases. More of

  • 8/22/2019 1 Solution Jun10

    16/20

    the developer's time may be for work on the system-level issues such as managing theconnection pool and application state and transaction management. Migrating to an EJB-

    centric design will allow the developer to stay focused on the application design.

    EJBCentric Applications

    An EJB-centric application extends the modular, component-based application describedearlier, with two main differences.

    1. First, this design uses a front component for a controller.2. Second, data represented by the JavaBeans components is maintained by enterprise

    beans.This design provides flexibility, manageability, and separation of developer responsibilities.

    Flexibility is provided by using a MVC architecture in conjunction with a front component.

    Model

    The model represents the data on which an application is based. In an EJB-centricapplication, enterprise beans hold the data needed by the application. All modifications to

    the data occur thorough events sent to the EJB controller.

    View

    A view presents the data represented by the model in a way that's targeted at a specifictype of client. Most enterprise applications will support a number of different views. Thesame model could have a Visual Basic client view, a Swing view, or a Web view. The view for

    a Web application consists of JSP files, which have sole responsibility for displaying themodel data. The JSP files can contain JavaBeans components, custom tags, or included JSPpage components

    Controller

    To ensure that a Web application runs smoothly with the Model-View-Controller architecture,a central point of control is necessary. This is provided by using a front component and somehelper classes. This controller maintains the data in the model and ensures that the data

    presented by the view is consistent with the corresponding model.

    The controller provides a level of control that isn't possible by using statically-linked Webpages. With static pages, there is no guarantee that all users of a Web site will use thepreferred point of entry. Without a single entry point, it is difficult to ensure that a Web

    application will be properly initialized to handle a user's request. A controller can alsoprovide a way to prevent deep linking to information within a site.

    Controller Components

    The controller is made up of many components responsible for taking data posted in an

    HTTP request and converting it into an event to update the model data. The componentsthat make up the controller include: front component, request processor, Web controller,and EJB controller.

    Figure shows a controller that converts an HTTP request into an event that updates theapplication model data. This figure shows the flow of an HTTP request from an HTTP client tothe controller mechanism. As mentioned before, all requests from HTTP clients go to a frontcomponent. The requests are then sent to the request processor, which converts them to

    events and then sends the events to the Web controller. The Web controller acts as a proxyand sends the event to the EJB controller, which processes the event and updates the modeldata maintained by the enterprise beans accordingly.

    All business logic is handled by the EJB controller and enterprise beans. The EJB controllerreturns a set of changed models to the Web controller. The Web controller then sends themodel update events to the respective views. The views then contact the enterprise beans

    that they mirror and update their data from the enterprise beans. The JavaBeanscomponents do not change any data; they only read the model data contained by the

    enterprise beans when they receive the model update notification.

  • 8/22/2019 1 Solution Jun10

    17/20

    Figure: Controller Conversion of HTTP Request to Model Change Event

    7-a Compare an applet with midlet. [5 Marks]

    Ans. Applet MIDlet

    A Java applet is a special kind of Javaprogram that a browser enabled with Javatechnology can download from theinternet and run.

    A MIDlet is a MID (Mobile Information Device)Profile application that runs on mobile devices.

    An applet must be a subclass of thejava.applet.Applet class.

    A MIDlet must be a subclass of thejavax.microedition.midlet.MIDlet class.

    Browser needs Java Plug-in software torun applet.

    Mobile device need to port CLDC/MIDP to runMIDlet.

    The browser's Java Plug-in softwaremanages the lifecycle of an applet.

    Mobile Devices application managementsoftware manages the lifecycle of a MIDlet.

    Include tag in the html page to

    run applet in the browser, whichdownloads the class file and runs it.

    Class files are packaged into JAR file and then

    deployed on the mobile device to run theMIDlet.

    Following methods define life cycle of

    applet:init()start()

    stop()destroy()

    Following methods define life cycle of applet:

    startApp()pauseApp()destroyApp()

    notifyPaused() and notifyDestroyed()

    7-b Explain the implementation ofCommandListener and ItemStateListener with an

    example. [10 Marks]

    Ans. CommandListener:

    CommandListener is an interface with a single method. This method is called when a

    command on the Displayable is invoked by the user:public void commandAction(Command c, Displayable d)

    To register the listener with a Displayable, use the following method:public void setCommandListener(CommandListener l)

    ItemStateListener:

  • 8/22/2019 1 Solution Jun10

    18/20

    Most items in a Form fire events when the user changes them. Your application can listen for

    these events by registering an ItemStateListener with the Form using the following

    method:public void setItemStateListener(ItemStateListener iListener)

    ItemStateListener is an interface with a single method. This method is called every time

    an item in a Form is changed:public void itemStateChanged(Item item)

    Implementation:

    Following code creates a Form with two items, an interactive Gauge and a StringItem. As

    you adjust the Gauge, its value is reflected in the StringItem using the ItemStateListener

    mechanism.Import javax.microedition.midlet.*;import javax.microedition.lcdui.*;

    public class GaugeTrackerMidletextends MIDletimplements ItemStateListener, CommandListener {

    Display display;Form form;Gauge gauge;StringItem stringItem;Command exitCommand;

    public GaugeTrackerMidlet() {int initialValue = 3;form = new Form(GaugeTracker);exitCommand = new Command(Exit, Command.EXIT, 2);gauge = new Gauge(GaugeTitle, true, 5, initialValue);stringItem = new StringItem(Value = , String.valueOf(initialValue));

    form.addCommand(exitCommand);form.setCommandListener(this);

    form.append(gauge);form.append(stringItem);form.setItemStateListener(this);

    }

    public void itemStateChanged(Item item) {if (item == gauge)stringItem.setText(String.valueOf(gauge.getValue()));

    }

    public void commandAction(Command c, Displayable s) {if (c == exitCommand)

    notifyDestroyed();}

    public void startApp() {if(display == null) display = Display.getDisplay(this);display.setCurrent(form);

    }

    public void pauseApp() {}

    public void destroyApp( oolean unconditional) {}

  • 8/22/2019 1 Solution Jun10

    19/20

    }

    7-c Explain the MVC architecture. [5 Marks]

    Ans. MVC (Model-View-Controller) architecture separates the core business model functionality ofthe web application from the presentation and control logic of the interface-specificapplication. With this arrangement, it is possible to have multiple use of the same data

    model of the Web application. Under MVC architecture, data (Model) and user interface(View) are separated from each other so that any change in the user interfaces does notaffect the data in the database, and vice versa.

    Describing the Model Component

    The model component displays the data on which an application is based. In a webapplication, JavaBeans hold the data needed by a web application to process user queries.Events sent to Web Controller serves the basis for all modifications to the data. The Modelcomponent represents the data and the business logic of the application and has no concernwith the presentation logic of the application.

    Describing the View Component

    A View provides the Graphical User Interface (GUI) for Model. A user interacts with theapplication through View, which represents the information based on Model, and allows theuser to alter data. A Model can have multiple Views.

    Model manages the database, the content of which can be changed and updated frequently.Any change in the database must be reflected to the user as soon as possible. Therefore, aview communicates with a Model to get information if any change takes place in thedatabase. Users who want to modify the content of a Model do not communicate with itdirectly. Instead, they communicate with the Model through a View, which communicateswith the Controller regarding the user input. The Controller then makes the required changesin the Model and also notifies the other associated Views.

    Describing the Controller Component

    The Controller component controls all the Views associated with a Model. When a userinteracts with the View component and tries to update the Model, the Controller componentinvokes various methods to update the Model. The Controller of an application also controls

    the data flow and transfers the requests between Model and View.

    Figure shows the interaction among the various MVC components:

    Figure: MVC architecture

    Figure shows that View uses the query methods of the Model to retrieve content. In addition,

  • 8/22/2019 1 Solution Jun10

    20/20

    whenever a user sends a request, it passes through the Controller. Then, the controllerintercepts the request from the View and passes it to the Model for appropriate action.

    Controller, which is a Servlet, stores all the business logic. A View, normally a JSP page,contains all the code for representation. A model is implemented by using a pure Java orbean class. The different components in the application, such as Controller, Model, and View,are reusable and make applications highly scalable.


Recommended