You are on page 1of 27

Internet & Web Development Technologies: Assignment No.1.

1] What is Layout? Explain the types of layout?


Layout Managers: Java technology uses Layout Managers to define the location and size of Graphical User Interface components. Java technology does not encourage (support) programmers to use absolute location and size of components. Java technology instead places components based on specified Layout Manager. A Layout Manager implements a layout policy that defines constraints between components in a container. Types of Layout Managers Java technology provides the following Layout Managers, each of which implements the LayoutManager interface. 1. FlowLayout 2. GridLayout 3. BorderLayout 4. CardLayout The FlowLayout is the default Layout Manager for Panel, and the BorderLayout is the default Layout Manager for Window class and its subclasses (Frame and Dialog). Setting Layout Managers: The following method defined in the Container class can be used for setting layout managers. void setLayout(LayoutManager mgr); So for example to set FlowLayout as the Layout Manager for a container C, the following can be used C.setLayout(new FlowLayout()); 1] FlowLayout Manager: FlowLayout places component in rows from left to right. Components towards the end of row are written on next row, if there is not enough space in the current row. The FlowLayout honors the specified size of a component. The size of a component never changes regardless of size of container. The following constructors of FlowLayout are provided by AWT FlowLayout(); FlowLayout(int alignment); FlowLayout(int alignment, int hor_gap, int ver_gap); Alignment can take values of constants - LEFT, CENTER and RIGHT. The default alignment for the components in a row is center. Default horizontal and vertical gaps are 5 pixels. 2] GridLayout Manager: A GridLayout Manager places the components in a rectangular grid. Each component's position is identified by a column and row. All the cells in the grid have same size and width. Each component is stretched (extended) to the cell size. So a GridLayout ignores the Component's preferred size. Puri Dnyaneshwar S. M.Sc(C.S)S.Y. S.R.T.M.U.N.Sub-Center,Latur Advance Java Page 1

The GridLayout class provides the following constructors. GridLayout(); GridLayout(int rows, int columns); GridLayout(int rows, int columns, int hor_gap, int ver_gap); This creates a row*col grid layout with the specified horizontal and vertical gaps. In the constructor, either rows or cols can be zero, but not both. The first constructor is equivalent to one row with any number of components. The default gap between components is zero pixels. 3] BorderLayout Manager: A BorderLayout Manager divides the window into five regions - North, East, West, South and Center. A component can be explicitly added to one of the regions using the add() method of the Container class. Any space left over by the component in North, East, South and West is occupied by the component in Center. Only the last component added to a region is shown, and not all regions need to be occupied by a component. So a container that uses BorderLayout may have up-to 5 components. The BorderLayout class defines the following constructors BorderLayout(); BorderLayout(int hor_gap, int ver_gap); As illustrated below, components can be added to the container using add() method defined in the Container class. Component add(Component comp); void add(Component comp, Object constraints); Here constraints can be NORTH, SOUTH, EAST, WEST and CENTER. These constants correspond to strings "North", "South", East", "West", and "Center" respectively. They describe the region where the component should be placed. The default region is CENTER. 4] CardLayout: CardLayout is a layout that is like a stack of cards. Each card is one pane and the layout can be used to switch between cards. It is an ideal layout in situations where panes have to be displayed one after the other eg. a wizard. CardLayout class from java.awt package provides methods like next(Component), previous(Component), first(Component), last(Component) to switch between the components added in cardlayout. It also has a show(Component, String) method will allows to switch to a particular component in the cardlayout by providing the components name. Example: //CommonLayouts import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; Puri Dnyaneshwar S. M.Sc(C.S)S.Y. S.R.T.M.U.N.Sub-Center,Latur Advance Java Page 2

import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.TitledBorder; public class CommonLayouts1 extends JFrame { public CommonLayouts1() { super("Common Layout Managers"); setSize(500, 380); JPanel desktop = new JPanel(); getContentPane().add(desktop); JPanel fr1 = new JPanel(); fr1.setBorder(new TitledBorder("FlowLayout")); fr1.setLayout(new FlowLayout()); fr1.add(new JButton("DNYAN_1")); fr1.add(new JButton("DNYAN_2")); fr1.add(new JButton("DNYAN_3")); fr1.add(new JButton("DNYAN_4")); desktop.add(fr1, 0); JPanel fr2 = new JPanel(); fr2.setBorder(new TitledBorder("GridLayout")); fr2.setLayout(new GridLayout(2, 2)); fr2.add(new JButton("SRTMUN_1")); fr2.add(new JButton("SRTMUN_2")); fr2.add(new JButton("SRTMUN_3")); fr2.add(new JButton("SRTMUN_4")); desktop.add(fr2, 0); JPanel fr3 = new JPanel(); fr3.setBorder(new TitledBorder("BorderLayout")); fr3.add(new JButton("Sub-Center_1"), BorderLayout.NORTH); fr3.add(new JButton("Sub-Center_2"), BorderLayout.EAST); fr3.add(new JButton("Sub-Center_3"), BorderLayout.SOUTH); fr3.add(new JButton("Sub-Center_4"), BorderLayout.WEST); desktop.add(fr3, 0); Puri Dnyaneshwar S. M.Sc(C.S)S.Y. S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 3

WindowListener wndCloser = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; addWindowListener(wndCloser); setVisible(true); } public static void main(String [] DNYAN) { new CommonLayouts1(); } } Output:

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 4

02] What is RMI? Describe the Steps to create the RMI Application.
The Java Remote Method Invocation (RMI) system allows an object running in one Java virtual machine to invoke methods on an object running in another Java virtual machine. RMI provides for remote communication between programs written in the Java programming language. Steps to create RMI Applications: 1] Step One: Enter and Compile the Source Code: This application uses four source files. The first file, AddServerIntf.java, defines the remote interface that is provided by the server. It contains one method that accepts two double arguments and returns their sum. All remote interfaces must extend the Remote interface, which is part of java.rmi. Remote defines no members. Its purpose is simply to indicate that an interface uses remote methods. All remote methods can throw a RemoteException. e.g. import java.rmi.*; public interface AddServerIntf extends Remote { double add(double d1, double d2) throws RemoteException; } The second source file, AddServerImpl.java, implements the remote interface. The implementation of the add () method is straightforward. All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objects available from remote machines. e.g. import java.rmi.*; import java.rmi.server.*; public class AddServerImpl extends UnicastRemoteObject implements AddServerIntf { public AddServerImpl() throws RemoteException { } public double add(double d1, double d2) throws RemoteException { return d1 + d2; } } The third source file, AddServer.java, contains the main program for the server machine. Its primary function is to update the RMI registry on that machine. This is done by using the rebind( ) method of the Naming class (found in java.rmi). That method associates a name with an object reference. The first argument to the rebind( ) method is a string that names the server as AddServer. Its second argument is a reference to an instance of AddServerImpl. e.g. import java.net.*; import java.rmi.*; public class AddServer { public static void main(String args[]) { try { AddServerImpl addServerImpl = new AddServerImpl(); Puri Dnyaneshwar S. M.Sc(C.S)S.Y. S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 5

Naming.rebind("AddServer", addServerImpl); } catch(Exception e) { System.out.println("Exception: " + e); } } } The fourth source file, AddClient.java, implements the client side of this distributed application. AddClient.java requires three command line arguments. The first is the IP address or name of the server machine. The second and third arguments are the two numbers that are to be summed. The application begins by forming a string that follows the URL syntax. This URL uses the rmi protocol. The string includes the IP address or name of the server and the string AddServer. The program then invokes the lookup( ) method of the Naming class. This method accepts one argument, the rmi URL, and returns a reference to an object of type AddServerIntf. All remote method invocations can then be directed to this object. The program continues by displaying its arguments and then invokes the remote add( ) method. The sum is returned from this method and is then printed. e.g. import java.rmi.*; public class AddClient { public static void main(String args[]) { try { String addServerURL = "rmi://" + args[0] + "/AddServer"; AddServerIntf addServerIntf = (AddServerIntf)Naming.lookup(addServerURL); System.out.println("The first number is: " + args[1]); double d1 = Double.valueOf(args[1]).doubleValue(); System.out.println("The second number is: " + args[2]); double d2 = Double.valueOf(args[2]).doubleValue(); System.out.println("The sum is: " + addServerIntf.add(d1, d2)); } catch(Exception e) { System.out.println("Exception: " + e); } } } 2] Step Two: Generate Stubs and Skeletons: Before you can use the client and server, you must generate the necessary stub. You may also need to generate a skeleton. In the context (background) of RMI, a stub is a Java object that resides on the client machine. Its function is to present the same interfaces as the remote server. Remote method calls initiated by the client are actually directed to the stub. The stub works with the other parts of the RMI system to formulate a request that is sent to the remote machine. A remote method may accept arguments that are simple types or objects. In the latter case, the object may have references to other objects. All of this information must be sent to the remote machine. That is, an object passed as an argument to a remote method call must be serialized and sent to the remote machine. Puri Dnyaneshwar S. M.Sc(C.S)S.Y. S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 6

Skeletons are not required by Java 2. However, they are required for the Java 1.1 RMI model. Because of this, skeletons are still required for compatibility between Java 1.1 And Java 2. A skeleton is a Java object that resides on the server machine. It works with the other parts of the 1.1 RMI systems to receive requests, perform deserialization, and invoke the appropriate code on the server. Again, the skeleton mechanism is not required for Java 2 code that does not require compatibility with 1.1.Because many readers will want to generate the skeleton. If a response must be returned to the client, the process works in reverse. Note that the serialization and deserialization facilities are also used if objects are returned to a client. To generate stubs and skeletons, you use a tool called the RMI compiler, which is invoked from the command line, as shown here: rmic AddServerImpl This command generates two new files: AddServerImpl_Skel.class (skeleton) and AddServerImpl_Stub.class (stub). When using rmic, be sure that CLASSPATH is set to include the current directory. As you can see, by default, rmic generates both a stub and a skeleton file. If you do not need the skeleton, you have the option to suppress it. 3] Step Three: Install Files on the Client and Server Machines: Copy AddClient.class, AddServerImpl_Stub.class, and AddServerIntf.class to a directory on the client machine. Copy AddServerIntf.class, AddServerImpl.class, AddServerImpl_Skel.class, AddServerImpl_Stub.class, and AddServer.class to a directory on the server machine. [RMI has techniques for dynamic class loading, but they are not used by the example at hand. Instead, all of the files that are used by the client and server applications must be installed manually on those machines.] 4] Step Four: Start the RMI Registry on the Server Machine: The Java 2 SDK provides a program called rmiregistry, which executes on the server machine. It maps names to object references. First, check that the CLASSPATH environment variable includes the directory in which your files are located. Then, start the RMI Registry from the command line, as shown here: start rmiregistry When this command returns, you should see that a new window has been created. You need to leave this window open until you are done experimenting with the RMI example. 5] Step Five: Start the Server: The server code is started from the command line, as shown here: java AddServer Recall that the AddServer code instantiates AddServerImpl and registers that object with the name AddServer. 6] Step Six: Start the Client: The AddClient software requires three arguments: the name or IP address of the server machine and the two numbers that are to be summed together. You may invoke it from the command line by using one of the two formats shown here: java AddClient server1 8 9 java AddClient 11.12.13.14 8 9 In the first line, the name of the server is provided. The second line uses its IP address (11.12.13.14).

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 7

You can try this example without actually having a remote server. To do so, simply install all of the programs on the same machine, start rmiregistry, start AddSever, and then execute AddClient using this command line: java AddClient 127.0.0.1 8 9 Here, the address 127.0.0.1 is the loop back address for the local machine. Using this address allows you to exercise the entire RMI mechanism without actually having to install the server on a remote computer. In either case, sample output from this program is shown here: The first number is: 8 The second number is: 9

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 8

03] Define Listener? List the All types of Listener.


All GUI systems, not just Java, call a method when the user does something that demands the program's attention, e.g clicking a button. The details of the connection between the GUI component and the called method. method vary from language to language. Java uses a pure object-oriented approach to implementing what they call listeners. There are several kinds of listeners in Java, depending on what the user does, but the most common is called an action listener, which is used with buttons, menu items, etc. Event Listeners A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and Process these notifications. Event Listener Interfaces The delegation event model has two parts: sources and listeners. Listeners are created by implementing one or more of the interfaces defined by the java.awt.event package. When an event occurs, the event source invokes the appropriate method defined by the listener and provides an event object as its argument. There are 11 commonly used Listener Interface: 1] ActionListener Interface: This interface defines the actionPerformed( ) method that is invoked when an action event occurs. Its general form Method: void actionPerformed(ActionEvent ae) Parameter: getActionCommannd Event generated by: Button, TextField, MenuItem, List 2] AdjustmentListener Interface: This interface defines the adjustmentValueChanged( ) method that is invoked when an adjustment event occurs. Its general form of Method: void adjustmentValueChanged(AdjustmentEvent ae) Parameter: getAdjectable , getAdjustmetTime , getValue. Event Generated by: Scrollbar.

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 9

3]ItemListener Interface: This interface defines the itemStateChanged( ) method that is invoked when the state of an item changes. Its general form of Method: void itemStateChanged(ItemEvent ie) Parameter: getItem, getItemSelectable , getStateChange . Event Generated by: Choice, List, ItemCheckbox. 4] TextListener Interface: This interface defines the textChanged( ) method that is invoked when a change occurs in a text area or text field. Its general Form of Method: void textChanged(TextEvent te) Parameter: TextEvent Event Generated by: Text Componants. 5] FocusListener Interface: This interface defines two methods. When a component obtains keyboard focus, focusGained( ) is invoked. When a component loses keyboard focus, focusLost( ) is called. Their general forms of Methods: void focusGained(FocusEvent fe) void focusLost(FocusEvent fe) Parameter: FocusEvent Event Generated by: Focus Listener componants. 6] KeyListener Interface: This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked when a key is pressed and released, respectively. The keyTyped( ) method is invoked when a character has been entered. For example, if a user presses and releases the A key, three events are generated in Sequence: key pressed, typed, and released. If a user presses and releases the HOME key, two key events are generated in sequence: key pressed and released. The general forms of these methods are shown here: void keyPressed(KeyEvent ke) void keyReleased(KeyEvent ke) void keyTyped(KeyEvent ke) Puri Dnyaneshwar S. M.Sc(C.S)S.Y. S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 10

Parameter: KeyOne, getKeyCharecter, getKeyCode, getKeyModifierText. Event Generated by: Key Listener componants. 7] MouseListener Interface: This interface defines five methods. If the mouse is pressed and released at the same point, mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method is called. When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked when the mouse is pressed and released, respectively. The general forms of these methods are shown here: void mouseClicked(MouseEvent me) void mouseEntered(MouseEvent me) void mouseExited(MouseEvent me) void mousePressed(MouseEvent me) void mouseReleased(MouseEvent me) Parameter: Mouseevent, getClickOn, getX, getY, getPoint, TranslatePoint. Event Generated by: Mouse Listener componants. 8] MouseMotionListener Interface: This interface defines two methods. The mouseDragged( ) method is called multiple times as the mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse is moved. Their general forms are shown here: void mouseDragged(MouseEvent me) void mouseMoved(MouseEvent me) Parameter: MouseEvent. Event Generated by: MouseMotion Listener componants 9] WindowListener Interface: This interface defines seven methods. The windowActivated( ) and windowDeactivated( ) methods are invoked when a window is activated or deactivated, respectively. If a window is iconified, the windowIconified( ) method is called. When a window is deiconified, the windowDeiconified( ) method is called. When a window is opened or closed, the windowOpened( ) or windowClosed( ) methods are called, respectively. ThewindowClosing( ) method is called when a window is being closed. Puri Dnyaneshwar S. M.Sc(C.S)S.Y. S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 11

The general forms of these methods are: void windowActivated(WindowEvent we) void windowClosed(WindowEvent we) void windowClosing(WindowEvent we) void windowDeactivated(WindowEvent we) void windowDeiconified(WindowEvent we) void windowIconified(WindowEvent we) void windowOpened(WindowEvent we) Parameter: WindowsEvent, getWindows. Event Generated by: Windows Listener componants 10] ComponentListener Interface: This interface defines four methods that are invoked when a component is resized, moved, shown, or hidden. Their general forms are shown here: void componentResized(ComponentEvent ce) void componentMoved(ComponentEvent ce) void componentShown(ComponentEvent ce) void componentHidden(ComponentEvent ce) Parameter: ComponentEvent Event Generated by: Component Listener componants 11] ContainerListener Interface: This interface contains two methods. When a component is added to a container, componentAdded( ) is invoked. When a component is removed from a container, componentRemoved( ) is invoked. Their general forms Method: void componentAdded(ContainerEvent ce) void componentRemoved(ContainerEvent ce) Parameter: getchild , getConainer. Event Generated by: Container Listener componants

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 12

04] Explain the Thread Life Cycle?


Java Thread Lifecycle: The following diagram shows the life cycle of a Java Thread. Thread has following states: Start, Stop, Blocked, Running, Runnable. These states can be changed to each other as shown in the diagram. Thread can sleep, notify, resume, start, stop, suspend, yield and wait. These activities lead the thread from one state to move to another one.

Every thread in java has a specific life cycle. Different Thread life cycle states are: 1. Newborn/Start State: A newly created thread will initially be in the newborn state of thread life cycle. 2. Runnable State: An active thread that is ready to run will be in Runnable State of thread life cycle. When the current running thread finishes its job or moves to Runnable / some other state, then this thread will move to running state. 3. Running State: An active thread that is currently running will be in Running State of thread life cycle. The thread in Running state can be put back to Runnable state. 4. Blocked State: Idle thread that is currently not Runnable is placed in Blocked State of thread life cycle. 5. Dead /Stop State: A thread that is killed will be put in dead state of thread life cycle. This is the last state in a thread life cycle.

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 13

05] Describe the RMI Architecture.


RMI (Remote Method Invocation) ARCHITECTURE:

The following is the Architecture of the RMI: Server: This JVM contains an object that provides the remote services. It registers its object into the Registry. Stub: This is generated in the server. This is used to understand or translate the request and response formats of the server and client in the server. Client: This is the program that accesses the RMI Registry for the services of the server. Skeleton: This is a class that remains in Client and help teh client to understand the request and response formats of server in client. RMI Registry: This is a Naming Registry that is used to bind the objects and return their references to the client.

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 14

06] Describe the Event Delegation Model.


The event model is based on the Event Source and Event Listeners. Event Listener is an object that receives the messages / events. The Event Source is any object which creates the message / event. The Event Delegation model is based on The Event Classes, The Event Listeners, Event Objects. There are three participants in event delegation model in Java; - Event Source the class which broadcasts the events - Event Listeners the classes which receive notifications of events - Event Object the class object which describes the event. An event occurs (like mouse click, key press, etc) which is followed by the event is broadcasted by the event source by invoking an agreed method on all event listeners. The event object is passed as argument to the agreed-upon method. Later the event listeners respond as they fit, like submit a form, displaying a message / alert etc.

Fig: Event Delegation Model The modern approach to handling events is based on the delegation event model, which defines standard and consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an event. Once received, the listener processes the event and then returns. The advantage of this design is that the application logic that processes events is Puri Dnyaneshwar S. M.Sc(C.S)S.Y. S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 15

cleanly separated from the user interface logic that generates those events. A user interface element is able to delegate the processing of an event to a separate piece of code. In the delegation event model, listeners must register with a source in order to receive an event notification. This provides an important benefit: notifications are sent only to listeners that want to receive them. This is a more efficient way to handle events than the design used by the old Java 1.0 approach. Previously, an event was propagated up the containment hierarchy until it was handled by a component. This required components to receive events that they did not process, and it wasted valuable time. The delegation event model eliminates this overhead. Events: In the delegation model, an event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse. Many other user operations could also be cited as examples. Events may also occur that are not directly caused by interactions with a user interface. For example, an event may be generated when a timer expires, a counter exceeds a value, software or hardware failure occurs, or an operation is completed. You are free to define events that are appropriate for your application. Event Sources: A source is an object that generates an event. This occurs when the internal state of that object changes in some way. Sources may generate more than one type of event. A source must register listeners in order for the listeners to receive notifications about a specific type of event. Each type of event has its own registration method. Here is the general form: public void addTypeListener(TypeListener el) Event Listeners: A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications. Event Classes: The classes that represent events are at the core of Javas event handling mechanism. Thus, we begin our study of event handling with a tour of the event classes. As you will see, they provide a consistent, easy-to-use means of encapsulating events. At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all events. Its one constructor is shown here: EventObject(Object src) Here, src is the object that generates this event. EventObject contains two methods: getSource( ) and toString( ). The getSource( ) method returns the source of the event. EventObject is a superclass of all events. AWTEvent is a superclass of all AWT events that are handled by the delegation event model. The package java.awt.event defines several types of events that are generated by Puri Dnyaneshwar S. M.Sc(C.S)S.Y. S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 16

The package java.awt.event defines several types of events that are generated by various user interface elements.

Event Class ActionEvent AdjustmentEvent ComponentEvent ContainerEvent FocusEvent ItemEvent

KeyEvent MouseEvent

MouseWheelEvent TextEvent WindowEvent

Description -Generated when a button is pressed, a list item is double-clicked, or a menu item is selected. -Generated when a scroll bar is manipulated. -Generated when a component is hidden, moved, resized,or becomes visible. - Generated when a component is added to or removed from a container. -Generated when a component gains or loses keyboard focus. -Generated when a check box or list item is clicked; alsooccurs when a choice selection is made or a checkable menu item is selected or deselected. -Generated when input is received from the keyboard. -Generated when the mouse is dragged, moved, clicked,pressed, or released; also generated when the mouse enters or exits a component. -Generated when the mouse wheel is moved. -Generated when the value of a text area or text field is changed. -Generated when a window is activated, closed, deactivated,deiconified, iconified, opened, or quit.

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 17

07] Explain Servlet Life Cycle?


The Life Cycle of a Servlet: A server loads and initializes the servlet The servlet handles zero or more client requests The server removes the servlet (Some servers do this step only when they shut down)

1] Creation and initialization: The container first creates the servlet instance and then executes the init() method. init() can be called only once in its life cycle by the following ways: a) Through the load-on-startup tag using the web.xml. This makes the servlet to be loaded and initialized when the server starts. b) For the first time only in its life cycle, just before the service() is invoked. c) Server administrator can request for the initialization of a servlet directly. 2] Execution of service: Whenever a client requests for the servlet, everytime the service() method is invoked during its life cycle. From service() then it is branched to the doGet() or doXx..() methods for an HttpServlet. The service() method should contain the code that serves the Servlet purpose. 3] Destroy the servlet: destroy() method is invoked first, then Servlet is removed from the container and then eventually garbage collected. destroy() method generally contains code to free any resources like jdbc connection that will not be garbage collected.

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 18

08] What is JDBC? Explain the types of JDBC.


JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code. It was developed by Java Soft, a subsidiary of Sun Microsystems. Definition: Java Database Connectivity in short called as JDBC. It is a java API which enables the java programs to execute SQL statements. It is an application programming interface that defines how a java programmer can access the database in tabular format from Java code using a set of standard interfaces and classes written in the Java programming language. JDBC has been developed under the Java Community Process that allows multiple implementations to exist and be used by the same application. JDBC provides methods for querying and updating the data in Relational Database Management system such as SQL, Oracle etc. The Java application programming interface provides a mechanism for dynamically loading the correct Java packages and drivers and registering them with the JDBC Driver Manager that is used as a connection factory for creating JDBC connections which supports creating and executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc architecture. Generally all Relational Database Management System supports SQL and we all know that Java is platform independent, so JDBC makes it possible to write a single database application that can run on different platforms and interact with different Database Management Systems. Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for accessing and managing database, but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not depended upon any language. In short JDBC helps the programmers to write java applications that manage these three programming activities: 1. It helps us to connect to a data source, like a database. 2. It helps us in sending queries and updating statements to the database and 3. Retrieving and processing the results received from the database in terms of answering to your query. A JDBC driver is a software component enabling a Java application to interact with a database. JDBC drivers are analogous to ODBC drivers, ADO.NET data providers, and OLE DB providers. To connect with individual databases, JDBC (the Java Database Connectivity API) requires drivers for each database. The JDBC driver gives out the connection to the database and implements the protocol for transferring the query and result between client and database. JDBC technology drivers fit into one of four categories. Type 1 Driver - JDBC-ODBC bridge: The JDBC type 1 driver, also known as the JDBC-ODBC bridge, is a database driver implementation that employs the ODBC driver to connect to the database. The driver converts JDBC method calls into ODBC function calls. Puri Dnyaneshwar S. M.Sc(C.S)S.Y. S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 19

The driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the underlying operating system the JVM is running upon. Also, use of this driver leads to other installation dependencies; for example, ODBC must be installed on the computer having the driver and the database must support an ODBC driver. The use of this driver is discouraged if the alternative of a pure-Java driver is available. The other implication is that any application using a type 1 driver is nonportable given the binding between the driver and platform. This technology isn't suitable for a hightransaction environment. Type 1 drivers also don't support the complete Java command set and are limited by the functionality of the ODBC driver. Functions: Translates query obtained by JDBC into corresponding ODBC query, which is then handled by the ODBC driver. Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver. This driver is native code and not Java, and is closed source. Client -> JDBC Driver -> ODBC Driver -> Database. Advantages: Easy to connect. Directly connected to the database. Disadvantages: Performance overhead since the calls have to go through the jdbc Overhead bridge to the ODBC driver, then to the native db connectivity interface. The ODBC driver needs to be installed on the client machine. Considering the client-side software needed, this is not suitable for applets. Compared to other driver types it's slow. The Sun driver has a known issue with character encodings and Microsoft Access databases. Microsoft Access may use an encoding that is not correctly translated by the driver, leading to the replacement in strings of, for example, and accented characters by question marks. One workaround is to avoid reading strings directly, but rather to read the raw bytes and then translate these into a string, specifying the correct source encoding: byte[] rawBytes = row.getBytes("COLUMN_NAME"); String columnValue = new String(rawBytes, "Windows-1252");

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 20

Schematic (diagram) of the JDBC-ODBC bridge. Type 2 Driver - Native-API Driver specification: The JDBC type 2 driver, also known as the Native-API driver, is a database driver implementation that uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. The type 2 driver is not written entirely in Java as it interfaces with non-Java code that makes the final database calls. The driver is compiled for use with the particular operating system. For platform interoperability, the Type 4 driver, being a full-Java implementation, is preferred over this driver. The vendor client library needs to be installed on the client machine. Not all databases have a client side library This driver is platform dependent This driver supports all java applications except Applets

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 21

Schematic (diagram) of the Native API driver. Type 3 Driver - Network-Protocol Driver: The JDBC type 3 driver, also known as the Pure Java Driver for Database Middleware, is a database driver implementation which makes use of a middle tier (level) between the calling program and the database. The middle-tier (application server) converts JDBC calls directly or indirectly into the vendorspecific database protocol. This differs from the type 4 driver in that the protocol conversion logic resides not at the client, but in the middle-tier. Like type 4 drivers, the type 3 driver is written entirely in Java. The same driver can be used for multiple databases. It depends on the number of databases the middleware has been configured to support. The type 3 driver is platform-independent as the platform-related differences are taken care by the middleware. Also, making use of the middleware provides additional advantages of security and firewall access. Functions: Follows a three tier (level) communication approach. Can interface to multiple databases - Not vendor specific. The JDBC Client driver written in java communicates with a middleware-net-server using a database independent protocol, and then this net server translates this request into database commands for that database. Thus the client driver to middleware communication is database independent. Client -> JDBC Driver -> Network-protocol driver -> Middleware-Net Server -> Any Database... Advantages: Puri Dnyaneshwar S. M.Sc(C.S)S.Y. S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 22

Since the communication between client and the middleware server is database independent, there is no need for the vendor db library on the client machine. Also the client to middleware need not be changed for a new database. The Middleware Server (which can be a fully fledged J2EE Application server) can provide typical middleware services like caching (connections, query results, and so on), load balancing, logging, auditing etc. Eg. For the above include jdbc driver features in Weblogic. Can be used in internet since there is no client side software needed. At client side a single driver can handle any database. (It works provided the middleware supports that database!) Disadvantages: Requires database-specific coding to be done in the middle tier. An extra layer added may result in a time-bottleneck. But typically this is overcome by providing efficient middleware services.

Schematic (diagram) of the Network Protocol driver. Type 4 Driver - Native-Protocol Driver: The JDBC type 4 driver, also known as the Direct to Database Pure Java Driver, is a database driver implementation that converts JDBC calls directly into a vendor-specific database protocol. Therefore it is called a THIN driver. Puri Dnyaneshwar S. M.Sc(C.S)S.Y. S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 23

Written completely in Java, type 4 drivers are thus platform independent. They install inside the Java Virtual Machine of the client. This provides better performance than the type 1 and type 2 drivers as it does not have the overhead of conversion of calls into ODBC or database API calls. Unlike the type 3 drivers, it does not need associated software to work. As the database protocol is vendor-specific, the JDBC client requires separate drivers, usually vendorsupplied, to connect to different types of databases. Functions: Type 4 drivers, coded entirely in Java, communicate directly with a vendor's database, usually through socket connections. No translation or middleware layers are required, improving performance. The driver converts JDBC calls into the vendor-specific database protocol so that client applications can communicate directly with the database server. Completely implemented in Java to achieve platform independence. This type includes (for example) the widely-used Oracle thin driver oracle.jdbc.driver.OracleDriver which connects using a format configuration of jdbc:oracle:thin:@URL Client -> Native-protocol JDBC Driver -> database server. Advantages: These drivers don't translate the requests into an intermediary format (such as ODBC), nor do they need a middleware layer to service requests. This can enhance performance considerably. The JVM can manage all aspects of the application-to-database connection; this can facilitate debugging. Provides a way to manage copies of the database for each user. Disadvantages: Drivers are database dependent.

Schematic of the Native-Protocol driver

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 24

09] What is Object Serialization? Explain with suitable example.


Serialization is the process of saving an object in a storage medium (such as a file, or a memory buffer) or to transmit it over a network connection in binary form. The serialized objects are JVM independent and can be re-serialized by any JVM. In this case the "in memory" java objects states are converted into a byte stream. This type of the file cannot be understood by the user. It is special types of object i.e. reused by the JVM (Java Virtual Machine). This process of serializing an object is also called deflating or marshalling an object. The given example shows the implementation of serialization to an object. This program takes a file name that is machine understandable and then serializes the object. The object to be serialized must implement java.io.Serializable class. Default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. class ObjectOutputStream extends java.io.OutputStream implements ObjectOutput, ObjectOutput interface extends the DataOutput interface and adds methods for serializing objects and writing bytes to the file. The ObjectOutputStream extends java.io.OutputStream and implements ObjectOutput interface. It serializes objects, arrays, and other values to a stream. Thus the constructor of ObjectOutputStream is written as: ObjectOutput ObjOut = new ObjectOutputStream(new FileOutputStream(f)); Above code has been used to create the instance of the ObjectOutput class with the ObjectOutputStream( ) constructor which takes the instance of the FileOuputStream as a parameter. The ObjectOutput interface is used by implementing the ObjectOutputStream class. The ObjectOutputStream is constructed to serialize the object. writeObject(): Method writeObject() writes an object to the given stream. Here is the code of program: //SerializingObject /* This Program Creates user defined file name with extention */ import java.io.*;

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 25

public class SerializingObject{

public static void main(String[] Dnyan) throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.print("Please Dnyan enter The File name : ");

String file = in.readLine();

System.out.print("Enter extention : ");

String ext = in.readLine();

String filename = file + "." + ext;

File f = new File(filename);

try{

ObjectOutput ObjOut = new ObjectOutputStream(new FileOutputStream(f));

ObjOut.writeObject(f);

ObjOut.close();

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 26

System.out.println( "Serializing an Object Creation completed successfully."); } catch(IOException e){ System.out.println(e.getMessage()); } } } Output:

Puri Dnyaneshwar S. M.Sc(C.S)S.Y.

S.R.T.M.U.N.Sub-Center,Latur Advance Java

Page 27

You might also like