NOTE: The following are the few sample questions and ... · content length since the same...

32
NOTE: The following are the few sample questions and answers for reference purpose only. Students should not depend only on these questions. They must study the complete syllabus while preparing for the exams. 1. Why swing are called light weight components Swing components depend less on the target platform and use less of the native GUI resource. Hence the Swing components that don't rely on native GUI are referred to as lightweight components. 2. Mention different types of jdbc drivers. Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access any kind of tabular data, especially relational database. It acts as a middle layer interface between java applications and database. The JDBC classes are contained in the Java Package java.sql and javax.sql. JDBC helps us to write Java applications that manage these three programming activities: 1. Connect to a data source, like a database. 2. Send queries and update statements to the database. 3. Retrieve and process the results received from the database in answer to our query. There are 4 types of JDBC drivers: 1. JDBC- Open Database Connectivity (ODBC) Bridge. 2. Part Java, Part Native Driver. 3. Intermediate Database Access Server. 4. Pure Java Driver. 3. Define JSP directives and its types The directives provide directions and instructions to the container, telling it how to handle certain aspects of the JSP processing. A JSP directive affects the overall structure of the servlet class. It usually has the following form − <%@ directive attribute = "value" %>

Transcript of NOTE: The following are the few sample questions and ... · content length since the same...

Page 1: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

NOTE: The following are the few sample questions and answers for

reference purpose only. Students should not depend only on these questions.

They must study the complete syllabus while preparing for the exams.

1. Why swing are called light weight components

Swing components depend less on the target platform and use less of the native GUI resource. Hence the Swing components that don't rely on native GUI are referred to as lightweight components.

2. Mention different types of jdbc drivers.

Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access any kind of tabular data, especially relational database. It acts as a middle layer interface between java applications and database.

The JDBC classes are contained in the Java Package java.sql and javax.sql.

JDBC helps us to write Java applications that manage these three programming activities:

1. Connect to a data source, like a database. 2. Send queries and update statements to the database. 3. Retrieve and process the results received from the database in answer to

our query.

There are 4 types of JDBC drivers:

1. JDBC- Open Database Connectivity (ODBC) Bridge. 2. Part Java, Part Native Driver. 3. Intermediate Database Access Server. 4. Pure Java Driver.

3. Define JSP directives and its types

The directives provide directions and instructions to the container, telling it how to handle certain aspects of the JSP processing.

A JSP directive affects the overall structure of the servlet class. It usually has the following form −

<%@ directive attribute = "value" %>

Page 2: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

Directives can have a number of attributes which we can list down as key-value pairs and separated by commas.

There are three types of directive tag −

1. The page directive 2. The include directive 3. The taglib directive

4. What are the methods of java beans properties

Simple Properties A simple property has a single value. It can be identified by the following design patterns, where N is the name of the property and T is its type.

public T getN( ); public void setN(T arg);

A read/write property has both of these methods to access its values. A read-only property has only a get method. A write-only property has only a set method. Boolean Properties A Boolean property has a value of true or false. It can be identified by the following design patterns, where N is the name of the property:

public boolean isN( ); public boolean getN( ); public void setN(boolean value);

Either the first or second pattern can be used to retrieve the value of a Boolean property. However, if a class has both of these methods, the first pattern is used. Indexed Properties An indexed property consists of multiple values. It can be identified by the following design patterns, where N is the name of the property and T is its type:

public T getN(int index); public void setN(int index, T value); public T[ ] getN( ); public void setN(T values[ ]);

Page 3: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

5. explain 2 difference between get n post method

DoGet DoPost

In doGet Method the parameters are appended to the URL and sent along with header information

In doPost, parameters are sent in separate line in the body

Maximum size of data that can be sent using doget is 240 bytes

There is no maximum size for data

Parameters are not encrypted Parameters are encrypted

doGet method generally is used to query or to get some information from the server

doPost is generally used to update or post some information to the server

doGet is faster if we set the response content length since the same connection is used. Thus increasing the performance

doPost is slower compared to doGet since doPost does not write the content length

6. what r heavy weight components

A heavyweight component is associated with its own native screen resource (commonly known as a peer).Components from the java.awt package, such as Button and Label, are heavyweight components.

7. What are implicit objects?

JSP provides certain implicit objects, based on the servlet API. These objects are accessed using standard variables, and are automatically available for use in JSP without writing any extra code. The implicit objects available in JSP are 1. request 2. response 3. pageContext 4. session 5. application 6. out 7. config 8. page

8. List the types of beans

Page 4: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

There are 3 types of enterprise bean in java. Session Bean: Session bean contains business logic that can be invoked by local, remote or webservice client. Message Driven Bean: Like Session Bean, it contains the business logic but it is invoked by passing message. Entity Bean: It encapsulates the state that can be persisted in the database. It is deprecated. Now, it is replaced with JPA (Java Persistent API). Types of Session Beans Session beans are of three types: stateful, stateless, and singleton. Stateful Session Beans The state of an object consists of the values of its instance variables. In a stateful session bean, the instance variables represent the state of a unique client/bean session. Because the client interacts (“talks”) with its bean, this state is often called the conversational state. As its name suggests, a session bean is similar to an interactive session. A session bean is not shared; it can have only one client, in the same way that an interactive session can have only one user. When the client terminates, its session bean appears to terminate and is no longer associated with the client. The state is retained for the duration of the client/bean session. If the client removes the bean, the session ends and the state disappears. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean ends, there is no need to retain the state. Stateless Session Beans A stateless session bean does not maintain a conversational state with the client. When a client invokes the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client but only for the duration of the invocation. When the method is finished, the client-specific state should not be retained. Clients may, however, change the state of instance variables in pooled stateless beans, and this state is held over to the next invocation of the pooled stateless bean. Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client. That is, the state of a stateless session bean should apply across all clients. Because they can support multiple clients, stateless session beans can offer better scalability for applications that require large numbers of clients. Typically, an application requires fewer stateless session beans than stateful session beans to support the same number of clients.

Page 5: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

A stateless session bean can implement a web service, but a stateful session bean cannot. Singleton Session Beans A singleton session bean is instantiated once per application and exists for the lifecycle of the application. Singleton session beans are designed for circumstances in which a single enterprise bean instance is shared across and concurrently accessed by clients. Singleton session beans offer similar functionality to stateless session beans but differ from them in that there is only one singleton session bean per application, as opposed to a pool of stateless session beans, any of which may respond to a client request. Like stateless session beans, singleton session beans can implement web service endpoints. Singleton session beans maintain their state between client invocations but are not required to maintain their state across server crashes or shutdowns. Applications that use a singleton session bean may specify that the singleton should be instantiated upon application startup, which allows the singleton to perform initialization tasks for the application. The singleton may perform cleanup tasks on application shutdown as well, because the singleton will operate throughout the lifecycle of the application.

9. How does servlet different from applet

APPLETS SERVLETS

A Java applet is a small application which is written in Java and delivered to users in the form of bytecode.

A servlet is a Java programming language class used to extend the capabilities of a server.

Applets are executed on client side.

Servlets are executed on server side.

Applets are used to provide interactive features to web applications that cannot be provided by HTML alone like capture mouse input etc.

Servlets are the Java counterpart to other dynamic Web content technologies such as PHP and ASP.NET.

Life cycle of Applets init(), stop(), paint(), start(), destroy().

Lifecycle of servlets are:- init( ), service( ), and destroy( ).

Page 6: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

APPLETS SERVLETS

Packages available in Applets are :- import java.applet.*; and import java.awt.*.

Packages available in servlets are:- import javax.servlet.*; and import java.servlet.http.*;

Applets use user interface classes like AWT and Swing. No User interface required.

Applets are more prone to risk as it is on the client machine.

Servlets are under the server security.

Applets utilize more network bandwidth as it executes on the client machine.

Servlets are executed on the servers and hence require less bandwidth.

Requires java compatible browser for execution.

It accepts input from browser and generates response in the form of HTML Page, Javascript Object, Applets etc.

10. When a client request is sent to the servlet container, how does the container choose which servlet to invoke

The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response. For Example--- <servlet>

<servlet-name>admin</servlet-name> <servlet-class>com.servlet.LoginServlet</servlet-class>

</servlet> <servlet-mapping>

<servlet-name> admin </servlet-name> <url-pattern> /artadmin </url-pattern>

</servlet-mapping>

Page 7: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

If the url in browser is http://localhost:8080/artadmin then, server will call LoginServlet. Based on the above mapping.

11. Explain RMI in brief

RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in one system (JVM) to access/invoke an object running on another JVM. RMI is used to build distributed applications; it provides remote communication between Java programs. It is provided in the package java.rmi.

12. Note on jar files

A JAR file allows us to efficiently deploy a set of classes and their associated resources. For example, a developer may build a multimedia application that uses various sound and image files. A set of Beans can control how and when this information is presented. All of these pieces can be placed into one JAR file. JAR technology makes it much easier to deliver and install software. Also, the elements in a JAR file are compressed, which makes downloading a JAR file much faster than separately downloading several uncompressed files. Digital signatures may also be associated with the individual elements in a JAR file. This allows a consumer to be sure that these elements were produced by a specific organization or individual. The package java.util.zip contains classes that read and write JAR files.

13. Describe entity java bean

An entity bean is a remote object that manages persistent data, performs complex business logic, potentially uses several dependent Java objects, and can be uniquely identified by a primary key. Entity beans are normally coarse-grained persistent objects, in that they utilize persistent data stored within several fine-grained persistent Java objects.

14. What r the different constructors of jtextfield class. Explain the different parameters used in it

The Swing text field is encapsulated by the JTextComponent class, which extends JComponent. It provides functionality that is common to Swing text components. One of its subclasses is JTextField, which allows us to edit one line of text. Some of its constructors are:

Page 8: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

JTextField( ) JTextField(int cols) JTextField(String s, int cols) JTextField(String s)

Here, s is the string to be presented, and cols is the number of columns in the text field.

15. what is the purpose of drivermanager class in jdbc

The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver( )

The most common approach to register a driver is to use Java's Class.forName( ) method, to dynamically load the driver's class file into memory, which automatically registers it. This method is preferable because it allows us to make the driver registration configurable and portable.

16. What is a scriptlet in jsp? write its syntax

Scriptlets are the block of java code that is executed during the request processing time.

<html> <body> <% int num1=10; int num2=40; int num3 = num1+num2; out.println("Scriplet Number is " +num3); %> </body> </html>

17. What is java bean? list the advantages of java bean

JavaBeans are classes that encapsulate many objects into a single object (the bean). It is a java class that should follow following conventions: It provides a default, no-argument constructor.

1) It should be serializable and that which can implement the Serializable interface.

2) It may have a number of properties which can be read or written.

Page 9: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

3) It may have a number of "getter" and "setter" methods for the properties.

18. explain the steps to write an rmi program

To write an RMI Java application, we would have to follow the steps given below

Define the remote interface

Develop the implementation class (remote object)

Develop the server program

Develop the client program

Compile the application

Execute the application

Demonstration of a Simple Client/Server Application Using RMI

A simple client server application can be built using RMI to demonstrate the steps involved in developing RMI application. The server receives a request from a client, processes it, and returns a result. In this example, the request specifies two numbers. The server adds these together and returns the sum.

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.

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.

import java.rmi.*;

Page 10: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

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.

import java.net.*; import java.rmi.*; public class AddServer { public static void main(String args[ ]) { try { AddServerImpl addServerImpl = new AddServerImpl(); Naming.rebind("AddServer", addServerImpl); System.out.println("Server Started"); } 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,

Page 11: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

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.

Step Two: Generate Stubs and Skeletons

Before we can use the client and server, we must generate the necessary stub.

In the context 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.

To generate stubs and skeletons, we 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.

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.

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, we must check that the CLASSPATH environment variable includes the directory in which our files are located. Then, start the RMI Registry from the command line, as shown here:

Page 12: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

start rmiregistry

When this command returns, we should see that a new window has been created. We need to leave this window open until we are done experimenting with the RMI example.

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”.

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.

java AddClient IPAddress Number_1 Number_2

Example: java AddClient 127.0.0.1 15 78

19. Explain rmi architechture

RMI stands for Remote Method Invocation. It is a mechanism that allows an object residing in one system (JVM) to access/invoke an object running on another JVM.

RMI is used to build distributed applications; it provides remote communication between Java programs. It is provided in the package java.rmi.

Architecture of an RMI Application

In an RMI application, we write two programs, a server program (resides on the server) and a client program (resides on the client).

Inside the server program, a remote object is created and reference of that object is made available for the client (using the registry).

The client program requests the remote objects on the server and tries to invoke its methods.

Page 13: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

The architecture of RMI application consists of a client-server programs. Client and server has four layers on their side. The client side layers are client, stub, Remote Reference Layer (RRL), and transport layer. The server side layers are server, skeleton, Remote Reference Layer (RRL), and transport layer.

Transport Layer − This layer connects the client and the server. It manages the existing connection and also sets up new connections.

Stub − A stub is a representation (proxy) of the remote object at client. It resides in the client system; it acts as a gateway for the client program.

Skeleton − This is the object which resides on the server side. stub communicates with this skeleton to pass request to the remote object.

RRL(Remote Reference Layer) − It is the layer which manages the references made by the client to the remote object.

Working of an RMI Application

The following points summarize how an RMI application works −

When the client makes a call to the remote object, it is received by the stub which eventually passes this request to the RRL.

Page 14: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

When the client-side RRL receives the request, it invokes a method called invoke( ) of the object remoteRef. It passes the request to the RRL on the server side.

The RRL on the server side passes the request to the Skeleton (proxy on the server) which finally invokes the required object on the server.

The result is passed all the way back to the client.

Marshalling and Unmarshalling

Whenever a client invokes a method that accepts parameters on a remote object, the parameters are bundled into a message before being sent over the network. These parameters may be of primitive type or objects. In case of primitive type, the parameters are put together and a header is attached to it. In case the parameters are objects, then they are serialized. This process is known as marshalling.

At the server side, the packed parameters are unbundled and then the required method is invoked. This process is known as unmarshalling.

RMI Registry

RMI registry is a namespace on which all server objects are placed. Each time the server creates an object, it registers this object with the RMIregistry ( using bind( ) or reBind( ) methods). These are registered using a unique name known as bind name.

To invoke a remote object, the client needs a reference of that object. At that time, the client fetches the object from the registry using its bind name (using lookup() method).

The following illustration explains the entire process –

Page 15: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

20. Explain batch updates in jdbc

Batch Processing allows us to group related SQL statements into a batch and submit them with one call to the database. When we send several SQL statements to the database at once, we reduce the amount of communication overhead, thereby improving performance. JDBC drivers are not required to support this feature. We should use the DatabaseMetaData.supportsBatchUpdates( ) method to determine if the target database supports batch update processing. The method returns true if our JDBC driver supports this feature. The addBatch( ) method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch( ) is used to start the execution of all the statements grouped together.

Page 16: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

The executeBatch( ) returns an array of integers, and each element of the array represents the update count for the respective update statement. Just as we can add statements to a batch for processing, we can remove them with the clearBatch( ) method. This method removes all the statements we added with the addBatch( ) method. However, we cannot selectively choose which statement to remove. Batching with Statement Object Here is a typical sequence of steps to use Batch Processing with Statement Object − Create a Statement object using either createStatement( ) methods. Set auto-commit to false using setAutoCommit( ). Add as many as SQL statements you like into batch using addBatch( ) method on created statement object. Execute all the SQL statements using executeBatch( ) method on created statement object. Finally, commit all the changes using commit( ) method. Example: import java.sql.*; import java.io.*; public class BatchUpdate { public static void main(String args[]){ try{ Class.forName("org.apache.derby.jdbc.ClientDriver"); Connection con=DriverManager.getConnection("jdbc:derby://localhost:1527/student","student","student"); con.setAutoCommit(false); PreparedStatement ps=con.prepareStatement("insert into studentinfo values(?,?)"); BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); while(true){ System.out.println("enter id"); String s1=br.readLine(); int id=Integer.parseInt(s1);

Page 17: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

System.out.println("enter name"); String name=br.readLine(); ps.setInt(1,id); ps.setString(2,name); ps.executeUpdate(); ps.addBatch(); System.out.println("Want to add more records y/n"); String ans=br.readLine(); if(ans.equals("n")){ break; } } con.commit(); System.out.println("record successfully saved"); con.close();//before closing connection commit() is called }catch(Exception e){System.out.println(e);} } }

21. Explain java bean and its advantages

JavaBeans are classes that encapsulate many objects into a single object (the bean). It is a java class that should follow following conventions: It provides a default, no-argument constructor.

1) It should be serializable and that which can implement the Serializable interface.

2) It may have a number of properties which can be read or written.

3) It may have a number of "getter" and "setter" methods for the properties.

Advantages of Java Beans A software component architecture provides standard mechanisms to deal with software building blocks. The following list enumerates some of the specific benefits that Java technology provides for a component developer:

1) A Bean obtains all the benefits of Java’s “write-once, run-anywhere” paradigm.

2) The properties, events, and methods of a Bean that are exposed to an application builder tool can be controlled.

Page 18: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

3) A Bean may be designed to operate correctly in different locales, which makes it useful in global markets.

4) Auxiliary software can be provided to help a person configure a Bean. This software is only needed when the design-time parameters for that component are being set. It does not need to be included in the run-time environment.

5) The configuration settings of a Bean can be saved in persistent storage and restored at a later time.

6) A Bean may register to receive events from other objects and can generate events that are sent to other objects.

22. Explain the lifecycle of servlet

Life cycle of servlet

Three methods are central to the life cycle of a servlet. These are init( ),

service( ), and destroy( ). They are implemented by every servlet and are invoked at specific times by the server. Let us consider a typical user scenario to understand when these methods are called.

First, assume that a user enters a Uniform Resource Locator (URL) to a web browser. The browser then generates an HTTP request for this URL. This request is then sent to the appropriate server.

Second, this HTTP request is received by the web server. The server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space of the server.

Third, the server invokes the init( ) method of the servlet. This method is invoked only when the servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself.

Fourth, the server invokes the service( ) method of the servlet. This method is called to process the HTTP request. We will see that it is possible for the servlet to read data that has been provided in the HTTP request. It may also formulate an HTTP response for the client.

The servlet remains in the server’s address space and is available to process any other HTTP requests received from clients. The service( ) method is called for each HTTP request.

Finally, the server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server.

Page 19: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

The server calls the destroy( ) method to relinquish any resources such as file handles that are allocated for the servlet.

Important data may be saved to a persistent store. The memory allocated for the servlet and its objects can then be garbage collected.

The init( ) Method

The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init( ) method simply creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this −

public void init() throws ServletException {

// Initialization code...

}

The service( ) Method

The service( ) method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service( ) method to handle requests coming from the client( browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service( ) method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method −

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

}

Page 20: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

The doGet( ) Method

A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet( ) method.

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Servlet code

}

The doPost( ) Method

A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost( ) method.

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Servlet code

}

The destroy( ) Method

The destroy( ) method is called only once at the end of the life cycle of a servlet. This method gives our servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such clean-up activities.

After the destroy( ) method is called, the servlet object is marked for garbage collection.

The destroy method definition looks like this −

public void destroy( ) {

// Finalization code...

}

23. Explain Japplet class in swings

Page 21: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

Japplet class Fundamental to Swing is the JApplet class, which extends Applet. Applets that use Swing must be subclasses of JApplet. JApplet is rich with functionality that is not found in Applet. For example, JApplet supports various “panes,” such as the content pane, the glass pane, and the root pane. When adding a component to an instance of JApplet, do not invoke the add( ) method of the applet. Instead, call add( ) for the content pane of the JApplet object. The content pane can be obtained via the method shown below:

Container getContentPane( )

The add( ) method of Container can be used to add a component to a content pane. Its form is shown below:

void add(comp)

Here, comp is the component to be added to the content pane.

Write one applet program.

24. Explain the architecture of corba with advantages n disadvantages.

Architecture is same as given in study material (WhatsApp)

Advantages of CORBA Maturity - CORBA is extremely feature-rich, supporting many programming languages, operating systems, and a diverse range of capabilities such as transactions, security, Naming and Trading services. Open standard - users can choose the implementation from a variety of CORBA vendors. Wide platform support - CORBA implementations are accessible for a wide variety of computers, including IBM OS/390 and Fujitsu GlobalServer mainframes, LINUX, Windows and several embedded operating systems. Wide language support - CORBA defines standardized language mappings for a wide variety of programming languages, such as C, C++, Java, Smalltalk,COBOL,Python and IDLScript. Efficiency - The on-the-wire protocol infrastructure of CORBA guarantees that messages between clients and servers are transmitted in a compact representation. Scalability - The flexible, server-side infrastructure of CORBA makes it possible to develop servers that can scale from handling a small number of objects up to handling a virtually unlimited number of objects. Disadvantages of CORBA

Page 22: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

Firewall unfriendly - There's no real CORBA standard to bind an ORB and its clients to a port or a port range, there are (only) vendor specific options. Regarded as complicated – some remote invocation of CORBA interfaces is at least as simple as over XMLRPC (which is regarded as easy). No standard to get the initial reference for the naming services. No official Perl making - There are at least two Perl ORBs available as open source, but neither the mapping is official, nor are the implementations complete.

25. Explain standard action tags associated with jsp

Standard actions are tags that affect the runtime behaviour of the JSP and the response sent back to the client. There are many JSP action tags or elements. Each JSP action tag is used to perform some specific tasks. The action tags are used to control the flow between pages and to use Java Bean. JSP actions use constructs in XML syntax to control the behavior of the servlet engine. We can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. There is only one syntax for the Action element, as it conforms to the XML standard − <jsp:action_name attribute="value" /> Action elements are basically predefined functions. Following table lists out the available JSP Actions −

S.No. Syntax & Purpose

1 jsp:include Includes a file at the time the page is requested.

2 jsp:useBean Finds or instantiates a JavaBean.

3 jsp:setProperty Sets the property of a JavaBean.

4 jsp:getProperty Inserts the property of a JavaBean into the output.

5 jsp:forward Forwards the requester to a new page.

6 jsp:plugin

Page 23: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.

7 jsp:element Defines XML elements dynamically.

8 jsp:attribute Defines dynamically-defined XML element's attribute.

9 jsp:body Defines dynamically-defined XML element's body.

10 jsp:text Used to write template text in JSP pages and documents.

26. Explain the steps involved for processing sql statements with jdbc

Processing SQL Statements with JDBC In general, to process any SQL statement with JDBC, we follow these steps:

1. Establishing a connection. 2. Create a statement. 3. Execute the query. 4. Process the ResultSet object. 5. Close the connection.

Establishing Connections First, establish a connection with the data source you want to use. A data source can be a DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver. This connection is represented by a Connection object. Creating Statements A Statement is an interface that represents a SQL statement. We execute Statement objects, and they generate ResultSet objects, which is a table of data representing a database result set. We need a Connection object to create a Statement object.

ExampleL stmt = con.createStatement(); There are three different kinds of statements: Statement: Used to implement simple SQL statements with no parameters.

Page 24: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

PreparedStatement: (Extends Statement.) Used for precompiling SQL statements that might contain input parameters. CallableStatement: (Extends PreparedStatement.) Used to execute stored procedures that may contain both input and output parameters. Executing Queries To execute a query, call an execute method from Statement such as the following: execute: Returns true if the first object that the query returns is a ResultSet object. Use this method if the query could return one or more ResultSet objects. Retrieve the ResultSet objects returned from the query by repeatedly calling Statement.getResultSet. executeQuery: Returns one ResultSet object. executeUpdate: Returns an integer representing the number of rows affected by the SQL statement. Use this method if you are using INSERT, DELETE, or UPDATE SQL statements.

Example ResultSet rs = stmt.executeQuery(query); Processing ResultSet Objects We access the data in a ResultSet object through a cursor. Note that this cursor is not a database cursor. This cursor is a pointer that points to one row of data in the ResultSet object. Initially, the cursor is positioned before the first row. We call various methods defined in the ResultSet object to move the cursor. For example, the method ResultSet.next is called to move the cursor forward by one row. Every time it calls next, the method outputs the data in the row where the cursor is currently positioned: When you are finished using a Statement, call the method Statement.close to immediately release the resources it is using. When we call this method, its ResultSet objects are closed. JDBC throws an SQLException when it encounters an error during an interaction with a data source. Write one program (lab program) which demonstrate connection to database, insertion, deletion, display the records.

27. Explain different jsp directives.

JSP Directives

Page 25: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

The directives provide directions and instructions to the container, telling it how to handle certain aspects of the JSP processing.

A JSP directive affects the overall structure of the servlet class. It usually has the following form −

<%@ directive attribute = "value" %>

Directives can have a number of attributes which we can list down as key-value pairs and separated by commas.

There are three types of directive tag −

1. The page directive 2. The include directive 3. The taglib directive

The page directive

The directives provide directions and instructions to the container, telling it how to handle certain aspects of the JSP processing.

The page directive is used to define and manipulate a number of important page-dependent attributes that affect the whole JSP, and communicates these attributes to the JSP container.

<% page ATTRIBUTE%>

<%@ page attribute="value" %>

Attributes of JSP page directive : Import

<html> <body> <%@ page import="java.util.Date" %> Today is: <%= new Date( ) %> </body> </html> Attributes of JSP page directive : contentType

<html> <body> <%@ page contentType=application/msword %> Today is: <%= new java.util.Date( ) %> </body>

Page 26: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

</html>

Attributes of JSP page directive : info

<html> <body> <%@ page info="composed by Sonoo Jaiswal" %> Today is: <%= new java.util.Date( ) %> </body> </html>

The include directive

Include directive instructs the container to include the content of the resource in the current JSP, by inserting it, inline, in the JSP in place of directive.

<% include file=“FileName” %> <% if((request.getParameter("username").equals("qwerty")) && (request.getParameter("password").equals("123456"))) {%> <jsp:forward page="JSPForward2.jsp"/> <%}else{%> <%@include file="index.html"%> <% }%>

The taglib directive

The JSP API allow us to define custom JSP tags that look like HTML or XML tags and a tag library is a set of user-defined tags that implement custom behavior.

The taglib directive declares that our JSP page uses a set of custom tags, identifies the location of the library, and provides means for identifying the custom tags in our JSP page.

<%@ taglib uri="uri" prefix = "prefixOfTag" >

Here, the uri attribute value resolves to a location the container understands and the prefix attribute informs a container what bits of markup are custom actions.

Page 27: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

28. Give the component of URL. write a program(lab program)

A URL specification is based on four components.

The first is the protocol to use, separated from the rest of the locator by a colon (:). Common protocols are http, ftp, gopher, and file, although these days almost everything is being done via HTTP (in fact, most browsers will proceed correctly if we leave off the “http://” from your URL specification).

The second component is the host name or IP address of the host to use; this is delimited on the left by double slashes (//) and on the right by a slash (/) or optionally a colon (:).

The third component, the port number, is an optional parameter, delimited on the left from the host name by a colon (:) and on the right by a slash (/). (It defaults to port 80, the predefined HTTP port; thus “:80” is redundant.)

The fourth part is the actual file path. Most HTTP servers will append a file named index.html or index.htm to URLs that refer directly to a directory resource. Thus, http://www.osborne.com/ is the same as http://www.osborne.com/index.htm.

Java’s URL class has several constructors, and each can throw a MalformedURLException. One commonly used form specifies the URL with a string that is identical to what we see displayed in a browser:

URL(String urlSpecifier)

The next two forms of the constructor allow us to break up the URL into its component parts:

URL(String protocolName, String hostName, int port, String path)

URL(String protocolName, String hostName, String path)

Another frequently used constructor allows us to use an existing URL as a reference context and then create a new URL from that context. Although this sounds a little contorted, it’s really quite easy and useful.

URL(URL urlObj, String urlSpecifier)

import java.net.*; public class PgmA6_URLDisplay { public static void main(String args[]) throws MalformedURLException { URL urlobj=new URL("http://www.jyotinivas.org/gallery.html");

Page 28: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

System.out.println("Protocol : "+urlobj.getProtocol()); System.out.println("Port : "+urlobj.getPort()); System.out.println("Default Port : "+urlobj.getDefaultPort()); System.out.println("Host : "+urlobj.getHost()); System.out.println("File : "+urlobj.getFile()); System.out.println("External form : "+urlobj.toExternalForm()); } }

29. Write difference between stateless and stateful session bean.

Stateless Session Beans A session bean represents work performed by a single client. That work can be performed within a single method invocation, or it may span multiple method invocations. If the work does span more than one method, the object must retain the user’s object state across the method calls, and a stateful session bean would therefore be required. Generally, stateless beans are intended to perform individual operations automatically and don’t maintain state across method invocations. They’re also amorphous, in that any client can use any instance of a stateless bean at any time at the container’s discretion. They are the lightest weight and easiest to manage of the various EJB component configurations. Stateful Session Beans Stateful session beans maintain state both within and between transactions. Each stateful session bean is therefore associated with a specific client. Containers are able to save and retrieve a bean’s state automatically while managing instance pools (as opposed to bean pools) of stateful session beans. Stateful session beans maintain data consistency by updating their fields each time a transaction is committed. To keep informed of changes in transaction status, a stateful session bean implements the SessionSynchronization interface. The container calls methods of this interface while it initiates and completes transactions involving the bean. Session beans, whether stateful or stateless, are not designed to be persistent. The data maintained by stateful session beans is intended to be transitional. It is used solely for a particular session with a particular client. A stateful session bean instance typically can’t survive system failures and other

Page 29: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

destructive events. While a session bean has a container-provided identity (called its handle), that identity passes when the client removes the session bean at the end of a session. If a client needs to revive a stateful session bean that has disappeared, it must provide its own means to reconstruct the bean’s state. Stateful vs. Stateless Session Beans A stateful session bean will maintain a conversational state with a client. The state of the session is maintained for the duration of the conversation between the client and the stateful session bean. When the client removes the stateful session bean, its session ends and the state is destroyed. The transient nature of the state of the stateful session bean should not be problematic for either the client or the bean, because once the conversation between the client and the stateful session bean ends, neither the client nor the stateful session bean should have any use for the state. A stateless session bean will not maintain conversational states for specific clients longer than the period of an individual method invocation. Instance variables used by a method of a stateless bean may have a state, but only for the duration of the method invocation. After a method has finished running either successfully or unsuccessfully, the states of all its instance variables are dropped. The transient nature of this state gives the stateless session bean beneficial attributes, such as the following: Bean pooling: Any stateless session bean method instance that is not currently invoked is equally available to be called by an EJB container or application server to service the request of a client. This allows the EJB container to pool stateless bean instances and increase performance. Scalability: Because stateless session beans are able to service multiple clients, they tend to be more scalable when applications have a large number of clients. When compared to stateful session beans, stateless session beans usually require less instantiation. Performance: An EJB container will never move a stateless session bean from RAM out to a secondary storage, which it may do with a stateful session bean; therefore, stateless session beans may offer greater performance than stateful session beans.

Page 30: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

Since no explicit mapping exists between multiple clients and stateless bean instances, the EJB container is free to service any client’s request with any available instance. Even though the client calls the create( ) and remove( ) methods of the stateless session bean, making it appear that the client is controlling the lifecycle of an EJB (Enterprise Java Bean), it is actually the EJB container that is handling the create() and remove() methods without necessarily instantiating or destroying an EJB instance.

30. Explain significance of serialization in java bean persistence

Bean Persistence A bean has the property of persistence when its properties, fields, and state information are saved to and retrieved from storage. Component models provide a mechanism for persistence that enables the state of components to be stored in a non-volatile place for later retrieval. The mechanism that makes persistence possible is called serialization. Object serialization means converting an object into a data stream and writing it to storage. Any applet, application, or tool that uses that bean can then "reconstitute" it by deserialization. The object is then restored to its original state. For example, a Java application can serialize a Frame window on a Microsoft Windows machine, the serialized file can be sent with e-mail to a Solaris machine, and then a Java application can restore the Frame window to the exact state which existed on the Microsoft Windows machine. Any applet, application, or tool that uses that bean can then "reconstitute" it by deserialization. All beans must persist. To persist, your beans must support serialization by implementing either the java.io.Serializable (in the API reference documentation) interface, or the java.io.Externalizable (in the API reference documentation) interface. These interfaces offer you the choices of automatic serialization and customized serialization. If any class in a class's inheritance hierarchy implements Serializable or Externalizable, then that class is serializable. Classes That Are Serializable

Page 31: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

Any class is serializable as long as that class or a parent class implements the java.io.Serializable interface. Examples of serializable classes include Component, String, Date, Vector, and Hashtable. Thus, any subclass of the Component class, including Applet, can be serialized. Notable classes not supporting serialization include Image, Thread, Socket, and InputStream. Attempting to serialize objects of these types will result in an NotSerializableException. The Java Object Serialization API automatically serializes most fields of a Serializable object to the storage stream. This includes primitive types, arrays,and strings. The API does not serialize or deserialize fields that are marked transient or static. Controlling Serialization You can control the level of serialization that your beans undergo. Three ways to control serilization are: Automatic serialization, implemented by the Serializable interface. The Java serialization software serializes the entire object, except transient and static fields. Customized serialization. Selectively exclude fields you do not want serialized by marking with the transient (or static) modifier. Customized file format, implemented by the Externalizable interface and its two methods. Beans are written in a specific file format. Default Serialization: The Serializable Interface The Serializable interface provides automatic serialization by using the Java Object Serialization tools. Serializable declares no methods; it acts as a marker, telling the Object Serialization tools that your bean class is serializable. Marking your class Serializable means you are telling the Java Virtual Machine (JVM) that you have made sure your class will work with default serialization. Here are some important points about working with the Serializable interface: Classes that implement Serializable must have an access to a no-argument constructor of supertype. This constructor will be called when an object is "reconstituted" from a .ser file. You don't need to implement Serializable in your class if it is already implemented in a superclass.

Page 32: NOTE: The following are the few sample questions and ... · content length since the same connection is used. Thus increasing the performance doPost is slower compared to doGet since

All fields except static and transient fields are serialized. Use the transient modifier to specify fields you do not want serialized, and to specify classes that are not serializable. Selective Serialization Using the transient Keyword To exclude fields from serialization in a Serializable object mark the fields with the transient modifier. transient int status; Default serialization will not serialize transient and static fields. Selective Serialization: writeObject and readObject If your serializable class contains either of the following two methods (the signatures must be exact), then the default serialization will not take place. private void writeObject(java.io.ObjectOutputStream out) throws IOException; private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException; You can control how more complex objects are serialized, by writing your own implementations of the writeObject and readObject methods. Implement writeObject when you need to exercise greater control over what gets serialized when you need to serialize objects that default serialization cannot handle, or when you need to add data to the serialization stream that is not an object data member. Implement readObject to reconstruct the data stream you wrote with writeObject. The Externalizable Interface

Use the Externalizable interface when you need complete control over your bean's serialization (for example, when writing and reading a specific file format). To use the Externalizable interface you need to implement two methods: readExternal and writeExternal. Classes that implement Externalizable must have a no-argument constructor.