You are on page 1of 20

PMRC-June 2010

1-a Ans. Write a note on structure of web applications. [10 marks] 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 the document root of the application. The document root is where XHTML/HTML pages, clientside 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 libraries lib: 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 web component annotations. You can also create application-specific subdirectories (that is, package directories) in the document root or the WEB-INF/classes/ directory. 1-b Ans. Explain the states in life cycle of midlet. [10 marks] 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 of MIDlet class allow the AMS to create, start, pause, and destroy a MIDlet.

MIDlet States (Pause-Active-Destroyed): The states allow the AMS to manage the activities of multiple MIDlets within a runtime environment. It can select which MIDlets are active at a given time by starting and pausing them 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 constructor is 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 back into the Active state. 5. The AMS can terminate the execution of the MIDlet by calling destroyApp(), at which point 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 to become Active. Summary: State By calling method Called by Constructor AMS pauseApp() Paused AMS notifyPaused() MIDlet startApp() Active AMS destroyApp() AMS Destroy notifyDestroyed() MIDlet

2-a Ans.

Write note on servlet lifecycle. [10 marks] Servlets follow the life-cycle, which governs the multithreaded environment that Servlets run in 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)

1. Initialization, 2. Service, and 3. 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 is performed many times. Initialization Phase The first phase of the Servlet life-cycle is initialization. It represents the creation and initialization 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 Servlet interface 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 the service() method to take two parameters, which are: 1. javax.serviet.ServletRequest and 2. 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, typically only one instance of a Servlet is loaded by a Web container at any given time. Initialization of this phase is done only once, and after that, each request is handled concurrently by threads executing the Servlet's service() method. Destruction Phase The destruction phase is the third and final phase of the Servlet life-cycle. The destruction phase 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 server decides 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 the Servlet 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 that init() method performs. For example, the Servlet might need to know different aspects

such as database settings, password files, server-specific performance parameters, hit count files, 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 HTML form that specifically lists POST as the METHOD. For example: <html> <form name=myform method=post> 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: @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException) { // Servlet code } @Override public 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 also may 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 method gives your Servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities. 2-b Ans. Describe model-2 architecture and state its advantages. [10 Marks] The drawbacks in the Model-1 architecture led to the introduction of a new model, called Model-2. The Model-2 architecture was targeted at overcoming the drawbacks of Model-1 and 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 the Servlet. Developers soon realized that JSPs and Servlets can be used together to develop a Web 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. In this type of design model, the presentation logic is separated from the business logic.

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 is accessed and updated. Model is generally implemented by using JavaBeans. View Renders the contents of a model. The View component accesses enterprise data 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 requests from client, determines the business logic to be performed, and delegates the responsibility for producing the next phase of the user interface to an appropriate View component. The Controller has complete control over each View, implying that any 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 without affecting the business logic. Allows each software component to perform a different task, making it easy to design an 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. 3-b Ans.

Will be updated soon... Write a note on image class, also state the types of images that can be included on canvas. [10 Marks] 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 Object Image class has no constructors, but the Image class offers a handful of createImage()

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 the JAR 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 Images The 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 Images 2. Mutable Images 4-a Ans. What is event handling? Elaborate the types of event handling in J2ME. [10 Marks] 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) and 2. 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 handling 2. 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

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 is the 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 of Displayable, 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 of key codes. MIDP defines the following game actions: DOWN LEFT RIGHT FIRE GAME_A GAME_B GAME_C GAME_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)

protected void showNotify() protected void hideNotify() protected abstract void paint(Graphics g) commandAction() method of the CommandListener interface 5-a Ans. Obfuscator [5 Marks] Why required? Because MIDP devices have so little memory, MIDlet suites should be as compact as possible. 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 names Removing unused classes, methods, and member variables Inserting illegal or questionable data to confuse decompilers Except for the last point, obfuscators can significantly reduce the size of compiled classes in a MIDlet suite JAR. When to use? Obfuscate the classes before they are preverified. 5-b Ans. GameCanvas [5 Marks] The GameCanvas class provides the basis for a game user interface. GameCanvas extends javax.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 of having to wait for the system software to call paint(). 2. You can control what region of the screen is updated. GameCanvas gives your application 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 whether the 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:

GameCanvas Bit Constants UP_PRESSED DOWN_PRESSED LEFT_PRESSED RIGHT_PRESSED FIRE_PRESSED GAME_A_PRESSED GAME_B_PRESSED GAME_C_PRESSED GAME_D_PRESSED

Corresponding GameCanvas Action Constants UP DOWN LEFT RIGHT FIRE GAME_A GAME_B GAME_C GAME_D

By grabbing the current state of the keys (a technique called polling), you can respond to user actions within the game loop instead of relying on the event callback methods, which run in a different thread. 5-c Ans. CLDC 1.0 and 1.1 [5 Marks] CLDC 1.0 CLDC 1.0 does not support floating-point types at all. That means there are no float or double primitive types. The corresponding wrapper types, java.lang.Float and java.lang.Double, have also been eliminated. The interrupt() method is not present in the java.lang.Thread class. In the String class valueOf() static methods that convert between floatingpoint primitives and Strings is eliminated. StringBuffers append() and insert() methods do not include overrides for floating-point types. Minimum memory 160 KB. Weak reference support not present

CLDC 1.1 CLDC 1.1 includes floating-point support, the primitive types double and float, and the wrapper types Double and Float. Various other classes have been modified for floating-point support in CLDC 1.1, but the changes are minor. The interrupt() method is available. The valueOf() method is available.

These methods are available.

Not present. Methods involving floating point numbers have been removed from Math class. 5-d Ans.

Minimum memory budget has been raised to 192 KB, mainly because of the added floating point functionality. Weak reference support (small subset of the Java SE weak reference classes) has been added New error class, NoClassDefFoundError, has been added. As it supports floating point types, includes several more methods in java.lang.Math.

Bluetooth [5 Marks] 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 for Bluetooth is an optional API that adds radio PAN connectivity to MIDP applications. The Bluetooth radio hardware operates in the 2.45-gigahertz Industrial, Scientific, and Medical (ISM) frequency band, allowing for unlicensed operation worldwide. Bluetooth networks are formed ad hoc and dynamically, when Bluetooth-enabled devices come into proximity 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 be expanded 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 transparent to 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

same time. Bluetooth devices can also support both client and server functionality simultaneously. 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 called an 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 in the 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 a printing 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 specify interoperability standards between different implementations. The Service Application Discovery 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 ability to 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 Access Profile, 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 Ans. What are the frameworks supported by JEE5? [10 Marks] Different frameworks supported by Java EE 5: 1. Java Server Faces 2. Hibernate 3. Seam

4. Struts 5. Spring Hibernate

Figure: The Hibernate architecture Hibernate provides a framework for mapping an object-oriented domain model to a relational database. The primary feature of Hibernate is to map JavaBean classes to database 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 provide Java 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 Java Objects (POJOs). Hibernate can be used both standalone Java applications and in Java EE applications 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 Java classes 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) that reduces 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 to manual coding with SQL and the JDBC API. The Hibernate architecture The Hibernate architecture consists of two technologies Hibernate and Java EE. Hibernate makes use of the existing Java APIs, including JDBC (Java Database Connectivity), Java Transaction API (JTA), Java Naming and Directory Interface (JNDI). JDBC loads database driver and establish a connection for accessing relational database. It uses all types of database driver that are supported by Hibernate. JNDI and JTA allow Hibernate to be integrated 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-oriented extension to SQL that bridges the gap between the Object-oriented systems and relational database. The syntax of HQL is very similar to SQL. It has a rich and powerful Objectoriented 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 Objectoriented systems are mapped to relational databases with a SQL-based Schema

HQL queries are case-insensitive, but the names of Java classes and properties are casesensitive. 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 classes and properties instead of tables and columns. HQL supports polymorphism and associations and 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 is based 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 through the 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 the changes. Then the controller selects the new view to be displayed according to the result 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

Struts tags. All framework components work together in a standard manner. The architecture 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 business logic 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. The main 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 single instance 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 it is 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, such as action, classes, and interceptors. Action Classes Action classes implement the business logic, or, in other words, they behave as wrappers around the business logic and interact with the model of the application. They are basically responsible for executing the business service according to user requests. Model Model 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 encapsulated within a view. There is no business logic available in the view. 6-b Ans. Write a note on web centric approach and EJB centric approach of creating web applications. [10 Marks] 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, and 4. 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 type is EJB-centric.

Basic HTML A web application contains HTML pages to provide static content. Such types of applications are 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 to display dynamic content, (for example, content generated using data from a database), a JSP 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 modularization of components would be useful.

Figure: Applications with Basic JSP Pages and Servlets

Figure : Process Flow of JSP Pages with Modular Components Applications with Modular Components When developing Web applications with dynamic content and a large degree of user interaction, you should use JSP pages with JavaBeans components, custom tags, and included JSP pages. These three types of components can be used to generate content, process requests, and handle the display of personalized content.

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, these components 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 can be effectively implemented using modular components. Applications that use modular components for request processing will be easier to develop and maintain. Figure depicts how 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 an account, 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

the developer's time may be for work on the system-level issues such as managing the connection pool and application state and transaction management. Migrating to an EJBcentric design will allow the developer to stay focused on the application design. EJBCentric Applications An EJB-centric application extends the modular, component-based application described earlier, 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-centric application, 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 specific type of client. Most enterprise applications will support a number of different views. The same 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 the model data. The JSP files can contain JavaBeans components, custom tags, or included JSP page 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 some helper 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 Web pages. With static pages, there is no guarantee that all users of a Web site will use the preferred 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 also provide 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 components that 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 the application model data. This figure shows the flow of an HTTP request from an HTTP client to the controller mechanism. As mentioned before, all requests from HTTP clients go to a front component. 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 proxy and sends the event to the EJB controller, which processes the event and updates the model data maintained by the enterprise beans accordingly. All business logic is handled by the EJB controller and enterprise beans. The EJB controller returns a set of changed models to the Web controller. The Web controller then sends the model 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 JavaBeans components do not change any data; they only read the model data contained by the enterprise beans when they receive the model update notification.

Figure: Controller Conversion of HTTP Request to Model Change Event 7-a Ans. Compare an applet with midlet. [5 Marks] Applet MIDlet A Java applet is a special kind of Java A MIDlet is a MID (Mobile Information Device) program that a browser enabled with Java Profile application that runs on mobile devices. technology can download from the internet and run. An applet must be a subclass of the A MIDlet must be a subclass of the java.applet.Applet class. javax.microedition.midlet.MIDlet class. Browser needs Java Plug-in software to Mobile device need to port CLDC/MIDP to run run applet. MIDlet. The browser's Java Plug-in software Mobile Devices application management manages the lifecycle of an applet. software manages the lifecycle of a MIDlet. Include <applet> tag in the html page to Class files are packaged into JAR file and then run applet in the browser, which deployed on the mobile device to run the downloads the class file and runs it. MIDlet. Following methods define life cycle of Following methods define life cycle of applet: applet: startApp() init() pauseApp() start() destroyApp() stop() notifyPaused() and notifyDestroyed() destroy() Explain the implementation of CommandListener and ItemStateListener with an example. [10 Marks] 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:

7-b Ans.

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 GaugeTrackerMidlet extends MIDlet implements 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) { }

} 7-c Ans. Explain the MVC architecture. [5 Marks] MVC (Model-View-Controller) architecture separates the core business model functionality of the web application from the presentation and control logic of the interface-specific application. 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 not affect 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 web application, 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 Model component represents the data and the business logic of the application and has no concern with the presentation logic of the application. Describing the View Component A View provides the Graphical User Interface (GUI) for Model. A user interacts with the application through View, which represents the information based on Model, and allows the user 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, a view communicates with a Model to get information if any change takes place in the database. Users who want to modify the content of a Model do not communicate with it directly. Instead, they communicate with the Model through a View, which communicates with the Controller regarding the user input. The Controller then makes the required changes in 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 user interacts with the View component and tries to update the Model, the Controller component invokes 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,

whenever a user sends a request, it passes through the Controller. Then, the controller intercepts 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 or bean class. The different components in the application, such as Controller, Model, and View, are reusable and make applications highly scalable.

You might also like