You are on page 1of 233

Core java Q1. What is the difference between an Abstract class and Interface? 1.

Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code. 2. An class can implement any number of interfaces, but subclass at most one abstract class. 3. An abstract class can have nonabstract methods. All methods of an interface are abstract. 4. An abstract class can have instance variables. An interface cannot. 5. An abstract class can define constructor. An interface cannot. 6. An abstract class can have any visibility: public, protected, private or none (package). An interface's visibility must be public or none (package). 7. An abstract class inherits from Object and includes methods such as clone() and equals(). Q2.What are checked and unchecked exceptions? Java defines two kinds of exceptions : Checked exceptions : Exceptions that inherit from the Exception class are checked exceptions. Client code has to handle the checked exceptions thrown by the API, either in a catch clause or by forwarding it outward with the throws clause. Examples - SQLException, IOxception. Unchecked exceptions : RuntimeException also extends from Exception. However, all of the exceptions that inherit from RuntimeException get special treatment. There is no requirement for the client code to deal with them, and hence they are called unchecked exceptions. Example Unchecked exceptions are NullPointerException, OutOfMemoryError, DivideByZeroException typically, programming errors. Q3.What is a user defined exception? User-defined exceptions may be implemented by defining a class to respond to the exception and embedding a throw statement in the try block where the exception can occur or declaring that the method throws the exception (to another method where it is handled). The developer can define a new exception by deriving it from the Exception class as follows: public class MyException extends Exception { /* class definition of constructors (but NOT the exception handling code) goes here public MyException() { super(); } public MyException( String errorMessage ) { super( errorMessage ); } } The throw statement is used to signal the occurance of the exception within a try block. Often, exceptions are instantiated in the same statement in which they are thrown using the syntax. throw new MyException("I threw my own exception.") To handle the exception within the method where it is thrown, a catch statement that handles MyException, must follow the try block. If the developer does not want to handle the exception in the method itself, the method must pass the exception using the syntax: public myMethodName() throws MyException Q4.What is the difference between C++ & Java? Well as Bjarne Stroustrup says "..despite the syntactic similarities, C++ and Java are very different languages. In many ways, Java seems closer to Smalltalk than to C++..". Here are few I discovered: Java is multithreaded Java has no pointers

Java has automatic memory management (garbage collection) Java is platform independent (Stroustrup may differ by saying "Java is a platform" Java has built-in support for comment documentation Java has no operator overloading Java doesnt provide multiple inheritance There are no destructors in Java

Q5.What are statements in JAVA ? Statements are equivalent to sentences in natural languages. A statement forms a complete unit of execution. The following types of expressions can be made into a statement by terminating the expression with a semicolon Assignment expressions Any use of ++ or - Method calls Object creation expressions These kinds of statements are called expression statements. In addition to these kinds of expression statements, there are two other kinds of statements. A declaration statement declares a variable. A control flow statement regulates the order in which statements get executed. The for loop and the if statement are both examples of control flow statements. Q6.What is JAR file? JavaARchive files are a big glob of Java classes, images, audio, etc., compressed to make one simple, smaller file to ease Applet downloading. Normally when a browser encounters an applet, it goes and downloads all the files, images, audio, used by the Applet separately. This can lead to slower downloads. Q7.What is JNI? JNI is an acronym of Java Native Interface. Using JNI we can call functions which are written in other languages from Java. Following are its advantages and disadvantages. Advantages: You want to use your existing library which was previously written in other language. You want to call Windows API function. For the sake of execution speed. You want to call API function of some server product which is in c or c++ from java client. Disadvantages: You cant say write once run anywhere. Difficult to debug runtime error in native code. Potential security risk. You cant call it from Applet. Q8.What is serialization? Quite simply, object serialization provides a program the ability to read or write a whole object to and from a raw byte stream. It allows Java objects and primitives to be encoded into a byte stream suitable for streaming to some type of network or to a file-system, or more generally, to a transmission medium or storage facility. A seralizable object must implement the Serilizable interface. We use ObjectOutputStream to write this object to a stream and ObjectInputStream to read it from the stream. Q9.Why there are some null interface in java ? What does it mean ? Give me some null interfaces in JAVA? Null interfaces act as markers..they just tell the compiler that the objects of this class need to be treated differently..some marker interfaces are : Serializable, Remote, Cloneable Q10. Is synchronised a modifier?indentifier??what is it?? It's a modifier. Synchronized methods are methods that are used to control access to an object. A

thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. Q11.What is singleton class?where is it used? Singleton is a design pattern meant to provide one and only one instance of an object. Other objects can get a reference to this instance through a static method (class constructor is kept private). Why do we need one? Sometimes it is necessary, and often sufficient, to create a single instance of a given class. This has advantages in memory management, and for Java, in garbage collection. Moreover, restricting the number of instances may be necessary or desirable for technological or business reasons--for example, we may only want a single instance of a pool of database connections. Q12.What is a compilation unit? The smallest unit of source code that can be compiled, i.e. a .java file. Q13.Is string a wrapper class? String is a class, but not a wrapper class. Wrapper classes like (Integer) exist for each primitive type. They can be used to convert a primitive data value into an object, and viceversa. Q14.Why java does not have multiple inheritance? The Java design team strove to make Java: Simple, object oriented, and familiar Robust and secure Architecture neutral and portable High performance Interpreted, threaded, and dynamic The reasons for omitting multiple inheritance from the Java language mostly stem from the "simple, object oriented, and familiar" goal. As a simple language, Java's creators wanted a language that most developers could grasp without extensive training. To that end, they worked to make the language as similar to C++ as possible (familiar) without carrying over C++'s unnecessary complexity (simple). In the designers' opinion, multiple inheritance causes more problems and confusion than it solves. So they cut multiple inheritance from the language (just as they cut operator overloading). The designers' extensive C++ experience taught them that multiple inheritance just wasn't worth the headache. Q15.Why java is not a 100% oops? Many people say this because Java uses primitive types such as int, char, double. But then all the rest are objects. Confusing question. Q16.What is a resource bundle? In its simplest form, a resource bundle is represented by a text file containing keys and a text value for each key. Q17.What is transient variable? Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null. Q18.What is Collection API? The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces. Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap. Example of interfaces: Collection, Set, List and Map.

Q19.Is Iterator a Class or Interface? What is its use? Iterator is an interface which is used to step through the elements of a Collection. Q20.What is similarities/difference between an Abstract class and Interface? Differences are as follows: Interfaces provide a form of multiple inheritance. A class can extend only one other class. Interfaces are limited to public methods and constants with no implementation. Abstract classes can have a partial implementation, protected parts, static methods, etc. A Class may implement several interfaces. But in case of abstract class, a class may extend only one abstract class. Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast. Similarities: Neither Abstract classes or Interface can be instantiated. Q21.What is a transient variable? A transient variable is a variable that may not be serialized. Q22.Which containers use a border Layout as their default layout? The window, Frame and Dialog classes use a border layout as their default layout. Q23.Why do threads block on I/O? Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed. Q24.How are Observer and Observable used? Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. Q21.What is a transient variable? A transient variable is a variable that may not be serialized. Q22.Which containers use a border Layout as their default layout? The window, Frame and Dialog classes use a border layout as their default layout. Q23.Why do threads block on I/O? Threads block on i/o (that is enters the waiting state) so that other threads may execute while the i/o Operation is performed. Q24.How are Observer and Observable used? Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects. Q25.What is synchronization and why is it important? With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors. Q26. Can a lock be acquired on a class? Yes, a lock can be acquired on a class. This lock is acquired on the class's Class object.

Q27. What's new with the stop(), suspend() and resume() methods in JDK 1.2? The stop(), suspend() and resume() methods have been deprecated in JDK 1.2. Q28. Is null a keyword? The null value is not a keyword. Q29. What is the preferred size of a component? The preferred size of a component is the minimum component size that will allow the component to display normally. Q30. What method is used to specify a container's layout? The setLayout() method is used to specify a container's layout. Q31. Which containers use a FlowLayout as their default layout? The Panel and Applet classes use the FlowLayout as their default layout. Q32. What state does a thread enter when it terminates its processing? When a thread terminates its processing, it enters the dead state. Q33. What is the Collections API? The Collections API is a set of classes and interfaces that support operations on collections of objects. Q34. Which characters may be used as the second character of an identifier, but not as the first character of an identifier? The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of anidentifier. Q35. What is the List interface? The List interface provides support for ordered collections of objects. Q36. How does Java handle integer overflows and underflows? It uses those low order bytes of the result that can fit into the size of the type allowed by the operation. Q37. What is the Vector class? The Vector class provides the capability to implement a growable array of objects Q38. What modifiers may be used with an inner class that is a member of an outer class? A (non-local) inner class may be declared as public, protected, private, static, final, or abstract. Q39. What is an Iterator interface? The Iterator interface is used to step through the elements of a Collection. Q40. What is the difference between the >> and >>> operators? The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out. Q41. Which method of the Component class is used to set the position and size of a component? setBounds() Q42. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

Q43. What is the difference between yielding and sleeping? When a task invokes its yield() method, it returns to the ready state. When a task invokes its sleep() method, it returns to the waiting state. Q44. Which java.util classes and interfaces support event handling? The EventObject class and the EventListener interface support event processing. Q45. Is sizeof a keyword? The sizeof operator is not a keyword. Q46. What are wrapped classes? Wrapped classes are classes that allow primitive types to be accessed as objects. Q47. Does garbage collection guarantee that a program will not run out of memory? Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection Q48. What restrictions are placed on the location of a package statement within a source code file? A package statement must appear as the first line in a source code file (excluding blank lines and comments). Q49. Can an object's finalize() method be invoked while it is reachable? An object's finalize() method cannot be invoked by the garbage collector while the object is still reachable. However, an object's finalize() method may be invoked by other objects. Q50. What is the immediate superclass of the Applet class? Panel Q51. What is the difference between preemptive scheduling and time slicing? Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors. Q52 Name three Component subclasses that support painting. The Canvas, Frame, Panel, and Applet classes support painting. Q53. What value does readLine() return when it has reached the end of a file? The readLine() method returns null when it has reached the end of a file. Q54. What is the immediate superclass of the Dialog class? Window Q55. What is clipping? Clipping is the process of confining paint operations to a limited area or shape. Q56. What is a native method? A native method is a method that is implemented in a language other than Java. Q57. Can a for statement loop indefinitely? Yes, a for statement can loop indefinitely. For example, consider the following: for(;;) ;

Q58. What are order of precedence and associativity, and how are they used? Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left Q59. When a thread blocks on I/O, what state does it enter? A thread enters the waiting state when it blocks on I/O. Q60. To what value is a variable of the String type automatically initialized? The default value of an String type is null. Q61. What is the catch or declare rule for method declarations? If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause. Q62. What is the difference between a MenuItem and a CheckboxMenuItem? The CheckboxMenuItem class extends the MenuItem class to support a menu item that may be checked or unchecked. Q63. What is a task's priority and how is it used in scheduling? A task's priority is an integer value that identifies the relative order in which it should be executed with respect to other tasks. The scheduler attempts to schedule higher priority tasks before lower priority tasks. Q64. What class is the top of the AWT event hierarchy? The java.awt.AWTEvent class is the highest-level class in the AWT event-class hierarchy. Q65. When a thread is created and started, what is its initial state? A thread is in the ready state after it has been created and started. Q66. Can an anonymous class be declared as implementing an interface and extending a class? An anonymous class may implement an interface or extend a superclass, but may not be declared to do both. Q67. What is the range of the short type? The range of the short type is -(2^15) to 2^15 - 1. Q68. What is the range of the char type? The range of the char type is 0 to 2^16 - 1. Q69. In which package are most of the AWT events that support the event-delegation model defined? Most of the AWT-related events of the event-delegation model are defined in the java.awt.event package. The AWTEvent class is defined in the java.awt package. Q70. What is the immediate superclass of Menu? MenuItem Q71. What is the purpose of finalization? The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected. Q72. Which class is the immediate superclass of the MenuComponent class. Object

Q73. What invokes a thread's run() method? After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed. Q74. What is the difference between the Boolean & operator and the && operator? If an expression involving the Boolean & operator is evaluated, both operands are evaluated. Then the & operator is applied to the operand. When an expression involving the && operator is evaluated, the first operand is evaluated. If the first operand returns a value of true then the second operand is evaluated. The && operator is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of the second operand is skipped. Q75. Name three subclasses of the Component class. Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, Scrollbar, or TextComponent Q76. What is the GregorianCalendar class? The GregorianCalendar provides support for traditional Western calendars. Q77. Which Container method is used to cause a container to be laid out and redisplayed? validate() Q78. What is the purpose of the Runtime class? The purpose of the Runtime class is to provide access to the Java runtime system. Q79. How many times may an object's finalize() method be invoked by the garbage collector? An object's finalize() method may only be invoked once by the garbage collector. Q80. What is the purpose of the finally clause of a try-catchfinally statement? The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught. Q81. What is the argument type of a program's main() method? A program's main() method takes an argument of the String[] type. Q82. Which Java operator is right associative? The = operator is right associative. Q83. What is the Locale class? The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region. Q84. Can a double value be cast to a byte? Yes, a double value can be cast to a byte. Q85. What is the difference between a break statement and a continue statement? A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the loop statement. Q86. What must a class do to implement an interface? It must provide all of the methods in the interface and identify the interface in its implements clause.

Q87. What method is invoked to cause an object to begin executing as a separate thread? The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread. Q88. Name two subclasses of the TextComponent class. TextField and TextArea Q89. What is the advantage of the event-delegation model over the earlier eventinheritance model? The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model. Q90. Which containers may have a MenuBar? Frame Q91. How are commas used in the intialization and iteration parts of a for statement? Commas are used to separate multiple statements within the initialization and iteration parts of a for statement. Q92. What is the purpose of the wait(), notify(), and notifyAll() methods? The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.. Q89. What is the advantage of the event-delegation model over the earlier eventinheritance model? The event-delegation model has two advantages over the event-inheritance model. First, it enables event handling to be handled by objects other than the ones that generate the events (or their containers). This allows a clean separation between a component's design and its use. The other advantage of the event-delegation model is that it performs much better in applications where many events are generated. This performance improvement is due to the fact that the event-delegation model does not have to repeatedly process unhandled events, as is the case of the event-inheritance model. Q90. Which containers may have a MenuBar? Frame Q91. How are commas used in the intialization and iteration parts of a for statement? Commas are used to separate multiple statements within the initialization and iteration parts of a for statement. Q92. What is the purpose of the wait(), notify(), and notifyAll() methods? The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.. Q93. What is an abstract method? An abstract method is a method whose implementation is deferred to a subclass. Q94. How are Java source code files named? A Java source code file takes the name of a public class or interface that is defined within the file.

A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the filemust take on a name that is different than its classes and interfaces. Source code files use the .java extension. Q95. What is the relationship between the Canvas class and the Graphics class? A Canvas object provides access to a Graphics object via its paint() method. Q96. What are the high-level thread states? The high-level thread states are ready, running, waiting, and dead. Q97. What value does read() return when it has reached the end of a file? The read() method returns -1 when it has reached the end of a file. Q98. Can a Byte object be cast to a double value? No, an object cannot be cast to a primitive value. Q99. What is the difference between a static and a nonstatic inner class? A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances. Q100. What is the difference between the String and StringBuffer classes? String objects are constants. StringBuffer objects are not. Q101. If a variable is declared as private, where may the variable be accessed? A private variable may only be accessed within the class in which it is declared. Q102. What is an object's lock and which object's have locks? An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object. Q103. What is the Dictionary class? The Dictionary class provides the capability to store key-value pairs. Q104. How are the elements of a BorderLayout organized? The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container. Q105. What is the % operator? It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand. Q106. When can an object reference be cast to an interface reference? An object reference be cast to an interface reference when the object implements the referenced interface. Q107. What is the difference between a Window and a Frame? The Frame class extends Window to define a main application window that can have a menu bar. Q108. Which class is extended by all other classes? The Object class is extended by all other classes.

Q109. Can an object be garbage collected while it is still reachable? A reachable object cannot be garbage collected. Only unreachable objects may be garbage collected.. Q110. Is the ternary operator written x : y ? z or x ? y : z ? It is written x ? y : z. Q111. What is the difference between the Font and FontMetrics classes? The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object. Q112. How is rounding performed under integer division? The fractional part of the result is truncated. This is known as rounding toward zero. Q113. What happens when a thread cannot acquire a lock on an object? If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available. Q114. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream classhierarchy? The Reader/Writer class hierarchy is character-oriented, and the InputStream/ OutputStream class hierarchy is byte-oriented. Q115. What classes of exceptions may be caught by a catch clause? A catch clause can catch any exception that may be assigned to the Throwable type. This includes the Error and Exception types. Q116. If a class is declared without any access modifiers, where may the class be accessed? A class that is declared without any access modifiers is said to have package access. This means that the class can only be accessed by other classes and interfaces that are defined within the same package. Q117. What is the SimpleTimeZone class? The SimpleTimeZone class provides support for a Gregorian calendar. Q118. What is the Map interface? The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values. Q119. Does a class inherit the constructors of its superclass? A class does not inherit constructors from any of its superclasses. Q120. For which statements does it make sense to use a label? The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement. Q121. What is the purpose of the System class? The purpose of the System class is to provide access to system resources. Q122. Which TextComponent method is used to set a TextComponent to the readonly state? setEditable() Q123. How are the elements of a CardLayout organized? The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

Q124. Is &&= a valid Java operator? No, it is not. Q125. Name the eight primitive Java types? The eight primitive types are byte, char, short, int, long, float, double, and boolean. Q126. Which class should you use to obtain design information about an object? The Class class is used to obtain information about an object's design. Q127. What is the relationship between clipping and repainting? When a window is repainted by the AWT painting thread, it sets the clipping regions to the area of the window that requires repainting. Q128. Is "abc" a primitive value? The String literal "abc" is not a primitive value. It is a String object. Q129. What is the relationship between an event-listener interface and an event-adapter class? An event-listener interface defines the methods that must be implemented by an event handler for a particular kind of event. An event adapter provides a default implementation of an event-listener interface. Q130. What restrictions are placed on the values of each case of a switch statement? During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value. Q131. What modifiers may be used with an interface declaration? An interface may be declared as public or abstract. Q132. Is a class a subclass of itself? A class is a subclass of itself. Q133. What is the highest-level event class of the eventdelegation model? The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy. Q134. What event results from the clicking of a button? The ActionEvent event is generated as the result of the clicking of a button. Q135. How can a GUI component handle its own events? A component can handle its own events by implementing the required event-listener interface and adding itself as its own event listener. Q136. What is the difference between a while statement and a do statement? A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once. Q137. How are the elements of a GridBagLayout organized? The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes. Q138. What advantage do Java's layout managers provide over traditional windowing systems? Java uses layout managers to lay out components in a consistent manner across all windowing

platforms. Since Java's layout managers aren't tied to absolute sizing and positioning, they are able to accomodate platform-specific differences among windowing systems. Q139. What is the Collection interface? The Collection interface provides support for the implementation of a mathematical bag an unordered collection of objects that may contain duplicates. Q140. What modifiers can be used with a local inner class? A local inner class may be final or abstract. Q141. What is the difference between static and non-staticvariables? A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance. Q142. What is the difference between the paint() and repaint() methods? The paint() method supports painting via a Graphics object. The repaint() method is used to cause paint() to be invoked by the AWT painting thread. Q143. What is the purpose of the File class? The File class is used to create objects that provide access to the files and directories of a local file system. Q144. Can an exception be rethrown? Yes, an exception can be rethrown. Q145. Which Math method is used to calculate the absolute value of a number? The abs() method is used to calculate absolute values. Q146. How does multithreading take place on a computer with a single CPU? The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially. Q147. When does the compiler supply a default constructor for a class? The compiler supplies a default constructor for a class if no other constructors are provided. Q148. When is the finally clause of a try-catch-finally statement executed? The finally clause of the try-catch-finally statement is always executed unless the thread of execution terminates or an exception occurs within the execution of the finally clause. Q149. Which class is the immediate superclass of the Container class? Component Q150. If a method is declared as protected, where may the method be accessed? A protected method may only be accessed by classes or interfaces of the same package or by subclasses of the class in which it is declared. Q151. How can the Checkbox class be used to create a radio button? By associating Checkbox objects with a CheckboxGroup. Q152. Which non-Unicode letter characters may be used as the first character of an identifier? The non-Unicode letter characters $ and _ may appear as the first character of an identifier

Q153. What restrictions are placed on method overloading? Two methods may not have the same name and argument list but different return types. Q154. What happens when you invoke a thread's interrupt method while it is sleeping or waiting? When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown. Q155. What is casting? There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference. Q156. What is the return type of a program's main() method? A program's main() method has a void return type.

Q157. Name four Container classes. Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane Q158. What is the difference between a Choice and a List? A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice. A List may be displayed in such a way that several List items are visible. A List supports the selection of one or more List items. Q159. What class of exceptions are generated by the Java run-time system? The Java runtime system generates RuntimeException and Error exceptions. Q160. What class allows you to read objects directly from a stream? The ObjectInputStream class supports the reading of objects from input streams.

Q161. What is the difference between a field variable and a local variable? A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declared local to a method. Q162. Under what conditions is an object's finalize() method invoked by the garbage collector? The garbage collector invokes an object's finalize() method when it detects that the object has become unreachable. Q163. How are this() and super() used with constructors? this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor. Q164. What is the relationship between a method's throws clause and the exceptions that can be thrown during themethod's execution? A method's throws clause must declare any checked exceptions that are not caught within the body of the method. Q165. What is the difference between the JDK 1.02 event model and the event-delegation model introduced withJDK 1.1?

The JDK 1.02 event model uses an event inheritance or bubbling approach. In this model, components are required to handle their own events. If they do not handle a particular event, the event is inherited by (or bubbled up to) the component's container. The container then either handles the event or it is bubbled up to its container and so on, until the highest-level container has been tried..In the event-delegation model, specific objects are designated as event handlers for GUI components. These objects implement event-listener interfaces. The event-delegation model is more efficient than the event-inheritance model because it eliminates the processing required to support the bubbling of unhandled events. Q166. How is it possible for two String objects with identical values not to be equal under the == operator? The == operator compares two objects to determine if they are the same object in memory. It is possible for two String objects to have the same value, but located indifferent areas of memory. Q167. Why are the methods of the Math class static? So they can be invoked as if they are a mathematical code library. Q168. What Checkbox method allows you to tell if a Checkbox is checked? getState() Q169. What state is a thread in when it is executing? An executing thread is in the running state. Q170. What are the legal operands of the instanceof operator? The left operand is an object reference or null value and the right operand is a class, interface, or array type. Q171. How are the elements of a GridLayout organized? The elements of a GridBad layout are of equal size and are laid out using the squares of a grid. Q172. What an I/O filter? An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. Q173. If an object is garbage collected, can it become reachable again? Once an object is garbage collected, it ceases to exist. It can no longer become reachable again. Q174. What is the Set interface? The Set interface provides methods for accessing the elements of a finite mathematical set. Sets do not allow duplicate elements. Q175. What classes of exceptions may be thrown by a throw statement? A throw statement may throw any expression that may be assigned to the Throwable type. Q176. What are E and PI? E is the base of the natural logarithm and PI is mathematical value pi. Q177. Are true and false keywords? The values true and false are not keywords. Q178. What is a void return type? A void return type indicates that a method does not return a value.

Q179. What is the purpose of the enableEvents() method? The enableEvents() method is used to enable an event for a particular object. Normally, an event is enabled when a listener is added to an object for a particular event. The enableEvents() method is used by objects that handle events by overriding their eventdispatch methods. Q180. What is the difference between the File and RandomAccessFile classes? The File class encapsulates the files and directories of the local file system. The RandomAccessFile class provides the methods needed to directly access data contained in any part of a file. Q181. What happens when you add a double value to a String? The result is a String object. Q182. What is your platform's default character encoding? If you are running Java on English Windows platforms, it is probably Cp1252. If you are running Java on English Solaris platforms, it is most likely 8859_1.. Q183. Which package is always imported by default? The java.lang package is always imported by default. Q184. What interface must an object implement before it can be written to a stream as an object? An object must implement the Serializable or Externalizable interface before it can be written to a stream as an object. Q185. How are this and super used? this is used to refer to the current object instance. super is used to refer to the variables and methods of the superclass of the current object instance. Q186. What is the purpose of garbage collection? The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources may be reclaimed and reused. Q187. What is a compilation unit? A compilation unit is a Java source code file. Q188. What interface is extended by AWT event listeners? All AWT event listeners extend the java.util.EventListener interface. Q189. What restrictions are placed on method overriding? Overridden methods must have the same name, argument list, and return type. The overriding method may not limit the access of the method it overrides. The overriding method may not throw any exceptions that may not be thrownby the overridden method. Q190. How can a dead thread be restarted? A dead thread cannot be restarted. Q191. What happens if an exception is not caught? An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked, which eventually results in the termination of the program in which it is thrown. Q192. What is a layout manager? A layout manager is an object that is used to organize components in a container.

Q193. Which arithmetic operations can result in the throwing of an ArithmeticException? Integer / and % can result in the throwing of an ArithmeticException. Q194. What are three ways in which a thread can enter the waiting state? A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (deprecated) suspend() method. Q195. Can an abstract class be final? An abstract class may not be declared as final. Q196. What is the ResourceBundle class? The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program's appearance to the particular locale in which it is being run. Q197. What happens if a try-catch-finally statement doesnot have a catch clause to handle an exception that is thrown within the body of the try statement? The exception propagates up to the next higher level try-catch statement (if any) or results in the program's termination. Q198. What is numeric promotion? Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integer and floating-point operations may take place. In numerical promotion, byte, char, and short values are converted to int values. The int values are also converted to long values, if necessary. The long and float values are converted to double values, as required. Q199. What is the difference between a Scrollbar and a ScrollPane? A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling. Q200. What is the difference between a public and a nonpublic class? A public class may be accessed outside of its package. A non-public class may not be accessed outside of its package. Q201. To what value is a variable of the boolean type automatically initialized? The default value of the boolean type is false. Q202. Can try statements be nested? Try statements may be tested. Q203. What is the difference between the prefix and postfix forms of the ++ operator? The prefix form performs the increment operation and returns the value of the increment operation. The postfix form returns the current value all of the expression and then performs the increment operation on that value. Q204. What is the purpose of a statement block? A statement block is used to organize a sequence of statements as a single statement group. Q205. What is a Java package and how is it used? A Java package is a naming context for classes and interfaces. A package is used to create a separate namespace for groups of classes and interfaces. Packages are also used to

organize related classes and interfaces into a single API unit and to control accessibility to these classes and interfaces. Q206. What modifiers may be used with a top-level class? A top-level class may be public, abstract, or final. Q207. What are the Object and Class classes used for? The Object class is the highest-level class in the Java class hierarchy. The Class class is used to represent the classes and interfaces that are loaded by a Java program.. Q208. How does a try statement determine which catch clause should be used to handle an exception? When an exception is thrown within the body of a try statement, the catch clauses of the try statement are examined in the order in which they appear. The first catch clause that is capable of handling the exception is executed. The remaining catch clauses are ignored. Q209. Can an unreachable object become reachable again? An unreachable object may become reachable again. This can happen when the object's finalize() method is invoked and the object performs an operation which causes it to become accessible to reachable objects. Q210. When is an object subject to garbage collection? An object is subject to garbage collection when it becomes unreachable to the program in which it is used. Q211. What method must be implemented by all threads? All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface. Q212. What methods are used to get and set the text label displayed by a Button object? getLabel() and setLabel() Q213. Which Component subclass is used for drawing and painting? Canvas Q214. What are synchronized methods and synchronized statements? Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement. Q215. What are the two basic ways in which classes that can be run as threads may be defined? A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface. Q216. What are the problems faced by Java programmers who don't use layout managers? Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system. Q217. What is the difference between an if statement and a switch statement? The if statement is used to select among two alternatives. It uses a boolean expression to decide which alternative should be executed. The switch statement is used to select among multiple alternatives. It uses an int expression to determine which alternative should be executed.

Q218. What happens when you add a double value to a String? The result is a String object. Q219. What is the List interface? The List interface provides support for ordered collections of objects.

Exception 1.What is an Exception? Ans.An unwanted, unexpected event that disturbs normal flow of the program is called Exception.Example: FileNotFondException. Q2.What is the purpose of Exception Handling? Ans.The main purpose of Exception Handling is for graceful termination of the program. Q3.What is the meaning of Exception Handling? Ans. Exception Handling doesnt mean repairing an Exception, we have to define alternative way to continue rest of the code normally. Example: If our programming requirement is to read the data from the file locating at London but at Runtime if London file is not available then we have to use local file alternatively to continue rest of program normally. This is nothing but Exception Handling. Q4.Explain Default Exception Handling Mechanism in java? Ans.If an exception raised, the method in which its raised is responsible for the creation of Exceptions object by including the following information:

Name of the Exception Description of the Exception Stack Trace After creating Exception object the method handover it to the JVM. JVM checks for Exception Handling code in that method. If the method doesnt contain any Exception handling code then JVM terminates the method abnormally and removes the corresponding entry from the stack. JVM identify the caller method and checks for Exception Handling code in that method. If the caller doesnt contain any exception handling code then JVM terminates that method abnormally and removes the corresponding entry from the stack. This process will be continue until main() method. If the main() method also doesnt contain exception handling code the JVM terminates that main() method and removes the corresponding entry from the stack. Just before terminating the program abnormally JVM handovers the responsibility of exception handling to the Default Exception Handler which is the component of JVM. Default Exception Handler just print exception information to the consol in the following format

Name of Exception: Description Stack Trace (Location of the Exception) Q5.What is the purpose of try? Ans We should maintain all risky code inside the try block.

Q6. What is the purpose of catch block? Ans.We have to maintain all Exception Handling code inside the catch block. Q7. Is try with multiple catch block is possible? Ans. The way of handling an exception is varied from exception to exception compulsory we have to write a separate catch block for every exception. Hence try will multiple catch block is possible and it is recommended to use. Example: try{ //Risky code } catch(IOException e) { //Hndling code for IOException } catch(ArithmeticException e) { //handling code for AE } catch(NullPointerExcetpion e) { // handling code for NPE } catch(Exception e) { //default exception handling code } Q8. If try with multiple catch block present is order of catch blocks important in which order we have to take? Ans. If try with multiple catch block present then the order of catch block is very important it should be from child to parent but not from parent to child. Q9. What are various methods to print Exception information? and differentiate them.

Ans. Throwable class defines the following method to print exception or error information . 1. printStackTrace() :- This method print exception information in the following format. Name of the Exception: Description StackTrace 2.toString():- This method print exception information in the following format. Name of the Exception: Description 3.getMessage():- This method prints only description of the exception. Description Q10.If an exception rised inside catch block then what will happen? Ans. If an exception raised inside catch block and it is not part of any try block then it is always abnormal termination. Q11. Is it possible to take try, catch inside try block?

Ans. Yes, It is possible to take try, catch inside try block. That is nesting of try catch is possible. Q12.Is it possible to take try, catch inside catch block? Ans. Yes, It is possible to take try, catch inside catch block. Q13. Is it possible to take try without catch? Ans. Yes, it is possible to take try without catch but compulsory finally block should be available. Q14. What is the purpose of finally block? Ans. The main purpose of finally block is, to maintain the cleanup code. This block will execute always. Q15. Is finally block will be execute always? Ans. Yes finally block will be executed always irrespective of whether exception raised or not raised whether exceptions are handled or not handle. There is one situation where the finally block wont be executed if the JVM is going to be shutdown. Q16. In which situation finally block will not executed? Ans. There is one situation where the finally block wont be executed if we are using system.exit(0) explicitly then JVM itself will be shutdown and there is no chance of executing finally block. Q17. If return statement present inside try is finally block will be executed? Ans. Yes, if return statement present inside try, then also finally block will be executed. finally block will dominate return statement also. Q18. What is the difference between final, finally and finalize()? Ans. final:- final is a modifier applicable for variables, methods and classes. final variable means constant and reassignment is not possible. final method means implementation is final in the child classes we cant override. final classmeans it wont participate in inheritance and child class creation is not possible. finally:- It is a block associated with try catch to maintain cleanup code. Finally block will be executed always irrespective of whether exception is raised or not raised or whether the exception is handle or not handle. finalize():- It is a method, Garbage collector always calls this method just before destroying any object to perform cleanup activities. Q19. Is it possible to write any statement between try-catch and finally? Ans. No, it is not possible to write any statement between try catch and finally. If we will try to write any statement between them then we will get compile time error. Q20. Is it possible to take two finally blocks for the same try? Ans. No, it is not possible to take two finally blocks for the same try. If we try to take then we will get compile time error. Q21. Is syntax try-finally-catch is valid ? Ans. No, this syntax is not valid. It should be like try-catch-finally then only code will compile. Q22. What is the purpose of throw? Ans. Sometimes we can create Exception object explicitly and we can handover that exception object to the JVM explicitly by throw keyword. The purpose of throw keyword is to handover our created exception object explicitly to the JVM. Example1: class Test{ public static void main(String[] args){ System.out.println(10/0); } } In this case ArithmeticException object created implicitly and handover to the JVM automatically by the main method.

Example2: Class Test{ Public static void main(String[] args){ Throw new ArithmeticException(/by Zero); } } In this case creation of an exception object and handover to the JVM explicitly by the programmer. Q23. Is it possible to throw an Error? Ans. Yes, It is possible to throw any Throwable type including Error. Q24. Is it possible to throw any java object? Ans. No, we can use throw keyword only for throwable objects otherwise we will get compile time error saying incompatible type. Q25. After throw is it allow to take any statement directly? Ans. After throw statement we are not allow to place any statement directly violation leads to compile time error saying Unreachable Statement. Q26. What is the purpose of throws? Ans. The main purpose of throws keyword is to delegate the responsibilities of exception handling to the caller. It requires in the case of checked exception. Q27. What is the difference between throw and throws? Ans. Sometimes we can create Exception object explicitly and we can handover that exception object to the JVM explicitly by throw keyword.The main purpose of throw keyword is to handover our created exception object explicitly to the JVM. The main purpose of throws keyword is to delegate the responsibilities of exception handling to the caller. It requires in the case of checked exception. Q28. What is the difference between throw and thrown? Ans. There is no terminology of thrown in java. Q29. Is it possible to use throws keyword for any java class? Ans. No, we can use throws keyword only for Throwable classes. Otherwise we will get compile time error saying Incompatible types. Q30. If we are taking catch block for an exception but there is no chance of rising that exception in try then what will happen? Ans. If there is no chance of raising an exception in try then we are not allow to write catch block for that exception violation leads to compile time error. But this rule is applicable only for fully checked exception. Q31. Explain Exception Handling keyword? Ans. Exception Handling keyword: Try :- To maintain Risky code. Catch:- To maintain Exception Handling code. Finally:- To maintain the clean up code. Throw:- To handover our created exception object to the JVM explicitly. Throws:- To delegate the responsibilities of Exception Handling to the caller. Q32. Which class act as root for entire java Exception hierarchy? Ans. Throwable class act as root for entire java Exception hierarchy. Q33. What is the difference between Error and Exception? Ans. Throwable class contain two child classes. Exception:- These are mostly caused by our program and are recoverable. Error:- These are not caused by our program, mostly caused by lake of system resources. These are non recoverable.

Q34. What is difference between checked exception and unchecked exception? Ans. The exceptions which are checked by the compiler for smooth execution of the program at Runtime is called checked exception. Example: IOException, InterruptedException.The exceptions which are not checked by the compiler are called unchecked exception. Example: ArithmeticException,RuntimeException. Q35.What is difference between partially checked and fully checked Exception? Ans. A checked exception is said to be fully checked if and only if all the child classes also checked otherwise it is called partially checked exception. Example: IOException:- fully checked exception Exception:- partially checked exception Throwable:- partially checked exception RuntimeException:- unchecked exception Q36. What is a customized Exception? Ans. Sometimes based on our programming requirement we have to create our own exception such type of exception are called customize Exception. Example: TooYoungException TooOldException InsufficientFundException Q37. Explain the process of creating the customized Exception. Ans. Creating customized Exception: Class TooYoungException extends RuntimeException{ TooYoungExcetpion(String desc){ Super(desc); } } Class TooOldException extends RuntimeException { TooOldException(String desc){ super(desc); } } Class custExcepiton{ Public static void main(String[] args){ Int age=Integer.parseInt(args[0]); If(age>60) { Throw new TooYoungException(Please wait some more time, definitely you will get best match); } Else if(age<18) { Throw new TooOldException(Your age is already crossed of marriage, no chance to getting marriage); } Else { System.out.println(Congratulation! You will get match details soon by your email); } } Q38. Explain control flow in try, catch, finally. Ans. Try{ Statement1; Statement2;

Statement3; } Catch(X e){ Statement4; } Finally{ Statement5; } Statement6; Case1: If there is no Exception then output is Statement1 Statement2 Statement3 Statement5 Statement6 Normal termination Case2: If an exception raised at statement2 and corresponding catch block has matched then output is Statement1 Statement4 Statement5 Statement5 Normal termination Case3: An exception raised at statement2 and corresponding catch has not matched then output is Statement1 Statement5 Abnormal termination Case4: An exception occurs at statement4 it always Abnormal termination but before that finally block will be executed and output is Statement1 Statement2 Statement5 Abnormal termination Case5: If an exception raised at statement5 or statement6, it is always abnormal termination. Q39. Can you give the most common occurred exception in your previous project. Ans. NullPointerException, ArrayIndexOutofBoundException, StackOverFlowError, ClassCastException, NoClassDefFoundError, ExceptionInitilizerError, IllegalArgumentException, NumberFormatException, IllegalStateException, AssertionError. Q40. Explain the cases where you used Exception Handling in your previous project?

Threading Q1. What is Multitasking? Ans. Executing several task simultaneously is called multitasking. Q2. What is the difference between process-based and Thread-based Multitasking? Ans.Process-based multitasking:- Executing several task simultaneously where each task is a separate independent process such type of multitasking is called process based Multitasking. Example:-While typing a program in the editor we can listen MP3 audio songs. At the same time we download a file from the net. all these task are executing simultaneously and each task is a separate independent program. hence it is process based multitasking. It is best suitable at operating system level. Thread-based multitasking:- Executing several task simultaneously where each task is a separate independent part of the same program is called Thread-based multitasking. and every independent part is called a thread. This type of multitasking is best suitable at programmatic level.

Q3. What is Multithreading and explain its application areas? Ans. Executing several thread simultaneously where each thread is a separate independent part of the same program is calledmultithreading. Java language provides inbuilt support for multithreading by defining a reach library, classes and interfaces like Thread, ThreadGroup, Runnable etc. The main important application area of multithreading are video games implementation, animation development, multimedia graphics etc. Q4.What is advantage of Multithreading? Ans. The main advantage of multithreading is reduces response time and improves performance of the system. Q5. When compared with C++ what is the advantage in java with respect to Multithreading? Ans.Java language provides inbuilt support for multithreading by defining a reach library, classes and interfaces like Thread, ThreadGroup, Runnable etc. But in c++ there is no inbuilt support for multithreading. Q6. In how many ways we can define a Thread? Among extending Thread and implementing Runnable which is recommended? Ans. We can define a Thread in the following two ways: 1. 2. by extending Thread class or by implementing Runnable interface.

Among the two ways of defining a thread implementing Runnable mechanism is always recommended. In the first approach as our Thread class already extending Thread there is no chance of extending any other. Hence, we missing the key benefit of oops(inheritance properties). Q7. What is the difference between t.start() and t.run() method? Ans. In the case of t.start() method, a new thread will be created which is responsible for the execution of run() method. But in the case of t.run() method no new thread will be created main thread executes run() method just like a normal method call.

Q8.

Explain about Thread Scheduler?

Ans. If multiple threads are waiting for getting the chance for executing then which thread will get chance first decided by Thread Scheduler. It is the part of JVM and its behavior is vendor dependent and we cant expect exact output.Whenever the situation comes to multithreading the guarantee behavior is very- very low. Q9. If we are not overriding run() method what will happened? Ans.If we are not overriding run() method then Thread class run() method will executed which has empty implementation and hence we will not get any output. Q10.Is overloading of run() method is possible? Ans.Yes, we can overload run() method but Thread class start() method always invokes no-argument run() method only. The other run() method we have to call explicitly then only will be executed. Q11.Is it possible to override start() method? Ans. Yes it is possible. But not recommended. Q12.If we are overriding start() method then what will happen? Ans. It we are overriding start() method then our own start() method will be executed just like a normal method call. In this case no new Thread will be created.

Q13. Explain life cycle of a Thread?

Ans. Once we create a Thread object then the Thread is said to be in New/Born state once we call t.start() method now the Thread will be entered into ready/Runnable state that is Thread is ready to execute. If Thread Scheduler allocates CPU now the Thread will entered into the Running state and start execution of run() method. After completing run() method the Thread entered into Dead State.

Q14. What is the importance of Thread class start() method? Ans. Start() method present in Thread class performing all low level joining formalities for the newly created thread like registering thread with Thread Scheduler etc and then start() method invoking run() method.As the start() method is doing all low level mandatory activities, Programmer has to concentrate only on run() method to define the job. Hence, start() method is a bigassistant to the programmer.Without executing Thread class start() method there is no chance of starting a new Thread.

Q15. After starting a Thread if we trying to restart the same thread once again what will happen? Ans. After starting a Thread restarting of the same Thread once again is not allowed violation leads to Runtime Exception saying IllegalThreadStateException.

Q16. Explain Thread class constructors? Ans. There are eight constructors are available in Thread class: 1. Thread t=new Thread(); 2. Thread t=new Thread(Runnable r); 3. Thread t=new Thread(String name); 4.Thread t=new Thread(Runnable r, String name); 5.Thread t=new Thread(ThreadGroup g, String name); 6.Thread t=new Thread(ThreadGroup g, Runnable r); 7.Thread t=new Thread(ThreadGroup g, Runnable r, String name); 8.Thread t=new Thread(ThreadGroup g, Runnable r, String name, long stacksize); Q17. How to get and set name of a Thread? Ans. For every Thread in java there is a name. To set and get the name of a Thread we can use the following methods. All methods are final. 1.Public final void setName(String name); - To set the name of a Thread 2.Public final String getName(); - To get the name of a Thread. Q18. What is the range of Thread priority in java? Ans. The valid range of a Thread priority is 1-10. (1 is least priority and 10 is highest priority) . Q19. Who uses Thread priority? Ans. Thread Scheduler uses priorities while allocating CPU. The Thread which is having highest priority will get chance first for execution. Q20. What is the default priority of the Thread? Ans. The default priority only for the main thread is 5 but for all remaining threads default priority will be inheriting from parentto child. Whatever priority parent thread has the same will be inherited to the child thread. Q21. Once we created a new Thread what about its priority? Ans. Whatever priority parent thread has the same will be inherited to the new child thread.

Q22. How to get and set priority of a Thread? Ans. To get and set priority of a Thread, Thread class defines the following two methods:; 1. Public final int getPriority();

2.

Public final void setPriority(int priority);

Q23. If we are trying to set priority of a Thread as 100 what will happen? Ans. If we are trying to set priority of a Thread as 100 then we will not get any compile time error but at the runtime we will get Runtime exception IllegalArgumentException. Because the valid range of the Thread priority is (1-10) only. Q24. If two threads having same priority then which thread will get chance first for execution? Ans. If two threads having same priority then which thread will get the chance first for execution decided by Thread Scheduler. It is the part of JVM and its behavior is vendor dependent and we cant expect exact output. Q25. If two threads having different priority then which thread will get chance first for execution? Ans. If two threads having different priority then the Thread which is having highest priority will get chance first for execution. Q26 .How we can prevent a thread from execution? Ans. We can prevent a Thread from executin by using the following methods: 1. 2. 3. Yield() Join() Sleep()

Q27. What is yield() method? Explain its purpose? Ans. yield() method causes the current executing thread to pause execution and give the chance for waiting thread are same priority. If there is no waiting thread or all the remaining waiting thread have low priority then the same thread will get chance once again for execution. The Thread which is yielded when it will get chance once again for execution depends upon mercy of Thread scheduler.Public static native void yield(); Q28.What is purpose of join() method? Ans. If a Thread wants to wait until some other Thread completion then we should go for join() method. Example: if a Thread t1 execute t2.join() ; then t1 will entered into waiting state until t2 Thread completion. Q29. Is join() method is overloaded? Ans. Yes join() method is overloaded method. Public final void join() throws InterruptedException By using this method thread will wait up to another thread completion . Public final void join(long ms) throws InterruptedException By using this method thread will wail upto sometime what we are passing as a argument in millisecond Public final void join(long ms, int ns)throws InterruptedException By using this method thread will wait up to sometime what we are passing as a argument in millisecond and nanosecond.

Q30 What is the purpose of sleep() method? Ans. If a Thread dont want to perform any operation for a particular amount of time then we should go for sleep() method.Whenever we are using sleep() method compulsory we should handle InterruptedException either by using try-catch or by using throws keyword otherwise we will get compile time error. Q31. What is synchronized keyword? Explain its advantages and disadvantages. Ans. Synchronized keyword is applicable for method and blocks only. We cant use for variables and classes. If a method declared as a synchronized then at a time only one Thread is allow to execute that method on the given object. The main advantages of synchronized keyword are, we can prevent data inconsistency problems and we can provide Threadsafty. But the main limitation of synchronized keyword is it increases waiting time of Threads and effect performance of the system. Hence if there is no specific requirement it is not recommended to use synchronized keyword. Q32.Where we can use synchronized keyword? Ans. Synchronization concept is applicable whenever multiple Threads are operating on the same object simultaneously. But whenever multiple Threads are operating on different objects then there is no impact of synchronization. Q33. What is object lock? Explain when it is required? Ans. Every object in java has a unique lock whenever we are using synchronization concept then only lock concept will coming to the picture. If a Thread wants to execute a synchronized method first it has to get the lock of the object. Once a Thread got the lock then it is allow to execute any synchronized method on that object. After completing synchronized method execution Thread releases the lock automatically.While a Thread executing synchronized method on the given object the remaining Threads are not allow to execute any synchronized method on that object simultaneously. But remaining Threads are allow to execute any non-synchronized method simultaneously. (Lock concept is implemented based on object but not based on method.) Q34.What is the class level lock? Explain its purpose. Ans. Every class in java has a unique lock if a Thread wants to execute static synchronized method that Thread has to get class level lock once a Thread got class level lock then only it is allow to execute static synchronized method. While a Thread executing any static synchronized method then remaining Threads are not allow to execute any static synchronized method of the same class simultaneously. But the remaining Threads are allow to execute the following method simultaneously: 1. 2. 3. Any static non-synchronized method. Synchronized instance methods Non-synchronized instance method. There is no relationship between object lock and class level lock, both are independent. Q35. While a thread executing any synchronized method on the given object is it possible to execute remaining synchronized method of the same object simultaneously by any other thread? Ans. No, it is no possible.

Q36. What is the difference between synchronized method and static synchronized method? Ans. If a Thread wants to execute a synchronized method first it has to get the lock of the object. Once a Thread got the lock then it is allow to execute any synchronized method on that object.If a Thread wants to execute static synchronized method that Thread has to get class level lock once a Thread got class level lock then only it is allow to execute static synchronized method.

Q37. What is the advantage of synchronized block over synchronized method? Ans. If very few lines of the code required synchronization then declaring entire method as the synchronized is not recommended. We have to declare those few lines of the code inside synchronized block. This approach reduces waiting time of the Thread and improves performance of the system. Q38. What is synchronized statement? Ans. The Statement which is inside the synchronized area (synchronized method or synchronized block) is called synchronized statement. Q39. How we can declare synchronized block to get class level lock? Ans. To get the class level lock we can declare synchronized block as follows: synchronized(Display.class) { } Q40. How two thread will communicate with each other? Ans. Two Threads will communicate with each other by using wait(), notify(), notifyAll() methods. Q41.wait(), notify(), notifyAll() method can available in which class? Ans. These methods are defined in Object class. Q42.Why wait(), notify(), notifyAll() method defines in object class instead of Thread class? Ans. These methods are defined in Object class but not in Thread because Threads are calling this method on the shared object. Q43.If a waiting thread got notification then it will entered into which state? Ans. It will entered into another waiting state to get lock. Q44.In which method threads can release the lock? Ans. Once a Thread calls wait() method it immediately releases the lock of that object and then entered into waiting state similarly after calling notify() method Thread releases the lock but may not immediately. Except these three methods( wait(), notify(), notifyAll() ) method Thread never releases the lock anywhere else. Q45. Explain wait(), notify(), notifyAll() method uses. Ans. Two Threads will communicate with each other by using wait(), notify() or notifyAll() methods. These methods are defined in Object class but not in Thread because Threads are calling this method. Q46. What is the difference between notify() and notifyAll()? Ans. To give notification to the single waiting Thread. We use notify() method and to give notification to all waiting thread we use notifyAll() method. Q47. Once a Thread got the notification then which waiting thread will get chance? Ans. It is depends on the Thread Scheduler. Q48. How a thread can interrupt another thread?

Ans. A Thread can interrupt another Thread by using interrupt() method. Q49. What is DeadLock? Is it possible to resolve DeadLock situation? Ans. If two Threads are waiting for each other forever such type of situation is called DeadLock. For the DeadLock, there are no resolution techniques but prevention techniques are available. Q50. Which keyword causes DeadLock situation? Ans. Synchronized keyword is the thing to causes of DeadLock. If we are not using properly synchronized keyword the program will entered into DeadLock situation. Q51. How we can stop a thread explacitly?

Ans. Thread class defines stop() method by using this method we can stop a Thread. But it is deprecated. And hence not recommended to use. Q52. Explain about suspend() and resume() method? Ans. A Thread can suspend another Thread by using suspend() method. A Thread can resume a suspended Thread by using resume() method. Q53.What is Starvation()? And Explain the difference between Deadlock and Starvation? Ans. A long waiting Thread is said to be in starvation (because of least priority) but after certain time defiantly it will get the chance for execution. But in the case of Deadlock two Threads will wait for each other forever. It will never get the chance for execution. Q54. What is race condition? Ans. Multiple Threads are accessing simultaneously and causing data inconsistency problem is called race condition, we can resolve this by using synchronized keyword. Q55. What is Daemon Thread? And give an example? Ans. The Threads which are running in the background are called Daemon Thread. Example: Garbage collector. Q56. What is the purpose of a Daemon Thread? Ans. The main purpose of Daemon Threads is to provide support for non-daemon Threads. Q57. How we can check Daemon nature of a Thread? Ans. We can check Daemon nature of a Thread by using isDaemon() method. Q58. Is it possible to change a Daemon nature of a Thread? Ans. Yes, we can change Daemon nature of a Thread by using setDaemon() method. Q59. Is main thread is Daemon or non-daemon? Ans. By default main thread is always non-daemon nature. Q60. Once we created a new thread is it daemon or non-daemon. Ans. Once we created a new Thread, The Daemon nature will be inheriting from parent to child. If the parent is Daemon the child is also Daemon and if the parent is non-daemon then child is also nondaemon. Q61. After starting a thread is it possible to change Daemon nature? Ans. We can change the Daemon nature before starting the Thread only. Once Thread started we are not allow to change Daemon nature otherwise we will get RuntimeException sying IllegalThreadStateException. Q62. When the Daemon thread will be terminated? Ans. Once last non-daemon Thread terminates automatically every Daemon Thread will be terminated. Q63. What is green Thread? Ans. A green thread refers to a mode of operation for the Java Virtual Machine (JVM) in which all code is executed in a single operating system thread. If the Java program has any concurrent threads, the JVM manages multi-threading internally rather than using other operating system threads. There is a significant processing overhead for the JVM to keep track of thread states and swap between them, so green thread mode has been deprecated and removed from more recent Java implementations. Q64.Explain about Thread group? Ans. Every Java thread is a member of a thread group. Thread groups provide a mechanism for collecting multiple threads into a single object and manipulating those threads all at once, rather than individually. For example, you can start or suspend all the threads within a group with a single method call. Java thread groups are implemented by the ThreadGroup api class in the java.lang package. Q65.What is the Thread Local? Ans. It's a way for each thread in multi-threaded code to keep its own copy of an instance variable. Generally, instance variable are shared between all threads that use an object; ThreadLocal is a way for each thread to keep its own copy of such a variable. The purpose might be that each thread keeps different data in that variable, or that the developer wants to avoid the overhead of synchronizing access to it. Q66. In your previous project where you used multithreading concept?

Collections Q1. What are limitations of object Arrays? The main limitations of Object arrays are

These are fixed in size ie once we created an array object there is no chance of increasing or decreasing size based on our requirement. Hence If we dont know size in advance , arrays are not recommended to use Arrays can hold only homogeneous elements. There is no underlying data structure for arrays and hence no readymade method support for arrays. Hence for every requirement programmer has to code explicitly

To over come these problems collections are recommended to use Q2. What are differences between arrays and collections? Collections Arrays 1. Arrays r fixed in size and hence once we 1. Collections are growable in nature and hence created an array we are not allowed to increase or based on our requirement we can increase or decrease the size based on our requirement. decrease the size. 2. Memory point of view arrays are not recommended to use 3. Performance point of view arrays are recommended to use 4. Arrays can hold only homogeneous elements 5. Arrays can hold both primitives as well as objects 2. Memory point of view collections are recommended to use. 3. Performance point of view collections are not recommended to use. 4. Collections can hold both homogeneous and heterogeneous elements. 5. Collections can hold only objects.

6. For any requirement, there is no ready method 6. For every requirement ready made method support compulsory programmer has to code support is available. Being a programmer we have explicitly. to know how to use those methods and we are not responsible to implement those. Q3. what are differences between arrays and ArrayList? Refer the answer of Q2 Q4. What are differences between arrays and Vector? Refer the answer of Q2

Q5. What is Collection API ? It defines set of classes and interfaces which can be used for representing a group of objects as single entity Q6. What is Collection framework?

It defines set of classes and inter faces which can be used for representing a group of objects as single entity Q7. What is difference between Collections and Collection? Collection is an interface which can be used for representing a group of individual objects as single entity and it acts as root interface of collection frame work. Collections is an utility class to define several utility methods for Collection implemented class objects. Q8. Explain about Collection interface?

This interface can be used to represent a group of objects as a single entity. It acts as root interface for entire collection framework. It defines the most commonly used methods which can be applicable for any collection implemented class object

Q9. Explain about List interface? List interface is a child interface of Collection interface. This can be used to represent group of individual objects in as a single entity where

Duplicates are allowed Insertion order is preserved

Q10. Explain about Set interface? Set is a child interface of Collection interface. it can be used to represent a group of individual objects as a single entity where

Duplicate objects are not allowed. Insertion order is not preserved

Q11. Explain about SortedSet interface? it is child interface of Set interface. it can be used to represent a group of individual objects in to a single entity where

All the objects are arranged in some sorting order (Can be natural sorting order or customizede). Duplicates are not allowed.

Q12. Explain about NavigableSet ? It is child interface of SortedSet and provides several utility methods for navigation purposes

It doesnt allows duplicates Insertion order is preserved It is introduced in 1.6 version

Q13. Explain about Queue interface?

If we want to represent a group of individual objects prior to processing, then we should go for Queue interface. It is child interface of Collection interface. It has introduced in 1.5 version. Q14. Explain about Map interface? Remember it is not a child Interface of Collection Interface and hence Map and Collection Interfaces doesnt have any relationship.

It can be used for representing a group of Objects as key, value pairs. Both keys and values should be objects Keys can t be duplicated but values can be duplicated. it has introduced in 1.2 version

Q15. Explain about SortedMap ?

If we want to represent a group of objects as key value pairs where all the entries are arranged according some sorting order of keys then we should go for SortedMap. It is child interface of Map. It has introduced in 1.2 version

Q16. Explain about NavigableMap?

It is child interface of SortedMap and defines several method for navigation purpose It is introduced in 1.6 version

Q17. Explain about ArrayList class? ArrayList is a Collection which can be used to represent a group of objects as a single entity.

it is a implemented class for List interface Introduced in 1.2 version The underlying data structure is resizable or growable array. Insertion order is preserved Duplicates are allowed Heterogeneous objects are allowed null insertion is possible This class implements RandomAccess , Serializable , Cloneable interfaces Best choice for retrieval purpose and worst if our frequent operation is insertion or deletion in the middle

Q18. What is RandomAccess Interface?

If a collection class implements RandomAccess interface then we can access any of its element with the same speed. RandomAccess interface is marker interface and it dosent contains any methods. ArrayList and vector classes implements this interface.

Q19. Explain about LinkedList class?

LinkedList is a Collection implemented class which can be used for representing a group of objects as a single entity.

LinkedList is the implemetation class for List interface Introduced in 1.2 version Underlying data Structure is DoubleLinkedList Allows duplicates Insertion order is preserved Allows heterogeneous objects null insertion is possible LinkedList class implements Seriallizable and Cloneable interface but not RandomAccess interface Best choice if frequent operation is insertion or deletion an objects in middle but worst choice if frequent operation is retrieval.

Q20. Explain about Vector class? Vector is a legacy collection class which can be used to represent a group of objects.

Introduced in 1.0 version. it is legacy class The underlying data structure is resizable or growable array. Insertion order is preserved Duplicates are allowed Heterogeneous objects are allowed It is a implemented class for List interface null insertion is possible Vector class implements RandomAccess ,Serializable,Cloneable interfaces Best Choice if frequent operation is retrieval and worst choice if frequent operation is insertion or deletion in the middle. All methods present in Vector class are synchronized hence Vector class object is thread safe.

Q21. What is difference between ArrayList and Vector?

Vector ArrayList 1. No method is synchronized in the ArrayList class 1. All methods in Vector are synchronized. 2. ArrayList object is not thread safe. 3. Relatively performance is high 4. Introduced in 1.2 version and it is non legacy 2. Vector is thread safe. 3. Relatively performance is low 4. Introduced in 1.0 version and it is legacy

Q22. How we can get synchronized version of ArrayList? Collections class contains synchronizedList() method for this Public static List synchronizedList(List l) EX ArrayList l= new ArrayList(); List l2=Collections.synchronizedList(l); Similarly we can get synchronized versions of Set and Map objects by the following methods.

Public static List synchronizedSet(Set s) Public static List synchronizedMap(Map m) Q23. What is difference between size and capacity of a Collection Object? size means number of objects present where as capacity means no of objects it can accommodate. Q24. What is difference between ArrayList and Linked List? ArrayList 1. The underlying data structure is resizable or growable array. 2. This is Best choice if frequent operation is retrieval and worst choice if frequent operation is insertion or deletion in the middle. 3. This class implements Serializable , Cloneable and RandomAccess interfaces. LinkedList 1. The underlying data structure is Double Linked List. 2. This is Best choice if frequent operation is insertion or deletion in the middle and worst choice if frequent operation is retrieval . 3. This class implements Serializable , Cloneable but not RandomAccess interface.

Q25. What are legacy classes and interfaces present in Collections framework ?

Enumeration ---Interface Dictonary ------Abstract class Hashtable -----Concrete class Properties -----Concrete class Vector -----Concrete class Stack -----Concrete class

Q26. what is difference Enumeration and Iterator? Enumeration 1. It is legacy interface and introduced in 1.0 version 2Applicable only for legacy classes and it is not universal cursor 3While iterating the elements we are not allowed to remove the objects just we can perform only read operation 4By using elements() method we can get Enumeration object Iterator 1 It is non-legacy and introduced in 1.2 version 2Applicable for any Collection implemented class object. 3While iterating we can perform removal also in addition to read operation. 4. By using iterator() method we can get Iterator object Q27. What are limitations of Enumeration?

While iterating the elements we are not allowed to perform removal operation It is applicable only for legacy classes and it is not a universal cursor. It can retrieve the elements only in forward direction

Q28. What is difference between enum and Enumeration?

An enum can be used to define a group of named constants .It has introduced in 1.5 version Ex Class Beer{ KO,KF,RC,FO } Enumeration is cursor to retrieve Objects one by one from Collection objects. Q29. What is difference between Iterator and ListIterator?

o o o o o o

ListIterator is the child interface of the Iterator Iterator is the single direction cursor where as ListIterator is bidirectional cursor. While iterating the elements by Iterator we can perform only read and remove operations. But by using ListIterator we can perform read,removal, replace and addition of new objects also. Iterator is applicable for every Collecton implemented class object but ListIterator is applicable only for List implemented class objects. Iterator can be get by using iterator() of Collection interface where as ListIterator can be get by using listIterator() method of List interface both are introduced in 1.2 version

Q30. What is relation between ListIterator and Iterator? ListIterator is child interface of Iterator Q31. Explain about HashSet class?

The underlying data structure is Hashtable null values are accepted duplicates are not allowed insertion order is based on hashcode of the object hence insertion order is not preserved best suitable if frequent operation is search operations HashSet class implements Serializable and Cloneable it is implementation class for Set interface heterogeneous objects are allowed it is introduced in 1.2 version

Q32. If we are trying to insert duplicate values in Set what will happen? If we are trying to insert duplicate objects to the HashSet , we wont get any compile time or run time errors just the add(Object o) returns false and it doesnt add that object. Q33. What is LinkedHashSet? It is the child class of HashSet. The main difference between HashSet and LinkedHashSet is: In the case of HashSet insertion order is not preserved , but in the case of LinkedHashSet insertion will be preserved. Q34. Differences between HashSet and LinkedHashSet? HashSet 1The Underlying datastructure is Hashtable LinkedHashSet 1The underlying datastructure is combination of

2Insertion Order is not preserved 3Introduced in 1.2 version

LinkedList and Hashtable 2 Insertion order is preserved. 3 Introduced in 1.4 version

Q35. What are major enhancements in 1.4 version of collection frame work? LinkedHashSet LinkedHashMap IdentityHashMap

Q36. Explain about TreeSet? It is Collection object which can be used to represent a group of objects according to some sorting order.

The underlying datastructure is Balanced tree Duplicates are not allowed All objects are stored according to some sorting order hence insertion order is not preserved Heterogeneous objects are not allowed violation leads to ClassCastException For an Empty TreeSet as firs element null value can be inserted but after inserting that first value if we are trying to insert any other objects then we will get NullPointerException For an non empty TreeSet if we are trying to inser null value at run time u will get NullPointerException

Q37. What are differences between List and Set interfaces? List 1Insertion Order is preserved 2Duplicate Objects are allowed Set 1Insertion Order is not preserved 2 Duplicate Objects are not allowed The implemented classes are HashSet, LinkedHashSet and Tree

3The implemented classes 3 are ArrayList,LinkedList , Vector and Stack classes Q38. What is Comparable interface?

This interface can be used for defining natural sorting order of the objects. It is present in java.lang package It contains a method public int compareTo(Object obj1)

Q39. What is Comparator interface?

This interface can be used for implementing customized sorting order. It is present in java.util package It contains two methods o public int compare(Object ,Object) o public boolean equals(Object)

Q40. What are differences between Comparable and Comparator? Comparable 1This can be used for natural sorting order 2This interface present in java.lang package 3Contains only one method: public int compareTo(Object obj1) 4 It is marker interface Comparator 1This can be used for implementing customized sorting 2 This is present in java.util package 3 It contains two methods. public int compare(Object ,Object) public Boolean equals(Object) 4 It is not a marker interface.

Q41. What is difference between HashSet and TreeSet? HashSet 1The underlying data structure is Hashtable 2Heterogeneous objects are allowed TreeSet 1The underlying data structure is balanced tree 2 Heterogeneous objects are not allowed bydefalut

3Insertion order is not preserved and it is based on 3 Insertion order is not preserved and all the hashcode of the objects objects are inserted according to some sorting order. 4null insertion is possible 4 As the first element only null insertion is possible and in all other cases we will get NullPointerException Q42. What is Entry interface? It is inner interface of Map. In the Map each key value pair is considered as Entry object. interface Map{ //more code here interface Entry{ Object getKey() Object getValue() Object setValue(Object new) } } Q43. Explain about HashMap? It is a Map Object which can be used used to represent a group of objects as key-value pairs.

The underlying data structure is Hashtable Duplicaes keys are not allowed duplicate values are allowed Insertion order is not preserved because insertion is based on hashcode of keys. Heterogeneous objects are allowed for both keys and values null key is allowed only once null values are allowed multiple times Introduced in 1.2 version

Q44. Explain about LinkedHashMap? It is child class of HashMap. It is exactly same as HashMap except the following difference. In the case of HashMap the insertion order is not preserved but in the case of LinkedHashMap insertion order is preserved. Introduced in 1.4 version Q45. Differences between HashMap and LinkedHashMap ? HashMap 1.The underlying data structure is Hashtable 2.Insertion order is not preserved and it is based on hashcode of keys 3.Introduced in 1.2 version LinkedHashMap 1.The underlying data structure is a combination of Hashtable and linkedlist 2 3 Insertion order is preserved Introduced in 1.4 version.

Q46. Differences between HashMap and Hashtable? HashMap 1.The underlying data structure is Hashtable Hashtable 1.The underlying data structure of Hashtable

2.No method is synchronized and hence HashMap 2 .All methods are synchronized and hence it is object is not thread safe thread safe 3.Performance is high 3. Performance is low 4.null insertion is possible for both keys and values 4. null insertion is not possible for both key and value violation leads to NullPointerException 5.Introduced in 1.2 version and it is non legacy 5. Introduced in 1.0 version and it is legacy

Q47. What is IdentityHashMap? It is exactly same as HashMap except the following difference. In the HashMap JVM uses equals() method to identify duplicate keys but in the case of IdentityHashMap JVM uses == operator for this.

Q48. What is difference between HashMap and IdentityHashMap? Refer Q47 for the answer. Q49. What is WeakHashMap? It is exactly same as HashMap except the following difference. In case of HashMap an Object is not eligible for garbage collection if it is associated with HashMap even though it dosent have any external references. ie HashMap dominates garbage collector. But in case of WeakHashMap , if an Object is not having any external references then it is always eligible for garabage collectoion even though it is associated with weakHashMap. ie garbage collector dominates WeakHashMap

Q50. What is difference between HashMap and WeakHashMap? Refer Q49 for the answer. Q51. What is TreeMap? TreeMap can be used to store a group of objects as key-value pairs where all the entries are arranged according to some sorting order of keys.

The underlying data structure is RED-BLACK Tree Duplicates keys are not allowed but values can be duplicated. Insertion order is not preserved because insertion is based on some sorting order If we are depending on Natural sorting order then keys should be homogeneous(violation leads to ClassCastException) but values need not homogeneous In case of customized sorting order we can insert heterogeneous keys and values For empty TreeMap as first entry with null values are allowed but after inserting that entry if we are trying to insert any other entry we will get NullPointerException For non empty TreeMap if we are trying to insert null keys we will get NullPointerException There are no restrictions for null values.

Q52. What is Hashtable Hashtable is a legacy Map and can be used to store objects as key value pairs.

The underlying data sturucture is Hashtabe Duplicates keys are not allowed but duplicate values are allowed null insertion is not possible for both keys and values all methods are synchronized insertion order is not preserved because it is based on hashcode of keys heterogeneous Objects are allowed for both keys and values introduced in 1.0 version it is legacy class

Q53. What is PriorityQueue? It represents a data structure to hold group of individual objects prior to processing based on some priority .it can be natural sorting order and it can be customized sorting order described by Comparator. It is the implementation class of Queue interface.

Insertion order is not preserved because here insertion is done based on some sorting order Duplicates are not allowed null insertion is not possible even as first element also If we are depending on natural sorting order Objects should be homogeneous violation leads to ClassCastException If we are depending on customized sorting order Objects can be heterogeneous also.

Q54. What is Arrays class?

It is utility class for arrays. It defines several utility methods for arrays like sorting an array or searching an element in array present in java.util package

Q55. We are planning to do an indexed search in a list of objects. Which of the two Java collections should you use:ArrayList or LinkedList? ArrayList

Q56. Why ArrayList is faster than Vector? All methods present in the Vector are synchronized and hence any method can be executed by only one thread at a time. It slows down the execution. But in ArrayList, no method is synchronized and hence multiple thread are allowed execute simultaneously which speed up the execution. Jdbc 1: What is the difference between Database and Database management system? Ans: Database is a collection of interrelated data. Database management system is a software which can be used to manage the data by storing it on to the data base and by retrieving it from the data base. And DBMS is a collection of interrelated data and some set of programs to access the data. There are 3 types of Database Management Systems.

Relational DataBase Management Systems(RDBMS): It is a software system, which can be used to represents data in the form of tables. RDBMS will use SQL2 as a Queries language. Object Oriented DataBase Management Systems(OODBMS): It is a software system, which can be used to represent the data in the form of objects. This DBMS will use OQL as a Query language. Object Relational DataBase Management Systems(ORDBMS): It is a DBMS which will represents some part of the data in the form of tables and some other part of the data in the form of objects. This management system will use SQL3 as a Query Language, it is a combination of SQL2 and OQL.

2: How a query could be executed when we send a query to Database? When we send an SQL Query from SQL prompt to the DataBaseEngine, then Database Engine will take the following steps.

Query Tokenization: This phase will take SQL query as an input and devide into stream of tokens. Query Parsing: This phase will take stream of tokens as an input, with them it tried to construct a query tree. If query parser constructs query tree successfully then it was an indication that no grammatical mistakes in the taken SQL query. Otherwise there are some syntactical errors in the taken SQL query. Query Optimization: This phase will take query tree as an input and performs number of query optimization mechanisms to reduce execution time and memory utilization. Query Execution: This phase will take optimized query as an input and executes that SQL query by using interpreters internally as a result we will get some output on the SQL prompt.

3: What is Driver? How many Drivers are available in JDBC? What are the types?

It is a process of interacting with the database from a java application. In JDBC applications we must specify the complete database logic in java application as for the java API representations, later on we need to send java represented database logic to the database engine(DBE).

DBE must execute the database logic but it was configured as per the java representations but DBE able to understand only Query Language representations. At the above situation if we want to execute our database logic, we need to use one interface in between java applicationand the database, that interface must convert java representations to query language representations and query language representations to java representations. Now this interface is called as a Driver.

Driver:

It is a software or an interface existed in between a java application and database, which will map java api calls with query language api calls and vice versa. Initially sun Microsystems has provided driver interface to the market with this sun Microsystems has given an intimation to all the database vendors to have their own implementation as per their requirements for the Driver interface. As a response all the database vendors are providing their own implementation for the Driver interface inorder to interact with the respective databases from a java application. The users of the respective databases they must get the respective database provided Driver implementation from the database software and make use as part of the JDBC applications to interact with the respective databases form a javaapplication.

Types of Drivers: There are 180+ number of Drivers in the market. But all these Drivers could be classified into the following 4 types.

Type Type Type Type

1 2 3 4

Driver Driver Driver Driver

Type 1 Driver:

o o o o
Advantages:

Type 1 Driver is also called as Jdbc-Odbc Driver or Bridge Driver. Jdbc-Odbc Driver is an implementation to Driver interface provided by the sun Microsystems along with the java software. Jdbc-Odbc Driver internally depends on the Microsoft product Odbc Driver. Odbc is nothing but open database connectivity. It is a open specification which can be used to interact with any type of databases.

This Driver is already available with java software thats why no need to bother about how to get the Driver implementation explicitily. Allmost all the databases could support this Driver.

Dis advantages:

This Driver internally depends on Odbc Driver thats why it is not suitable for internet or web applications or networkapplications. This Driver is a slower Driver, why because Jdbc-Odbc Driver will convert java calls to Odbc calls. Then Odbc Driver has to convert Odbc calls to query language calls. This driver is not portable Driver why because it was not complete the java implementations in Jdbc-Odbc Driver. It we want to use Jdbc-Odbc Driver in our jdbc applications then we must require to install Odbc-Native Library.

Type 2 Driver: Type 2 Driver is also called as part java part native Driver. i.e., this Driver was designed by using some part of the java implementations and some other part of the database vendor provided native implementations. This Driver is also called as native driver. Advantages: When compared to Type 1 driver it is efficient driver why because Type 2 driver directly will convert java api calls to database vendor api calls. Dis advantages:

If we want to use Type 2 Driver in our Jdbc applications then we must require to install database vendor native api. It is a costful Driver. It is not suitable for web applicadtions, distributed applications and web applications. Type 2 Driver performance is low when compared to Type 3 and Type 4 drivers. This driver is not portable driver. Why because this driver was not designed completely in java technology.

Type 3 Driver:

o o o o
Advantages:

It is also called as middleware database access server driver. This driver could be used to interact with multiple databases from the multiple clients. This driver could be used in collaboration with application server. This driver is suggestable for network applications.

It is a fastest driver among all the drivers available in the market. To use Type 3 driver in our jdbc applications it is not required to install odbc native library and database native library. It is very much suitable for network applications.

Dis advantages:

This driver is not suitable for simple jdbc applications. This driver requires minimum 3-Tier Architecture. When compared to Type1 and Type2 drivers.. Type3 driver is efficient and portable. But when compared to Type4 driver, Type3 driver is not portable.

Type 4 Driver:

o o o o

This driver is also called as pure java driver i.e, this driver was completely implemented by using java technology. When compared to Type1, Type2 and Type3 drivers.. Type4 driver is portable driver. Type4 driver can be used for any kind of applications. Type4 driver is a cheapest driver when compared to all the drivers thats why it is frequently used driver.

4: What is JDBC and What are the steps to write a JDBC application?

The process of interacting with the database from a java application is called as JDBC(Java Database Connectivity) To interact with the database from a java application we will use the following five steps. 1. 2. 3. 4. 5. load and register the driver. Establish a connection between java application and the database. prepare either statement object or PreparedStatement object or CallebleStatement object as per the applicationrequirements. write and executer the sql queries. terminate the connection which we have established.

5: How to load a JDBC driver?

o o

o o o

In general sun Microsystems has provided Driver interface for this all the database vendors has provided their own implementation. If we want to use the database vendor provided Driver implementation to our jdbc application, first we need to make the availability of the respective Drivers .class file to JVM, for this we need to set class path environment variable to the location where we have the driver implementation. Sun Microsystems is also provided an implementation to the Driver interface in the form of JdbcOdbcDriver class as part of the java software. If we want to use JdbcOdbcDriver in our jdbc applications no need to set class path environment variable. Why because it was already available in the java softwares predefined library. JdbcOdbcDriver internally depends on the mocrosoft product Odbc driver. If we want to use the JdbcOdbcDriver in our jdbc applications first we must configure Odbc driver, for this we will use the following path.

Start/ conrlol panel / performance and maintenance / administrative tools / data source(Odbc)/ user dsn / click on Add / select microsofr Odbc for oracle / finish / provide data source name only / click on ok / ok.

To load the drivers class byte code to the memory we will use the following method.

Public void forName(String class name) Eg: Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);

Where forName() is a static method, which can be used to load the respective driver class byte code to the memory.

Each and every driver class has already a static block at the time of loading the respective driver class byte code to the memory automatically the available static block could be executed, by this DriverManager.registerDriver(.) method will be executed as part of the static block. By the execution of the registerDriver(.) method automatically the specified driver will be register to the jdbc application. If you want to design any jdbc application, we need to use some pre-defined library, which was provided by the Jdbc API in the form of java.sql package, thats why we need to import java.sql package in our jdbc application.

Note:- The best alternative for Class.forName(..) is DriverManagre.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver()); To register the driver.

6:

How to establish a Database connection between java application and Database?

If we want to establish a connection between java application and the database we will the following piece of code. Connection con= DriverManager.getConnection(jdbc:odbc:nag,nag,system,manager); Where getConnectin() is a static method from DriverManager class, which can be used to return connection object. 7: Basically Connection is an interface, how getConnection() will create an object for Connection interface? Ans: Connection is an interface from java.sql package, for which getConnection(_) was return an anonymous inner class object of the Connection interface. Note:- Anonymous inner class is a nameless inner class, which can be sued to provide an implementation either for the interfaces or for abstract classes. Eg: interface I { void m1(); } Class Outer { I i = new I(){ public void m1() { } public void m2() { }

} } Outer o = new Outer(); o.i.m1(); correct o.i.m2(); wrong

getConnection(_) is a static method from DriverManager class, which will call internally connect() method, this connect() will establish a virtual socket connection in between the java application and the database. 8: What is the requirement to use Statement object?

After establishing a connection between java application and the database we need to write the sql queries and we need to execute them. To execute the sql queries we will use some pre-defined library, which was defined in the form of Statement object, PreparedStattement object and CallableStatement object. As per the application requirements we need to create either Statement object or CallableStatement object and PreparedStatement object. To create Statement object dwe will use the following method from connection object.

public Statement createStatement() Eg: Statement st = con.createStatement(); 9: How to execute SQL Queries from a java application? To execute the sql queries we will use the following methods from Statement object.

st.executeQuery() st.executeUpdate() st.execute()

10: What are the differences between executeQuery(), executeUpdate() and execute() methods? Ans: where executeQuery() can be used to execute selection group sql queries to fetch the data from database. When we use selection group sql query with executeQuery() then JVM will send that sql query to the database engine, database engine will execute it, by this database engine(DBE) will fetch the data from database and send back to the java application. Java is a purely object oriented technology. Thats why the jdbc application will maintain the fetched data from database, in the form of an object at heap memory, called as ResultSet object. public ResultSet executeQuery(String sqlquery) where executeUpdate() can be used to execute updation group sql query to update the database. When we provide updation group sql query as a parameter to executeUpdate(), then JVM will send that sql query to DBE, here DBE will execute it and perform updations on the database, by this DBE will identify the number of records got updated value called as records updated count and return back to the java application. public int executeUpdate(String sqlquery) where execute() can be used to execute either selection group sql queries or updation group queries. When we use selection group sql query with the execute() then we will get ResultSet object at heap memory with the fetched data. But execute() will return true as a Boolean value. When we use updation group sql query with execute() then we will get records updated count value at jdbc application. But execute() will return false as a Boolean value. public boolean execute(String sqlquery) 11: How to create a table dynamically from a jdbc application?. //import section import java.sql.*; import java.io.*; public class CreateTableEx { public static void main(String[] args)throws Exception { //create buffered reader object BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //load and register the driver Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);

//establish connection Connection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga); //create statement object Statement st = con.createStatement(); //take table name as dynamic input System.out.println(Enter table name); String tname = br.readLine(); //execute sql query St.executeUpdate(create table+tname+(eno number,ename varchar2(10),esal number,eaddr varchar2(10))); System.out.println(table created successfully); //closing the connection con.close();

} }

12: How to insert records into a table from a JDBC application? import java.sql.*; import java.io.*; public class InsertTableEx { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); Class.forName(oracle.jdbc.driver.OracleDriver); Connection con = DriverManager.getConnection(jdbc:oracle:thin:@localhost:1521:xe,system,durga); Statement st = con.createStatement(); while(true) { System.out.println(Enter emp number); Int eno = Integer.parseInt(br.readLine()); System.out.println(Enter emp name); String ename = br.readLine(); System.out.println(Enter emp sal); Float esal = Float.parseFloat(br.readLine()); System.out.println(Enter emp address); String eaddr = br.readLine(); st.executeUpdate(insert into emp1 values(+eno+,+ename+,+esal+,+eaddr+)); System.out.println(read successfully inserted); System.out.println(one more record[y/n]); String option = br.readLine(); If(option.equals(n)) break; } } } 13: How to update a table from a jdbc application?.

import java.sql.*; public class UpdateTableEx { public static void main(String[] args)throws Exception { //load n register the driver in alternative way to Class.forName DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); Connection con = DriverManager.getConnection(jdbc:oracle:thin:@localhost:1521:xee,system,durga); Statement st = con.createStatement(); int updateCount = st.executeUpdate(update emp1 set esal = esal+500 where esal<9000); System.out.println(records updated..+updateCount); con.close(); } } 14: How to delete records from a table from jdbc application?. import java.sql.*; public class DeleteTableEx { public static void main(String[] args)throws Exception { Class.forName(oracle.jdbc.driver.OracleDriver); Connection con = DriverManager.getConnection(jdbc:oracle:thin:@localhost:1521:xe,system,durga); Statement st = con.createStatement(); int updateCount = sst.executeUpdate(delete from emp3 where esal>=7000); System.out.println(records deleted+updateCount); con.close(); } }

15:What is ment by ResultSet object and How to Fetch the Data from Database?. ResultSet:ResultSet is an Object which can be used to maintain the fetched data from database in the JDBC applications When we execute a selection group sql query, either with executeQuety() or with execute() automatically a ResultSet object will be created at heap memory with the fetched data from database.

To get the ResultSet object reference directly we will use executeQuery(..). When we create a ResultSet object automatically a cursor will be create called as ResultSet cursor to read the data from ResultSet object.

When we create the ResultSet object by default ResultSet cursor will be created before the first record. If we want to read the data from ResultSet object every time we need to check whether the next record is available or not. If the next record is available automatically we need to move that ResultSet cursor to next record position. To perform this work we will use the following method from ResultSet interface. public boolean next()

After getting ResultSet cursor to a record position then we need to get the data from respective fields of the particularrecord, for this we will use following method.

public xxx getXxx(int fno) (or) public xxx getXxx(String fname) where xxx is byte, shor, int, long, float, double, char. Eg: while(rs.next()) { System.out.println(rs.getInt(1)+ }

+rs.getString(2)+

+rs.getFloat(3)+

+rs.getString(4));

The following example demonstrates how to fetch the data from database through ResultSet object. import java.sql.*; public class FetchEx { public static void main(String[] args)throws Exception { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Connection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(select * from emp1); System.out.println(ENO ENAME ESAL EADDR); System.out.println(********************************); while(rs.next()) { System.out.println(rs.getInt(1)++rs.getString(2)+ +rs.getFloat(3)+ +rs.getString(4)); } } } 16:Ingeneral execute() method can be used to execute selection group SQl queries for getting the data from Database , but execute() return a boolean value true so here how it possible to fetch the data from database?

Execute() can be used to execute both selection group sql query and updation group sql query. If we use execute() to execute a selection group sql query then DBE(Database engine) will execute that sql query and send back the fetched data from database to java application. Now java application will prepare a ResultSet object with the fetched data but execute() will return true as a Boolean value. At this situation to get the reference of the ResultSet object explicitily, we will use the following method from Statement object. public ResultSet getResultSet() Eg: boolean b = st.execute(select * from emp1); System.out.println(b); ResultSet rs = st.getResultSet();

17:Ingeneral execute() method can be used to execute updatation group SQl queries for updating the data on Database , but execute() return a boolean value false so here how it possible to get the records updated count value(int value)?

Execute() can be used to execute both selection group sql queries and updation group sql queries.

If we use execute() to execute an updation group sql query then DBE will execute it and send back the records updated count value to the java application. But execute() will return false as a Boolean value. At this instance, to get the records updated count value explicitly we will use the following method from Statement object. public int getUpdateCount() Eg: import java.sql.*; public class FetchEx { public static void main(String[] args)throws Exception { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);

Connection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga); Statement st = con.createStatement(); boolean b = st.execute(update emp1 set esal=esal+500 where esal<9000); System.out.println(b); int updateCount = st.getUpdateCount();j System.out.println(updateCount); } } 18: If we use selection group SQL query to executeUpdate() ,what happened?

If we use selection group sql query as a parameter to executeUpdate() then JVM will send that sql query to the DBE, DBE will fetch the data and send back to the java application here java application will store the fetched data in the form of ResultSet object. But executeUpdate() is expecting records updated count value.

Due to this contradiction JVM will rise an exception like java.lang.SQLException. If we handle the above exception properly then we will get ResultSet abject and we will get the data from Database import java.sql.*; class Test { public static void main(String[] args) { Statement st=null; try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Connection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga); st = con.createStatement(); boolean b = st.executeUpdate(select * from emp1); } catch(Exception e) { ResultSet rs=st.getResultSet(); System.out.println(ENO ENAME ESAL EADDR); System.out.println(********************************); while(rs.next()) { System.out.println(rs.getInt(1)++rs.getString(2)+ +rs.getFloat(3)+ +rs.getString(4)); } e.printStackTrace();

} }

19: If we use updatation group SQL query to executeQuery() ,what happened?

If we use updation group sql query as a parameter to executeQuery() then JVM will send that sql query to the DBE, DBE will perform updations on the database and send back records updated count value to the java application. But here executeQuery() is expecting ResultSet object reference. Due to this contradiction JVM will rise an exception like java.lang.SQLException.

import java.sql.*; class Test { public static void main(String[] args) { Statement st=null; try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); DriverManager.getConnection(jdbc:odbc:nag,system,durga);

st = con.createStatement(); boolean b = st.executeQuery(update emp1 set esal=esal+1000 where } catch(Exception e) { int count=st.getUpdateCount(); System.out.println(count); e.printStackTrace(); } }

esal <10000);

20: What is ment by ResultSet and What are the types of ResultSets are available in JDBC application?

In jdbc applications ResultSets could be classified in the following two ways.

On the basis of ResultSet privilizations (Concurancy):-

There are 2 types of ResultSets.

o o

Read only ResultSet Updatable ResultSet data only. To refer

Read only ResultSet:- It is a ResultSet, which will allow the users to read the this ResultSet, we will use the following constant from ResultSet interface. public static final int CONCUR_READ_ONLY;

Updatable ResultSet:- If is a ResultSet object, which will allow users to perform some updations on its content. To refer this ResultSet we will use the following constant from ResultSet interface. public static final int CONCUR_UPDATABLE; 2)On the basis of the ResultSet cursor movement:There are 2 types of ResultSets.

o o

Forward only ResultSet Scrollable ResultSet

Forward only ResultSet:- It is a ResultSet object, which will allow the users to iterate the data in any forward direction. To refer this ResultSet object we will use the following constant from ResultSet interface. public static final int TYPE_FORWARD_ONLY;

Scrollable ResultSet:- These are the ResultSet objects, which will allow the users to iterate the data in both forward and backward directions. There are 2 types of Scrollable ResultSets.

Scroll sensitive ResultSets Scroll in sensitive ResultSets.

21: What is the difference between ScrollSensitive ResultSet and ScrollInsensitive ResultSets? Ans: Scroll sensitive ResultSet is a ResultSet object, which will allow the later updations from database automatically after creating it. To refer this ResultSet we will use the following constant. public static final int TYPE_SCROLL_SENSITIVE; Scroll insensitive ResultSet is a ResultSet object, which will not allow later updations from database after creating it. To refer this ResultSet we will use the following constant from ResultSet interface.

public static final int TYPE_SCROLL_INSENSITIVE;

22:What is the default ResultSet type in JDBC application and How it is possible to create a specific type of ResultSet object?

The default ResultSet type in the jdbc applications is Read only and forward only. In jdbc applications we are able to specify the following types of the ResultSet combination to any particular ResultSet.

o o o o o o

read-only, forward only read-only, scroll sensitive read-only, scroll insensitive updatable, forward only updatable, scroll sensitive updatable, scroll insensitive

if we want to specity a particular type to the ResultSet object then we should use either of the above constants combination as a parameter to createStatement() method, for this we will use the following method.

public Statement createStatement(int forward / ScrollSensitive / ScrollInsensitive, int readonly / updatable) Eg: Statement st = con. createSensitive(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = con.executeQuery(.); 23:How to iterate the data from Scrollable ResultSet objuect in both forward and backword direction?

to iterate the data in forward direction from a ResultSet object we will use the following 2 methods.

public Boolean next() public xxx getXxx(int fieldno.) Where xxx may be byte, short, char, int, long, float, double.

To iterate the data in backward direction from Scrollable ResultSet object we will use the following 2 methods.

public Boolean previous() public xxx getXxx(int fieldno) Where previous() is a Boolean method, which can be used to check whether the previous record is available or not, if it is available then cursor will be moved to previous record position.

The following example demonstrates how to iterate the data in both forward and backward direction from the ResultSet object import java.sql.*; public class ScrollResEx { public static void main(String[] args)throws Exception { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Connection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga); Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSEITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs = st.executeQuery(select * from emp1); System.out.println(data in forward direction); System.out.println(ENO ENAME ESAL EADDR); System.out.println(**********************************); While(rs.next()) { System.out.println(rs.getInt(1)+ +rs.getString(2)+ +rs.getFloat(3)+ +rs.getString(4)); } System.in.read(); System.out.println(data in backward direction); System.out.println(ENO ENAME ESAL EADDR); System.out.println(***********************************); While(rs.previous()) { System.out.println(rs.getInt(1)+ +rs.getString(2)+ +rs.getFloat(3)+ } } } 24: how to generate ScrollSensitive Result Set and how to reflect the later updations from database automatically to the ResultSet object?

+rs.getString(4));

import java.sql.*; public class Test { Public static void main(String[] args)throws Exception { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Connection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga); Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSEITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs = st.executeQuery(select * from emp1); rs.next(); System.out.println(old salary emp111.+rs.getFloat(3)); System.in.read();//application is in pause, perform database updations Rs.refreshRow(); System.out.println(new salary of emp111..+rs.getFloat(3)); } } Where refreshRow() is a method from Scrollable ResultSet object, which can be used to refresh the current row in the ResultSet object to allow the later updations from database. Prototype of this method is public void refreshRow() 25: How to insert records into Database throws Updatable ResultSet? If we want to insert a new record on to the database through Updatable ResultSet object, we will use the following steps. Step1: Get the Updatable ResultSet object with fetched data. Step2: Move ResultSet cursor to the end of the ResultSet object, where we need to take a buffer to hold new records data temporarily, for this we use the following method from updatable ResultSet object. public void moveToInsertRow() Step3: Insert new records data on to the buffer temporarily at Updatable ResultSet object for this we will use the following method format. public void updateXxx(int fieldno,xxx value) Where xxx may be byte, short, int, char, double, float, long. Step4: Make the temporary insertion as the permanent insertion in Updatable ResultSet object as will as in database, for this wewill use the following method. public void insertRow() The following example demonstrates how to insert no. of records onto the database through Updatable ResultSet objects.

import java.sql.*; import java.io.*; public class UpdateResEx { public static void main(String[] args)throws Exception { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Connection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga); Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSEITIVE,ResultSet.CONCUR_UPDATABLE);

ResultSet rs = st.executeQuery(select * from emp1); BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); rs.moveToInsertRow(); while(true) { System.out.println(enter employee number); int eno = Integer.parseInt(br.readLine()); System.out.println(enter employee name); String ename = br.readLine(); System.out.println(enter employee salary); float esal = Float.parseFloat(br.readLine()); System.out.println(enter employee address); String eaddr = br.readLine(); rs.updateInt(1,eno); rs.updateString(2,ename); rs.updateFloat(3,esal); rs.updateString(4,eaddr); rs.insertRow(); System.out.println(record successfully inserted); System.out.println(one more record[y/n]); String option = br.readLine(); if(option.equals(n)) break; } } 26: How to perform updations on Database throws Updatable ResultSet? By using Updatable ResulSet object we are able to perform some updations on to the database. To perform updations on to the database through Updatable ResultSet object we will use the following steps. Step1: Get the Updatable ResultSet objectd with the fetched data. Step2: Move ResultSet cursor to a record where we want to perform updations, for this we will use the following method. public void absolute(int recordno.) Step3: Perform Temporary updations on to the particular record, for this we will use following method. public void updateXxx(int fieldno,xxx value) Step4: Make the temporary updation as a parmenent updation on to the Updatable ResultSet object as well as to the database. For this we will use the following method. public void updateRow() The following example demonstrates how to perform updations on to the database through Updatable ResultSet object. import java.sql.*; public class UpdateResEx1 { public static void main(String[] args)throws Exception { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Connection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga); Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSEITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs = st.executeQuery(select * from emp1); rs.absolute(3); float newsal = rs.getFloat(3)+500; rs.updateFloat(3,newsal);

rs.updateRow(); }

27:what is meant by ResultSetMetaData ?How to get The ResultSet metadata of a ResultSet object? Data about the data is called as Metadata. Similarily data about the data available in ResultSet object called as ResultSetMetadata.

ResultSet Metadata includes the number of columns of a table in ResultSet object, all the column names, column datatypes and the column display sizes. To get the ResultSet Metadata object we will use the following method from ResultSet object.

public ResultSetMetaData getMetaData()

To get the number of columns available in ResultSet object we will use the following method from ResultSetMetaData object.

public int getColumnCount()

To get the name of a particular column, we will use the following method.

public String getColumnName(int fieldno)

To get the column datatype of a particular column, we will use the following method

public String getColumnTypeName(int fieldno)

To get the column display size of a particular column we will use the following method.

public int getColumnDisplaySize(int fieldno) The following example demonstrates how to get ResultSetMetaData from a ResultSet object import java.sql.*; public class ResultSetMD { public static void main(String[] args)throws Exception { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Connection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga); Statement st = con.createStatement(); ResultSet rs = st.executeQuery(select * from emp1); ResultSetMetaData rsmd = rs.getMetaData(); int count = rsmd.getColumnCount(); System.out.println(number of columns......+count); for(int i=1;i<=count;i++) { System.out.println(rsmd.getColumnName(i)+ +rsmd.getColumnTypeName(i)+ +rsmd.getColumnDisplaySize(i)); System.out.println()

} }

28: how to display the data with the respective field names import java.sql.*; public class RSMD1 { public static void main(String[] args)throws Exception { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Connection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga); Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSEITIVE,ResultSet.CONCUR_UPDATABLE); ResultSet rs = st.executeQuery(select * from emp1); ResultSetMetaData rsmd = rs.getMetaData(); System.out.println(rsmd.getColumnName(1)+ +rsmd.getColumnName(2)+ +rsmd.getColumnName(3)+ +rsmd.getColumnName(4)); System.out.println(********************************); while(rs.next()) { System.out.println(rs.getInt(1)+ +rs.getString(2)+ rs.getFloat(3)+ +rs.getString(4)); } } } 29: What are the differences between Statement and PreparedStatement? (or) Tell me the situations where we should go for PreparedStatement over Statement object. Ans:

When we have a requirement to execute same kind of sql query in the next sequence then we should go for PreparedStatement over Statement object. For the above requirement if we use Statement object, every time execution of the same sql query DBE must perform query tokenization, query parsing, query optimization and query execution. This approach will increase burden to the DBE. To reduce burden to the DBE we should go for an alternative. That is PreparedStatement over Statement object. For the same requirement if we use PreparedStatement object then for our complete requirement DBE will go for only one time query parsing (tokenization, parsing, optimization and execution);

If we want to use PreparedStatement object for the above requirement then we will use following steps. Step1: Prepare PrepareStatement object by providing generalized sql query format with the required number of parameters, for this we will use the following method from Statement object. public PreparedStatement prepareStatement(String sqlqueryformat) Eg: PreparedStatement pst = con.prepareStatement(insert into emp1 values(?,?,?,?));

When JVM encounters above instruction jvm will pickup specified generalized sql query format and send to the DBE, here DBE will process query format only one time and prepare a Buffer with the specified parameters, called as query plan. As a result PreparedStatement object will be created with the parameters at java side.

Step2: Set the values to parameters in PreparedStatement object. After getting PreparedStatement object with parameters, we need to set some values to perform an operation, for this we will use the following method. public void setXxx(int parano,xxx value) where xxx may be byte, short, char, int, long, float, double. Eg: pst.setInt(1,111); pst.setString(2,abc); When JVM encounters the above method then jvm will set the specified values to the specified parameters at the PreparedStatement object, intern that parameter values could be reflected to query plan. Step3: Given an intimation to DBE to perform the respective operation. After setting the values to the parameters we should give an intimation to the DBE explicitly pickup the values from query plan and perform the operation specified in generalized sql query format, for this we will use the following methods.

If the generalized sql query belongs to selection group then we will use following method from PreparedStatement object

public ResultSet executeQuery()

If the generalized sql query belongs to updation group then we will use the following method.

public int executeUpdate() 30: Hhow to insert number of records into a table through Prepared Statement object. import java.sql.*; import java.io.*; public class PreparedInsertEx { public static void main(String[] args)throws Exception { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Connection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga); PreparedStatement pst= con.prepareStatement(insert into emp1 values(?,?,?,?)); BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); while(true) { ; } }

31: how to update the database through PreparedStatement object. import java.sql.*; public class PreparedUpdateEx { public static void main(String[] args)throws Exception { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Connection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga); PreparedStatement pst = con.prepareStatement(update emp1 set esal = esal+? Where esal<?);

Pst.setInt(1,500); Pst.setFloat(2,10000.0f); Int count = pst.executeUpdate(); System.out.println(no. of records updated:+count); } } 32:how to fetch the data from database through PreparedStatement object. import java.sql.*; public class UpdateResEx { public static void main(String[] args)throws Exception { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Connection con = DriverManager.getConnection(jdbc:odbc:nag,system,durga); PreparedStatement pst = con.prepareStatement(select * from emp1 where esal<=?); Pst.setFloat(1,10000.0f); ResultSet rs = pst.executeQuery(); System.out.println(ENO ENAME ESAL EADDR); System.out.println(******************************); While(rs.next()) { System.out.println(rs.getInt(1)+ +rs.getString(2)+ +rs.getFloat(3)+ +rs.getString(4)); } } } 33:What is meant by Transaction? How it is possible to maintain Transactions in JDBC applications?

Transaction is nothing but an unit of work performed by the applications. Every transaction should have the following properties. Atomicity Consistency Isolation Durability Where atomicity is nothing but perform all the operations or not to perform all the operations in a transaction. That is everytransaction must be in either success state or failure state. As part of the jdbc applications when we establish a connection automatically the connection should have a default nature called as auto commit. Auto commit in the sense when we send an sql query to the connection then connection will carry that to the DBE and make the DBE to execute provided sql query and store the results on the database permanently. The connections default auto commit nature violates the transactions atomicity property. To preserve transactions atomicity property we should change the connections auto commit nature to non-auto commit nature, for this we will use the following method.

Public void setAutoCommit(Boolean b) Where b=true connection is in auto commit And b=false connection not in auto commit.

If we use connections non auto commit nature in our jdbc applications then we must use either commit or rollback operations explicitily as part of the transactions.

Public void commit() Public void rollback() The following example demonstrates how to maintain the transactions with atomicity property in the jdbcapplications. import java.sql.*; public class TransactionEx { public static void main(String[] args)throws Exception { Connection con = null; try { Class.forName(sun.jdbc.odbd.JdbcOdbcDriver); Con = DriverManager.getConnection(jdbc:odbc:nag,system,durga); con.setAutoCommit(false); Statement st = con.createStatement(); st.executeUpdate(insert into emp1 values(888,fff,8000,hhh)); st.executeUpdate(update emp1 set esal = esal-500 where esal>= abc ); st.executeUpdate(delete emp1 where esal<7000); con.commit(); } catch(Exception e) { con.rollback(); System.out.println(e); } } } 34:What is meant by SavePoint?How to use Savepoints in JDBC applications?

Save point is a concept introduced by jdbc 3.0 which can be used to block a set of instructions execution in the transactions committing operation. To set a save point we will use the following method.

public SavePoint setSavePoint()

To block a set of sql queries execution prior to the save point we will use the following method.

public void rollback(savepoint s)

To release a savepoint we will use the following method

public void releaseSavePoint();

SavePoint concept could not be supported be type1 driver, it could be supported by type4 driver. Even type 4 driver is supporting up to setSavePoint() and rollback() , not releaseSavepoint();

Eg: import java.sql.*; public class SavePointEx { public static void main(String[] args)throws Exception { Connection con = null; try { Class.forName(oracle.jdbc.driver.OracleDriver); con = DriverManager.getConnection(jdbc:oracle:thin:@locajhost:1521:xe,system,durga); con.setAutoCommit(false); Statement st = con.createStatement(); st.executeUpdate(insert into emp1 values(111,fff,8000,hhh)); savepoint sp= con.Savepoint(); st.executeUpdate(insert into emp1 values(222,ggg,7000,iii) ); con.rollback(sp); st.executeUpdate(insert into emp1 values(333,hhh,9000,jjj)); con.commit(); } catch(Exception e) { con.rollback(); System.out.println(e); } } }

Jsp 1. What is JSP ? Describe its concept. Java Server Pages (JSP) is a server side component for the generation of dynamic information as the response. Best suitable to implement view components (presentation layer components). It is part of SUNs J2EE platform. 2 . Explain the benefits of JSP? These are some of the benefits due to the usage of JSP they are: Portability, reusability and logic components of the language can be used across various platforms. Memory and exception management. Has wide range of API which increases the output functionality. Low maintenance and easy deployment. Robust performance on multiple requests. 3. Is JSP technology extensible? Yes, it is. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries. 4 .Can we implement an interface in a JSP? No 5 What are the advantages of JSP over Servlet?

1. 2. 3. 4. 5.

Best suitable for view components we can separate presentation and business logic The JSP author not required to have strong java knowledge If we are performing any changes to the JSP, then not required to recompile and reload explicitly We can reduce development time.

6. Differences between Servlets and JSP? Servlets 1. Best suitable for processing logic 2. we cannot separate business and presentation logic 3. Servlet developer should have strong knowledge in Java 4. For source code changes ,we have to perform explicitly compilation 5. Relatively development time is more JSP 1. Best suitable for presentation logic 2. Separation of presentation and businesslogic is possible 3.JSP author is not required to have strong knowledge in Java 4. For source code changes ,it is not required to perform explicit compilation 5. Relatively development time is less

7 . Explain the differences between ASP and JSP? The big difference between both of these technologies lies with the design of the software. JSP technology is server and platform independent whereas ASP relies primarily on Microsoft technologies. 8 . Can I stop JSP execution while in the midst of processing a request? Yes. Preemptive termination of request processing on an error condition is a good way to maximize the throughput of a high-volume JSP engine. The trick (assuming Java is your scripting language) is to use the return statement when we want to terminate further processing. 9. How to Protect JSPs from direct access ? If the JSP is secured resource then we can place inside WEB-INF folder so that end user is not allowed to access directly by the name. We can provide the url pattern by configuring in web.xml <web-app> <servlet> <servlet-name>Demo JSP</servlet-name> <jsp-file>/WEB-INF/test.jsp</jsp-file> <sevlet> <servlet-mapping> <servlet-name>Demo JSP</servlet-name> <url-pattern>/test</url-pattern> </servlet-mapping> .. </web-app> 10. Explain JSP API ? The JSP API contains only one package : javax.servlet.jsp It contains the following 2 interfaces:

1. JspPage:

This interface defines the two life cycle methods jspInit() and jspDestroy().

1. HttpJspPage:
This interface defines only one life cyle method _jspService() method. Every generated servlet for the jsps should implement either JspPage or HttpJspPage interface either directly or indirectly. 11. What are the lifecycle phases of a JSP? Life cycle of JSP contains the following phases: 1. 2. 3. 4. 5. 6. 7. Page translation: -converting from .jsp file to .java file Page compilation: converting .java to .class file Page loading : This class file is loaded. Create an instance :- Instance of servlet is created jspInit() method is called _jspService() is called to handle service calls jspDestroy() is called to destroy it when the servlet is not required.

12. Explain the life-cycle mehtods in JSP? The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance. The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects. The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance. 13. Difference between _jspService() and other life cycle methods. JSP contains three life cycle methods namely jspInit( ), _jspService() and jspDestroy(). In these, jspInit() and jspDestroy() can be overridden and we cannot override _jspService(). Webcontainer always generate _jspService() method with JSP content. If we are writing _jspService() method , then generated servlet contains 2 _jspService() methods which will cause compile time error. To show this difference _jspService() method is prefixed with _ by the JSP container and the other two methods jspInit() and jspDestroy() has no special prefixes. 14 What is the jspInit() method? The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets. This method is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data. 15. What is the _jspService() method? SThe _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request comes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse objects as its arguments. A page author cannot override this method, as its implementation is provided by the container. 16. What is the jspDestroy() method?

The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP page is about to be destroyed. This method is similar to the destroy() method of servlets. It can be overridden by a page author to perform any cleanup operation such as closing a database connection. 17. What JSP lifecycle methods can I override? We can override jspInit() and jspDestroy() methods but we cannot override _jspService() method. 18. How can I override the jspInit() and jspDestroy() methods within a JSP page? By using JSP declation tag <%!

public void jspInit() { ... } public void jspDestroy() { ... }

%> <%!

%>

19 . Explain about translation and execution of Java Server pages? A java server page is executed within a Java container. A Java container converts a Java file into a servlet. Conversion happens only once when the application is deployed onto the web server. During the process of compilation Java compiler checks for modifications if any modifications are present it would modify and then execute it. 20 . Why is _jspService() method starting with an '_' while other life cycle methods do not? _jspService() method will be written by the container hence any methods which are not to be overridden by the end user are typically written starting with an '_'. This is the reason why we don't override _jspService() method in any JSP page. 21. How to pre-compile JSP? Add jsp_precompile as a request parameter and send a request to the JSP file. This will make the jsp pre-compile. http://localhost:8080/jsp1/test.jsp?jsp_precompile=true It causes excution of JSP life cycle until jspInit() method without executing _jspService() method. 22. The benefits of pre-compiling a JSP page? It removes the start-up lag that occurs when a container must translate a JSP page upon receipt of the first request. 23.How many JSP scripting elements and explain them? Inside JSP four types of scripting elements are allowed. 1. Scriptlet <% any java code Can be used to place java code. %>

2. declarative <%! Java declaration %> Can be used to declare class level variables and methods 3. expression: <%= java expression %> To print java expressions in the JSP 4. comment <%-jsp comment --%>

24. What is a Scriptlet? JSP scriptlet can be used to place java code. Syntax: <% Any java code %> The java code present in the scriptlet will be placed directly inside _jspService() method . 25. What is a JSP declarative? JSP declarations are used to declare class variables and methods (both instance and static) in a JSP page. These declations will be placed directly at class level in the generated servlet and these are available to the entire JSP. Syntax: <%! Eg: This is my declarative %>

<%! int j = 10; %>

26. How can I declare methods within my JSP page? We can declare methods by using JSP declarative tag. <%! public int add(inti,intj){ return i+j; } %> 27. What is the difference b/w variable declared inside a declaration and variable declared in scriplet ? Variable declared inside declaration part is treated as a instance variable and will be placed directly at class level in the generated servlet. <%! int k = 10; %> Variable declared in a scriptlet will be placed inside _jspService() method of generated servlet.It acts as local variable.

<% int k = 10; %> What is a Expression? JSP Expression can be used to print expression to the JSP. Syntax: <%= java expression %> Eg: <%= new java.util.Date() %>

The expression in expression tag should not ends with semi-colon The expression value will become argument to the out.pritln() method in the generated servlet 28.What are the three kinds of comments in JSP and what's the difference between them?

Three types of comments are allowed in JSP 1. JSP Comment: <%-- this is jsp comment --%> This is also known as hidden comment and it is visible only in the JSP and in rest of phases of JSP life cycle it is not visible. 1. HTML Comment: <!-- this is HTMl comment -- > This is also known as template text comment or output comment. It is visible in all phases of JSP including source code of generated response. 1. Java Comments. With in the script lets we can use even java comments . <% // single line java comment /* this is multiline comment */ %> This type of comments also known as scripting comments and these are visible in the generated servlet also. 29. What is output comment? The comment which is visible in the source of the response is called output comment.

<!-- this is HTMl comment -- > 30. What is a Hidden Comment? <%-- this is jsp comment --%> This is also known as JSP comment and it is visible only in the JSP and in rest of phases of JSP life cycle it is not visible. 31. How is scripting disabled? Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows: <jsp-property-group> <url-pattern>*.jsp</url-pattern> <scripting-invalid>true</scripting-invalid> </jsp-property-group> 32. What are the JSP implicit objects? Implicit objects are by default available to the JSP. Being JSP author we can use these and not required to create it explicitly. 1. 2. 3. 4. 5. 6. 7. 8. 9. request response pageContext session application out config page exception

33. How does JSP handle run-time exceptions? You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example: <%@ page errorPage="error.jsp" %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %> In the error pages we can access exception implicit object.

34. How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?

You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive in the JSP. <%@ page isThreadSafe="false" %> The generated servlet can handle only one client request at time so that we can make JSP as thread safe. We can overcome data inconsistency problems by this approach. The main limitation is it may affect the performance of the system. 35. What is the difference between ServletContext and PageContext? ServletContext: Gives the information about the container and it represents an application. PageContext: Gives the information about the Request and it can provide all other implicit JSP objects . 36 . Is there a way to reference the "this" variable within a JSP page? Yes, there is. The page implicit object is equivalent to "this", and returns a reference to the generated servlet. 37 . Can you make use of a ServletOutputStream object from within a JSP page? Yes . By using getOutputStream() method on response implicit object we can get it. 38 .What is the page directive is used to prevent a JSP page from automatically creating a session? session object is by default available to the JSP. We can make it unavailable by using page directive as follows. <%@ page session="false"> 39. What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface orSynchronization? Synchronized keyword is recommended to use to get thread-safety. 40. What are various attributes Of Page Directive ? Page directive contains the following 13 attributes. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. language extends import session isThreadSafe info errorPage isError page contentType isELIgnored buffer autoFlush pageEncoding

41 . Explain about autoflush? This command is used to autoflush the contents. If a value of true is used it indicates to flush the buffer whenever it is full. In case of false it indicates that an exception should be thrown whenever the buffer is full. If you are trying to access the page at the time of conversion of a JSP into servlet will result in error. 42. How do you restrict page errors display in the JSP page? You first set "errorPage" attribute of PAGE directive to the name of the error page (ie errorPage="error.jsp")in your jsp page . Then in the error.jsp page set "isErrorpage=TRUE". When an error occur in your jsp page, then the control will be automatically forward to error page. 43. What are the different scopes available fos JSPs ? There are four types of scopes are allowed in the JSP.

1. page - with in the same page 2. request - after forward or include also you will get the request scope data. 3. session - after senRedirect also you will get the session scope data. All data stored in session
is available to end user till session closed or browser closed.

4. application - Data will be available throughout the application. One user can store data in
application scope and other can get the data from application scope. 44. when do use application scope? If we want to make our data available to the entire application then we have to use application scope. 45. What are the different scope valiues for the <jsp:useBean>?

The different scope values for <jsp:useBean> are 1. page 2. request 3.session 4.application 46. How do I use a scriptlet to initialize a newly instantiated bean? jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone. The following example shows the today property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action. <jsp:useBean id="foo" class="com.Bar.Foo" > <jsp:setProperty name="foo" property="x" value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>" / >

<%-- scriptlets calling bean setter methods go here --%> </jsp:useBean > 47 . Can a JSP page instantiate a serialized bean? No problem! The use Bean action specifies the beanName attribute, which can be used for indicating a serialized bean. For example: A couple of important points to note. Although you would have to name your serialized file "filename.ser", you only indicate "filename" as the value for the beanName attribute. Also, you will have to place your serialized file within the WEB-INF/jspbeans directory for it to be located by the JSP engine. 48.How do we include static files within a jsp page ? We can include static files in JSP by using include directive (static include) <%@ include file=header.jsp %> The content of the header.jsp will be included in the current jsp at translation time. Hence this inclusion is also known as static include. 49.In JSPs how many ways are possible to perform inclusion? In JSP, we can perform inclusion in the following ways.

1. By include directive: <%@ include file=header.jsp %> The content of the header.jsp will be included in the current jsp at translation time. Hence this inclusion is also known as static include. 1. By include action: <jsp:include page=header.jsp /> The response of the jsp will be included in the current page response at request processing time(run time) hence it is also known as dynamic include. 1. by using pageContext implicit object <% pageContext.include(/header.jsp); %> This inclusion also happened at request processing time(run time).

1. by using RequestDispatcher object <% RequestDispatcher rd = request.getRequestDispatcher(/header.jsp); Rd.incliude(request,response); %> 50.In which situation we can use static include and dynamic include in JSPs ? If the target resource ( included resource) wont change frequently, then it is recommended to use static include. <%@ include file=header.jsp %> If the target resource(Included page) will change frequently , then it is recommended to use dynamic include. < jsp:include page=header.jsp />

Ejb

1). What are the Differences between EJB 3.0 and EJB 2.1?

Differences are: 1) EJB 3.0 allows developers to program EJB components as ordinary Java objects with ordinary Java business interfaces rather than as heavy weight components like EJB 2 (home, remote). 2) In EJB 3.0 you can use annotation or deployment descriptors but in EJB 2 you have to use deployment descriptors. 3) EJB 3 introduced persistence API for database access. In EJB 2 you can use Entity bean. 4) EJB 3.0 is much faster the EJB2 2). What are the key features of the EJB technology?

1. EJB components are server-side components written entirely in the Java programming
language 2. EJB components contain business logic only - no system-level programming & services, such as transactions, security, life-cycle, threading, persistence, etc. are automatically managed for the EJB component by the EJB server. 3. EJB architecture is inherently transactional, distributed, portable multi-tier, scalable and secure. 4. EJB components are fully portable across any EJB server and any OS. 5. EJB architecture is wire-protocol neutralany protocol can be utilized like IIOP,JRMP, HTTP, DCOM,etc. 3). What is the difference between EJB and RMI

Both of them are java solution for distributed computing. RMI offers remote access to an object running in another JVM and no other services. But EJB offers far more services than RMI apart from remote method calling. EJB leverages this remote-object feature of RMI and ORB (RMI-IIOP) which can be called by any COBRA client, but also provides other services such as persistence, transaction management, security, resource management, object pooling and messaging. 4).What are the ways for a client application to get an EJB object? 1. The client has the JNDI name of the EJB object; this name is used to get the EJB object. 2) The client has the JNDI name of the Home object, this is a more usual case; this name is used to get the Home object, then a finder method is invoked on this Home to obtain one or several entity bean objects. The client may also invoke a "create" method on the Home object to create a new EJB object (session or entity). 3) The client has got a handle on an EJB object. A handle is an object that identifies an EJB object; it may be serialized, stored, and used later by a client to obtain a reference to the EJB Object, using the getEJBObject method(). 4) The client has got a reference to an EJB object, and some methods defined on the remote interface of this Enterprise Bean return EJB objects. 5). What are the different kinds of enterprise beans? Stateless session bean- An instance of these non-persistent EJBs provides a service without storing an interaction or conversation state between methods. Any instance can be used for any client. Stateful session bean- An instance of these non-persistent EJBs maintains state across methods and transactions. Each instance is associated with a particular client. Entity bean- An instance of these persistent EJBs represents an object view of the data, usually rows in a database. They have a primary key as a unique identifier. Entity bean persistence can be either container-managed or bean-managed. Message-driven bean- An instance of these EJBs is integrated with the Java Message Service (JMS) to provide the ability for message-driven beans to act as a standard JMS message consumer and perform asynchronous processing between the server and the JMS message producer. 6). What is Entity Bean? The entity bean is used to represent data in the database. It provides an object-oriented interface to data that would normally be accessed by the JDBC or some other back-end API. More than that, entity beans provide a component model that allows bean developers to focus their attention on the business logic of the bean, while the container takes care of managing persistence,transactions, and access control. There are two basic kinds of entity beans: container-managed ersistence (CMP) andbean-managed persistence (BMP). Container-managed persistence beans are the simplest for the bean developer to create and the most difficult for the EJB server to support. This is because all the logic for synchronizing the bean's state with the database is handled automatically by the container. This means that the bean developer doesn't need to write any data access logic, while the EJB server is supposed to take care of all the persistence needs automatically. With CMP, the container manages the persistence of the entity bean. Vendor tools are used to map the entity fields to the database and absolutely no database access code is written in the beanclass. The bean-managed persistence (BMP) enterprise bean manages synchronizing its state with the database as directed by the container. The bean uses a database API to read and write its fields to the database, but the container tells it when to do each synchronization operation and manages the

transactions for the bean automatically. Bean-managed persistence gives the beandeveloper the flexibility to perform persistence operations that are too complicated for the container or to use a data source that is not supported by the container. 7). Why does EJB needs two interfaces(Home and Remote Interface)? There is a pure division of roles between the two . Home Interface is the way to communicate with the container which is responsible for creating , locating and removing beans and Remote Interface is the link to the bean that allows access to all methods and members 8).What is an EJB Context? EJBContext is an interface that is implemented by the container, and it is also a part of the beancontainer contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details

9). Does the container create a separate instance of the generated EJBHome and EJBObject classes? The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. While referring the EJB Object classes the container creates a separate instance for each client request. The instance pool maintenance is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is again up to the implementer. 10). What's difference between httpsession and EJB session bean ? A session in a Servlet, is maintained by the Servlet Container through the HttpSession object, that is acquired through the request object. You cannot really instantiate a new HttpSession object, and it doesn't contains any business logic, but is more of a place where tostoreobjects. A session in EJB is maintained using the SessionBeans. You design beans that can contain business logic, and that can be used by the clients. You have two different session beans: Stateful and Stateless. The first one is somehow connected with a single client. It maintains the state for that client, can be used only by that client and when the client "dies" then the session bean is "lost". A Stateless Session Bean doesn't maintain any state and there is no guarantee that the same client will use the same stateless bean, even for two calls one after the other. The lifecycle of a Stateless Session EJB is slightly different from the one of a Stateful Session EJB. Is EJB Container's responsibility to take care of knowing exactly how to track each session and redirect the request from a client to the correct instance of a Session Bean. The way this is done is vendor dependant, and is part of the contract.

11). What are the key benefits of the EJB technology? 1. Rapid application development 2. Broad industry adoption 3. Application portability 4. Protection of IT investment

12). Why do we have a remove method in both EJBHome and EJBObject? With the EJBHome version of the remove, you are able to delete an entity bean without first instantiating it (you can provide a Primary Key object as a parameter to the remove method). The home version only works for entity beans. On the other hand, the Remote interface version works on an entity bean that you have already instantiated. In addition, the remote version also works on session beans (stateless and stateful) to inform the container of your loss of interest in this bean. 13). What are the services provided by container? Container services are totally depends upon the "vendor implementation". But more or less most of the vendors suppots the basic services like, LifeCycle Management - It is Automatic... Resource Management-Creating and destroying the objects based the current load of requests for better usage of memory. Session Management - it is used by Developer coded callback methods... Transaction Management - it is used by configuring deployment descriptor (DD) ... Security management - it is used by configuring deployment descriptor (DD) ... The other services, if any will be in advanced versions, and depends on Vendor specific. 14). Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB? You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable. This has to be consider as ?passed-by-value?, that means that its read-only in the EJB. If anything is altered from inside the EJB, it wont be reflected back to the HttpSession of the Servlet Container.The ?pass-by-reference? can be used between EJBs Remote Interfaces, as they are remote references. While it IS possible to pass an HttpSession as a parameter to an EJB object, it is considered to be ?bad practice (1)? in terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejbs api. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/backend 15). What is the difference between a Coarse Grained? Entity Bean and a Fine Grained? Entity Bean? A ?fine grained? entity bean is pretty much directly mapped to one relational table, in third normal form. A ?coarse grained? entity bean is larger and more complex, either because its attributes include values or lists from other tables, or because it ?owns? one or more sets of dependent objects. Note that the coarse grained bean might be mapped to a single table or flat file, but that single table is going to be pretty ugly, with data copied from other tables, repeated field groups, columns that are dependent on non-key fields, etc. Fine grained entities are generally considered a liability in large systems because they will tend to increase the load on several of the EJB server?s subsystems (there will be more objects exported through the distribution layer, more objects participating in transactions, more skeletons in memory, more EJB Objects in memory, etc.) 16). Does Stateful Session bean support instance pooling? Stateful Session Bean conceptually doesn't have instance pooling. What is the difference between JavaBean and EJB? A Java Bean is a software component written in the Java programming language that conforms to the JavaBeans component specification. The JavaBeans APIs became part of the "core" Java APIs as of the 1.1 release of the JDK. The JavaBeans specification defines a Java-based software component model that adds a number of features to the Java programming language. Some of these features include: * introspection

* * * *

customization events properties persistence

Enterprise JavaBeans (EJBs) are Java-based software components that are built to comply with Java's EJB specification and run inside of an EJB container supplied by a J2EE provider. An EJB container provides distributed application functionality such astransaction support, 17). What are the Interfaces need to create to implement Session Bean with Exmaple? Session bean class (CartBean) Home interface (CartHome) Remote interface (Cart) Session bean class (CartBean) : public class CartBean implements SessionBean { String customerName; String customerId; Vector contents; public void ejbCreate(String person) throws CreateException { if (person == null) { throw new CreateException("Null person not allowed."); } else { customerName = person; } customerId = "0"; contents = new Vector(); } public void ejbCreate(String person, String id) throws CreateException { if (person == null) { throw new CreateException("Null person not allowed."); } else { customerName = person; } IdVerifier idChecker = new IdVerifier(); if (idChecker.validate(id)) { customerId = id; } else { throw new CreateException("Invalid id: "+ id); } contents = new Vector(); } public void addBook(String title) {

contents.addElement(title); } public void removeBook(String title) throws BookException { boolean result = contents.removeElement(title); if (result == false) { throw new BookException(title + "not in cart."); } } public Vector getContents() { return contents; } public public public public public } Home Interface: public interface CartHome extends EJBHome { Cart create(String person) throws RemoteException, CreateException; Cart create(String person, String id) throws RemoteException, CreateException; } The signatures of the ejbCreate and create methods are similar, but differ in important ways. The rules for defining the signatures of the create methods of a home interface follow. The number and types of arguments in a create method must match those of its corresponding ejbCreate method. The arguments and return type of the create method must be valid RMI types. A create method returns the remote interface type of the enterprise bean. (But an ejbCreate method returns void.) The throws clause of the create method must include the java.rmi.RemoteException and the javax.ejb.CreateException Remote Interface : public interface Cart extends EJBObject { public void addBook(String title) throws RemoteException; public void removeBook(String title) throws BookException, RemoteException; public Vector getContents() throws RemoteException; } The method definitions in a remote interface must follow these rules: Each method in the remote interface must match a method implemented in the enterprise bean class. The signatures of the methods in the remote interface must be identical to the signatures of the corresponding methods in the enterprise bean class. The arguments and return values must be valid RMI types. The throws clause must include the java.rmi.RemoteEx CartBean() {} void ejbRemove() {} void ejbActivate() {} void ejbPassivate() {} void setSessionContext(SessionContext sc) {}

18). How many EJB Objects are created for a Bean? For a Session bean - one EJB object for one bean instance. For entity bean it depends, if 2 users are accessing one row at time then one EJB object is used for both the beans other wise for each bean one EJB object. 19). What are the parameters must follow for Session Bean ? It implements the SessionBean interface. The class is defined as public. The class cannot be defined as abstract or final. It implements one or more ejbCreate methods. It implements the business methods. It contains a public constructor with no parameters. It must not define the finalize method. 20).When you will chose Stateful session bean and Stateless session bean? Stateful session beans are used when there is converstional state and when there is a need of temporary storage Stateless session bean are used when there is no conversational state and when session bean has to be used only for database access 21). What is the difference between Stateful session bean and Stateless session bean? 1. A stateful session beans can keep data between client accesses. wheras a stateless session bean cannot. 2) A stateful seesion bean contain the state of client after seesion is expired. whereas a stateless bwan cnanot. 3) A stateful session beans use the bean of pools for client application n after use them it return the bean in the pool. whereas a stateless session bean cannot.

22). What are the callbacks method in Session Bean ? public public public public public void void void void void ejbCreate() {} ejbRemove() {} ejbActivate() {} ejbPassivate() {} setSessionContext(SessionContext sc) {}

23). How is Stateful Session bean maintain their states with client? When a client refers to a Stateful Session object reference, all calls are directed to the same object on the EJB container. The container does not require client identity information or any cookie object to use the correct object. This means that for a client to ensure that calls are directed to the same object on the container, all it has to do is to use same reference for every call. For example the following holds for all stateful session beans: StatefulHome sfh = ...//get home interface for stateful bean Stateful bean1 = sfh.create(); Stateful bean2 = sfh.create(); if (bean1.isIdentical(bean1)){} //this is true!

if (bean1.isIdentical(bean2)){} //this is false! //Note that the second test would evaluate to true for stateless beans Thus, if you're calling a Stateful Session Bean from a servlet, your servlet need to keep the reference to the remote object in the HttpSession object between client calls for you to be able to direct calls to the same object on the container. Likewise, if you're calling from an application, you only obtain the reference to the bean once and reuse the object throughout the application session. 24). What is the free pool? The free pool is a data structure the EJB container uses to cache anonymous instances of a given bean type. The free poolimproves performance by reusing objects and skipping container callbacks when it can. 25). Without home and remote interfaces cant we implement ejb? Was just reading about EJB 3.0. I suppose with EJB 3.0, Home interface is absolutely gone and implementing Business Interface is not mandatory. All enterprise beans in EJB 3.0 are just POJO (Plain Old Java Object) with appropriate annotations. 26). When are stateless EJBs passivated? Stateless ejbs are never passivated. Since stateless ejbs do not have state, there is no need to passivate them. They are put back into the free pool after each method call so they will be available to service other requests. 27). Is method overloading allowed in EJB? Yes you can overload methods Should synchronization primitives be used on bean methods? - No. The EJB specification specificallystates that the enterprise bean is not allowed to use thread primitives. The container is responsible for managing concurrent access to beans at runtime. 28). What is handle and why it is used in EJB? The handle mechanism allows a client application to maintain a reference to an EJB object. A handle object may be obtained by calling the getHandle() method on the reference to an EJB object. The main interest is that the handle class implements java.io.serializable interface, which means that a handle may be serialized. This allows the client to store the handle, or to pass it to another process. The handle may then be deserialized and used to obtain the reference to the EJB object, by calling the getEJBObject() method. Handles on session bean objects are valid until the session bean object exists, i.e. their life time is limited to that of the client. Handles on entity bean objects are valid during the complete life time of the entity bean object; this means that such handles may be used by different clients and stored for a long time; the EJB server holding the entity bean objects may be stopped and restarted, the handle will still be valid. If we consider the entity bean object of the example above (a2), the way to obtain a handle on this object is the following (the handle class is defined in the javax.ejb package): Handle h = a2.getHandle();The handle object may then be serialized and stored in a file: ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("handlefile")); out.writeObject(h); out.close(); Then, a client can read the handle, and retrieve the referenced object:

ObjectInputStream in = new ObjectInputStream(new FileInputStream("handlefile")); Handle h = (Handle) in.readObject(); Account a = (Account)PortableRemoteObject.narrow(h.getEJBObject(), Account.class); The EJB Specification allows the client to obtain a handle for the home interface. This allows the client to store a reference to an entity bean's home interface in stable storage. The client code must use the javax.rmi.PortableRemoteObject.narrow(...) method to convert the result of the getEJBHome() method invoked on a handle to the home interface type 29). Implement Local and Remote Interfaces in EJB? Remote BeansThe EJB 1.1 specification defines all EJBs as remote objects. This means that every time you make a call to an EJB, you are making a remote call. This means that there is considerable overhead to each EJB call, and hence performance implications. To combat this, server vendors invented a way of circumventing the remote calls to some degree. Oracle's solution with OC4J was the pass-by-reference setting, which determined whether EJB objects were communicated by reference to the object, or whether the whole object had to be passed to the client. An EJB has a remote interface and a home interface, with the exception of MessageDrivenBeans. The remote interface extends the interface javax.ejb.EJBObject and the home interface extends the interface javax.ejb.EJBHome. The EJB is accessible from any client, in any JVM, provided they have the proper authorization. For example, the Home and Remote interfaces of an EJB called EMP may look like this. Remote: public interface Emp extends EJBObject { long getEmpno() throws RemoteException; void setEmpno(long newDeptno) throws RemoteException; String getEname() throws RemoteException; void setEname(String newDname) throws RemoteException; Home: public interface DeptHome extends EJBHome { public Emp create() throws RemoteException, CreateException; public Dept findByPrimaryKey(DeptPK primaryKey) throws RemoteException, FinderException; Note that both the home and the remote interface throw a RemoteException in all of their method definitions. The ejb-jar.xml deployment descriptor for these EJBs would look something like the snippets below: <entity> <ejb-name>Emp</ejb-name> <home>ejb.cmplocal.EmpHome</home> <remote>ejb.cmplocal.Emp</remote> <ejb-class>ejb.cmplocal.EmpBean</ejb-class> . . . Local BeansThe EJB 2.0 specification standardize a means of making local connections to EJBs with Local Interfaces. For an EJB to be classed as a local EJB, it must implement the local versions of the home and remote

interfaces, javax.ejb.EJBLocalObject for the Home interface, and javax.ejb.EJBLocalHome. For a client to call the Local interface, they must be running in the same JVM as the JVM that the EJB exists in. This means that not only an EJB can call a local EJB , Servlets or JSPs can also call the EJB via it's local interface if they are packaged together as part of same application. For example, the LocalHome and Local interfaces of an EJB called EMP may look like this. Local: public interface Emp extends EJBLocalObject { long getEmpno(); void setEmpno(long newEmpno); String getEname(); void setEname(String newEname); LocalHome: public interface EmpHome extends EJBLocalHome { public Emp create() throws CreateException; public Emp findByPrimaryKey(EmpPK primaryKey) throws FinderException; The ejb-jar.xml deployment descriptor for these EJBs would look something like the snippets below: <entity> <ejb-name>Emp</ejb-name> <local-home>ejb.cmplocal.EmpHome</local-home> <local>ejb.cmplocal.Emp</local> <ejb-class>ejb.cmplocal.EmpBean</ejb-class> <cmp-version>2.x</cmp-version> <abstract-schema-name>Emp</abstract-schema-name> . . . Note that now the local interfaces no longer throw the RemoteException, showing that they are not remotely called methods. Also, the XML contains different elements. There is now a local-home and a local tag. Also we are declaring that this is an EJB 2.x bean, using the cmp-version tag. Calling Local BeansCalling a local bean from Java code is very simple, and very similar to using a remote bean. The code to call a remote bean is shown below. try { Context ctx = new InitialContext(); Object o = ctx.lookup("Emp"); EmpHome empHome = PortableRemoteObject.narrow(o, EmpHome.class) return empHome.findByDeptno(getDeptno()); } catch (RemoteException r) { System.err.println("Error loading Employees(Remote): " + r.getMessage()); return null; } catch (NamingException n) { System.err.println("Error loading Employees(Naming): " + n.getMessage()); return null; } catch (FinderException f) {

System.err.println("Error loading Employees(Finder): " + f.getMessage()); return null; } The code for a local bean is similar, but we no longer have to worry about the PortableRemoteObject, as the bean is no longer remote. try { Context ctx = new InitialContext(); Object o = ctx.lookup("java:comp/env/LocalEmp"); EmpHome empHome = (EmpHome)o; return empHome.findByDeptno(getDeptno()); } catch (NamingException n) { System.err.println("Error loading Employees(Naming): " + n.getMessage()); return null; } catch (FinderException f) { System.err.println("Error loading Employees(Finder): " + f.getMessage()); return null; } As you can see, the local bean has to lookup the EJB slightly differently, even though they are running in the same container. Also, there is no RemoteException thrown by the find or the create methods, so the exception does not have to be caught. There is one more difference, and that is in the ejb-jar.xml deployment descriptor. For an EJB to look up a local EJB, it must point to the correct location using an <ejb-local-ref> tag. If this is not used, the container will not be able to find the bean. For each EJB that needs to use the local EJB, the XML below must be in the deployment descriptor. <entity> <ejb-name>Dept</ejb-name> . . . <ejb-local-ref> <ejb-ref-name>LocalEmp</ejb-ref-name> <ejb-ref-type>Entity</ejb-ref-type> <local-home>ejb.cmplocal.EmpHome</local-home> <local>ejb.cmplocal.Emp</local> <ejb-link>Emp</ejb-link> </ejb-local-ref> </entity> This example will allow the EJB Dept to call the local EJB Emp using the name LocalEmp. This is required because EJBs can have both local and remote interfaces, and to call the EJB Emp via it's remote interface the EJB Dept would look up the name Emp rather than the local reference LocalHome. 30). How can I call one EJB from inside of another EJB? In case of Remote : EJBs can be clients of other EJBs. It just works. Really. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference. For Example : Context ctx = new InitialContext(); //get Home interface of bean //narrow -retype EmpHome lhome = (EmpHome ) javax.rmi.PortableRemoteObject.narrow(ctx.lookup("java:comp/env/LocalEmp"), EmpHome .class);

//get remote interface Emplbean = lhome.create(); //now you can call bussiness method on remote interface like lbean.doSomething() Incase of Local : but we no longer have to worry about the PortableRemoteObject, as the bean is no longer remote Context ctx = new InitialContext(); Object o = ctx.lookup("java:comp/env/LocalEmp"); EmpHome empHome = (EmpHome)o; 31). What is the difference between Message Driven Beans and Stateless Session beans In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways: Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls. Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic. Note: Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary. The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls 32). Can you control when passivation occurs? The developer, according to the specification, cannot directly control when passivation occurs. Although for Stateful Session Beans,the container cannot passivate an instance that is inside a transaction. So using transactions can be a a strategy to controlpassivation. The ejbPassivate() method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic. Some EJB containers, such as BEA WebLogic, provide the ability to tune the container to minimize passivation calls. Taken from the WebLogic 6.0 DTD -"The passivation-strategy can be either "default" or "transaction". With the default setting the container will attempt to keep a working set of beans in the cache. With the "transaction" setting, the container will passivate the bean after every transaction (or method call for a non-transactional invocation). 33). How to call any EJB from a servlet/JSP/Java Client? Context ctx = new InitialContext(); //get Home interface of bean //narrow -retype

BeanHome lhome = (BeanHome) javax.rmi.PortableRemoteObject.narrow(ctx.lookup("cz.train.Bean"), BeanHome.class); //get remote interface Bean lbean = lhome.create(); //now you can call bussiness method on remote interface like lbean.doSomething() 34). Can the primary key in the entity bean be a Java primitive type such as int? The primary key can't be a primitive type--use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive) 35). What are the methods of Entity Bean? An entity bean consists of 4 groups of methods: 1. create methods: To create a new instance of a CMP entity bean, and therefore insert data into the database, the create() method on the bean's home interface must be invoked. They look like this: EntityBeanClass ejbCreateXXX(parameters), where EntityBeanClass is an Entity Bean you are trying to instantiate, ejbCreateXXX(parameters) methods are used for creating Entity Bean instances according to the parameters specified and to some programmer-defined conditions. A bean's home interface may declare zero or more create() methods, each of which must have corresponding ejbCreate() and ejbPostCreate() methods in the bean class. These creation methods are linked at run time, so that when a create() method is invoked on the home interface, the container delegates the invocation to the corresponding ejbCreate() and ejbPostCreate() methods on the bean class. 2. finder methods: The methods in the home interface that begin with "find" are called the find methods. These are used to query the EJB server for specific entity beans, based on the name of the method and arguments passed. Unfortunately, there is no standard query language defined for find methods, so each vendor will implement the find method differently. In CMP entity beans, the find methods are not implemented with matching methods in the bean class; containers implement them when the beanis deployed in a vendor specific manner. The deployer will use vendor specific tools to tell the container how a particular find method should behave. Some vendors will use object-relational mapping tools to define the behavior of a find method while others will simply require the deployer to enter the appropriate SQL command. There are two basic kinds of find methods: single-entity and multi-entity. Single-entity find methods return a remote reference to the one specific entity bean that matches the find request. If no entity beans are found, the method throws an ObjectNotFoundException . Every entity bean must define the single-entity find method with the method name findByPrimaryKey(), which takes the bean's primary key type as an argument. The multi-entity find methods return a collection ( Enumeration or Collection type) of entities that match the find request. If no entities are found, the multi-entity find returns an empty collection. 3. remove methods: These methods (you may have up to 2 remove methods, or don't have them at all) allow the client to physically remove Entity beans by specifying either Handle or a Primary Key for the Entity Bean. 4. home methods: These methods are designed and implemented by a developer, and EJB specification doesn't have any requirements for them except the need to throw a RemoteException is each home method.

36). What is the difference between Container-Managed Persistent (CMP) bean and BeanManaged Persistent(BMP) ? Container-managed persistence(CMP) beans are the simplest for the bean developer to create and the most difficult for the EJB server to support. This is because all the logic for synchronizing the bean's state with the database is handled automatically by the container. This means that the bean developer doesn't need to write any data access logic, while the EJB server is supposed to take care of all the persistence needs automatically. With CMP, the container manages the persistence of the entity bean. A CMP bean developer doesn't need to worry about JDBC code and transactions, because the Container performs database calls and transaction management instead of the programmer. Vendor tools are used to map the entity fields to the database and absolutely no database access code is written in the bean class. All table mapping is specified in the deployment descriptor. Otherwise, a BMP bean developer takes the load of linking an application and a database on his shoulders. The bean-managed persistence (BMP) enterprise bean manages synchronizing its state with the database as directed by the container. The bean uses a database API to read and write its fields to the database, but the container tells it when to do each synchronization operation and manages the transactions for the bean automatically. Bean-managed persistence gives the beandeveloper the flexibility to perform persistence operations that are too complicated for the container or to use a data source that is not supported by the container.BMP beans are not 100% database-independent, because they may contain database-specific code, but CMP beans are unable to perform complicated DML (data manipulation language) statements. EJB 2.0 specification introduced some new ways of querying database (by using the EJB QL - query language). 37).Can Entity Beans have no create() methods? Yes. In some cases the data is inserted NOT using Java application, so you may only need to retrieve the information, perform its processing, but not create your own information of this kind 38). What is bean managed transaction? If a developer doesn't want a Container to manage transactions, it's possible to implement all database operations manually by writing the appropriate JDBC code. This often leads to productivity increase, but it makes an Entity Bean incompatible with some databases and it enlarges the amount of code to be written. All transaction management is explicitly performed by a developer. 39). What are transaction isolation levels in EJB? 1. Transaction_read_uncommitted- Allows a method to read uncommitted data from a DB(fast but not wise). 2. Transaction_read_committed- Guarantees that the data you are getting has been committed. 3. Transaction_repeatable_read - Guarantees that all reads of the database will be the same during the transaction (good for read and update operations). 4. Transaction_serializable- All the transactions for resource are performed serial. 40). What is the difference between ejbCreate() and ejbPostCreate The purpose of ejbPostCreate() is to perform clean-up database operations after SQL INSERTs (which occur when ejbCreate() is called) when working with CMP entity beans. ejbCreate() is called before database INSERT operations. You need to use ejbPostCreate() to define operations, like set a flag, after INSERT completes successfully. When working with BMP entity beans, this is not necessary. You have full control over the entire

process, so you can place all the necessary logic surrounding your INSERT statement directly in the ejbCreate() method. Even if you are creating BMP entity beans, the recommendation would still be to include an empty ejbPostCreate() method. Although some application servers will not enforce it, the spec indicates that this placeholder should be there. 41).What is the difference between sessioncontext and entitycontext? Since EnterpriseBeans live in a managed container,the container is free to call your EJB components methods at its leisure. The container houses the information like current status of bean,security credentials of the user currently accessing the bean in one object is called EJBContext Object. A context represents a way for beans to perform callbacks and modify their current status SessionContext is EJB context for session bean EntityContext is EJB context for entity bean Message driven context is EJB context for message driven bean 42). What is the difference between ejbStore() and ejbLoad()? ejbStore() will be called before ejbPassivate() and is used to store the object to persistent database. ejbLoad() will be called before ejbActivate() and is used to retrieve the object from persistence datastore. 43). What is the difference between EAR, JAR and WAR file? J2EE defines three types of archives: 1. Java Archives (JAR)A JAR file encapsulates one or more Java classes, a manifest, and a descriptor. JAR files are the lowest level of archive. JAR files are used in J2EE for packaging EJBs and client-side Java Applications. 2. Web Archives (WAR)WAR files are similar to JAR files, except that they are specifically for web applications made from Servlets, JSPs, and supporting classes. 3. Enterprise Archives (EAR)An EAR file contains all of the components that make up a particular J2EE application. 44).How to implement an entity bean which the PrimaryKey is an autonumeric? The EJB 2 Spec (10.8.3 - Special case: Unknown primary key class) says that in cases where the PrimaryKeys are generated automatically by the underlying database, thebean provider must declare the findByPrimaryKey method to return java.lang.Object and specify the Primary Key Class as java.lang.Object in the Deployment Descriptor.

When defining the Primary Key for the Enterprise Bean, the Deployer using the Container Provider's tools will typically add additional container-managed fields to the concrete subclass of theentity bean class. In this case, the Container must generate the Primary Key value when the entity bean instance is created (and before ejbPostCreate is invoked on the instance.) 45). Is Decorator an EJB design pattern? No. Decorator design pattern, is the one which exhibits very low level runtime polymorphism, for the specific and single object (Instance of the class), but not for atleast for a class. It is the stuff to add specific functionality to a single & pointed object and leaves others like it unmodified. It is having close similarities like aspect stuff, but not with EJB stuff. 46). What is lazy loading? Lazy loading means not creating an object until the first time it is accessed. Lazy loading typically looks like this: public class Example { private Vector data = null; public Vector getData() { if (this.data == null) { this.data = new Vector(); // Load data into vector ... } return this.data; } } This technique is most useful when you have large hierarchies of objects (such as a product catalog). You can lazy-load subordinate objects as you navigate down the hierarchy, and thereby only creat objects when you need them. 47). What is Message Driven Bean? An MDB is essentially a message consumer that can listen to a message destination or a message endpoint and gets activated when a message arrives. By design, MDBs are anonymous in nature and hence cannot be directly invoked by a client. The only way to invoke an MDB is to send a message to the destination or endpoint to which it is listening. As MDBs are stateless in nature and are not related to any specific client, they can be pooled for concurrent processing of messages. 48). What is CMR? CMR is an acronym for Container Managed Relation-ships. CMR, represented by the cmr fields in the deployment descriptor, which represents the relationship exists between different entities (entity beans), which are in turn exhibiting the database to the real world. The relationships are one-one, one-many, & many-many. All the relations/ referential integrities will be managed by container, then the definition's in the deployment descriptor's are called as Container Managed Relationships (CMR).. 49). Can a Session Bean be defined without ejbCreate() method? The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not return an error because there is no ejbCreate() method.

However, the J2EE spec is explicit: the home interface of a Stateless Session Bean must have a single create() method with no arguments, while the session bean class must contain exactly one ejbCreate() method, also without arguments. Stateful Session Beans can have arguments (more than one create method) 50). What are the optional clauses in EJB QL? WHERE and ORDERBY clauses are optional in EJB QL where as SELECT and FROM are required clauses. 51). Can I use session beans and hibernate (instead of entity beans) for persitance? Yes, we can. It's same as BMP. 52). If session has thrown ApplicaitonException would you use EJBContext. setRollBackOnly method? According to the EJB specification, when the ApplicationException is thrown, the EJBContext.setRollBackOnly method is not called. Typically, an enterprise bean marks a transaction for rollback to protect data integrity before throwing an application exception, because application exceptions do not automatically cause the Container to rollback thetransaction. For example, an AccountTransfer bean which debits one account and credits another account could mark a transaction for rollback if it successfully performs the debit operation, but encounters a failure during the credit operation. 53). What is the difference between activation and passivation? This would be the difference between Activation and Passivation: While the bean is in the ready stage, the EJB container may decide to deactivate, or passivate, the bean by moving it from memory to secondary storage. (Typically, the EJB container uses a leastrecently-used algorithm to select a bean for passivation.) The EJB container invokes the bean's ejbPassivate method immediately before passivating it. If a client invokes a business method on the bean while it is in the passive stage, the EJB container activates the bean, moving it back to the ready stage, and then callsthe bean's ejbActivate method. 54). How do you check whether the session is active in Stateful session bean ? In Stateful session bean session is not itself a separate entity. it is contained in the bean it self. So in order to check tht we need the check whether the Stateful session bean is present or not which is done by just invoking the home interface with the jndi 55). What is the difference between find and select methods in EJB? # A select method can return a persistent field (or a collection thereof) of a related entity bean. A finder method can return only a local or remote interface (or a collection of interfaces). # Because it is not exposed in any of the local or remote interfaces, a select method cannot be invoked by a client. It can be invoked only by the methods implemented within the entity bean class. A select method is usually invoked by either a business or a home method. # A select method is defined in the entity bean class. For bean-managed persistence, a finder method

is defined in the entity bean class, but for container-managed persistence it is not. 56). What is the difference between local interface and remote interface? We can describe the following common rules for choosing whether to use remote client view or local client view: When you will potentially use a distributed environment (if your enterprise bean should be independent of its deployment place), you should obviously choose remote client view. Use remote client view when you need to be sure that parameters passed between your EJB and the client (and/or other enterprise beans) should be passed "by value" instead of "by reference." With pass-by-value, the bean will have its own copy of the data, completely separated from the copy of the data at the client. With local client view, you can do pass-by-reference, which means your bean, as well as the client, will work directly with one copy of the data. Any changes made by the bean will be seen by the client and vice versa. Pass-by-reference eliminates time/system expenses for copying data variables, which provides a performance advantage. If you create an entity bean, you need to remember that it is usually used with a local client view. If your entity bean needs to provide access to a client outside of the existing JVM (i.e., a remote client), you typically use a session bean with a remote client view. This is the so-called Session Facade pattern, the goal of which is that the session bean provides the remote client access to the entity bean. If you want to use container-managed relationship (CMR) in your enterprise bean, you must expose local interfaces, and thus use local client view. This is mentioned in the EJB specification. Enterprise beans that are tightly coupled logically are good candidates for using local client view. In other words, if one enterprise bean is always associated with another, it is perfectly appropriate to colocate them (i.e., deploy them both in one JVM) and organize them through a local interface. 57). Why CMP beans are abstract classes? We have to provide abstract data to object mapping that maps the fields in our bean to a batabase, and abstract methods methods that corelate these fields. 58). What is the difference between normal Java object and EJB? Java Object: is a reusable component. EJB : is a distributed component used to develop business applications. Container provides runtime environment for EJBs. 59). What is abstract schema? Abstract schema is part of an entity bean's deployment descriptor which defines the bean's persistent fields and their relationship.Abstract schema is specifed for entity beans with container managed persistence. We specify the name of the Abstract schema name in the deployment descriptor. The queries written in EJB QL for the finder methods references this name. The information provided in this Abstract Schema is used by the container for persistence management and relationship management. 60). What is clustering. What are the different algorithms used for clustering? Clustering is the use of multiple computers and storage devices to create what seems to be a single system. Clustering is often used to increase a system's availability and for load balancing on highlytrafficked Web sites. Clustering algorithms find groups of items that are similar. For example, clustering could be used by an insurance company to group customers according to income, age, types of policies purchased and prior claims experience. It divides a data set so thatrecords with similar content are in the same group, and groups are as different as possible from each other. Since the categories are unspecified,

this is sometimes referred to as unsupervised learning. Main strategies of clustering: 1. Hierarchical clustering 2. K-clustering (partitioning) 3. Self Organizing Maps (SOM) 4. Hybrids (incremental) 61). Why did I get a LockTimedOutException?

A. When you get a LockTimedOutException while invoking a stateful session EJB, one of two
things has occurred: * You have <allow-concurrent-calls> set to true in your weblogic-ejb-jar.xml descriptor and your call timed out while waiting to be processed. The timeout used in this case is the value <trans-timeout-seconds> element of the weblogic-ejb-jar.xml descriptor or its default value of 30 seconds. * You do not have <allow-concurrent-calls> set to true and you attempt to invoke a stateful session bean that is already busy processing another request. In this case, the second method call will not block and a LockTimedOutException will be thrown immediately. 62). What is the life cycle of MDB? The lifetime of an MDB instance is controlled by the container. Only two states exist: Does not exist and Ready , as illustrated in the following figure: The life of an MDB instance starts when the container invokes newInstance() on the MDB class to create a new instance. Next, the container calls setMessageDrivenContext() followed by ejbCreate() on the instance. The bean then enters the Ready state and is ready to consume messages. When a message arrives for the bean, the container invokes the onMessage() method of one of the available instances, passing a Message object in argument. Message s can be consumed and processed concurrently by using multiple instances of the same type. The container invokes ejbRemove() on the bean instance when it no longer needs the instance. The bean instance can performclean up operations here. 63). Can an entity bean be a listener for JMS messages? No. Message driven beans should be used to consume JMS messages. 64). What is Entity Bean. What are the various types of Entity Bean? Entity bean represents the real data which is stored in the persistent storage like Database or file system. For example, There is a table in Database called Credit_card. This table contains credit_card_no,first_name, last_name, ssn as colums and there are 100 rows in the table. Here each row is represented by one instance of the entity bean and it is found by an unique key (primary key) credit_card_no. There are two types of entity beans. 1) Container Managed Persistence(CMP) 2) Bean Managed Presistence(BMP) 65). What is IIOP ? It is Internet Inter Object Resource Broker Protocl 66). Why don't stateful session beans have a pool? Stateful session beans get instantiated once for each seperate client request and it stores the client information in it, there is no threading concept in EJB hence if there will be an instance pool will exist then there is a possiblity of information leak between different session objects. therefore there is no concept of instance pooling in stateful session bean. 67). Without using entity beans can we do database transactions?

Without using entity beans we can do database transactions through Springs .Spring can be used to configure declarative transaction management, remote access to your logic using RMI or web services, mailing facilities and various options in persisting your data to a database 68). What is the use of using session facade design pattern in EJB'S? There are many uses, important one is to reduce network traffic I you are calling many EJB from your Servlet then this is not advised, because it has to make many network trips, so what you do you call a Stateless session bean and this in turn calls other EJB, since they are in same container there is less network calls other thing you can do now is you can convert them to LOCAL EJB which has not network calls. This increases your server bandwidthJ. Problem solver this is good for a highly available system. 69). What is the difference between session and entity beans? When should I use one or the other? An entity bean represents persistent global data from the database; a session bean represents transient user-specific data that will die when the user disconnects (ends his session). Generally, the session beans implement business methods (e.g.Bank.transferFunds) that call entity beans (e.g. Account.deposit, Account.withdraw) 70). Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB? You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as passed-by-value, that means that its read-only in the EJB. If anything is altered from inside the EJB, it wont be reflected back to the HttpSession of the Servlet Container.The pass-by-reference can be used between EJBs Remote Interfaces, as they are remote references. While it is possible to pass an HttpSession as a parameter to an EJB object, it is considered to be bad practice in terms of object-oriented design. This is because you are creating an unnecessary coupling between back-end objects (EJBs) and front-end objects (HttpSession). Create a higher-level of abstraction for your EJBs API. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your EJB needs to support a non HTTP-based client. This higher level of abstraction will be flexible enough to support it. 71).What is EJB role in J2EE? EJB technology is the core of J2EE. It enables developers to write reusable and portable serverside business logic for the J2EE platform. 72).what are Container-Managed Transactional attributes ? Not Supported The bean is not involved in a transaction. If the bean invoker calls the bean while involved in a transaction, the invoker'stransaction is suspended, the bean executes, and when the bean returns, the invoker's transaction is resumed. Required The bean must be involved in a transaction. If the invoker is involved in a transaction, the bean uses the invoker's transaction. If the invoker is not involved in a transaction, the container starts a new transaction for the bean.

Supports Whatever transactional state that the invoker is involved in is used for the bean. If the invoker has begun a transaction, the invoker's transaction context is used by the bean. If the invoker is not involved in a transaction, neither is the bean. RequiresNew Whether or not the invoker is involved in a transaction, this bean starts a new transaction that exists only for itself. If the invoker calls while involved in a transaction, the invoker's transaction is suspended until the bean completes. Mandatory The invoker must be involved in a transaction before invoking this bean. The bean uses the invoker's transaction context. Never The bean is not involved in a transaction. Furthermore, the invoker cannot be involved in a transaction when calling the bean. If the invoker is involved in a transaction, a RemoteException is thrown 73).How is persistence implemented in enterprise beans? Persistence in EJB is taken care of in two ways, depending on how you implement your beans: container managed persistence (CMP) or bean managed persistence (BMP) For CMP, the EJB container which your beans run under takes care of the persistence of the fields you have declared to be persisted with the database - this declaration is in the deployment descriptor. So, anytime you modify a field in a CMP bean, as soon as the method you have executed is finished, the new data is persisted to the database by the container. For BMP, the EJB bean developer is responsible for defining the persistence routines in the proper places in the bean, for instance, the ejbCreate(), ejbStore(), ejbRemove() methods would be developed by the bean developer to make calls to the database. The container is responsible, in BMP, to call the appropriate method on the bean. So, if the bean is being looked up, when the create() method is called on the Home interface, then the container is responsible for calling the ejbCreate() method inthe bean, which should have functionality inside for going to the database and looking up the data. 74). Are we allowed to change the transaction isolation property in middle of a transaction? No. You cannot change the transaction isolation level in the middle of transaction. 75). For Entity Beans, What happens to an instance field not mapped to any persistent storage, when the bean is passivated? The specification infers that the container never serializes an instance of an Entity bean (unlike stateful session beans). Thuspassivation simply involves moving the bean from the ready to the pooled bin. So what happens to the contents of an instance variable is controlled by the programmer. Remember that when an entity bean is passivated the instance gets logically disassociated from its remote object. Be careful here, as the functionality of passivation/activation for Stateless Session, Stateful Session and Entity beans is completely different. For entity beans the ejbPassivate method notifies the entity bean that it is being disassociated with a particular entity prior to reuse or for dereference. 76). What is a Message Driven Bean, what functions does a message driven bean have and how do they work in collaboration with JMS? Message driven beans are the latest addition to the family of component bean types defined by the EJB specification. The original bean types include session beans, which contain business logic and maintain a state associated with client sessions, and entity beans, which map objects to persistent data. Message driven beans will provide asynchrony to EJB based applications by acting as JMS message consumers. A message bean is associated with a JMS topic or queue and receives JMS messages sent by EJB clients or other beans. Unlike entity beans and session beans, message beans do not have home or remote interfaces. Instead, message driven beans are instantiated by the container as required. Like stateless session beans, message beans maintain no client-specificstate, allowing the container to optimally manage a pool of message-bean instances. Clients send JMS messages to message beans in exactly the same manner as they would send messages to any other JMS destination. This similarity is a fundamental design goal of the JMS capabilities of the new

specification. To receive JMS messages, message driven beans implement the javax.jms.MessageListener interface, which defines a single onMessage() method. When a message arrives, the container ensures that a message bean corresponding to the message topic/queue exists (instantiating it if necessary), and calls its onMessage method passing the clients message as the single argument. The message beans implementation of this method contains thebusiness logic required to process the message. Note that session beans and entity beans are not allowed to function as message beans. 77).What is the advantage of putting an Entity Bean instance from the Ready State to Pooled state? The idea of the Pooled State is to allow a container to maintain a pool of entity beans that has been created, but has not been yet synchronized or assigned to an EJBObject. This mean that the instances do represent entity beans, but they can be used only for serving Home methods (create or findBy), since those methods do not relay on the specific values of the bean. All these instances are, in fact, exactly the same, so, they do not have meaningful state. Jon Thorarinsson has also added: It can be looked at it this way: If no client is using an entity bean of a particular type there is no need for cachig it (the data is persisted in the database). Therefore, in such cases, the container will, after some time, move the entity bean from the Ready State to the Pooled state to save memory. Then, to save additional memory, the container may begin moving entity beans from the Pooled State to the Does Not Exist State, because even though the beans cache has been cleared, the bean still takes up some memory just being in the Pooled State. 78). What is Session Bean? The entity bean is used to represent data in the database. It provides an object-oriented interface to data that would normally be accessed by the JDBC or some other back-end API. More than that, entity beans provide a component model that allows bean developers to focus their attention on the business logic of the bean, while the container takes care of managing persistence,transactions, and access control. There are two basic kinds of entity beans: container-managed ersistence (CMP) andbean-managed persistence (BMP). Container-managed persistence beans are the simplest for the bean developer to create and the most difficult for the EJB server to support. This is because all the logic for synchronizing the bean's state with the database is handled automatically by the container. This means that the bean developer doesn't need to write any data access logic, while the EJB server is supposed to take care of all the persistence needs automatically. With CMP, the container manages the persistence of the entity bean. Vendor tools are used to map the entity fields to the database and absolutely no database access code is written in the beanclass. The bean-managed persistence (BMP) enterprise bean manages synchronizing its state with the database as directed by the container. The bean uses a database API to read and write its fields to the database, but the container tells it when to do each synchronization operation and manages the transactions for the bean automatically. Bean-managed persistence gives the beandeveloper the flexibility to perform persistence operations that are too complicated for the container or to use a data source that is not supported by the container. 79).If my session bean with single method insert record into 2 entity beans, how can I know that the process is done in same transaction (the attributes for these beans are Required) It depends on the transaction attribute of the session bean also. You have to set the transaction attribute of the session bean either to Required or RequiresNew. 80).Can i map more than one table in a CMP? No, you cannot map more than one table to a single CMP Entity Bean. CMP has been, in fact, designed to map a single table.

81). Difference between SessionBean remove() and EntityBean remove() method? SessionBean remove() : inform the container of your loss of interest in this bean. Container will remove the instance. EntityBean remove() : delete an entity bean without first instantiating it. Delete the row of the table using mentioned primary key. 82). Does each stateless session bean have its own EJBObject? This is container specific as it is responsible for hadling the beans. There may be a 1:N or M:N relationship between EJBObject and the session Bean. Struts FAQs Q 1. What is MVC? Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data. Model: The model contains the core of the application's functionality. The model enca psulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller. View: The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur. Controller: The controller reacts to the user input. It creates and sets the model. Q 2. What is a framework? Framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement. Q 3. What is Struts framework? Struts framework is an open-source framework for developing the web applications in Java EE, based on MVC-2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java. Struts provides its own Controller component and integrates with other technologies to provide the Model and the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as VelocityTemplates, XSLT, and other presentation systems.

Q 4. What is Jakarta Struts Framework? Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java. Q 5. What is ActionServlet?

The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests. Q 6. What is role of ActionServlet? ActionServlet performs the role of Controller:

Process user requests Determine what the user is trying to achieve according to the request Pull data from the model (if necessary) to be given to the appropriate view, Select the proper view to respond to the user Delegates most of this grunt work to Action classes Is responsible for initialization and clean-up of resources

Q 7. What is Action Class? Any java class which extends from org.apache.struts.action.Action is called Action class. The Action is part of the controller. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. There should be no database interactions in the action. The action should receive the request, call business objects (which then handle database, or interface with J2EE, etc) and then determine where to go next. Even better, the business objects could be handed to the action at runtime (IoC style) thus removing any dependencies on the model. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.. Q 8. Write code of any Action Class? package com.durgasoft; import javax.servlet.http.*; import org.apache.struts.action.*; public class TestAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,HttpServletResponse response) throws Exception { return mapping.findForward("success"); } } Q 9. What is ActionForm? Any java class which extends from org.apache.struts.action.ActionForm is called ActionForm. An ActionForm is also called JavaBean. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side. Q10. What is Struts Validator Framework? Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings. Q11. How you will display validation fail errors on jsp page? Following tag displays all the errors: <html:errors/> Q12. What is RequestProcessor? The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations. The Controller receives the request from the browser, invoke a business operation and coordinating the view to return to the client.The controller is implemented by a java servlet, this servlet is centralized point of control for the web application. In struts framework the controller responsibilities are implemented by several different components like The ActionServlet Class The RequestProcessor Class The Action Class The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your application. The controller is implemented by the ActionServlet class. All incoming requests are mapped to the central controller in thedeployment descriptor as follows. <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> </servlet> All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows. <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> <servlet-mapping> A request URI that matches this pattern will have the following form. http://localhost:8080/mycontext/actionName.do The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends with /* as shown below. <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>/do/*</url-pattern> <url-pattern>*.do</url-pattern> A request URI that matches this pattern will have the following form. http://localhost:8080/mycontext/do/action_Name The class org.apache.struts.action.requestProcessor process the request from the controller. You can sublass the RequestProcessor with your own version and modify how the request is processed. Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation associated with the requested action. In the Struts framework this helper class is descended of org.apache.struts.action.Action class. It acts as a bridge between a client-side user action and business operation. The Action classdecouples the client request from the business model. This decoupling allows for more than one-to-one mapping between the user request and an action. The Action class also can perform other functions such as authorization, logging before invoking businessoperation. the Struts Action class contains several methods, but most important method is the execute() method. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception

The execute() method is called by the controller when a request is received from a client. The controller creates an instance of the Action class if one doesn?t already exist. The strut framework will create only a single instance of each Action class in your application. Action are mapped in the struts configuration file and this configuration is loaded into memory at startup and made available to the framework at runtime. Each Action element is represented in memory by an instance of the org.apache.struts.action. ActionMapping class. The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request. <action> path= "/somerequest" type="com.somepackage.someAction" scope="request" name="someForm" validate="true" input="somejsp.jsp" <forward name="Success" path="/action/xys" redirect="true"/> <forward name="Failure" path="/somejsp.jsp" redirect="true"/> </action> Once this is done the controller should determine which view to return to the client. The execute method signature in Action class has a return type org.apache. struts.action.ActionForward class. The ActionForward class represents a destination to which the controller may send control once an action has completed. Instead of specifying an actual JSP page in the code, you can declaratively associate as action forward through out the application. The action forward are specified in the configuration file. <action> path= "/somerequest" type="com.somepackage.someAction" scope="request" name="someForm" validate="true" input="somejsp.jsp" <forward name="Success" path="/action/xys" redirect="true"/> <forward name="Failure" path="/somejsp.jsp" redirect="true"/> </action> The action forward mappings also can be specified in a global section, independent of any specific action mapping. <global-forwards> <forward name="Success" path="/action/somejsp.jsp" /> <forward name="Failure" path="/someotherjsp.jsp" /> </global-forwards> Q13. How you will handle exceptions in Struts? In Struts you can handle the exceptions in two ways: a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within <action>..</action> tag. Example: <exception key="database.error.duplicate" path="/UserExists.jsp" type="mybank.account.DuplicateUserException"/> b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception. Q14. What are the different kinds of actions in Struts?

The different kinds of actions in Struts are: ForwardAction, IncludeAction, DispatchAction, LookupDispatchAction, SwitchAction Q15. What is DispatchAction? The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke. Q16. How to use DispatchAction? To use the DispatchAction, follow these steps : 1. 2. 3. 4. Create a class that extends DispatchAction (instead of Action) In a new class, add a method for every function you need to perform on the service The method has the same signature as the execute() method of an Action class. Do not override execute() method Because DispatchAction class itself provides execute() method. Add an entry to struts-config.xml

Q17. What is LookupDispatchAction? The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle. Q18. What is the use of LookupDispatchAction? LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. Since the key is always the same, the LookupDispatchAction shields your application from the side effects of I18N. Q19. What is difference between LookupDispatchAction and DispatchAction? The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly. Q20. What is SwitchAction? The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application. The SwitchAction class can be used as is, without extending. Q21. What if <action> element has <forward> declaration with same name as global forward? In this case the global forward is not used. Instead the <action> elements <forward> takes precendence. Q22. What is difference between ActionForm and DynaActionForm?

An ActionForm represents an HTML form that the user interacts with over one or more pages. You will provide properties to hold the state of the form with getters and setters to access them. Whereas, using DynaActionForm there is no need of providing properties to hold the state. Instead these properties and their type are declared in the struts-config.xml. The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger. The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment. ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file. ActionForm were designed to act as a Firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.get Parameter( .. ).

DynaActionForm construction at runtime requires a lot of Java Reflection (Introspection) machinery that can be avoided.

Q23. What is the life cycle of ActionForm? The lifecycle of ActionForm invoked by the RequestProcessor is as follows:

Retrieve or Create Form Bean associated with Action "Store" FormBean in appropriate scope (request or session) Reset the properties of the FormBean Populate the properties of the FormBean Validate the properties of the FormBean Pass FormBean to Action

Q24.What are the important tags of struts-config.xml ? <struts-config> <!-- ========== Form Bean Definitions ============ --> <form-beans> <form-bean name="login" type=" LoginForm" /> </form-beans> <!-- ========== Global Forward Definitions ========= --> <global-forwards> </global-forwards> <!-- ========== Action Mapping Definitions ======== --> <action-mappings> <action path="/login" type="LoginAction" > </action> </action-mappings> <!-- ========== Properties Definitions ============ --> <message-resources parameter="MessageResources" /> <!-- ========== Validator framework Definitions ============ --> <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/org/apache/struts/validator/validator-rules.xml, /WEB-INF/validation.xml"/> </plug-in> </struts-config>

Q25. What are the core classes of the Struts Framework? A: Core classes of Struts Framework are ActionForm, Action, ActionMapping, Action Forward, ActionServlet etc. Q26. What is action mappings? An action mapping is a configuration file entry that, in general, associates an action name with an action. An action mapping can contain a reference to a form bean that the action can use, and can additionally define a list of local forwards that is visible only to this action. Q27. Describe validate() and reset() methods ? validate () and reset() methods defined inActionForm class. validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionMessage as ActionErrors. Following is the method signature for the validate() method. public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set. public void reset() {} Q28. Give the Details of XML files used in Validator Framework? The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xmldefines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean. Q29. How you will enable front-end validation based on the xml in validation.xml? The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code: <html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="true" /> generates the client side java script for the form "logonForm" as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script. Q30. What is the difference between perform() and execute() methods? perform() method defined in Struts 1.0. but it is was deprecated in the Struts Version 1.1. In Struts 1.x, Action.perform() is the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic. As we already mentioned, to support declarative exception handling, the method signature changed in perform. Now execute just throws Exception. Action.perform() is now deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action, depending on which one is available. Q31. What are the various Struts tag libraries? Struts is very rich framework and it provides very good and user friendly way to develop web application forms. Struts provide many tag libraries to ease the development of web applications. These tag libraries are: * Bean tag library - Tags for accessing JavaBeans and their properties. * HTML tag library - Tags to output standard HTML, including forms, text boxes, checkboxes, radio buttons etc.. * Logic tag library - Tags for generating conditional output, iteration capabilities and flow management * Tiles or Template tag library - For the application using tiles * Nested tag library - For using the nested beans in the application

Q32. What are the difference between <bean:message> and <bean:write>? <bean:message>: This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle. <bean:write>: This tag is used to output property values from a bean. <bean:write> is a commonly used tag which enables the programmers to easily present the data. Q33. What are difference between ActionErrors and ActionMessage? ActionMessage: A class that encapsulates messages. Messages can be either global or they are specific to a particular bean property. Each individual message is described by an ActionMessage object, which contains a message key (to be looked up in an appropriate message resources database), and up to four placeholder arguments used for parametric substitution in the resulting message. ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Validation errors are either global to the entire ActionForm bean they are associated with, or they are specific to a particular bean property (and, therefore, a particular input field on the corresponding form). Q34. What is the use of ForwardAction? The ForwardAction class is useful when youre trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller and its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined action, you dont have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction. Q35. What is IncludeAction? The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the IncludeAction class to include another resource in the response to the request being processed. Q36. What are the steps need to use DynaActionForm? Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. You need to make changes in two places: In struts-config.xml: change your <form-bean> to be an org.apache.struts.action.Dyna ActionForm instead of some subclass of ActionForm

<form-bean name="loginForm" type="org.apache.struts.action.DynaActionForm" > <form-property name="userName" type="java.lang.String"/> <form-property name="password" type="java.lang.String" /> </form-bean> In your Action subclass that uses your form bean: o import org.apache.struts.action.DynaActionForm o downcast the ActionForm parameter in execute() to a DynaActionForm o access the form fields with get(field) rather than getField()

Q.37 In struts what happens if made any changes in actionservlet? The ActionServlet plays the role of controller wich is responsible for handling the request and selecting the correct Application Module and storing ApplicationConfig and MessageResource bundle in the request object. If we modify the ActionServlet the Controller may or may not work what happens that depends on your modification, You have not specify whether you want to create your own custom ActionServlet by extending ActionServlet and overriding the methods in it or what exactly you want to modify.

Hibernate FAQs1

1.what is the advantage of Hibernate over jdbc? There are so many 1) Hibernate is data base independent, your code will work for all ORACLE,MySQL ,SQLServer etc. In case of JDBC query must be data base specific. So hibernate based persistance logic is database independent persistance logic and JDBC based persistance logic is database dependent logic. 2) As Hibernate is set of Objects , 3) No need to learn SQL language.You can treat TABLE as a Object . Only Java knowledge is need. In case of JDBC you need to learn SQL. 3) Dont need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance. In case of JDBC you need to tune your queries. 4) You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you can store your data into Cache for better performance. In case of JDBC you need to implement your java cache . 5) Hibernate supports Query cache and It will provide the statistics about your query and database status. JDBC Not provides any statistics. 6) Development fast in case of Hibernate because you dont need to write queries 7) No need to create any connection pool in case of Hibernate. You can use c3p0. In case of JDBC you need to write your own connection pool 8) In the xml file you can see all the relations between tables in case of Hibernate. Easy readability. 9) You can load your objects on start up using lazy=false in case of Hibernate. JDBC Dont have such support. 10 ) Hibernate Supports automatic versioning of rows but JDBC Not. 2.What is Hibernate? Hibernate is an open source, light weight Object Relational Mapping tool to develop the database independent persistence login in java and j2ee based applications. Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration and mapping files. Its purpose is to relieve the developer from a significant amount of relational data persistencerelated programming tasks 3.What is ORM ? ORM stands for object/relational mapping, means providing the mapping between class with table and member variables with columns is called ORM. ORM is the automated persistence of objects in a Java application to the tables in a relational database. 4.hat does ORM consists of ? An ORM solution consists of the following four pieces:

API for performing basic CRUD operations API to express queries referring to classes Facilities to specify metadata Optimization facilities : dirty checking,lazy associations fetching

5.What are the ORM levels ? The ORM levels are:

Pure relational (stored procedure.) Light objects mapping (JDBC) Medium object mapping

Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

. 6.Why do you need ORM tools like hibernate? The main advantage of ORM like hibernate is that it can develop the database independent persistence logic. Apart from this, ORM provides following benefits:

Improved productivity o High-level object-oriented API o Less Java code to write o No SQL to write Improved performance o Sophisticated caching o Lazy loading o Eager loading Improved maintainability o A lot less code to write Improved portability ORM framework generates database-specific SQL for you

7.What Does Hibernate Simplify? Hibernate simplifies:

Saving and retrieving your domain objects Making database column and table name changes Centralizing pre save and post retrieve logic Complex joins for retrieving related items Schema creation from object model

8.What is the main difference between Entity Beans and Hibernate ? 1)In Entity Bean at a time we can interact with only one data Base. Where as in Hibernate we can able to establishes the connections to more than One Data Base. Only thing we need to write one more configuration file. 2) EJB need container like Weblogic, WebSphare but hibernate don't nned. It can be run on tomcat. 3) Entity Beans does not support OOPS concepts where as Hibernate does. 4) Hibernate supports multi level cacheing, where as Entity Beans doesn't. 5) In Hibernate C3P0 can be used as a connection pool. 6) Hibernate is container independent. EJB not. 9.What are the Core interfaces and classes of Hibernate framework?

The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.

Configuration class (org.hibernate.cfg package) Session interface (org.hibernate package) SessionFactory interface (org.hibernate package) Transaction interface (org.hibernate package) Query and Criteria interfaces (org.hibernate package)

10.What is the general flow of Hibernate communication with RDBMS? The general flow of Hibernate communication with RDBMS is :

Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files because mapping file can be configured in configuration file. Create session factory from configuration object Get one session from this session factory Create HQL Query Execute query to get list containing Java objects. 11.What is the need for Hibernate mapping file? Hibernate mapping file is used to provides the mapping between java class with table member variables with column names of the table. And also we can configure primary key generation algorithm, relations and so on. Typical mapping file look as follows:

12.What are the important tags of hibernate.cfg.xml? This file can be used to provide the database information like driverclass name, url, database usename, database password, dialect, connection pooling mapping file and so on.

Following are the important tags of hibernate.cfg.xml:

13.What role does the Session interface play in Hibernate? The main runtime interface between a Java application and Hibernate The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object

representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects. The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states: transient: never persistent, not associated with any Session persistent: associated with a unique Session detached: previously persistent, not associated with any Session Session session = sessionFactory.openSession(); Session interface role:

Wraps a JDBC connection Factory for Transaction Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

14.What role does the SessionFactory interface play in Hibernate? SessionFactorys are immutable. The behaviour of a SessionFactory is controlled by properties supplied at configuration time. These properties are defined on Environment. The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the wholeapplicationcreated during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work Implementors must be threadsafe. SessionFactory sessionFactory = configuration.buildSessionFactory(); 15.What are the most common ways to specify the Hibernate configuration properties? The most common methods of Hibernate configuration are:

Programmatic configuration By using setProperty(-) method of org.hibernate.cfg.Configuration.

XML configuration (hibernate.cfg.xml) By using .properties file By Using annotaions.(from Hibernate 3.3 on words)

16.How do you map Java Objects with Database tables?

First we need to write Java domain objects (beans with setter and getter). Write hbm.xml, where we map java class to table and database columns to Java class variables.

Example : <hibernate-mapping> <class name="com.durgasoft.EmployeeBean" table="EMPLOYEE"> <id name=eid colume=id/> <property name="ename" column="NAME" length="255" not-null="true" type="java.lang.String"/> <property name="address" column="ADDR" length="255" not-null="true" type="java.lang.String"/> </class> </hibernate-mapping>

17.How do you define sequence generated primary key algorithm in hibernate? By using <id>, <generator> tags we can configure the primary key and primary key generation algorithm. Example:<id name="userid" column="USER_ID" type="java.lang.Long"> <generator class="sequence"> <param name="table">SEQ_NAME</param> <generator> </id> 18.What is component mapping in Hibernate?

A component is an object saved as a value, not as a reference A component can be saved directly without needing to declare interfaces or identifier properties Required to define an empty constructor Shared references not supported

19 . Difference between getCurrentSession() and openSession() in Hibernate ? getCurrentSession() : Obtains the current session. The "current session" refers to a Hibernate Session bound by Hibernate behind the scenes, to the transaction scope. A Session is opened when getCurrentSession() is called for the first time and closed when the transaction ends. It is also flushed automatically before the transaction commits. You can call getCurrentSession() as often and anywhere you want as long as the transaction runs. Only the Session that you obtained with sf.getCurrentSession() is flushed and closed automatically. openSession() : If you decide to use manage the Session yourself the go for sf.openSession() , you have to flush() and close() it. It does not flush and close() automatically. Example : Transaction tx =session.berginTransaction(); Session session = factory.openSession(); try { tx.begin(); // Do some work session.createQuery(...); session.persist(...); session.flush(); // Extra work you need to do tx.commit(); } catch (RuntimeException e) { tx.rollback(); throw e; // or display error message } finally { session.close(); // Extra work you need to do }

20.What are the types of Hibernate instance states ? Three types of instance states:

Transient -The instance is not associated with any persistence context Persistent -The instance is associated with a persistence context Detached -The instance was associated with a persistence context which has been closed currently not associated

21.What are the types of inheritance models in Hibernate? There are three types of inheritance models in Hibernate:

Table per class hierarchy Table per subclass Table per concrete class

22.What is Hibernate Query Language (HQL)? Hibernate Query Language is query language which is used to develop the data independent query language in the application. This HQL queries are not related to any database. Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an objectoriented extension to SQL. 23.What are the ways to express joins in HQL? HQL provides four ways of expressing (inner and outer) joins:-

An implicit association join An ordinary join in the FROM clause A fetch join in the FROM clause. A theta-style join in the WHERE clause.

24 . Transaction with plain JDBC in Hibernate ? If you don't have JTA and don't want to deploy it along with your application, you will usually have to fall back to JDBC transaction demarcation. Instead of calling the JDBC API you better use Hibernate's Transaction and the built-in session-per-request functionality: To enable the thread-bound strategy in your Hibernate configuration: set hibernate.transaction.factory_class to org.hibernate.transaction.JDBCTransactionFactory set hibernate.current_session_context_class to thread Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); // Do some work session.load(...); session.persist(...); tx.commit(); // Flush happens automatically } catch (RuntimeException e) { tx.rollback(); throw e; // or display error message

} finally { session.close(); } 25 . What are the general considerations or best practices for defining your Hibernate persistent classes? 1.You must have a default no-argument constructor for your persistent classes and there should be getXXX()and setXXX() methods for all your persistable instance variables. 2.You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object. 3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster. 4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects. 26 . Difference between session.update() and session.lock() in Hibernate ? The session.update method is used to update the persistence object in the in the database. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction. 27.What are the Collection types in Hibernate ?

Set List Array Map Bag

28.What is the difference between sorted and ordered collection in hibernate? sorted collection vs. order collection :order collection sorted collection A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections Order collection is sorting a collection by framework. The sorting occurs in the memory of specifying the order-by clause for sorting this JVM which running Hibernate, after the data being collection when retrieval. read from database using java comparator. If your collection is not large, it will be more If your collection is very large, it will be more efficient way to sort it. efficient way to sort it .

29.What are the ways to express joins in HQL? HQL provides four ways of expressing (inner and outer) joins:-

An implicit association join An ordinary join in the FROM clause A fetch join in the FROM clause. A theta-style join in the WHERE clause.

30.What do you mean by Named SQL query? Named SQL queries are defined in the mapping xml document and called wherever required. Example: <sql-query name = "empdetails"> <return alias="emp" class="com.durgasoft.Employee"/> SELECT emp.EMP_ID AS {emp.empid}, emp.EMP_ADDRESS AS {emp.address}, emp.EMP_NAME AS {emp.name} FROM Employee EMP WHERE emp.NAME LIKE :name </sql-query> Invoke Named Query : List people = session.getNamedQuery("empdetails") .setString("TomBrady", name) .setMaxResults(50) .list(); 31.How do you invoke Stored Procedures? <sql-query name="selectAllEmployees_SP" callable="true"> <return alias="emp" class="employee"> <return-property name="empid" column="EMP_ID"/> <return-property name="name" column="EMP_NAME"/> <return-property name="address" column="EMP_ADDRESS"/> { ? = call selectAllEmployees() } </return> </sql-query>

32.Explain Criteria API The interface org.hibernate.Criteria represents a query against a particular persistent class. The Session is a factory for Criteria instances. Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set. Example : List employees = session.createCriteria(Employee.class) .add(Restrictions.like("name", "a%") ) .add(Restrictions.like("address", "Boston")) .addOrder(Order.asc("name") ) .list();

33.Whats the difference between load() and get()? get()

load()

Only use the load() method if you are sure that the If you are not sure that the object exists, then object exists. use one of the get() methods. load() method will throw an exception if the unique id get() method will return null if the unique id is is not found in the database. not found in the database. load() just returns a proxy by default and database get() will hit the database immediately. wont be hit until the proxy is first invoked.

34.What is the difference between and merge and update ? Use update() if you are sure that the session does not contain an already persistent instance with the same identifier, and merge() if you want to merge your modifications at any time without consideration of the state of the session.

35.Define cascade and inverse option in one-many mapping? cascade - enable operations to cascade to child entities. cascade="all|none|save-update|delete|all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

36.Define HibernateTemplate? org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions. 37.What are the benefits does HibernateTemplate provide? The benefits of HibernateTemplate are :

HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session. Common functions are simplified to single method calls. Sessions are automatically closed. Exceptions are automatically caught and converted to runtime exceptions.

38. How do you switch between relational databases without code changes? Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.

39.If you want to see the Hibernate generated SQL statements on console, what should we do? By using show_sql property of the hibernate configuration file In Hibernate configuration file set as follows: <property name="show_sql">true</property>

40.What are derived properties? The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

41.Define cascade and inverse option in one-many mapping? cascade - enable operations to cascade to child entities. cascade="all|none|save-update|delete|all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

42 . Explain about transaction file? Transactions denote a work file which can save changes made or revert back the changes. A transaction can be started by session.beginTransaction() and it uses JDBC connection, CORBA or JTA. When this session starts several transactions may occur. 43 . Difference between session.save() , session.saveOrUpdate() and session.persist()? All methods are used to store the data in to database session.save() : save() method uSave does an insert and will fail if the primary key is already persistent. session.saveOrUpdate() : saveOrUpdate() insert the data in the database if that primary key data not available and it update the data if primary key data not availabt session.persist() :it is the same like session.save(). But session.save() return Serializable object but session.persist() return void. For Example : if you do :System.out.println(session.save(question)); This will print the generated primary key. if you do :System.out.println(session.persist(question)); Compile time error because session.persist() return void. 44 . Explain about the id field? This id field is used to configure the primary key in the mapping file, and also we can configure primary key generation algorithm. 45.What is the use of dynamic-insert and dynamic-update attributes in a class mapping? Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.

dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

46.What is automatic dirty checking? Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.

47.What are Callback interfaces? Callback interfaces allow the application to receive a notification when something interesting happens to an objectfor example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality. 48.What is Hibernate proxy? The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked. 49.How can Hibernate be configured to access an instance variable directly and not through a setter method ? By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object. 50.How can a whole class be mapped as immutable? Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application. 51 . Explain about transparent persistence of Hibernate? Transparent persistence is provided for Plain old Java objects or POJOs. For proper functioning of the applications importance should be given to the methods equals () and hash Code methods (). It has a requirement which should be strictly followed in the applications which is a no-argument constructor. 52 . Explain about the dirty checking feature of Hibernate? Dirty checking feature of the Hibernate allows users or developers to avoid time consuming data base write actions. This feature makes necessary updations and changes to the fields which require a change, remaining fields are left unchanged or untouched. 53 . What is the effect when a transient mapped object is passed onto a Sessions save? When a Sessions save () is passed to a transient mapped object it makes the method to become more persistent. Garbage collection and termination of the Java virtual machine stays as long as it is deleted explicitly. It may head back to its transient state. 54 . Explain about addClass function? This function translates a Java class name into file name. This translated file name is then loaded as an input stream from the Javaclass loader. This addClass function is important if you want efficient usage of classes in your code. Spring FAQs 1. What is IOC (or Dependency Injection)? The basic concept of the Inversion of Control pattern (also known as dependency injection) is that you do not create your objects but describe how they should be created. You don't directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (in the case of the Spring framework, the IOC container) is then responsible for hooking it all up. i.e., Applying IoC, objects are given their dependencies at creation time by some external entity that coordinates each object in the system. That is, dependencies are injected into objects. So, IoC means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

2. What are the different types of IOC (dependency injection) ? There are three types of dependency injection:

Constructor Injection (e.g. Pico container, Spring etc): Dependencies are provided as constructor parameters. Setter Injection (e.g. Spring): Dependencies are assigned through JavaBeans properties (ex: setter methods). Interface Injection (e.g. Avalon): Injection is done through an interface.

Note: Spring supports only Constructor and Setter Injection 3. What are the benefits of IOC (Dependency Injection)? Benefits of IOC (Dependency Injection) are as follows:

Minimizes the amount of code in your application. With IOC containers you do not care about how services are created and how you get references to the ones you need. You can also easily add additional services by adding a new constructor or a setter method with little or no extra configuration. Make your application more testable by not requiring any singletons or JNDI lookup mechanisms in your unit test cases. IOC containers make unit testing and switching implementations very easy by manually allowing you to inject your own objects into the object under test. Loose coupling is promoted with minimal effort and least intrusive mechanism. The factory design pattern is more intrusive because components or services need to be requested explicitly whereas in IOC the dependency is injected into requesting piece of code. Also some containers promote the design to interfaces not to implementations design concept by encouraging managed objects to implement a well-defined service interface of your own. IOC containers support eager instantiation and lazy loading of services. Containers also provide support for instantiation of managed objects, cyclical dependencies, life cycles management, and dependency resolution between managed objects etc.

4. What is Spring ? Spring is an open source framework created to address the complexity of enterprise application development. One of the chief advantages of the Spring framework is its layered architecture, which allows you to be selective about which of its components you use while also providing a cohesive framework for J2EE application development. 5. What are the advantages of Spring framework? The advantages of Spring are as follows:

Spring has layered architecture. Use what you need and leave you don't need now. Spring Enables POJO Programming. There is no behind the scene magic here. POJO programming enables continuous integration and testability. Dependency Injection and Inversion of Control Simplifies JDBC Open source and no vendor lock-in.

6. What are features of Spring ? Lightweight: spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 1MB. And the processing overhead is also very negligible. Inversion of control (IOC): Loose coupling is achieved in spring using the technique Inversion of Control. The objects give their dependencies instead of creating or looking for dependent objects.

Aspect oriented (AOP): Spring supports Aspect oriented programming and enables cohesive development by separating application business logic from system services. Container: Spring contains and manages the life cycle and configuration of application objects. MVC Framework: Spring comes with MVC web application framework, built on core Spring functionality. This framework is highly configurable via strategy interfaces, and accommodates multiple view technologies like JSP, Velocity, Tiles, iText, and POI. But other frameworks can be easily used instead of Spring MVC Framework. Transaction Management: Spring framework provides a generic abstraction layer for transaction management. This allowing the developer to add the pluggable transaction managers, and making it easy to demarcate transactions without dealing with low-level issues. Spring's transaction support is not tied to J2EE environments and it can be also used in container less environments. JDBC Exception Handling: The JDBC abstraction layer of the Spring offers a meaningful exception hierarchy, which simplifies the error handling strategy. Integration with Hibernate, JDO, and iBATIS: Spring provides best Integration services with Hibernate, JDO and iBATIS contexts for Web-based applications. As a result, the Spring framework supports integration with Jakarta Struts. The Web module also eases the tasks of handling multi-part requests and binding request parameters to domain objects. 7 . What is web module? This module is built on the application context module, providing a context that is appropriate for webbased applications. This module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and programmatic binding of request parameters to your business objects. It also contains integration support with Jakarta Struts. 8. What are the types of Dependency Injection Spring supports? Setter Injection: Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean. Constructor Injection: Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator. 9. What is Bean Factory ? A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.

BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client. BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.

10. What is Application Context? A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:

A means for resolving text messages, including support for internationalization. A generic way to load file resources. Events to beans that are registered as listeners.

11. What is the difference between Bean Factory and Application Context ? On the surface, an application context is same as a bean factory. But application context offers much more..

Application contexts provide a means for resolving text messages, including support for i18n of those messages. Application contexts provide a generic way to load file resources, such as images. Application contexts can publish events to beans that are registered as listeners. Certain operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. ResourceLoader support: Springs Resource interface us a flexible generic abstraction for handling low-level resources. An application context itself is a ResourceLoader, Hence provides an application with access to deployment-specific Resource instances. MessageSource support: The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable

12. What are the common implementations of the Application Context ? The three commonly used implementation of 'Application Context' are

ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating contextdefinitions as classpath resources. The application context is loaded from the application's classpath by using the code . ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml"); FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code . ApplicationContext context = new FileSystemXmlApplicationContext("bean.xml"); XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.

13. How is a typical spring implementation look like ? For a typical Spring Application we need the following files:

An interface that defines the functions. An Implementation that contains properties, its setter and getter methods, functions etc., Spring AOP (Aspect Oriented Programming) A XML file called Spring configuration file. Client program that uses the function.

14. What is the typical Bean life cycle in Spring Bean Factory Container ? Bean life cycle in Spring Bean Factory Container is as follows:

The spring container finds the beans definition from the XML file and instantiates the bean. Using the dependency injection, spring populates all of the properties as specified in the bean definition If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the beans ID. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself. If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization() methods will be called. If an init-method is specified for the bean, it will be called. Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.

15. What do you mean by Bean wiring ? The act of creating associations between application components (beans) within the Spring container is reffered to as Bean wiring. 16. What do you mean by Auto Wiring? The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for your bean by inspecting the contents of the BeanFactory. The autowiring functionality has five modes.

no byName byType constructor autodirect

17. What is DelegatingVariableResolver? Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard Java Server Facesmanaged beans mechanism which lets you use JSF and Spring together. This variable resolver is called asDelegatingVariableResolver 18. How to integrate Java Server Faces (JSF) with Spring? JSF and Spring do share some of the same features, most noticeably in the area of IOC services. By declaring JSF managed-beans in the faces-config.xml configuration file, you allow the FacesServlet to instantiate that bean at startup. Your JSF pages have access to these beans and all of their properties.We can integrate JSF and Spring in two ways:

DelegatingVariableResolver: Spring comes with a JSF variable resolver that lets you use JSF and Spring together.

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <faces-config> <application> <variable-resolver> org.springframework.web.jsf.DelegatingVariableResolver </variable-resolver> </application> </faces-config>

The DelegatingVariableResolver will first delegate value lookups to the default resolver of the underlying JSF implementation, and then to Spring's 'business context' WebApplicationContext. This allows one to easily inject dependencies into one's JSF-managed beans.

FacesContextUtils:custom VariableResolver works well when mapping one's properties to beans in faces-config.xml, but at times one may need to grab a bean explicitly. The FacesContextUtils class makes this easy. It is similar to WebApplicationContextUtils, except that it takes a FacesContext parameter rather than a ServletContext parameter.

ApplicationContext ctx = FacesContextUtils.getWebApplicationContext(FacesContext.getCurrentInstance()); 19. What is Java Server Faces (JSF) - Spring integration mechanism? Spring provides a custom JavaServer Faces VariableResolver implementation that extends the standard JavaServer Faces managed beans mechanism. When asked to resolve a variable name, the following algorithm is performed:

Does a bean with the specified name already exist in some scope (request, session, application)? If so, return it Is there a standard JavaServer Faces managed bean definition for this variable name? If so, invoke it in the usual way, and return the bean that was created. Is there configuration information for this variable name in the Spring WebApplicationContext for this application? If so, use it to create and configure an instance, and return that instance to the caller. If there is no managed bean or Spring definition for this variable name, return null instead. BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.

As a result of this algorithm, you can transparently use either JavaServer Faces or Spring facilities to create beans on demand. 20. What is Significance of JSF- Spring integration ? Spring - JSF integration is useful when an event handler wishes to explicitly invoke the bean factory to create beans on demand, such as a bean that encapsulates the business logic to be performed when a submit button is pressed.

21. How to integrate your Struts application with Spring? To integrate your Struts application with Spring, we have two options:

Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file. Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a getWebApplicationContext() method.

22. What are ORMs Spring supports ? Spring supports the following ORMs :

Hibernate iBatis JPA (Java Persistence API) TopLink JDO (Java Data Objects) OJB

23. What are the ways to access Hibernate using Spring ? There are two approaches to Springs Hibernate integration:

Inversion of Control with a HibernateTemplate and Callback Extending HibernateDaoSupport and Applying an AOP Interceptor

24. How to integrate Spring and Hibernate using HibernateDaoSupport? Spring and Hibernate can integrate using Springs SessionFactory called LocalSessionFactory. The integration process is of 3 steps.

Configure the Hibernate SessionFactory Extend your DAO Implementation from HibernateDaoSupport Wire in Transaction Support with AOP

25. What are Bean scopes in Spring Framework ? The Spring Framework supports exactly five scopes (of which three are available only if you are using a web-aware ApplicationContext). The scopes supported are listed below: Description Scopes a single bean definition to a single object instance per Spring IoC container. Scopes a single bean definition to any number of object instances. Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext. Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext. Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

Scope singleton prototype request session global session

26. What is AOP? Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns, or behavior that cuts across the typical divisions of responsibility,

such as logging and transaction management. The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. 27. How the AOP used in Spring? AOP is used in the Spring Framework:To provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management, which builds on the Spring Framework's transaction abstraction.To allow users to implement custom aspects, complementing their use of OOP with AOP. 28. What do you mean by Aspect ? A modularization of a concern that cuts across multiple objects. Transaction management is a good example of a crosscutting concern in J2EE applications. In Spring AOP, aspects are implemented using regular classes (the schema-based approach) or regular classes annotated with the @Aspect annotation (@AspectJ style). 29. What do you mean by JointPoint? A point during the execution of a program, such as the execution of a method or the handling of an exception. In Spring AOP, a join point always represents a method execution. 30. What do you mean by Advice? Action taken by an aspect at a particular join point. Different types of advice include "around," "before" and "after" advice. Many AOP frameworks, including Spring, model an advice as an interceptor, maintaining a chain of interceptors "around" the join point. 31. What are the types of Advice? Types of advice:

Before advice: Advice that executes before a join point, but which does not have the ability to prevent execution flow proceeding to the join point (unless it throws an exception). After returning advice: Advice to be executed after a join point completes normally: for example, if a method returns without throwing an exception. After throwing advice: Advice to be executed if a method exits by throwing an exception. After (finally) advice: Advice to be executed regardless of the means by which a join point exits (normal or exceptional return). Around advice: Advice that surrounds a join point such as a method invocation. This is the most powerful kind of advice. Around advice can perform custom behavior before and after the method invocation. It is also responsible for choosing whether to proceed to the join point or to shortcut the advised method execution by returning its own return value or throwing an exception

32. What are the types of the transaction management Spring supports ? Spring Framework supports:

Programmatic transaction management. Declarative transaction management.

33. What are the benefits of the Spring Framework transaction management ? The Spring Framework provides a consistent abstraction for transaction management that delivers the following benefits:

Provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO. Supports declarative transaction management. Provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.

Integrates very well with Spring's various data access abstractions.

34. Why most users of the Spring Framework choose declarative transaction management ? Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container. 35. Explain the similarities and differences between EJB CMT and the Spring Framework's declarative transaction management ? The basic approach is similar: it is possible to specify transaction behavior (or lack of it) down to individual method level. It is possible to make a setRollbackOnly() call within a transaction context if necessary. The differences are:

Unlike EJB CMT, which is tied to JTA, the Spring Framework's declarative transaction management works in any environment. It can work with JDBC, JDO, Hibernate or other transactions under the covers, with configuration changes only. The Spring Framework enables declarative transaction management to be applied to any class, not merely special classes such as EJBs. The Spring Framework offers declarative rollback rules: this is a feature with no EJB equivalent. Both programmatic and declarative support for rollback rules is provided. The Spring Framework gives you an opportunity to customize transactional behavior, using AOP. With EJB CMT, you have no way to influence the container's transaction management other than setRollbackOnly(). The Spring Framework does not support propagation of transaction contexts across remote calls, as do high-end applicationservers.

36. What are object/relational mapping integration module? Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provide support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Springs transaction management supports each of these ORM frameworks as well as JDBC. 37. When to use programmatic and declarative transaction management ? Programmatic transaction management is usually a good idea only if you have a small number of transactional operations. On the other hand, if your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure. 38. Explain about the Spring DAO support ? The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one to switch between the persistence technologies fairly easily and it also allows one to code without worrying about catching exceptions that are specific to each technology. 39. What are the exceptions thrown by the Spring DAO classes ? Spring DAO classes throw exceptions which are subclasses of DataAccessException(org.springframework.dao.DataAccessException).Spring provides a convenient translation from technology-specific exceptions like SQLException to its own exception class hierarchy with the DataAccessException as the root exception. These exceptions wrap the original exception.

40. What is SQLExceptionTranslator ? SQLExceptionTranslator, is an interface to be implemented by classes that can translate between SQLExceptions and Spring's own data-access-strategy-agnostic org.springframework.dao.DataAccessException. 41. What is Spring's JdbcTemplate ? Spring's JdbcTemplate is central class to interact with a database through JDBC. JdbcTemplate provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling. JdbcTemplate template = new JdbcTemplate(myDataSource); 42. What is PreparedStatementCreator ? PreparedStatementCreator:

Is one of the most common used interfaces for writing data to database. Has one method createPreparedStatement(Connection) Responsible for creating a PreparedStatement. Does not need to handle SQLExceptions.

43. What is SQLProvider ? SQLProvider:

Has one method getSql() Typically implemented by PreparedStatementCreator implementers. Useful for debugging.

44. What is RowCallbackHandler ? The RowCallbackHandler interface extracts values from each row of a ResultSet.

Has one method processRow(ResultSet) Called for each row in ResultSet. Typically stateful.

45. What are the differences between EJB and Spring ? Spring and EJB feature comparison. EJB Spring

Feature Transaction management

Must use a JTA transaction manager. Supports transactions that span remote method calls.

Supports multiple transaction environments through its PlatformTransactionManager interface, including JTA, Hibernate, JDO, and JDBC. Does not natively support distributed transactionsit must be used with a JTA transaction manager. Can define transactions declaratively through the Springconfiguration file or through class metadata. Can define which methods to apply transaction behavior explicitly or by using

Declarative transaction support

Can define transactions declaratively through the deployment descriptor. Can define transaction behavior per method or per class by using the

wildcard character *.

regular expressions.

Cannot declaratively Can declaratively define rollback behavior define rollback behavior per method and per exception type. this must be done programmatically. Persistence Supports programmatic beanProvides a framework for integrating with several managed persistence and persistence technologies, including JDBC, declarative container managed Hibernate, JDO, and iBATIS. persistence. Declarativesecurity Supports declarative No security implementation out-of-the security through users box. and roles. The management and Acegi, an open source security framework implementation of users built on top of Spring, provides and roles is container declarative security through the specific. Springconfiguration file or class Declarative security is configured in the deployment descriptor. Provides container-managed remote method calls.

metadata.

Distributed computing

Provides proxying for remote calls via RMI, JAXRPC, and web services.

46 . Do I need any other SOAP framework to run Spring Web Services? You don't need any other SOAP framework to use Spring Web services, though it can use some of the features of Axis 1 and 2. 47 . I get NAMESPACE_ERR exceptions when using Spring-WS. What can I do about it? If you get the following Exception: NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces. Most often, this exception is related to an older version of Xalan being used. Make sure to upgrade to 2.7.0. 48 .Does Spring-WS run under Java 1.3? Spring Web Services requires Java 1.4 or higher. 49. Does Spring-WS work under Java 1.4? Spring Web Services works under Java 1.4, but it requires some effort to make it work. Java 1.4 is bundled with the older XML parser Crimson, which does not handle namespaces correctly. Additionally, it is bundled with an older version of Xalan, which also has problems. Unfortunately, placing newer versions of these on the class path does not override them. . The only solution that works is to add newer versions of Xerces and Xalan in the lib/endorsed directory of your JDK, as explained in those FAQs (i.e.$JAVA_HOME/lib/endorsed). The following libraries are known to work with Java 1.4.2: Version 2.8.1 2.7.0 1.3.04

Library Xerces Xalan XML-APIs

SAAJ

1.2

If you want to use WS-Security, note that the XwsSecurityInterceptor requires Java 5, because an underlying library (XWSS) requires it. Instead, you can use the Wss4jSecurityInterceptor. 50 .Does Spring-WS work under Java 1.6? Java 1.6 ships with SAAJ 1.3, JAXB 2.0, and JAXP 1.4 (a custom version of Xerces and Xalan). Overriding these libraries by puttingdifferent version on the classpath will result in various classloading issues, or exceptions in org.apache.xml.serializer.ToXMLSAXHandler. The only option for using more recent versions is to put the newer version in the endorsed directory (see above). 51 . Why do the Spring-WS unit tests fail under Mac OS X? For some reason, Apple decided to include a Java 1.4 compatibility jar with their JDK 1.5. This jar includes the XML parsers which were included in Java 1.4. No other JDK distribution does this, so it is unclear what the purpose of this compatibility jar is. The jar can be found at /System/Library/Frameworks/JavaVM.framework/Versions/1.5.0/Classes/.compatibility/14compatibilit y.jar. You can safely remove or rename it, and the tests will run again. 52 . What is SAAJ? SAAJ is the SOAP with Attachments API for Java. Like most Java EE libraries, it consists of a set of interfaces (saaj-api.jar), and implementations (saaj-impl.jar). When running in a Application Server, the implementation is typically provided by the application server. Previously, SAAJ has been part of JAXM, but it has been released as a seperate API as part of the , and also as part ofJ2EE 1.4. SAAJ is generally known as the packagejavax.xml.soap. Spring-WS uses this standard SAAJ library to create representations of SOAP messages. Alternatively, it can use 53 . What version of SAAJ does my application server support? SAAJ Version 1.1 1.1/1.2* 1.3** 1.2 1.3 1.3***

Application Server BEA WebLogic 8 BEA WebLogic 9 BEA WebLogic 10 IBM WebSphere 6 SUN Glassfish 1 JBoss 4.2

54 .I get a NoSuchMethodError when using SAAJ. What can I do about it? If you get the following stack trace: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.ws.soap.saaj.SaajSoapMessageFactory' defined in ServletContext resource [/WEB-INF/springws-servlet.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: javax.xml.soap.MessageFactory.newInstance(Ljava/lang/String;)Ljavax/xml/soap/MessageFactory; Caused by: java.lang.NoSuchMethodError: javax.xml.soap.MessageFactory.newInstance(Ljava/lang/String;)Ljavax/xml/soap/MessageFactory; Like most J2EE libraries, SAAJ consists of two parts: the API that consists of interfaces (saaj-api.jar) and the implementation (saaj-impl.jar). The stack trace is due to the fact that you are using a new version of the API (SAAJ 1.3), while your application server provides an earlier version of the implementation (SAAJ 1.2 or even 1.1). Spring-WS supports all three versions of SAAJ (1.1 through 1.3), but things break when it sees the 1.3 API, while there is no 1.3 implementation.

The solution therefore is quite simple: to remove the newer 1.3 version of the API, from the class path, and replace it with the version supported by your application server. 55 . I get an UnsupportedOperationException "This class does not support SAAJ 1.1" when I use SAAJ under WebLogic 9. What can I do about it? WebLogic 9 has a known bug in the SAAJ 1.2 implementation: it implement all the 1.2 interfaces, but throws UnsupportedOperationExceptions when you call them. Confusingly, the exception message is This class does not support SAAJ 1.1, even though it supports SAAJ 1.1 just fine; it just doesn't support SAAJ 1.2. See alsot Spring-WS has a workaround for this, we basically use SAAJ 1.1 only when dealing with WebLogic 9. Unfortunately, other frameworks which depend on SAAJ, such as XWSS, do not have this workaround. These frameworks happily call SAAJ 1.2 methods, which throw this exception. The solution is to not use BEA's version of SAAJ, but to use another implementation, like the one from Axis 1, or SUN. In you application context, use the following: <bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"> <property name="messageFactory"> <bean class="com.sun.xml.messaging.saaj.soap.MessageFactoryImpl"/> </property> </bean>

56 . I get an UnsupportedOperationException "This class does not support SAAJ 1.1" when I use SAAJ under WebLogic 10. What can I do about it? Weblogic 10 ships with two SAAJ implementations. By default the buggy 9.x implementation is used (which lives in the package weblogic.webservice.core.soap), but there is a new implementation, which supports SAAJ 1.3 (which lives in the package weblogic.xml.saaj). By looking at the DEBUG logging when Spring Web Services starts up, you can see which SAAJ implementation is used. To use this new version, you have to create a message factory bean like so: <bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"> <property name="messageFactory"> <bean class="weblogic.xml.saaj.MessageFactoryImpl"/> </property> </bean>

57 . I get an IndexOutOfBoundsException when I use SAAJ under JBoss. What can I do about it? The SAAJ implementation provided by JBoss has some issues. The solution is therefore not to use the JBoss implementation, but to use another implementation. For instance, you can use SUN's reference implementation like so: <bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"> <property name="messageFactory"> <bean class="com.sun.xml.messaging.saaj.soap.ver1_1.SOAPMessageFactory1_1Impl"/> </property> </bean>

58 . Does Spring-WS run on IBM WebSphere? WebSphere bundles some libraries which are out-of-date, and need to be upgraded with more recent versions. Specifically, this includes XML-apis, Xerces, Xalan, and WSDL4J. There are a couple of ways to upgrade these libraries, all using parent-last or application-first classloading.

Package the libraries as part of the WAR (in WEB-INF/lib), and run the web application with the parent-last (application-first) classloading. Package the libraries as part of the EAR, add class-path entries to the manifest of the web application, and run the entire application with the parent-last classloading.

Create a new classloader in the WebSphere console, and associate the libraries with. Set this classloader to parent-last.

The last approach has the advantage of restricting the parent-last classloading to the conflicting libraries only, and not to the entire application. 59. Why does Spring-WS only support contract-first? Note that Spring-WS only requires you to write the XSD; the WSDL can be generated from that. 60 . How do I retrieve the WSDL from a Service? The &WSDL query parameter does not work. The &WSDL query parameter is a way to get a WSDL of a class. In SWS, a service is generally not implemented as a single class, but as a collection of endpoints. There are two ways to expose a WSDL:

Simply add the WSDL to the root of the WAR, and the file is served normally. This has the disadvantage that the "location" attribute in the WSDL is static, i.e. it does not necessarily reflect the host name of the server. You can transform locations by using a WsdlDefinitionHandlerAdapter. Use theMessageDispatcherServlet, which is done is the samples. Every WsdlDefinition listed in the *-servlet.xml will be exposed under the bean name. So if you define a WsdlDefinition namedecho, it will be exposed as echo.wsdl (i.e.http://localhost:8080/echo/echo.wsdl).

61 What is web module? Spring comes with a full-featured MVC framework for building web applications. Although Spring can easily be integrated with other MVC frameworks, such as Struts, Springs MVC framework uses IoC to provide for a clean separation of controller logic frombusiness objects. It also allows you to declaratively bind request parameters to your business objects. It also can take advantage of any of Springs other services, such as I18N messaging and validation. 62 What is a BeanFactory? A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the applicationsconfiguration and dependencies from the actual application code. 63 What is AOP Alliance? AOP Alliance is an open-source project whose goal is to promote adoption of AOP and interoperability among different AOP implementations by defining a common set of interfaces and components. 64 What is Spring configuration file? Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other. 65 .What does a simple spring application contain? These applications are like any Java application. They are made up of several classes, each performing a specific purpose within the application. But these classes are configured and introduced to each other through an XML file. This XML file describes how to configure the classes, known as theSpring configuration file.

66 What is XMLBeanFactory? BeanFactory has many implementations in Spring. But one of the most useful one isorg.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. To create an XmlBeanFactory, pass a java.io.InputStream to the constructor. The InputStream will provide the XML to the factory. For example, the following code snippet uses a java.io.FileInputStream to provide a bean definition XML file toXmlBeanFactory. BeanFactory factory = new XmlBeanFactory(new FileInputStream("beans.xml")); To retrieve the bean from a BeanFactory, call the getBean() method by passing the name of the bean you want to retrieve. MyBean myBean = (MyBean) factory.getBean("myBean")

67 . What are important ApplicationContext implementations in spring framework?

ClassPathXmlApplicationContext This context loads a context definition from an XML file located in the class path, treating context definition files as class path resources. FileSystemXmlApplicationContext This context loads a context definition from an XML file in the filesystem. XmlWebApplicationContext This context loads the context definitions from an XML file contained within a web application.

68 . Explain Bean lifecycle in Spring framework?

The spring container finds the beans definition from the XML file and instantiates the bean. Using the dependency injection, spring populates all of the properties as specified in the bean definition. If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the beans ID. If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself. If there are any BeanPostProcessors associated with the bean, their postProcessBeforeInitialization() methods will be called. If an init-method is specified for the bean, it will be called. Finally, if there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization()methods will be called.

69 What is bean wiring? Combining together beans within the Spring container is known as bean wiring or wiring. When wiring beans, you should tell the container what beans are needed and how the container should use dependency injection to tie them together. 70 How do add a bean in spring application? <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"> <beans> <bean id="foo" class="com.act.Foo"/> <bean id="bar" class="com.act.Bar"/> </beans>

71. What are singleton beans and how can you create prototype beans? Beans defined in spring framework are singleton beans. There is an attribute in bean tag named singleton if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans. <beans> <bean id="bar" class="com.act.Foo" singleton=false/> </beans> 72 . What are the important beans lifecycle methods? There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container. The second method is the teardown method which is called when the bean is unloaded from the container. 73 . How can you override beans default lifecycle methods? The bean tag has two more important attributes with which you can define your own custom initialization and destroy methods. Here I have shown a small demonstration. Two new methods fooSetup and fooTeardown are to be added to your Foo class. <beans> <bean id="bar" class="com.act.Foo" init-method=fooSetup destroy=fooTeardown/> </beans> 74 . What are Inner Beans? When wiring beans, if a bean element is embedded to a property tag directly, then that bean is said to the Inner Bean. The drawback of this bean is that it cannot be reused anywhere else. 75. What are the different types of bean injections? There are two types of bean injections.

By setter By constructor

76. What is Auto wiring? You can wire the beans as you wish. But spring framework also does this work for you. It can auto wire the related beans together. All you have to do is just set the autowire attribute of bean tag to an autowire type. <beans> <bean id="bar" class="com.act.Foo" Autowire=autowire type/> </beans> 77 . What are different types of Autowire types? There are four different types by which autowiring can be done.

o o o o

byName byType constructor autodetect

78. What are the different types of events related to Listeners? There are a lot of events related to ApplicationContext of spring framework. All the events are subclasses of org.springframework.context.Application-Event. They are

ContextClosedEvent This is fired when the context is closed. ContextRefreshedEvent This is fired when the context is initialized or refreshed. RequestHandledEvent This is fired when the web context handles any request.

79. What is an Aspect? An aspect is the cross-cutting functionality that you are implementing. It is the aspect of your application you are modularizing. An example of an aspect is logging. Logging is something that is required throughout an application. However, because applications tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense. However, you can create a logging aspect and apply it throughout your application using AOP. 80 . What is a Jointpoint? A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified. These are the points where your aspects code can be inserted into the normal flow of your application to add new behavior. 81 What is an Advice? Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice isinserted into an application at joinpoints. 82 What is a Pointcut? A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint that is supported by the AOP framework. These Pointcuts allow you to specify where theadvice can be applied. 83 What is an Introduction in AOP? An introduction allows the user to add new methods or attributes to an existing class. This can then be introduced to an existing class without having to change the structure of the class, but give them the new behavior and state. 84 What is a Target? A target is the class that is being advised. The class can be a third party class or your own class to which you want to add your own custom behavior. By using the concepts of AOP, the target class is free to center on its major concern, unaware to any advice that is being applied. 85 . What is a Proxy?

A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the proxy object are the same. 86 .What is meant by Weaving? The process of applying aspects to a target object to create a new proxy object is called as Weaving. The aspects are woven intothe target object at the specified joinpoints. 87 What are the different points where weaving can be applied?

Compile Time Classload Time Runtime

88 . What are the different advice types in spring?

Around : Intercepts the calls to the target method Before : This is called before the target method is invoked After : This is called after the target method is returned Throws : This is called when the target method throws and exception Around : org.aopalliance.intercept.MethodInterceptor Before : org.springframework.aop.BeforeAdvice After : org.springframework.aop.AfterReturningAdvice Throws : org.springframework.aop.ThrowsAdvice

89 What are the different types of AutoProxying?

BeanNameAutoProxyCreator DefaultAdvisorAutoProxyCreator Metadata autoproxying 90 What kind of exceptions those spring DAO classes throw? The springs DAO class does not throw any technology related exceptions such as SQLException. They throw exceptions which are subclasses of DataAccessException. 91 What is DataAccessException? DataAccessException is a RuntimeException. This is an Unchecked Exception. The user is not forced to handle these kinds of exceptions. 92 How can you configure a bean to get DataSource from JNDI? <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>java:comp/env/jdbc/myDatasource</value> </property> </bean> 93 How can you create a DataSource connection pool? <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driver"> <value>${db.driver}</value> </property> <property name="url"> <value>${db.url}</value> </property> <property name="username"> <value>${db.username}</value> </property> <property name="password">

<value>${db.password}</value> </property> </bean> 94 How JDBC can be used more efficiently in spring framework? JDBC can be used more efficiently with the help of a template class provided by spring framework called as JdbcTemplate. 95 How JdbcTemplate can be used? With use of Spring JDBC framework the burden of resource management and error handling is reduced a lot. So it leaves developers to write the statements and queries to get the data to and from the database. JdbcTemplate template = new JdbcTemplate(myDataSource); A simple DAO class looks like this. public class StudentDaoJdbc implements StudentDao { private JdbcTemplate jdbcTemplate; public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } more.. } The configuration is shown below. <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="dataSource"/> </property> </bean> <bean id="studentDao" class="StudentDaoJdbc"> <property name="jdbcTemplate"> <ref bean="jdbcTemplate"/> </property> </bean> <bean id="courseDao" class="CourseDaoJdbc"> <property name="jdbcTemplate"> <ref bean="jdbcTemplate"/> </property> </bean> 96 How do you write data to backend in spring using JdbcTemplate? The JdbcTemplate uses several of these callbacks when writing data to the database. The usefulness you will find in each of these interfaces will vary. There are two simple interfaces. One is PreparedStatementCreator and the other interface is BatchPreparedStatementSetter. 97 Explain about PreparedStatementCreator? PreparedStatementCreator is one of the most common used interfaces for writing data to database. The interface has one method createPreparedStatement(). PreparedStatement createPreparedStatement(Connection conn) throws SQLException; When this interface is implemented, we should create and return a PreparedStatement from the Connection argument, and the exception handling is automatically taken care off. When this interface is implemented, another interface SqlProvider is also implemented which has a method called getSql() which is used to provide sql strings to JdbcTemplate. 98 Explain about BatchPreparedStatementSetter? If the user what to update more than one row at a shot then he can go for BatchPreparedStatementSetter. This interface provides two methods setValues(PreparedStatement ps, int i) throws SQLException; int getBatchSize(); The getBatchSize() tells the JdbcTemplate class how many statements to create. And this also determines how many times setValues() will be called. 99. Explain about RowCallbackHandler and why it is used?

In order to navigate through the records we generally go for ResultSet. But spring provides an interface that handles this entire burden and leaves the user to decide what to do with each row. The interface provided by spring is RowCallbackHandler. There is a method processRow() which needs to be implemented so that it is applicable for each and everyrow. void processRow(java.sql.ResultSet rs); 100 What is JDBC abstraction and DAO module? Using this module we can keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. A new layer of meaningful exceptions on top of the error messages given by several database servers is bought in this module. In addition, this module uses Springs AOP module to provide transaction management services for objects in a Spring application.

Inner class

1. What is inner class and when we should go for inner classes?

Some times we can declare a class inside another class such type of classes are called inner classes Example Class Car{ //more code here Class Engine{ //more code here } } Without existing Car object there is no chance of existing Engine object, hence Engine class has declared inside Car class.

2.How many types of inner classes are present? There are four types of inner classes are present

o o o o

Normal or regular inner class Method local inner class Anonymous inner class Static nested class

3.What is method local inner class?

Sometimes we can declare a class inside a method such type of classes are called method local

inner classes

The main purpose of method local inner classes is to define method specific functionality The scope of method local inner classes is the scope of the method where it is declared.

This is the mostly rarely used type of inner classes.

Example class Test{ public void m1(){ class Inner { public void sum(int I,int j){ System.out.println(i+J); }//sum }//inner Inner i=new Inner(); i.sum(10,20); //more code here I.sum(100,303); //more code here i.sum(102,84); }//m1() Public static void main(){ New Test().m1(); }

4.What is anonymous inner class?

Some times we can declare a inner class without name such type of inner classes are called anonymous inner classes

Anonymous inner classes can be divided into 3 Anonymous inner class Anonymous inner class Anonymous inner class

categories that extends a class that implements an interface that defines inside a method argument

ANONYMOUS INNER CLASS THAT EXTENDS A CLASS Example Class popcorn{ Public void taste(){ System.out.println(it is salty); } //more code here } Class Test{ Public static void main(String[] args) { Popcorn p=new Popcorn() { // here we are creating child class for popcorn Public void taste(){ System.out.println(it is sweet); } };//here semicolon indicates we r creating child class object with parent // class reference here child class dosent contain name

p.taste()// it is sweet Popcorn p=new Popcorn(); p1.taste() //it is salty } }

ANONYMOUS INNER CLASS THAT IMPLEMENTS AN INTERFACE example class Test{ Public static void main(String[] args){ Runnable r=new Runnable(){ Public void run(){ for(int i=0;i<10;i++){ System.out.printin(child thread); } } }; Thread t=new Thread(r); t.start(); for(int i=0;i<10;i++){ System.out.printin(main thread); } } } Dont become fool that here we are creating object of interface Runnable.Here we are actually creating an object of class that is implemented Runnable interface.

ANONYMOUS INNER CLASS THAT DEFINES INSIDE A METHOD ARGUMENT Example Class Test{ Public static void main(String[] args){ New Thread(new Runnable() { Public void run(){ for(int i=0;i<10;i++){ System.out.printin(child thread); } } }).start(); for(int i=0;i<10;i++){ System.out.printin(main thread); } }//main }//Test

5. With out having name of class how we can create an object and utilize the functionality of Anonymous inner class? By using parent class names 6. What is difference between anonymous inner class and general class?

A general class can extend only one class at a time of course inner class can extend only one class at a Time. A general class can implement any no of interfaces at a time but a anonymous inner class can implement only one interface at a time A general class can extend a class and can implement an interface simultaneously but an anonymous inner class can extend a class or can implement an interface one at a time but not

both simualtaneously

7. What is difference between normal inner class and static nested class?

Normal Inner Class 1. Inner class object always associated with outer class object ie without existing outer class object there is no chance of existing inner class object. Inside normal inner class we cant declare static members. We cant place main method in normal inner class and hence innocation of inner class directly from command prompt is not possible. From normal inner class we can access both static and non static members of outer class.

Static Nested Class 1. Nested class object never associated with

outer class object , ie without existing outer class object inner class object can exist 3. Inside static nested class can declare static members

2.

4.

2.

We can place main method in static nested class and hence innocation of nested class directly from command prompt is possible From static nested class we can access only static member of outer class

5.

3.

8.What is static nested calss?why the term nested instead of inner in static nested class? Some times we can declare inner class with static modifier such type of inner class are called static nested classes.the term nested instead of static because without existing outer class object inner class object can exist. Example Class outer{ Static class Nested{ Public static void main(String[] args){ System.out.println(nested class main()); } } Public static void main(String[] args){ System.out.println(outer class main()); }

Java Outer O/P Outer class main()

Java Outer$Nested O/P Nested class main()

9. Inside inner class is it possible to declare main()? No it is not possible to declare main () inside inner class but in static nested class it is possible

for

Example refer above code Weblogic Application Server FAQs

1.What is application server?

An application server is a software framework dedicated to the efficient execution of procedures (scripts, routines, programs ...) for supporting the construction of applications. The term was created in the context of web applications. In these, the application server acts as a set of components accessible to the software developer through an API defined by the platform itself. These components are usually performed in the same machine where the web server is running, and their main job is to support the construction of dynamic pages. Other uses of the term can refer to: o the services that a server makes available o the computer hardware on which the services run Java application servers Following the success of the Java platform, the term application server sometimes refers to a J2EE or Java EE 5 applicationserver. Some of the better-known Java Enterprise Edition application servers include: o Apache Tomcat (Apache Software Foundation) o Tcat Server (MuleSoft) o WebSphere Application Server and WebSphere Application Server Community Edition (IBM) o Sybase Enterprise Application Server (Sybase Inc) o WebLogic Server (Oracle) o JBoss (Red Hat) o Apache Geronimo (Apache Software Foundation) o Oracle OC4J (Oracle) o SAP Netweaver AS (ABAP/Java) (SAP) o WebObjects (Apple Inc.) The web modules include servlets and JavaServer Pages. Business logic resides in Enterprise

JavaBeans (EJB-3 and later). The Hibernate project offers an EJB-3 container implementation for the JBoss application server. Tomcat from Apache and JOnAS from ObjectWeb exemplify typical containers which can store these modules. A Java Server Page (JSP) (a servlet from Java) executes in a web container the Java equivalent of CGI scripts. JSPs provide a way to create HTML pages by embedding references to the server logic within the page. HTML coders and Java programmers can work side by side by referencing each other's code from within their own. JavaBeans are the independent class components of the Java architecture from Sun Microsystems.

2.What is web server?

The primary function of a web server is to deliver web pages (HTML documents) and associated content (e.g. images, style sheets, JavaScript's) to clients. A client, commonly a web browser or web crawler, makes a request for a specific resource using HTTP and, if all goes well, the server responds with the content of that resource. The resource is typically a real file on the server's secondary memory, but this is not necessarily the case and depends on how the web server is implemented. While the primary function is to serve content, a full implementation of HTTP also includes a way of receiving content from clients. This feature is used for submitting web forms, including uploading of files. Many generic web servers also support server-side scripting (e.g. Apache HTTP Server and PHP). This means that the behavior of the web server can be scripted in separate files, while the actual server software remains unchanged. Usually, this functionality is used to create HTML documents on-the-fly as opposed to return fixed documents. This is referred to as dynamic and static content respectively. History of web servers In 1989 Tim Berners-Lee proposed to his employer CERN (European Organization for Nuclear Research) a new project, which had the goal of easing the exchange of information between scientists by using a hypertext system. As a result of the implementation of this project, in 1990 Berners-Lee wrote two programs: o a browser called Worldwide Web; o the world's first web server, later known as CERN httpd, which ran on NeXTSTEP. Between 1991 and 1994 the simplicity and effectiveness of early technologies used to surf and exchange data through the World Wide Web helped to port them to many different operating systems and spread their use among lots of different social groups of people, first in scientific organizations, then in universities and finally in industry. In 1994 Tim Berners-Lee decided to constitute the World Wide Web Consortium to regulate the further development of the many technologies involved (HTTP, HTML, etc.) through a standardization process. Common features o Virtual hosting to serve many web sites using one IP address. o Large file support to be able to serve files whose size is greater than 2 GB on 32 bit OS. o Bandwidth throttling to limit the speed of responses in order to not saturate the network and to be able to serve more clients.

3.What is the difference between Web server and Application Server? Application Server

Webserver serves pages for viewing in web browser, application server provides exposes business logic for clientapplications through various protocols Webserver exclusively handles http requests. Application server serves business logic to application programs through any number of protocols. Webserver delegation model is fairly simple, when the request comes into the webserver, it simply passes the request to the program best able to handle it(Server side program). It may

not support transactions and database connection pooling. Application server is more capable of dynamic behavior than webserver. We can also configure application server to work as a webserver. Simply application server is a superset of webserver.

WEB Server

Web Server serves static HTML pages or gifs, jpegs, etc., and can also run code written in CGI, JSP etc. A Web server handles the HTTP protocol. Eg of some web server are IIS or apache. An Application Server is used to run business logic or dynamically generated presentation code. It can either be .NET based or J2EE based (BEA WebLogic Server, IBM WebSphere, JBoss). A J2EE application server runs servlets and JSPs (infact a part of the app server called web container is responsible for running servlets and JSPs) that are used to create HTML pages dynamically. In addition, J2EE application server can run EJBs - which are used to execute business logic. An Application server has a 'built-in' web server; in addition to that it supports other modules or features like e-businessintegration, independent management and security module, portlets etc.

4.What is the Domain in Weblogic serve?

o o o

Domain is a logically related group of Oracle WebLogic Server resources that are managed as a single unit Domain Provides one point of administration Can logically separate: Development, test, and production applications Organizational divisions

5.What are the Domain Restrictions?

o o o o

Each domain requires its own Administration Server. A cluster cannot span multiple domains. The Managed Servers in a domain must run the same version of Oracle WebLogic Server. The Administration Server in a domain must run the same or higher version as Managed Servers in the domain.

6.What is the server?

o o

A server is an instance of weblogic.Server executing in a Java Virtual Machine (JVM). A server: Runs on a designated Oracle WebLogic Server machine Has a dedicated amount of RAM Is multithreaded Two types of servers: Administration Server Managed Server

7.What is the Administration server? Administration server is central point of control for a domain. It stores the configuration information and logs for a domain. And it runs the Weblogic Administration console. 8.What is the Managed Server? Managed server is a server in a domain that is not the Administration server. It contacts the administration server for configuration information. It runs business application in a production

environment. It is independent of all other Managed servers in a domain (unless they are not in a cluster). You can have many managed servers in a domain. Individual managed servers are typically added for capacity and application isolation. 9.How Administration server and Managed servers will interact?

o o o o

The Administration Server stores the master copy of the domain configuration, including the configuration for all Managed Servers in the domain. Each Managed Server stores a local copy of the domain configuration file. When a Managed Server starts, it connects to the Administration Server to synchronize the configuration. When the configuration is changed, the Administration Server sends the changed configuration to the Managed Servers.

10.What is a Machine in Oracle Weblogic Server? A Machine in a Oracle Weblogic server is a computer that hosts the Oracle Weblogic Server instances. Runs a supported operating system platform and it is used by Node Manager to restart a failed Managed servers.

11.What is a Cluster in Oracle Weblogic server? A cluster is a Logical group of Weblogic servers. Oracle Weblogic server provides HIGH AVAILABILITY & LOAD BALANCING with help of cluster. 12.What is a Node Manager? A Node Manager is a utility or process running on a physical server that enables starting, stopping, suspending or restarting the Administration and Managed servers remotely. It is not associated with a Domain. [Node manager can start any server instances that are resides on the same physical server]. 13.How many ways we can install Oracle Weblogic Server? You can install Oracle Weblogic server in three different ways.

GUI mode (extract server103_linux32.bin/double click on server103_win32.exe ) Console mode (c:\>server103_linux32.bin mode=console log=c:\consoleinstal.log) Silent mode (c:\> server103_linux32.bin mode=silent silent_xml=path_to_silent.xml log=c:\silentinstal.log)

14.What is the default database for Weblogic server? Point base is the default database. This database comes along with Weblogic software bundle. 15.How many ways we can configure a domain? You can configure Oracle Weblogic server domains in two ways.

Graphical Mode (config.cmd [Scripts are in the <WL_HOME>/common/bin directory]) Console Mode (config.cmd mode=console)

16.How many ways you can start Administration server? You can start the Administration server using 5 ways.

o o o o o

weblogic.Server (only in development) Start menu (only Windows) DOMAIN_DIR/bin/startWebLogic.sh WebLogic Scripting Tool (WLST) and Node Manager WLST without Node Manager

17.How many ways you can configure managed servers? You can configure the Managed server using 3 was.

o o o

Domain Configuration Wizard Administration Console Command Line (WLST)

18.How many ways you can configure a machines? You can configure machines by using following:

o o o

Domain Configuration Wizard Administration Console Command Line (WLST)

19.How many ways you can start managed servers? Start Managed Servers by using:

o o o o

weblogic.Server DOMAIN_DIR/bin/startManagedWebLogic.sh Administration Console WLST and Node Manager

20.How do I provide user credentials for starting a server? When you create a domain, the Configuration Wizard prompts you to provide the username and password for an initial administrative user. If you create the domain in development mode, the wizard saves the username and encrypted password in a boot identity file. A WebLogic Server instance can refer to a boot identity file during its startup process. If a server instance does not find such a file, it prompts you to enter credentials. If you create a domain in production mode, or if you want to change user credentials in an existing boot identity file, you can create a new boot identity file. WebLogic Server does not support copying a boot identity file from one server root directory to another. For information on creating and using boot identity files, see Boot Identity Files in Administration Console Online Help. 21.Can I start a Managed Server if the Administration Server is unavailable? By default, if a Managed Server is unable to connect to the specified Administration Server during startup, it can retrieve its configuration by reading a configuration file and other files directly. You cannot change the server's configuration until the Administration Server is available. A Managed Server that starts in this way is running in Managed Server Independence mode. For more information, see Starting a Managed Server When the Administration Server Is Not Accessible in Configuring and Managing WebLogic Server. 22.What is the function of T3 in WebLogic Server? T3 provides a framework for WebLogic Server messages that support for enhancements. These enhancements include abbreviations and features, such as object replacement, that work in the context of WebLogic Server clusters and HTTP and other product tunneling. T3 predates Java Object Serialization and RMI, while closely tracking and leveraging these specifications. T3 is a superset of Java Object. Serialization or RMI; anything you can do in Java Object Serialization and RMI can be done over T3. T3 is mandated between WebLogic Servers and between programmatic clients and a WebLogic Server cluster. HTTP and IIOP are optional protocols that can be used to communicate between other processes and WebLogic Server. It depends on what you want to do. For example: when you want to communicate between a browser and WebLogic Server -- use HTTP, or an ORB and WebLogic Server-IIOP. 23.What is the easiest way to set the classpath? WebLogic Server installs the following script that you can use to set the classpath that a server requires:

WL_HOME\server\bin\setWLSEnv.cmd (on Windows) WL_HOME/server/bin/setWLSEnv.sh (on UNIX) Where WL_HOME is the directory in which you installed WebLogic Server. For more information, see "Setting the Classpath" in the WebLogic Server Command Reference. 24.How do I edit the config.xml file? The persistent configuration for a domain of WebLogic Servers and clusters is stored in an XML configuration file (config.xml). You can modify this file in the following ways:

Using the Administration Console. If you want to create scripts that automate domain management, use the weblogic.Admin utility. See "weblogic.Admin Command-Line Reference". If you want to create Java-based management applications, use the Java Management Extensions (JMX) ApplicationProgramming Interface (API). See the Programming WebLogic Management Services with JMX guide. If you want to edit the config.xml file directly (not recommended), see the BEA WebLogic Server Configuration Reference.

25.Is there a quick way to create and start a remote Managed Server? The recommended approach is to use the Domain Configuration Wizard, as described in "Setting Up and Starting Managed Servers on a Remote Machine" in Creating WebLogic Configurations Using the Configuration Wizard at http://download.oracle.com/docs/cd/E13196_01/platform/docs81/confgwiz/multi.html. For a streamlined approach, follow the instructions at "Starting Managed Servers From a WebLogic Server Script" in the Administration Console Online Help. 26.The Tree View pane of the WebLogic Console is not visible in my browser. How do I enable it?

Enable the Sun Java Plug-In from the control panel.

27.What is the importance of the Boot Identity file and how will you create it?

o o

o o

If you create boot identity file, it will not ask the user name and password at server startup time. Create a file called boot.properties in the <DOMAIN_HOME>\servers\<server_name>\security directory that contains two lines: username=username password=password The first time you start the server; the server reads the Boot Identity file and overwrites it with an encrypted version of the username and password. Thereafter, the server remembers the credentials for subsequent startup cycles.

28.What is the MSI mode in Weblogic? How can you enable and disable this option?

o o o o o

MSI is nothing but Managed Server Independence. By default, Managed Servers can function independently of the Administration Server. A Managed Server instance can start in MSI mode if the Administration Server is unavailable. Configure MSI mode from the Administration Console. To start a Managed Server in MSI mode, perform the following: Ensure that the Managed Servers root directory contains the config subdirectory.

If the config subdirectory does not exist, copy it from the Administration Servers root directory. Start the Managed Server at the command line or by using a script. Environment > Servers > Server_Name > Tuning > Advanced > Managed Server Independence Enabled check box.

29.If the Administration server not available while starting the Managed server which is already enabled MSI, what are the files it will look for?

o o

If the Administration Server is unavailable at boot time, Managed Servers search for: config.xml SerializedSystemIni.dat boot.properties(optional) Each Managed Server looks in its local config directory for config.xml, a replica of the domains config.xml. You cannot change the configuration of the Managed Server that is running in MSI mode until it restores communication with the Administration Server.

30.What if Administration server goes down? What is the behavior of the managed servers? What are all the things will available or not available?

The Administration Server: Can go down without affecting the operation of the Managed Servers Can be restarted when the Managed Servers are still running When an Administration Server goes down: The domain log entries are unavailable while it is down Managed Servers can start in independent mode The Administration Console and the management tools are unavailable

31.If an administration server running machine got crashed, how will you restart the server with same configuration on new machine?

Oracle WebLogic Server allows the creation of a backup of the server as follows: Install Oracle WebLogic Server on a backup machine. Copy the application files to a backup machine. Copy the configuration files to a backup machine. Restart the Administration Server on a new machine. The new Administration Server contacts the Managed Servers and informs them that it is running on a new IP address.

32.How can you run Multiple Weblogic server instances in a same physical machine?

You can run multiple instances of WLS using different configurations on the same physical machine at the same time by either: Assigning multiple IP addresses to a machine (multihoming) and defining each server to use a unique IP address Specifying the same IP address but using different listen ports A multihomed machine: Is a machine with multiple IP addresses Can run a different WLS instance that is bound to each IP address Can be used to configure a cluster on a single machine

33.How will you create Domain Template? Explain briefly?

o o o

o o

A domain template defines the full set of resources within a domain. Oracle provides sample templates for creating any platform domain. There are three ways to create domain templates: WLST offline command line tool pack command Domain Template Builder (config_builder.sh under WL_HOME/common/bin) Use the Domain Template Builder to create a domain template or an extension template. Using the Domain Template Builder: Define a domain and replicate it across multiple projects Distribute a domain packed with an application that has been developed to run in it

34.What are the default Weblogic provided Groups for security realm?

Administrators Deployers Operators Monitors AppTesters CrossDomainConnectors AdminChannelUsers

35.What are the default Weblogic provided Roles for security realm?

Admin Deployer Operator Monitor AppTester CrossDomainConnectors AdminChannelUsers Anonymous

36.What is the default Weblogic provided domain template file name and location? Wls.jar is the default domain template and the location is WL_HOME\common\templates\domains 37.What are the elements of the Administration console?

Change Center Domain Structure How do I Tool Bar Breadcrumb Navigation System Status

38.What are the Node elements of the Administration console or Domain Structure?

Environment (Servers, Clusters, Virtual Hosts, Migratable Targets, Machines ) Deployment Services (Messaging, JDBC, Persistent Store, JTA, File T3, jCOM ) Security Realms Interoperability

Diagnostics (Log Files, Diagnostics Modules, Diagnostics Images, Archives, Context)

39.What are the Tool Bar elements in Weblogic?

Welcome Message Connected to Home Log Out Preferences Record Help Search

40.How will you enable the Administration Console? By default, the Administration Console is enabled. If you disable it, you can re-enable it using the WebLogic Scripting Tool (WLST). Start the Administration Server, then invoke WLST and use the following commands: Using WLST to Re-enable the Console connect("username","password") edit() startEdit() cmo.setConsoleEnabled(true) save() activate() The following attribute(s) have been changed on MBeans which require server re-start.MBean Changed : com.bea:Name=mydomain,Type=Domain Attributes changed : ConsoleEnabled Activation complete ddisconnect() exit() 41.How will you Enable and disable the domain configuration lock? The Administration Console Change Center provides a way to lock a domain configuration so you can make changes to the configuration while preventing other accounts from making changes during your edit session. The domain configuration locking feature is always enabled in production domains. It can be enabled or disabled in development domains. It is disabled by default when you create a new development domain. To enable or disable the domain configuration locking feature in a development domain:

In the banner toolbar region at the top of the right pane of the Console, click Preferences. Click User Preferences. Select or clear Automatically Acquire Lock and Activate Changes to enable or disable the feature. Click Save. After you finish

When you enable domain configuration locking, you must use the Change Center to lock and edit for the domain configuration. 42.What are Dynamic and Non-Dynamic Changes in the Weblogic Console? what is the difference? Some changes you make in the Administration Console take place immediately when you activate them. Other changes require you to restart the server or module affected by the change. These latter

changes are called non-dynamic changes. Non-dynamic changes are indicated in the Administration Console with this warning icon,. Changes to dynamic configuration attributes become available once they are activated, without restarting the affected server or system restart. These changes are made available to the server and run-time hierarchies once they are activated. Changes to non-dynamic configuration attributes require that the affected servers or system resources be restarted before they become effective. If a change is made to a non-dynamic configuration setting, no changes to dynamic configuration settings will take effect until after restart. This is to assure that a batch of updates having a combination of dynamic and non-dynamic attribute edits will not be partially activated. Note that WebLogic Servers change management process applies to changes in domain and server configuration data, not tosecurity or application data. 43.What is the information is going to store in the security folder of the Domain directory contents? This directory holds the security-related files that are the same for every WebLogic Server instance in the domain:

SerializedSystemIni.dat

This directory also holds security-related files that are only needed by the domains Administration Server:

DefaultAuthorizerInit.ldift DefaultAuthenticatorInit.ldift DefaultRoleMapperInit.ldift

44.What is the use of SerializedSystemIni.dat file in Weblogic? It is important to protect passwords that are used to access resources in a WebLogic Server domain. In the past, usernames and passwords were stored in clear text in a WebLogic security realm. Now all the passwords in a WebLogic Server domain are hashed. The SerializedSystemIni.dat file contains the hashes for the passwords. It is associated with a specific WebLogic Server domain so it cannot be moved from domain to domain. If the SerializedSystemIni.dat file is destroyed or corrupted, you must reconfigure the WebLogic Server domain. Therefore, you should take the following precautions: Make a backup copy of the SerializedSystemIni.dat file and put it in a safe location. Set permissions on the SerializedSystemIni.dat file such that the system administrator of a WebLogic Server deployment has write and read privileges and no other users have any privileges. 45.Explain about Domain Directory Contents? By default, WebLogic Server creates domain directories under the BEA_HOME/user_projects/domains directory. This section describes the contents of the domain directory and its subfolders. In this section, domain-name, deployment-name, and server-name represent names that you define when you create a domain. Individual applications in a domain might create additional files and directories in the domain directory. If you have not yet created a domain, you can see an example of an existing domain directory by looking in WL_HOME/examples/domains/wl_server where WL_HOME is the directory in which you installed WebLogic Server. Domain-name The name of this directory is the name of the domain. autodeploy This directory provides a quick way to deploy applications in a development server. When the

WebLogic Server instance is running in development mode, it automatically deploys any applications or modules that you place in this directory. The files you place in this directory can be Java EE applications, such as:

An EAR file A WAR, EJB JAR, RAR, or CAR archived module An exploded archive directory for either an application or a module

Bin This directory contains scripts that are used in the process of starting and stopping the Administration Server and the Managed Servers in the domain. These scripts are generally provided as .sh files for UNIX and .cmd files for Windows. The bin directory can optionally contain other scripts of domain-wide interest, such as scripts to start and stop database management systems, full-text search engine processes, etc. Config This directory contains the current configuration and deployment state of the domain. The central domain configuration file, config.xml, resides in this directory. Config/configCache Contains data that is used to optimize performance when validating changes in the domains configuration documents. This data is internal to WebLogic Server and does not need to be backed up. Config/diagnostics This directory contains system modules for instrumentation in the WebLogic Diagnostic Framework. Config/jdbc This directory contains system modules for JDBC: global JDBC modules that can be configured directly from JMX (as opposed to JSR-88). Config/jms This directory contains system modules for JMS: global JMS modules that can be configured directly from JMX (as opposed to JSR-88). Config/lib This directory is not used in the current release of WebLogic Server. Config/nodemanager This directory holds configuration information for connection to the Node Manager. Config/security This directory contains system modules for the security framework. It contains one security provider configuration extension for each kind of security provider in the domains current realm. Config/startup This directory contains system modules that contain startup plans. Startup plans are used to generate shell scripts that can be used as part of server startup. ConfigArchive This directory contains a set of JAR files that save the domains configuration state. Just before pending changes to the configuration are activated, the domains existing configuration state,

consisting of the config.xml file and the other related configuration files, is saved in a versioned JAR file with a name like config.jar#1, config.jar#2, etc. The maximum number of versioned JAR files to be kept is specified by the archiveConfigurationCount attribute of DomainMBean. Once this maximum number is reached, the oldest conversion archive is deleted before a new one is created. Console-ext This directory contains extensions to the Administration Console, which enable you to add content to the WebLogic Server Administration Console, replace content, and change the logos, styles and colors without modifying the files that are installed with WebLogic Server. For example, you can add content that provides custom monitoring and management facilities for yourapplications. See Extending the Administration Console. Init-info This directory contains files used for WebLogic domain provisioning. You should not modify any files in this directory. Lib Any JAR files you put in this directory are added to the system classpath of each server instance in the domain when the servers Java virtual machine starts. Pending This directory contains domain configuration files representing configuration changes that have been requested, but not yet activated. Once the configuration changes have been activated, the configuration files are deleted from this directory. Security This directory holds those security-related files that are the same for every WebLogic Server instance in the domain:

SerializedSystemIni.dat

This directory also holds security-related files that are only needed by the domains Administration Server:

DefaultAuthorizerInit.ldift DefaultAuthenticatorInit.ldift DefaultRoleMapperInit.ldift

Servers This directory contains one subdirectory for each WebLogic Server instance in the domain. The subdirectories contain data that is specific to each server instance. Servers/server-name This directory is the server directory for the WebLogic Server instance with the same name as the directory. Servers/server-name/bin This directory holds executable or shell files that can be or must be different for each server. The server environment script (setServerEnv.sh or setServerEnv.cmd) is an example of a file that resides here because it can differ from one WebLogic Server instance to the next, for example, depending on whether the server instance has its own startup plan.

Servers/server-name/cache This directory holds directories and files that contain cached data. By cached here we mean that the data is a copy, possibly in a processed form (compiled, translated, or reformatted), of other data. Servers/server-name/cache/EJBCompilerCache This directory is a cache for compiled EJBs. Servers/server-name/data This directory holds files that maintain persistent per-server state used to run the WebLogic Server instance, other than security state, as opposed to temporary, cached or historical information. Files in this directory are important data that must be retained as the WebLogic Server instance is brought up, is brought down, crashes, restarts, or is upgraded to a new version. Servers/server-name/data/ldap This directory holds the embedded LDAP database. The run-time security state for the WebLogic Server instance is persisted in this directory. Servers/server-name/data/store This directory holds WebLogic persistent stores. For each persistent store, there is a subdirectory that holds the files that represent the persistent store. The name of the subdirectory is the name of the persistent store. By convention there is one store named default. Servers/server-name/logs This directory holds logs and diagnostic information. This information is historical in nature. It is not crucial to the operation of the server, and can be deleted (while the WebLogic Server instance is down, at least) without affecting proper operation. However, the information can be quite useful for debugging or auditing purposes and should not be deleted without good reason. Servers/server-name/logs/diagnostic_images This directory holds information created by the Server Image Capture component of the WebLogic Diagnostic Framework. Servers/server-name/logs/jmsServers This directory contains one subdirectory for each JMS server in the WebLogic Server instance. Each such subdirectory contains the logs for that JMS server. The name of the subdirectory is the name of the JMS server. Servers/server-name/logs/connector This directory is the default base directory for connector module (JCA ResourceAdapter) logs. Servers/server-name/security This directory holds security-related files that can be or must be different for each WebLogic Server instance. The file boot.properties is an example of a file that resides here because it can differ from one server to the next. This directory also maintains files related to SSL keys. Servers/server-name/tmp This directory holds temporary directories and files that are created while a server instance is running. For example, a JMS paging directory is automatically created here unless another location is specified. Files in this directory must be left alone while the server is running, but may be freely deleted when the server instance is shut down. Tmp This directory stores temporary files used in the change management process. You should not modify any files in this directory.

user_staged_config By default, configuration information is automatically copied from the Administration Server to each Managed Server. If instead you prefer to stage configuration changes manually, you can use this directory as an alternative to the config directory. 46.How many ways you can change the configuration changes? The change management features of WLS:

o o

Enable you to distribute configuration changes throughout a domain securely, consistently, and predictably Are the same, regardless of whether you are using: The WLS Administration Console The WebLogic Scripting Tool (WLST) The Java Management Extension (JMX) APIs

47.What is the user of WLST in Weblogic?

The WLS command-line tools are useful: For automating common administration activities As an alternative to the Administration Console When graphical tools are not supported WLST provides a command-line interface for: Creating new WLS domains Retrieving and updating WLS domain configurations Deploying applications Obtaining run-time server statistics

48.How many WLST modules are there? Explain?

Online mode: Connected to a running server Access to all WLS configuration and run-time attributes Create and activate change sessions similar to the WLS console Offline mode: Domain not running Access to only persisted domain configuration (config.xml) Create or update domains similar to using the Configuration Wizard

49.What is the Node Manager (NM)? Explain briefly? Node Manager (NM):

o o o o o

Starts and stops Managed Servers remotely: server, domain, and cluster Available as either a Java-based or (for UNIX or Linux) a script-based process Monitors and acts on server health Runs on the same computers as the Managed Servers Can be run automatically in the background, as a Windows service or a UNIX daemon

50.How many versions of Node Managers are available?

There are two versions of Node Manager: Java-based Node Manager Script-based Node Manager

o o

Java-based Node Manager runs within a Java Virtual Machine (JVM) process. Script-based Node Manager (used only for UNIX and Linux systems) does not have as much security, but provides the ability to remotely manage servers over a network using Secure Shell (SSH).

51.How Node Manager will work with the Weblogic Server? How will you configure Node Manager in WLS?

o o o

Node Manager must run on each computer that hosts the WLS instances that you want to control with Node Manager. You should configure each computer as a machine in Oracle WebLogic Server, and assign each server instance, which is to be controlled by Node Manager, to the machine that the server instance runs on. Node Manager should run as an operating system service, so that it automatically restarts upon system failure or reboot.

52.What is the Node Manager Default Behavior?

o o

After WebLogic Server is installed, Node Manager is ready-to-run if Node Manager and Administration Server are on the same machine. By default, the following behaviors are configured: The Administration Console can use Node Manager to start the Managed Servers. Node Manager monitors the Managed Servers that it started. The automatic restart of Managed Servers is enabled.

53.To start Node Manager at system start up time, what we have to do? We have to configure Node Manager as a Operating System Service.

o o

It is recommended that you run Node Manager (NM) as: A Windows service on Windows platforms and A daemon on UNIX platforms Running NM during system startup allows it to restart automatically when the system is rebooted. Node Manager can be configured to start at boot time, as either of these: A Windows service A UNIX daemon

54.How will you configure Node Manager as Windows Service?

o o o

Edit installNodeMgrSvc.cmd to specify Node Managers listen address and listen port. Run installNodeMgrSvc.cmd to reinstall Node Manager as a service, listening on the updated address and port. Delete the Node Manager Service using uninstallNodeMgrSvc.cmd.

55.Explain about Weblogic server Log Message Format? When a WebLogic Server instance writes a message to the server log file, the first line of each message begins with #### followed by the message attributes. Each attribute is contained between angle brackets. Here is an example of a message in the server log file: ####<Jan 05, 2010 10:46:51 AM EST> <Notice> <WebLogicServer> <MyComputer> <examplesServer> <main> <<WLS Kernel>> <> <null> <1080575211904> <BEA-000360>

<Server started in RUNNING mode> In this example, the message attributes are: Localeformatted Timestamp, Severity, Subsystem, Machine Name, Server Name, Thread ID, User ID, Transaction ID, Diagnostic Context ID, Raw Time Value, Message ID, and Message Text. If a message is not logged within the context of a transaction, the angle brackets for Transaction ID are present even though no Transaction ID is present. If the message includes a stack trace, the stack trace is included in the message text. WebLogic Server uses the host computers default character encoding for the messages it writes. 56.What is the Log Message Formant of Output to Standard Out and Standard Error? When a WebLogic Server instance writes a message to standard out, the output does not include the #### prefix and does not include the Server Name, Machine Name, Thread ID, User ID, Transaction ID, Diagnostic Context ID, and Raw Time Value fields. Here is an example of how the message from the previous section would be printed to standard out: <jan 01, 2010 10:51:10 AM EST> <Notice> <WebLogicServer> <BEA-000360> <Server started in RUNNING mode>In this example, the message attributes are: Locale-formatted Timestamp, Severity, Subsystem, Message ID, and Message Text. 57.How many log Message Severity levels are there in Weblogic? Explain? The severity attribute of a WebLogic Server log message indicates the potential impact of the event or condition that the message reports. Meaning Used for messages from the Diagnostic Action Library. Upon enabling diagnosticinstrumentation of server and application classes, TRACE messages follow the request path of a method. Used for reporting normal operations; a low-level informational message. An informational message with a higher level of importance. A suspicious operation or configuration has occurred but it might not affect normal operation. A user error has occurred. The system or application can handle the error with no interruption and limited degradation of service. A system or service error has occurred. The system can recover but there might be a momentary loss or permanent degradation of service. A particular service is in an unusable state while other parts of the system continue to function. Automatic recovery is not possible; the immediate attention of the administrator is needed to resolve the problem.

Severity TRACE

INFO NOTICE WARNING ERROR CRITICAL ALERT

EMERGENCY The server is in an unusable state. This severity indicates a severe system failure or panic. DEBUG A debug message was generated.

58.What is the default log Message Severity levels in Weblogic? WebLogic Server subsystems generate many messages of lower severity and fewer messages of higher severity. For example, under normal circumstances, they generate many INFO messages and no EMERGENCY messages. 59.What is the Log Message Severity Level sequence from lowest to highest impact? A log level object can specify any of the following values, from lowest to highest impact: TRACE, DEBUG, INFO, NOTICE, WARNING, ERROR, CRITICAL, ALERT, EMERGENCY 60.How will you specify the logging implementation in Weblogic? We will specify the logging implementation using "Java Logging API" or "Log4j" in Weblogic. About Log4j Log4j has three main components: loggers, appenders, and layouts. The following sections provide a brief introduction to Log4j.

Loggers Log4j defines a Logger class. An application can create multiple loggers, each with a unique name. In a typical usage of Log4j, anapplication creates a Logger instance for each application class that will emit log messages. Loggers exist in a namespace hierarchy and inherit behavior from their ancestors in the hierarchy. Appenders Log4j defines appenders (handlers) to represent destinations for logging output. Multiple appenders can be defined. For example, an application might define an appender that sends log messages to standard out, and another appender that writes log messages to a file. Individual loggers might be configured to write to zero or more appenders. One example usage would be to send all logging messages (all levels) to a log file, but only ERROR level messages to standard out. Layouts Log4j defines layouts to control the format of log messages. Each layout specifies a particular message format. A specific layout is associated with each appender. This lets you specify a different log message format for standard out than for file output, for example. Java Logging API WebLogic logging services provide the Commons LogFactory and Log interface implementations that direct requests to the underlying logging implementation being used by WebLogic logging services. To use Commons Logging, put the WebLogic-specific Commons classes, $BEA_HOME/modules/com.bea.core.weblogic.commons.logging_1.3.0.0.jar, together with the commons-logging.jar file in one of the following locations: APP-INF/LIB or WEB-INF/LIB directory DOMAIN_NAME/LIB directory Server CLASSPATH Note: WebLogic Server does not provide a Commons logging version in its distribution. 61.What is the user of Log Filters in Weblogic? Log filters:

o o o

Control the log messages that get published Are based on the values of message attributes Can be applied to different message destinations: Server log file Server memory buffer Server standard out Domain log file

62.What is the user of Network channels in Weblogic? Adds flexibility to the networking configuration:

o o o o o o

Multiple NICs for a single WLS server Specific NICs or multiple port numbers on a NIC for specific WLS servers Ability to use multiple IP addresses with each server Ability to use a single IP address with multiple ports Ability to configure the cluster multicast port number independently of the port numbers used by the cluster members Multiple SSL configurations on one server

Network channels:

o o o o o

Define the set of basic attributes of a network connection to WLS Can assign multiple channels to a single server (segment network traffic) Can prioritize internal (non-URL) connections Can separate incoming client traffic from internal server to server traffic in a domain A default channel gets generated when a server is created.

63.How will you configure a web application in Weblogic? Web applications are configured using the web.xml and weblogic.xml deployment descriptors, which:

Define the run-time environment Map URLs to servlets and JSPs Define application defaults such as welcome and error pages Specify J2EE security constraints Define work managers for applications Set the context root for the application

64.What information will be available in web.xml file? The web.xml file is a deployment descriptor that is used to configure the following:

Servlets and JSP registration Servlet initialization parameters JSP tag libraries MIME type mappings Welcome file list Error pages Security constraints and roles Resources EJB references

65.What information will be available in weblogic.xml file? Using weblogic.xml, you can configure the following:

The applications root context path Application logging Security role mappings Advanced session settings Session clustering References to shared libraries References to server resources (data sources, EJBs, and so on) Work managers and threading Virtual directories JSP compiler options

66.To configure a web service Applications in Weblogic, what are all the files required as a deployment descriptor? A Web service application:

Responds to HTTP client requests using the Simple Object Access Protocol (SOAP) Uses the same structure as a Java EE Web application Supports two additional deployment descriptors: webservices.xml

weblogic-webservices.xml

67. What is the Virtual directory Mappings? Which file you are going to provide these virtual directory mappings? Virtual directories:

Can be used to refer to physical directories Enable you to avoid the need to hard code paths to physical directories Allow multiple Web applications to share common physical directories for specific requests such as images Decrease duplication of files across applications Are configured in weblogic.xml

Example: <virtual-directory-mapping> <local-path>c:/usr/gifs</local-path> <url-pattern>/images/*</url-pattern> <url-pattern>*.jpg</url-pattern> </virtual-directory-mapping> <virtual-directory-mapping> <local-path>c:/usr/common_jsps.jar</local-path> <url-pattern>*.jsp</url-pattern> </virtual-directory-mapping> 68.What is the deployment descriptor file for ejb applications? What are all the information is going to provide in that file? Ejb application deployment descriptor file in Weblogic is weblogic-ejb-jar.xml. Using weblogic-ejb-jar.xml, you can configure the following:

Security role mappings Advanced security settings EJB clustering EJB pooling and caching Work managers and threading

69.What is an Enterprise Application?

An enterprise application is a grouping of several resources into one deployable unit that is packaged in an .ear file. These resources include: Web applications (.war) EJB applications (.jar) Java applications (.jar) Resource adapters (.rar)

70.What is the user of Enterprise Applications? Use enterprise applications to:

Avoid namespace clashes Declare application wide security roles Deploy an application as one unit Share application wide EJB resources Configure local JDBC data sources Configure local JMS resources

Configure local XML resources

71.What is the user of weblogic-application.xml deployment descriptor file? Using weblogic-application.xml, you can configure:

o o o

References to shared libraries Work managers and threading Default EJB and Web application parameter values

We can configure enterprise wide WLS-specific features with the weblogic-application.xml deployment descriptor:

o o o o o

XML parsers XML entity mappings JDBC data sources JMS connection factories and destinations Security realms

72.What is the user of Weblogic shared java EE Libraries? A Shared Java EE library:

o o o o

Is a reusable portion of a Web or enterprise application Is referenced by other deployed applications Avoids duplicating source files among Java EE projects Can contain deployment descriptors that are merged with the applications descriptors

73.Explain about deployment methods in Weblogic?

WLS supports three deployment methods: Auto-deployment Console deployment Command-line deployment You can deploy: Enterprise, Web, and EJB applications Web services J2EE libraries JDBC, JMS, and Diagnostic Framework modules Resource adapters Optional packages Client application archives Applications and EJBs can be deployed: In an archived file (.ear, .war, .jar) In an exploded (open) directory format

74.How many ways we can deploy an application to Weblogic servers? Several methods are available to deploy the Oracle WebLogic Server applications and shared libraries, including:

o o o o

Administration Console WebLogic Scripting Tool (WLST) weblogic.Deployer Java class wldeploy Ant task

Auto-deployment folder

75.Explain about auto deployment in Weblogic? If Production Mode is OFF: You can install an application simply by copying it (manually or using the console) to the autodeploy directory of the domain o The Administration Server monitors this directory for new, changed, or removed applications o This configures, targets, and deploys the application only to the Administration Server Location of Applications Directory: $BEA_HOME/user_projects/domains/domain_name/autodeploy

76.Explain about FastSwap and On-Demand Deployment in Weblogic? WebLogics FastSwap feature is: Enabled using the WebLogic deployment descriptors Available only if the domain is not running in production mode Applicable only to Web applications that are not archived o When enabled: WebLogic automatically reloads the modified Java class files within applications Developers can perform iterative development without an explicit redeployment On-demand deployment:

Excerpt from weblogic.xml: <fast-swap>true</fast-swap> 77.While deploying an application to Weblogic, what is the difference between Development and Production Mode?

o o

An Administration Server starts using either: The development mode, which turns auto-deployment on The production mode, which turns auto-deployment off The Administration Server starts in the mode selected at domain creation time. The mode is set for all Oracle WebLogic Servers in a given domain.

78.Explain about console deployment method? Deploying with the console allows full administrator control:

o o o o o

Installation from a location of your choice Manual configuration of application name Targeting of application to individual servers and/or clusters Configuring the application without targeting it Activating deployment when desired

79.Explain about command line deployment?

o o

The weblogic.Deployer utility allows you to perform deployment operations similar to those available in the console. weblogic.Deployer actions can also be scripted with the Ant task wldeploy.

weblogic.Deployer Syntax: % java weblogic.Deployer [options] [-deploy|-undeploy|-redeploy|-start|-stop|-listapps] [file(s)] Prepare and deploy a new application: java weblogic.Deployer -adminurl t3://adminserver:7001 -username myuser password mypass name HRServices -source /usr/HRServices.ear -targets serverA deploy Redeploy an application: java weblogic.Deployer -adminurl t3://adminserver:7001 -username myuser password mypass name HRServices redeploy Undeploy an application: java weblogic.Deployer -adminurl t3://adminserver:7001 -username myuser password mypass name HRServices undeploy List all applications: java weblogic.Deployer -adminurl t3://adminserver:7001 -username myuser password mypass -listapps 80.What is JNDI?

o o

The Java Naming and Directory Interface is an API for uniformly accessing the different naming and directory services. This is a major step forward because: Different services use vastly different naming schemes Java applications can now navigate seamlessly across databases, files, directories, objects, and networks

71.What is the user of weblogic-application.xml deployment descriptor file? Using weblogic-application.xml, you can configure:

o o o

References to shared libraries Work managers and threading Default EJB and Web application parameter values

We can configure enterprise wide WLS-specific features with the weblogic-application.xml deployment descriptor:

o o o o o

XML parsers XML entity mappings JDBC data sources JMS connection factories and destinations Security realms

72.What is the user of Weblogic shared java EE Libraries? A Shared Java EE library:

o o o o

Is a reusable portion of a Web or enterprise application Is referenced by other deployed applications Avoids duplicating source files among Java EE projects Can contain deployment descriptors that are merged with the applications descriptors

73.Explain about deployment methods in Weblogic?

WLS supports three deployment methods:

Auto-deployment Console deployment Command-line deployment You can deploy: Enterprise, Web, and EJB applications Web services J2EE libraries JDBC, JMS, and Diagnostic Framework modules Resource adapters Optional packages Client application archives Applications and EJBs can be deployed: In an archived file (.ear, .war, .jar) In an exploded (open) directory format

74.How many ways we can deploy an application to Weblogic servers? Several methods are available to deploy the Oracle WebLogic Server applications and shared libraries, including:

o o o o o

Administration Console WebLogic Scripting Tool (WLST) weblogic.Deployer Java class wldeploy Ant task Auto-deployment folder

75.Explain about auto deployment in Weblogic? If Production Mode is OFF: You can install an application simply by copying it (manually or using the console) to the autodeploy directory of the domain o The Administration Server monitors this directory for new, changed, or removed applications o This configures, targets, and deploys the application only to the Administration Server Location of Applications Directory: $BEA_HOME/user_projects/domains/domain_name/autodeploy

76.Explain about FastSwap and On-Demand Deployment in Weblogic? WebLogics FastSwap feature is: Enabled using the WebLogic deployment descriptors Available only if the domain is not running in production mode Applicable only to Web applications that are not archived o When enabled: WebLogic automatically reloads the modified Java class files within applications Developers can perform iterative development without an explicit redeployment On-demand deployment:

Excerpt from weblogic.xml: <fast-swap>true</fast-swap> 77.While deploying an application to Weblogic, what is the difference between Development and Production Mode?

o o

An Administration Server starts using either: The development mode, which turns auto-deployment on The production mode, which turns auto-deployment off The Administration Server starts in the mode selected at domain creation time. The mode is set for all Oracle WebLogic Servers in a given domain.

78.Explain about console deployment method? Deploying with the console allows full administrator control:

o o o o o

Installation from a location of your choice Manual configuration of application name Targeting of application to individual servers and/or clusters Configuring the application without targeting it Activating deployment when desired

79.Explain about command line deployment?

o o

The weblogic.Deployer utility allows you to perform deployment operations similar to those available in the console. weblogic.Deployer actions can also be scripted with the Ant task wldeploy.

weblogic.Deployer Syntax: % java weblogic.Deployer [options] [-deploy|-undeploy|-redeploy|-start|-stop|-listapps] [file(s)] Prepare and deploy a new application: java weblogic.Deployer -adminurl t3://adminserver:7001 -username myuser password mypass name HRServices -source /usr/HRServices.ear -targets serverA deploy Redeploy an application: java weblogic.Deployer -adminurl t3://adminserver:7001 -username myuser password mypass name HRServices redeploy Undeploy an application: java weblogic.Deployer -adminurl t3://adminserver:7001 -username myuser password mypass name HRServices undeploy List all applications: java weblogic.Deployer -adminurl t3://adminserver:7001 -username myuser password mypass -listapps 80.What is JNDI?

o o

The Java Naming and Directory Interface is an API for uniformly accessing the different naming and directory services. This is a major step forward because: Different services use vastly different naming schemes Java applications can now navigate seamlessly across databases, files, directories, objects, and networks

81.Why the JNDI required in Weblogic? In Oracle WebLogic Server, JNDI serves as a repository and lookup service for J2EE objects, including:

o o o

Enterprise JavaBeans (EJB) home stubs JDBC DataSources JMS connection factories, queues, and topics

Remote Method Invocation (RMI) stubs

82.What is the use of Naming Services? A naming service provides a method for mapping identifiers to entities or objects. Definition Binding Namespace The association of an atomic name and an object A set of unique names in a naming system Example www.example.com is bound to 209.10.217.38. www.example.com/ products

Term

83.Explain about Contexts and Sub-contexts in JNDI?

o o o

Subcontexts are referenced through the dot delimiters (.). The subcontexts must be created before objects are placed into them. Typically when objects are bound to a JNDI tree, subcontexts are automatically created based on the JNDI name.

If the following context exists: com.oracle.examples You cannot bind: com.oracle.examples.ejb.SomeObject Without first creating: com.oracle.examples.ejb 84.How can I set deployment order for applications? WebLogic Server 8.1 allows you to select the load order for applications. See the ApplicationMBean LoadOrder attribute inApplication. WebLogic Server deploys server-level resources (first JDBC and then JMS) before deploying applications.Applications are deployed in this order: connectors, then EJBs, then web Applications. If the application is an EAR, the individual components are loaded in the order in which they are declared in the application.xml deployment descriptor. 85.Can I refresh static components of a deployed application without having to redeploy the entire application? Yes. You can use weblogic.Deployer to specify a component and target a server, using the following syntax: java weblogic.Deployer -adminurl http://admin:7001 -name appname -targets server1,server2 -deploy jsps/*.jsp 86.When should I use the -nostage option? Set the staging mode to -nostage (using weblogic.Deployer or the Administration Console) if you don't want to copy deployment files but want to deploy an application from its present location. All target servers must be able to access the same set of deployment files. 87.When should I use the external_stage option? Set -external_stage using weblogic.Deployer if you want to stage the application yourself, and prefer to copy it to its target by your own means. 88.What are the Deployment Tools for Developers? WebLogic Server provides several tools for deploying applications and stand-alone modules:

wldeploy is an Ant task version of the weblogic.Deployer utility. You can automate deployment tasks by placing wldeploy commands in an Ant build.xml file and running Ant to execute the commands. weblogic.PlanGenerator is a command-line tools that enables developers to export an applications configuration for deployment to multiple WebLogic Server environments. The deployment API allows you to perform deployment tasks programmatically using Java classes. The autodeploy domain directory allows you to deploy an application quickly for evaluation or testing in a development environment.

89.What is the Deployment order of Weblogic Server at Server Startup time? By default, WebLogic Server deploys applications and resources in the following order:

JDBC system modules JMS system modules J2EE Libraries and optional packages Applications and stand-alone modules Startup classes

Note: WebLogic Server security services are always initialized before server resources, applications, and startup classes are deployed. For this reason, you cannot configure custom security providers using startup classes, nor can custom security provider implementations rely on deployed server resources such as JDBC. 90.How will you Kill the JVM or running Weblogic server in different operating systems? Each WebLogic Server instance runs in its own JVM. If you are unable to shut down a server instance using the scripts which are provided by the Weblogic (stopWeblogic.cmd/ stopManagedWeblogic.cmd), you can use an operating system command to kill the JVM. Caution: If you kill the JVM, the server immediately stops all processing. Any session data is lost. If you kill the JVM for an Administration Server while the server is writing to the config.xml file, you can corrupt the config.xml file. Some common ways to kill the JVM are as follows:

If the shell (command prompt) in which you start the server is still open, you can type Ctrl-C. On a Windows computer, you can use the Task Manager to kill a JVM.

On a UNIX computer, you can use the ps command to list all running processes. Then you can use the kill command to kill the JVM . 91. Can I generate deployment descriptor files automatically? Yes, WebLogic Builder automatically generates deployment descriptor files for your J2EE applications. See WebLogic Builder Online Help. 92.Can I set the deployment order for application modules? For standalone modules? The Load Order attribute controls the deployment order of standalone modules and applications relative to other modules andapplications of the same type. For example, standalone EJBs with smaller Load Order values are deployed before those with higher values. Modules that are deployed as part of an Enterprise Application (EAR file or directory) are deployed in the order in which they are specified in the application.xml deployment descriptor. 93.What is the difference between the WL_HOME/config/examples/applications folder and the WL_HOME/config/examples/stage folder? The applications folder is intended for applications that are not yet ready for a production environment. WebLogic Server dynamically deploys the contents of the applications folder. The stage folder (or a folder that you create for the same purpose) is for storing copies of deployment files that are ready for deployment in a production environment (deployments that use the stage or external_stage deployment modes). 94.How do I turn the auto-deployment feature off? The auto-deployment feature checks the applications folder every three seconds to determine whether there are any newapplications or any changes to existing applications and then dynamically deploys these changes.

The auto-deployment feature is enabled for servers that run in development mode. To disable autodeployment feature, use one of the following methods to place servers in production mode: In the Administration Console, click the name of the domain in the left pane, then select the Production Mode checkbox in the right pane. At the command line, include the following argument when starting the domain's Administration Server: -Dweblogic.ProductionModeEnabled=true Production mode is set for all WebLogic Server instances in a given domain. 95.I downloaded the WebLogic Server installation file, but the installation program will not run. What should I do? The installation file may have been corrupted during the download. Run a checksum on the installation file and check with technical support for the proper values. 96.Do I need to install WebLogic Server as root on Solaris? No you don't need to be root, depending on directory permissions. 97.Can I run the Configuration Wizard outside the installer? Yes. You can start the Configuration Wizard from the Start menu or using a script in the utils directory. See Creating Domains and Servers in Configuring and Managing WebLogic Server. 98.How do I edit the config.xml file? The persistent configuration for a domain of WebLogic Servers and clusters is stored in an XML configuration file (config.xml). You can modify this file in the following ways:

Use the Administration Console. See "Using the Administration Console" in the Administration Console Online Help. If you want to create scripts that automate domain management, use the weblogic.Admin utility. See "weblogic.Admin Command-Line Reference" in the . If you want to create Java-based management applications, use the Java Management Extensions (JMX) ApplicationProgramming Interface (API). See the Programming WebLogic Management Services with JMX guide. If you want to edit the config.xml file directly (not recommended), see the BEA WebLogic Server Configuration Reference.

99.What is the free pool? The free pool is a data structure the EJB container uses to cache anonymous instances of a given bean type. The free pool improves performance by reusing objects and skipping container callbacks when it can. 100.Can I use the PointBase DBMS included with WebLogic Server for development or production? PointBase Server is an all-Java DBMS product included in the WebLogic Server distribution solely in support of WebLogic Server evaluation, either in the form of custom trial applications or through packaged sample applications provided with WebLogic Server. Non-evaluation development and/or production use of the PointBase Server requires a separate license be obtained by the end user directly from PointBase. 101.How can I enable Oracle Advanced Security encryption on the JDBC Oracle Thin driver with a WebLogic JDBC Connection Pool? Oracle Advanced Security encryption relies on features available through connection properties in the JDBC driver from Oracle. You can specify connection properties in a WebLogic JDBC connection pool in the Properties attribute. This attribute is available on the JDBC Connection Pool > Configuration > General tab in the Administration Console. When WebLogic Server createsdatabase connections for the connection pool, it passes the properties to the JDBC driver so that connections are created with the specified properties. For example, to enable Oracle Advanced Security encryption, you may want to specify the following options: Properties: user=SCOTT oracle.net.encryption_client=ACCEPTED

oracle.net.encryption_types_client=RC4_256 oracle.net.crypto_checksum_client=ACCEPTED protocol=thin Note: See the Oracle documentation for details about required properties for Oracle Advanced Security encryption. Properties listed above are for illustration only. The resulting entry in the config.xml file would look like: <JDBCConnectionPool DriverName="oracle.jdbc.driver.OracleDriver" Name="oraclePool" Password="{3DES}1eNn7kYGZVw=" Properties="user=SCOTT; oracle.net.encryption_client=ACCEPTED; oracle.net.encryption_types_client=RC4_256; oracle.net.crypto_checksum_client=ACCEPTED; protocol=thin" URL="jdbc:oracle:thin:@server:port:sid"/> Note: Line breaks added for readability. 102.When should I use a TxDataSource instead of a DataSource? When you select Honor Global Transactions in the Administration Console, you create a JDBCTxDataSource in the config.xml file (the default). If you clear the Honor Global Transactions check box, you create a JDBCDataSource in the config.xml file. See "When to Enable Global Transactions in a Data Source" in the Administration Console Online Help. 103.Can I enable requests to a JDBC connection pool for a database connection to wait until a connection is available? Yes. You can set two JDBC connection pool properties to enable connection requests to wait for a connection:

ConnectionReserveTimeoutSeconds HighestNumWaiters

104.What happens when my database is restarted or becomes unreachable? Does my connection pool stick around? Yes. The pool is independent of its ability to communicate with to the DBMS. All connections in the connection pool may become defunct, but the connection pool still exists. You can configure the connection pool so that WebLogic Server tests the connections in the pool and replaces bad connections when it can. To manually restart the connection pool using the Administration Console after a database failure, you can undeploy the connection pool by removing all of its deployment targets, and then redeploy the connection pool by adding deployment targets. To do this from the command line using "weblogic.Admin", set the "Targets" attribute of the pool to an empty string ("") and then set it to the desired set of targets. 105.When should I use MultiPools? You can use MultiPools in one of two ways 1) For high availability in the event a database connection fails, or 2) For load balancing between JDBC connection pools. Because you can choose only one option, you need to determine the primary purpose of your MultiPool. Note: If you implement Multipools for a JDBC application, do not configure driver-level load balancing or failover for the connection pools used by the MultiPoolthe MultiPool provides the same functionality as configuring driver-level load balancing or failover. 106.What is JDBC? JDBC is an API for accessing databases in a uniform way. JDBC provides:

o o o o

Platform-independent access to databases Location transparency Transparency to proprietary database issues Support for both two-tier and multitier models for database access

The Java Database Connectivity (JDBC) specification:

o o o

Is a platform- and vendor-independent mechanism for accessing and updating a database Provides transparency from proprietary vendor issues Requires the use of a driver

JDBC drivers are supplied by WLS or your database vendor. 107.What is the use of Data Source in Weblogic? Data sources:

o o o

Allow database connectivity to be managed by the application server Use a dynamic pool of reusable database connections Are obtained by applications from the servers JNDI tree

108.What is the scope of the Data Source in Weblogic server?

o o

Each data source configuration or module is persisted as a separate XML document. The system modules that are created with the console or WLST are: Stored in the domain's config/Jdbc directory Available to all applications in the domain Application-specific modules are: Deployed as part of Java EE enterprise applications Accessible only by the containing application

109.List default Weblogic provided JDBC Drivers?

Oracle and third-party drivers are included in WLS installation for many popular database products: Oracle 9i, 10g, and 11g Sybase Adaptive Server Microsoft SQL Server IBM DB2 Informix MySQL PointBase By default, these drivers are added to servers classpath.

110.What is a Data Source?

o o

A data source object provides a way for a JDBC client to obtain a database connection from a connection pool. A data source: Is stored in the Oracle WebLogic Server JNDI tree Can support transactions Is associated with a connection pool

111.What is a Connection Pool?

o o

A connection pool is a group of ready-to-use database connections associated with a data source. Connection pools: Are created at Oracle WebLogic Server startup Can be administered using the Administration Console Can be dynamically resized to accommodate increasing load

112.What are the benefits of having Data Sources and Connection Pools in Weblogic? The following are some advantages of this approach: Time and overhead are saved by using an existing database connection. Connection information is managed in one location in the Administration Console. The number of connections to a database can be controlled. The DBMS can be changed without the application developer having to modify the underlying code. A connection pool allows an application to borrow a DBMS connection

113.How Data Sources are used in Weblogic? A client retrieves a data source through a JNDI lookup and uses it to obtain a database connection. 114.What is Multi Data Sources?

Multi data source: Is an abstraction around a group of data sources Determines which data source to use to satisfy the request depending on the algorithm selected in the multi data source configuration: Load balancing or failover Is bound to the JNDI tree XA support for multi data sources: The WLS JDBC supports using multi data sources in XA transactions. You can configure the data sources contained within the multi data source to use XA JDBC drivers.

115.What is the functionality of Message-Oriented Middleware?

Message-oriented middleware refers to an infrastructure that supports messaging. Typical message-oriented middleware architectures define the following elements: Message structure The way to send and receive messages Scaling guidelines

116.Explain about Point-to-Point (Queue)? Many producers can serialize messages to multiple receivers in a queue. 117.Explain about Publish-Subscribe (Topics)? Publishing and subscribing to a topic decouples producers from consumers. 118.Explain about Oracle WebLogic Server JMS Features? Oracle WebLogic Server JMS supports:

o o

PTP and pub/sub domains Guaranteed and transactional message delivery

o o o

Durable subscribers Distributed destinations Recovery from failed servers

119.How will you implement Messaging Service in Weblogic?

o o

In Oracle Weblogic Server, the messaging service is implemented through a JMS server. A JMS server receives and distributes messages.

120.What is the user of Connection Factories in JMS?

JMS connection factories are used to set default client connection parameters, including: Message priority Message time-to-live (TTL) Message persistence Transactional behavior Acknowledgement policy Flow control WLS provides a default client connection factory that: Uses WebLogics default connection settings Is located on the server JNDI tree at weblogic.jms.ConnectoryFactory

121.What is the use of Destination in JMS? How many types of Destinations are available in JMS?

o o o

A destination is a lightweight object that is stored in JNDI. It is the target on a JMS server for sending or receiving messages. The JMS destination types are: Queue Topic

122.Explain about Queue Destinations? In JMS point-to-point messaging, note the following:

o o o

Clients communicate with a queue destination. Messages are distributed to consumers in a serial fashion (first in, first out). Each message is delivered only to a single consumer.

123.Explain about Topic Destinations? In JMS publish/subscribe messaging, the following is true:

o o o

Clients communicate with a topic destination. Messages are broadcast to all subscribers. A message can be saved until at least one subscriber has consumed it (durable).

124.Explain about Threshold and Quotas in JMS?

o o

A threshold and a quota can be set for the server and destination objects. A quota is a limit defined for the JMS-administered objects; it includes the following values:

The maximum number of bytes that can be stored The maximum number of messages that can be stored A threshold is a limit that triggers message paging, flow control, and logged warnings, using: Upper and lower values for the number of bytes Upper and lower values for the number of messages

125.Difference between Durable Subscribers and Subscriptions?

o o o o

Durable subscribers register durable subscriptions for guaranteed message delivery even if the subscribers are inactive. A subscriber is considered active if the Java object that represents it exists. By default, subscribers are nondurable. Administrators configure: Where the messages are persisted Persistent connection factories and destinations

126.What is Persistent Messaging? When to Use it?

o o

Persistent messaging permits messages in memory to be written out to a persistent store. Configure persistent messaging if: Development requires durable subscriptions (use durable subscribers in the application) You require that in-progress messages persist across server restarts

127.How will you Configuring a Durable Subscription in Weblogic?

To configure durable subscriptions, an administrator must: Create and configure a JMS store Configure connection factories or destinations as persistent Associate the JMS store with the JMS server The JMS store can be configured to use either: A file store A JDBC store (a connection pool)

128.How a Durable Subscription Works?

o o

If a subscriber client is active, messages are delivered normally. When the client becomes active again, its ID is used to retrieve and redeliver messages.

129.What Node manager can do in Weblogic server? You can use Node Manager to:

Start, shut down, and restart an Administration Server Start, shut down, suspend, and restart Managed Servers Automatically restart the Administration and Managed Servers on failure Monitor servers and collect log data

130.Does the WebLogic JMS server find out about closed or lost connections, crashes, and other problems and does it recover from them?

Yes, but how it does this depends on whether a Java client crashes or WebLogic Server crashes, as follows:

If a Java client crashes then the JMS server will clean up all the outstanding server-side resource from the crashed client JVM, such as: JMS connection(s) from the crashed client JVM JMS temporary destination(s) created under the above JMS connection(s) JMS session(s) created under the above JMS connection(s) JMS client(s) created under the above JMS session(s) (connection consumer and regular consumer) JMS browser(s) created under the above session(s) JMS producer(s) created under the above session(s) If WebLogic Server crashes and it is the front-end to the JMS server, then: A JMS client will lose all the server-side resources listed above. The client's javax.jms.ExceptionListener.onException(...) will be called (if javax.jms.JMSConnection.setExceptionListener is set) with a LostServerException, which extends JMSException. If WebLogic server crashes and it is a back-end to the JMS server, then: A JMS client may partially lose some of the server-side resources listed above (only the resource on the crashed server, such as JMS temporary destination(s), JMS client(s) and JMS browser(s). The client's javax.jms.ExceptionListener.onException(...) will be called (if weblogic.jms.extensions.WLSession.setExceptionListener is set) with a ConsumerClosedException, which extends JMSException.

131.What Is the Java Message Service? An enterprise messaging system enables applications to communicate with one another through the exchange of messages. A message is a request, report, and/or event that contains information needed to coordinate communication between differentapplications. A message provides a level of abstraction, allowing you to separate the details about the destination system from the application code. The Java Message Service (JMS) is a standard API for accessing enterprise messaging systems. Specifically, JMS:

Enables Java applications sharing a messaging system to exchange messages Simplifies application development by providing a standard interface for creating, sending, and receiving messages

132.How many Messaging Modules are available in Weblogic? JMS supports two messaging models: point-to-point (PTP) and publish/subscribe (pub/sub). The messaging models are very similar, except for the following differences:

PTP messaging model enables the delivery of a message to exactly one recipient. Pub/sub messaging model enables the delivery of a message to multiple recipients.

133.Explain about Point-to-Point Messaging? The point-to-point (PTP) messaging model enables one application to send a message to another. PTP messaging applicationssend and receive messages using named queues. A queue sender (producer) sends a message to a specific queue. A queue receiver (consumer) receives messages from a specific queue. 134.Explain about Publish/Subscribe Messaging? The publish/subscribe (pub/sub) messaging model enables an application to send a message to multiple applications. Pub/sub messaging applications send and receive messages by subscribing to a topic. A topic publisher (producer) sends messages to a specific topic. A topic subscriber (consumer) retrieves messages from a specific topic. 135.Explain about Message Persistence?

As per the Message Delivery Mode section of the JMS Specification, messages can be specified as persistent or non-persistent:

A persistent message is guaranteed to be delivered once-and-only-once. The message cannot be lost due to a JMS provider failure and it must not be delivered twice. It is not considered sent until it has been safely written to a file or database. WebLogic JMS writes persistent messages to a WebLogic persistent store (disk-base file or JDBC-accessible database) that is optionally targeted by each JMS server during configuration. Non-persistent messages are not stored. They are guaranteed to be delivered at-mostonce, unless there is a JMS provider failure, in which case messages may be lost, and must not be delivered twice. If a connection is closed or recovered, all non-persistent messages that have not yet been acknowledged will be redelivered. Once a non-persistent message is acknowledged, it will not be redelivered.

136.Topics vs. Queues? Surprisingly, when you are starting to design your application, it is not always immediately obvious whether it would be better to use a Topic or Queue. In general, you should choose a Topic only if one of the following conditions applies:

The same message must be replicated to multiple consumers. A message should be dropped if there are no active consumers that would select it. There are many subscribers, each with a unique selector.

It is interesting to note that a topic with a single durable subscriber is semantically similar to a queue. The differences are as follows:

If you change a topic selector for a durable subscriber, all previous messages in the subscription are deleted, while if you change a queue selector for consumer, no messages in the queue are deleted. A queue may have multiple consumers, and will distribute its messages in a roundrobin fashion, whereas a topic subscriber is limited to only one consumer.

137.Asynchronous vs. Synchronous Consumers? In general, asynchronous (onMessage) consumers perform and scale better than synchronous consumers:

Asynchronous consumers create less network traffic. Messages are pushed unidirectionally, and are pipelined to the message listener. Pipelining supports the aggregation of multiple messages into a single network call.

Note: In WebLogic Server, your synchronous consumers can also use the same efficient behavior as asynchronous consumers by enabling the Prefetch Mode for Synchronous Consumers option on JMS connection factories

Asynchronous consumers use fewer threads. An asynchronous consumer does not use a thread while it is inactive. Asynchronous consumer consumes a thread for the duration of its receive call. As a result, a thread can remain idle for long periods, especially if the call specifies a blocking timeout. For application code that runs on a server, it is almost always best to use asynchronous consumers, typically via MDBs. The use of asynchronous consumers prevents the application code from doing a blocking operation on the server. A blocking operation, in turn, idles a server-side thread; it can even cause deadlocks. Deadlocks occur when blocking operations consume all threads. When no threads remain to handle the operations required unblocking the blocking operation itself, that operation never stops blocking.

138.What is a Distributed Destination? A distributed destination is a set of destinations (queues or topics) that are accessible as a single, logical destination to a client. A distributed destination has the following characteristics:

It is referenced by its own JNDI name. Members of the set are usually distributed across multiple servers within a cluster, with each destination member belonging to a separate JMS server.

139.Why Use a Distributed Destination? Applications that use distributed destinations are more highly available than applications that use simple destinations because WebLogic JMS provides load balancing and failover for member destinations of a distributed destination within a cluster. Once properly configured, your producers and consumers are able to send and receive messages through the distributed destination. WebLogic JMS then balances the messaging load across all available members of the distributed destination. When one member becomes unavailable due a server failure, traffic is then redirected toward other available destination members in the set. 140.How many Types of Distributed Destinations are available?

Uniform Distributed Destinations Weighted Distributed Destinations

Uniform Distributed Destinations In a uniform distributed destination (UDD), each of the member destinations has a consistent configuration of all distributed destination parameters, particularly in regards to weighting, security, persistence, paging, and quotas. Oracle recommends using UDDs because you no longer need to create or designate destination members, but instead rely on WebLogic Server to uniformly create the necessary members on the JMS servers to which a UDD is targeted. This feature of UDDs provides dynamic updating of a UDD when a new member is added or a member is removed. Weighted Distributed Destinations In a weighted distributed destination, the member destinations do not have a consistent configuration of all distributed destination parameters, particularly in regards to weighting, security, persistence, paging, and quotas. Oracle recommends converting weighted distributed destinations to UDDs because of the administrative inflexibility when creating members that are intended to carry extra message load or have extra capacity (more weight). Lack of a consistent member configuration can lead to unforeseen administrative and application problems because the weighted distributed destination cannot be deployed consistently across a cluster. 141.What is JNDI? JNDI (Java Naming and Directory Interface) is a Java EE lookup service that maps names to services and resources. JNDI provides a directory of advertised resources that exist on a particular stand-alone (unclustered) WebLogic server, or within a WebLogic server cluster. Examples of such resources include JMS connection factories, JMS destinations, JDBC (database) data sources, and application EJBs. A client connecting to any WebLogic server in a WebLogic cluster can transparently reference any JNDI advertised service orresource hosted on any WebLogic server within the cluster. The client doesn't require explicit knowledge of which particular WebLogic server in the cluster hosts a desired resource. 142.What is a JMS connection factory? A JMS connection factory is a named entity resource stored in JNDI. Applications, message driven beans (MDBs), and messaging bridges lookup a JMS connection factory in JNDI and use it to create JMS connections. JMS connections are used in turn to create JMS sessions, producers, and consumers that can send or receive messages. 143.What is a JMS connection-id? JMS connection-ids are used to name JMS client connections. Durable subscribers require named connections, otherwise connections are typically unnamed. Note that within a clustered set of servers or stand-alone server, only one JMS client connection may use a particular named connection at a

time. An attempt to create new connection with the same name as an existing connection will fail. 144.What is the difference between a JMS topic and a JMS queue? JMS queues deliver a message to one consumer, while JMS topics deliver a copy of each message to each consumer. 145.What is a non-durable topic subscriber? A non-durable subscriber creates unnamed subscriptions that exist only for the life of the JMS client. Messages in a non-durable subscription are never persistedeven when the message's publisher specifies a persistent quality of service (QOS). Shutting down a JMS server terminates all non-durable subscriptions. 146.What is a durable subscriber? A durable subscriber creates named subscriptions that continue to exist even after the durable subscriber exits or the server reboots. A durable subscriber connects to its subscription by specifying topic-name, connection-id, and subscriber-id. Together, the connection-id and subscriber-id uniquely name the subscribers subscription within a cluster. A copy of each persistent message published to a topic is persisted to each of the topic's durable subscriptions. In the event of a server crash and restart, durable subscriptions and their unconsumed persistent messages are recovered. 147.What is the WebLogic Store-and-Forward Service? The WebLogic Store-and-Forward (SAF) Service enables WebLogic Server to deliver messages reliably between applications that are distributed across WebLogic Server instances. For example, with the SAF service, an application that runs on or connects to a local WebLogic Server instance can reliably send messages to a destination that resides on a remote server. If the destination is not available at the moment the messages are sent, either because of network problems or system failures, then the messages are saved on a local server instance, and are forwarded to the remote destination once it becomes available. 148.When should I use the WebLogic Store-and-Forward Service? The WebLogic Store-and-Forward (SAF) Service should be used when forwarding JMS messages between WebLogic Server 9.0 or later domains. The SAF service can deliver messages:

Between two stand-alone server instances. Between server instances in a cluster. Across two clusters in a domain. Across separate domains.

149.What is a messaging bridge? Messaging bridges are administratively configured services that run on a WebLogic server. They automatically forward messages from a configured source JMS destination to a configured target JMS destination. These destinations can be on different servers than the bridge and can even be foreign (non-WebLogic) destinations. Each bridge destination is configured using the four common properties of a remote provider:

The The The The

initial context factory. connection URL. connection factory JNDI name. destination JNDI name.

Messaging bridges can be configured to use transactions to ensure exactly-once message forwarding from any XA capable (global transaction capable) JMS provider to another. 150.When should I use a messaging bridge? Typically, messaging bridges are used to provide store-and-forward high availability design requirements. A messaging bridge is configured to consume from a sender's local destination and forward it to the sender's actual target remote destination. This provides high availability because the sender is still able to send messages to its local destination even when the target remote destination is unreachable. When a remote destination is not reachable, the local destination automatically begins to store messages until the bridge is able to forward them to the target destination when the target becomes available again.

151.When should I avoid using a messaging bridge? Other methods are preferred in the following situations:

Receiving from a remote destinationuse a message driven EJB or implement a client consumer directly. Sending messages to a local destinationsend directly to the local destination. Environment with low tolerance for message latency. Messaging Bridges increase latency and may lower throughput. Messaging bridges increase latency for messages as they introduce an extra destination in the message path and may lower throughput because they forward messages using a single thread. Forward messages between WebLogic 9.0 domainsUse WebLogic Store-and-Forward.

152.How many types of JMS stores are available?

The JMS store can be configured to use either: A file store A JDBC store (a connection pool)

153.How will you configure a JMS JDBC Store?

To configure JMS JDBC persistence, perform the following: Create a JDBC DataSource. Create a JMS store and refer to the JDBC DataSource. Refer to the JMS store from the JMS server configuration. The required infrastructure (tables and so on) is created automatically.

154.What Is a Transaction?

o o o

A transaction is a mechanism to handle groups of operations as though they were one. Either all operations in a transaction occur or none occur at all. The operations involved in a transaction might rely on multiple servers and databases.

155.How many Types of Transactions are there? Explain?

o o o

A local transaction deals with a single resource manager. Local transactions use the non-Extended Architecture (non-XA) interface between Oracle WebLogic Server and the resource manager. A distributed transaction coordinates or spans multiple resource managers. Global transactions can deal with multiple resource managers. Global transactions use the Extended Architecture (XA) interface between Oracle WebLogic Server and the resource managers. You need to create non-XA or XA resources for local transactions. However, for global transactions, you need to create only XA resources.

156.Explain about Two-Phase Commit Protocol?

The Two-Phase Commit (2PC) protocol uses two steps to commit changes within a distributed transaction. Phase 1 asks the RMs to prepare to make the changes. Phase 2 asks the RMs to commit and make the changes permanent or to roll back the entire transaction.

A global transaction ID (XID) is used to track all the changes associated with a distributed transaction.

157.Explain about Extended Architecture Protocol (XA)? The Extended Architecture (XA) protocol:

o o o

Is the interface that is used between WLS and the RMs Implements the 2PC protocol Allows programs to control the RMs that are involved in distributed transactions

158.What is the user of Transaction Log? Each server has a transaction log that stores information about committed transactions coordinated by the server that may not have been completed. Oracle WebLogic Server uses the transaction log when recovering from system crashes or network failures. You cannot directly view the transaction log because the records are in a binary format and are stored in the default persistent store for the server.

159.Explain about Logging Last Resource?

You can configure a JDBC data source to enable the Logging Last Resource (LLR) transaction optimization, which: Enables one non-XA resource to participate in a global transaction Has improved performance and the same ACID guarantee as XA The LLR optimization improves performance by: Removing the need for an XA JDBC driver to connect to the database. XA JDBC drivers are typically inefficient compared to non-XA JDBC drivers. Reducing the number of processing steps to complete the transaction, which also reduces network traffic and I/O Removing the need for XA processing at the database level (if the database is the one non-XA resource)

160.What Is LDAP? The Lightweight Directory Access Protocol:

o o o o

Is derived from X.500 Provides a hierarchical lookup service Supports sophisticated searching Can be secured via SSL

161.Explain Security Realms?

o o o o o

A security realm is a collection of system resources and security service providers. Only one security realm can be active at a given time. A single security policy is used in any realm. Users must be recognized by an authentication provider of the security realm. Administration tasks include creating security realms.

162.What Is SSL? Secure Sockets Layer (SSL) is a protocol that enables:

Connection security through encryption

o o o

A server to authenticate to a client A client to authenticate to a server (optional) Data integrity such that the data that flows between a client and server is protected from tampering by a third party

163.What Is a Deployment Plan?

It is an optional XML document that resides outside an application archive. It configures an application for deployment to a specific WLS environment. It is created and owned by administrators or developers for a particular environment.

A JavaEE deployment plan:

Is an XML file that is associated with an application Resides outside an application archive Sets or overrides the values in the JavaEE deployment descriptors

Allows a single application to be easily customized to multiple deployment environments 164.What are the Advantages of Production Redeployment? Saves the trouble of:

Scheduling application downtime Setting up redundant servers to host new application versions Managing client access to multiple application versions manually Retiring older versions of an application manually Explain about Packaging Applications? When you deploy applications to a single Managed Server, you can deploy the applications in an exploded format. Oracle recommends deploying packaged applications to a cluster of Managed Servers as .war, .ear, or .jar file

165.What are the Oracle WebLogic Server SSL Requirements?

To enable Oracle WebLogic Server SSL, you must: Obtain an appropriate digital certificate Install the certificate Configure SSL properties Configure two-way authentication (if desired) SSL impacts performance.

166.What is the user of keytool Utility in WLS?

keytool is a standard J2SE SDK utility for managing: The generation of private keys and the corresponding digital certificates Keystores (databases) of private keys and the associated certificates The keytool utility can the display certificate and keystore contents.

167.How WLS Protecting Against Attacks? What kinds of Attacks are there?

WLS can help protect applications against several attacks: Man-in-the-middle attacks Denial of service (DoS) attacks Large buffer attacks Connection starvation attacks The slides that follow detail the countermeasures that WLS provides to address these attacks.

168.Explain about Man-in-the-Middle Attacks?

In the man-in-the-middle attack, a third party poses as a destination host intercepting messages between the client and the real host. Instead of issuing the real destination hosts SSL certificate, the attacker issues his or her own hoping that the client would accept it as being from the real destination host. The man-in-the-middle attacks can be resisted by using a Host Name Verifier. A Host Name Verifier validates that the host to which an SSL connection is made is the intended or authorized party. WLS provides a Host Name Verifier by default. A custom Host Name Verifier can be created by implementing the interfaceweblogic.security.SSL.HostnameVerifier

169.Explain about Denial of Service Attacks (DOS)?

DoS attacks are attempts by attackers to prevent legitimate users of a service from using that service. There are three basic types of attack: Consumption of scarce, limited, or nonrenewable resources Destruction or alteration of configuration information Physical destruction or alteration of network components

Harden WLS against denial of service attacks by:

Filtering incoming network connections Configuring consumable WLS resources with the appropriate threshold and quotas Limiting access to configuration information and backing up configuration files Preventing unauthorized access by protecting passwords against password-guessing attacks

170.Explain about Filtering Network Connections?

WLS can be configured to accept or deny network connections based on the origin of the client. This feature can be used to: Restrict the location from which connections to WLS are made Restrict the type of connection made, that is, allow only SSL connections and reject all others To filter network connections, create a class that implements the ConnectionFilter interface and install it using the Administration Console.

171.Explain about Large Buffer Attacks?

o o

Individuals can try to bring down a Web site by sending a large buffer of data, which starves the system of memory. Administrators can combat this attack by setting a threshold for incoming data.

172.Explain about Connection Starvation?

o o o

Individuals can try to take down a Web site by sending small, incomplete messages that cause the server to wait. Administrators can combat this attack by setting a threshold. Connections time out while waiting for the remainder of the data if they have reached the threshold set by the administrator.

173.Explain about User Lockout?

o o o

Individuals attempt to hack into a computer using various combinations of usernames and passwords. Administrators can protect against this security attack by setting the lockout attributes. The administrator can unlock a locked user using the console.

174.How will you Protecting the Administration Console?

o o o

You can configure a separate administration port for all administration traffic. You can change the Context path of the console. You can disable the console (application).

175.What are the advantages of Deployment Plan?

o o

Works by setting or overriding the deployment property values that are defined in an applications WLS deployment descriptor Helps to easily modify an applications WLS configuration for deployment into different multiple WLS environments without modifying the deployment descriptor files that are included in the application archive

Enables an application to be deployed to multiple domains or to multiple target servers and clusters that have a different configuration within the same 1. domain

176.What is the user of weblogic.PlanGenerator?

1. Is a Java-based deployment configuration tool


2.

3.

Is primarily intended for developers who want to export portions of an Oracle WebLogic Server deployment configuration into an XML deployment plan Enables you to generate a basic Oracle WebLogic Server configuration for applications that have only J2EEdeployment descriptors

177.How will you generate a Deployment Plan Using the Administration Console? 1. The Administration Console automatically generates or updates the deployment plan.

2.

You can generate a deployment plan using the Administration Console using the following steps: Prepare the deployment files. Install the application archive. Save the configuration changes to a deployment plan.

178.How many types of Staged Deployment are available in WLS? You can configure deployment per server or for each application as:

1. staged (default): Files are copied to the preconfigured staging directory for
preparation and activation.

2. nostage: Files are deployed from a static location. 3. external_stage: Files are copied by a user or a third-party tool before deployment.
179.Explain about Production Redeployment? 1. You can redeploy a revised version of a production application alongside the older version: Without affecting the existing clients to the application Without interrupting the availability of the application to the new client request Oracle WebLogic Server automatically manages client connections so that: Existing clients continue to use the older application New client requests are directed to the newer application

2.

The older version is undeployed after all current clients complete their work. 180.Explain about Application Availability, after deploying/install to WLS? 1. By default, when an application is redeployed: It is unavailable to clients for a brief time Existing clients lose any conversational state Some types of applications require availability 24 hours a day, seven days a week. Third-party proxy solutions are possible, but they require multiple servers.

2. 3.

181.Explain about WebLogic Production Redeployment? 1. Production redeployment: 1. Allows two versions of a single Web application or module to run simultaneously 2. Requires you to include unique version information either: Within the applications META-INF/MANIFEST.MF file As part of the deployment process When a new version is redeployed, WLS automatically: Routes existing clients to the prior (retired) version Routes new clients to the new version Undeploys the prior version when all existing clients finish their work or their conversations time out

2.

182.What are the Requirements and Restrictions for Production Redeployment in WLS? 1. Production redeployment is supported for:

2.

3. 4. 5.

Stand-alone Web Application (WAR) modules and Enterprise Applications (EARs) whose client accesses the application via a Web application (HTTP) Enterprise Applications that are accessed by inbound JMS messages from a global JMS destination, or from inbound JCA requests All types of Web Services, including conversational and reliable Web Services Production redeployment is not supported for: Stand-alone EJB or Resource Archive (RAR) modules Applications that use JTS drivers Applications that obtain JDBC data sources via the DriverManager API instead of using the JNDI lookup Applications that include the EJB 1.1 container-managed persistence (CMP) EJBs A deployed application must specify a version number. WLS can host a maximum of two different versions of an application at one time. When you are redeploying a new version of an application, the following features cannot change: Deployment targets Security model Persistent store settings

183.Redeploying Versus Distributing an applications in WLS? 1. Distributing is an alternative to deploying an application. Distributing an application prepares it for deployment by copying its files to all target servers and validating the files. You can start a distributed application in Administration mode. Access to the application is then restricted to a configured Administration channel. Distributing a new version of the application makes it available for testing before being released for general consumption. Redeploying a new version of an application places the application immediately into use and makes it available to new client requests.

2. 3.

184.How will you Distributing a New Application Version in WLS? 1. 2. 3. 4. 5. Use the weblogic.Deployer distribute command. After the application is distributed, start the application in Administration mode. Test the application. When ready, start the application (without using adminmode). Optionally set a retirement timeout for the older version of the application.

185.How will you Create MANIFEST.mf file for Production Redeployment? 1. Create MANIFEST.mf with the following contents: Name: java/util/ Specification-Title: Java Utility Classes Specification-Version: 1.2 Specification-Vendor: Sun Microsystems, Inc. Implementation-Title: java.util Implementation-Version: build57 Implementation-Vendor: Sun Microsystems, Inc. Then add an entry for WLS versioning:

2.

Weblogic-Application-Version: Version1.0Beta 186.What is a cluster Definition?

1. 2.

A cluster is a group of Oracle WebLogic Server instances that work in coordination. Clustering provides: High availability Load balancing Scalability

187.What Is a Cluster? A cluster: 1. 2. Is a logical group of Oracle WebLogic Servers within a domain Supports features to provide high availability for: Whole servers Web applications/services EJB applications JMS Is transparent to a client

3.

188.What are the Benefits of Clustering? 1. 2. 3. There are two main benefits of clustering together Oracle WebLogic Servers: 1. Scalability 2. High availability Scalability is the ability to provide more capacity for an application, in this case, by adding additional servers without having to make major architectural changes. High availability ensures that when a server (in a cluster) fails, there are other servers to take over the work, so that the client is not affected.

189.What are the Key Capabilities of clustering? The key capabilities of a WebLogic cluster are: 1. Application failover When an object in an application that is performing a task becomes unavailable, another object takes over and finishes the job. Site failover

2.

3.

4.

When all the services and applications in a single site fail, they can switch to a separate site and continue processing. Server migration When a server fails, pinned services can be migrated to another server in a cluster. Load balancing Tasks and communications are evenly distributed across multiple servers.

190.Explain about Cluster Architecture? 1. Applications are generally broken into multiple tiers, each representing its distinct functionality: 1. Web tier 2. Presentation tier 3. Business or object tier WebLogic provides clustering support for all three tiers. Other services, such as JMS and JDBC, can take advantage of clusters but loadbalancing and failover is a little different.

2. 3.

191.How the Server will communicate in a Cluster?

The Oracle WebLogic Server instances in a cluster communicate with one another using two different techniques: Unicast/multicast (UDP) Sockets (peer-to-peer TCP) The server instances use IP unicast or multicast to broadcast the availability of services and heartbeats that indicate continued availability. IP multicast broadcasts one-to-many communications among clustered instances. IP unicast is an alternative to multicast to handle cluster messaging and communications. The unicastconfiguration is much easier because it does not require cross-network configuration that multicast requires. IP sockets are used for peer-to-peer communications between server instances.

192.Explain about Cluster Communication in WLS? 1. Members of a cluster cooperate to achieve high availability using the following: Broadcast messages such as heartbeats Peer-to-peer IP sockets You can configure broadcast communication to use either: IP unicast A dedicated IP multicast address (224.0.0.0 through 239.255.255.255) and port If heartbeats are not received from a cluster member, the server is marked as failed and its services are not used.

2.

3.

193.How the Weblogic Server detect a server Failure? 4. WebLogic clusters detect the failure of a server instance in the following ways:

5. 6.

Through the use of IP sockets Through the Oracle WebLogic Server heartbeat If a server in the cluster unexpectedly closes its socket, it is marked as failed and its services are not used. Server instances use multicast to broadcast heartbeats every 10 seconds to the other server instances in the cluster.

If three heartbeats are missed from a peer server, the server is marked as failed and its services are not used.

194.Explain about One-to-Many Communications in WLS? 2. Oracle WebLogic Server uses one-to-many communication for: Clusterwide JNDI updates Cluster heartbeats Because all one-to-many communications occur over IP multicast, when you design a cluster, consider the following factors: If your cluster spans multiple subnets, your network must be configured to reliably transmit messages. A firewall can break IP multicast transmissions. The multicast address should not be shared with other applications. Multicast storms may occur.

3.

195.Explain about Peer-to-Peer Communications in WLS? Oracle WebLogic Server uses peer-to-peer communications for: 4. Accessing the nonclustered objects that reside on a remote server instance in the cluster Replicating HTTP session states and stateful session EJB states between a primary and a secondary server Accessing the clustered objects that reside on a remote server instance (typically, in a multitiercluster architecture)

5.
6.

196.Explain about Multitier Communications in WLS? 7. Multitier clusters require more IP sockets than a combined-tier cluster: One socket for replicating session states One socket for each Oracle WebLogic Server in the EJB cluster, for accessing remote objects As an example, using a three-node cluster, the worst-case scenario would be five open sockets per server: One primary and secondary replicated session Each server simultaneously invokes a remote EJB method on each node in the cluster.

2.

197.How many cluster Configuration Options are available in WLS? There are multiple ways to create and configure an Oracle WebLogic Server cluster: 3. 4. 5. 6. Administration Console Configuration Wizard WebLogic Scripting Tool (WLST) Using the Cluster MBean

198.Explain about Two-Phase Deployment? 7. 8. Applications are deployed using two-phase deployment (TPD). Applications are copied to the cluster and activated in two phases: Phase 1: Application components and modules are distributed to the server. Phase 2: The application is deployed if phase 1 is successful and client access is permitted. This ensures that an application is available and active on each node before clients can access it.

9.

199.How will you Deploy Applications to a Cluster? 10. All nodes must be running before an application is deployed to a cluster. 11. If phase 2 of the two-phase deployment fails, the application is still deployed to other nodes in thecluster. 12. WebLogic allows partial deployment of applications to a partitioned server. 13. Session replication for deployed applications may fail if a node is partitioned at the time of deployment. Avoid this by using the enforceClusterConstraints tag with weblogic.Deployer. Or select the Enable Cluster Constraints check box in the console. 14. Do not change cluster membership while deploying applications to the cluster. 200.Explain about HTTP Session Failover? 15. Web applications use HTTP sessions to track information in server memory for each client. 16. By default, when a client fails over to another server in the cluster, its session information is lost. 17. Oracle WebLogic Server supports several Session Replication strategies to recover sessions from failed servers: In-memory replication JDBC replication File replication 18. Replication is configured for each Web application within its weblogic.xml file. 19. Similar options are available for stateful EJB applications. 201.Explain about HTTP Session State Replication in WLS?

1. Oracle WebLogic Server provides clustering support for JSPs and servlets by
2. replicating the HTTP session state. To benefit from HTTP session state clustering, you must ensure that the session state is persistent, by configuring: In-memory replication JDBC replication File system replication You must also access the cluster via a collection of Web servers with identically configured proxy plug-ins or load-balancing hardware.

3.

4. Session persistence is configured using the <session-descriptor> element in the


weblogic.xml deploymentdescriptor file. Each persistence method has its own set of configurable parameters. 202.Explain about Replication Groups in WLS? 1. 2. 3. A replication group is a logical grouping of related servers in a cluster. WLS enables you to determine where to put backup objects using replication groups. WLS attempts to: Send backup objects to a preferred secondary replication group, if it is configured Send backup objects to a different machine Avoid sending backup objects to servers in the same replication group

203.What is the user of Replication Groups in WLS? 1. Replication groups: Represent a subset of servers within a cluster Help to determine the placement of secondary sessions (avoid replicating within the same room, forexample) Are not explicitly defined in the console-like machines and clusters WLS attempts to:

2.

Send secondary sessions to servers that are assigned to the preferred secondary replication group of the primary server Avoid sending secondary sessions to servers that are assigned to the same replication group as the primary server 204.Explain about In-Memory Replication in WLS? 1. Each users session always exists on two servers: Primary Secondary Every update to the primary session is automatically replicated on the secondary server, either: Synchronously (default) Asynchronously (batch) WLS can replicate: HttpSession objects Stateful session EJBs Session objects exist on only two servers. Secondary: The server is determined by the replication group and machine definition. The object is created immediately after the primary object is created. Primary failure makes the backup object the primary object.

2.

3.

4. 5.

6.

205.What are all the Requirements for In-Memory Replication in WLS? 1. 2. Subsequent requests from the same client must have access to the same primary object. To use in-memory replication for the HTTP session state, clients must access the cluster using either: 1. The load-balancing hardware (WLS aware)

2. 3.

A collection of Web servers, or a single Web server, with WebLogic proxy plugins (configured identically) Oracle WebLogic Server configured with HTTPClusterServlet

206.How will you Configuring In-Memory Replication in WLS? 1. 2. 3. Configure the proxy server (if applicable). Optionally define replication groups and/or machines. Specify the persistence type in the weblogic.xml deployment descriptor; the options include: 1. replicated 2. replicated_if_clustered 3. async-replication-across-cluster

207.Explain about JDBC Replication in WLS?

HTTP sessions are persisted to a database using a common JDBC data source. The required data definition language (DDL) file is available in the documentation. All members of the cluster have access to any clients session for failover purposes (no primary orsecondary). All server instances have access to all sessions. Subsequent requests from the same client can be handled by any server. Great failover capability Significant performance reduction

Changing session objects causes (slow) database synchronization.

203.What is the user of Replication Groups in WLS?

Replication groups: Represent a subset of servers within a cluster Help to determine the placement of secondary sessions (avoid replicating within the same room, for example) Are not explicitly defined in the console-like machines and clusters WLS attempts to: Send secondary sessions to servers that are assigned to the preferred secondary replication group of the primary server Avoid sending secondary sessions to servers that are assigned to the same replication group as the primary server

204.Explain about In-Memory Replication in WLS?

Each users session always exists on two servers: Primary Secondary Every update to the primary session is automatically replicated on the secondary server, either: Synchronously (default) Asynchronously (batch) WLS can replicate: HttpSession objects

Stateful session EJBs Session objects exist on only two servers. Secondary: The server is determined by the replication group and machine definition. The object is created immediately after the primary object is created. Primary failure makes the backup object the primary object.

205.What are all the Requirements for In-Memory Replication in WLS?

Subsequent requests from the same client must have access to the same primary object. To use in-memory replication for the HTTP session state, clients must access the cluster using either: The load-balancing hardware (WLS aware) A collection of Web servers, or a single Web server, with WebLogic proxy plug-ins (configured identically) Oracle WebLogic Server configured with HTTPClusterServlet

206.How will you Configuring In-Memory Replication in WLS?

Configure the proxy server (if applicable). Optionally define replication groups and/or machines. Specify the persistence type in the weblogic.xml deployment descriptor; the options include: replicated replicated_if_clustered async-replication-across-cluster

207.Explain about JDBC Replication in WLS?

HTTP sessions are persisted to a database using a common JDBC data source. The required data definition language (DDL) file is available in the documentation. All members of the cluster have access to any clients session for failover purposes (no primary orsecondary). All server instances have access to all sessions. Subsequent requests from the same client can be handled by any server. Great failover capability Significant performance reduction Changing session objects causes (slow) database synchronization.

208.How will you Configuring JDBC Replication in WLS?

Create the required table in the database. Create a JDBC data source that has read/write privileges for your database. Configure JDBC session persistence in the weblogic.xml deployment descriptor.

Ex: <session-descriptor>

<persistent-store-type>jdbc</persistent-store-type> <persistent-store-pool>MyDataSource</persistent-store-pool> </session-descriptor> 209.JDBC Persistent Table Configuration A database table named WL_SERVLET_SESSIONS must exist with read/write access:

210.Explain about File Replication? File replication is similar to JDBC replication, but it persists sessions to a highly available file system.

Session state may also be stored in a file. For file-based persistence: You must create the directory in which to store the file The file must have the appropriate access privileges

211.How will you Configuring File Replication in WLS?

Create a folder shared by all servers on the cluster on a highly available file system. Assign read/write privileges to the folder. Configure file session persistence in the weblogic.xml deployment descriptor.

Ex: <session-descriptor> <persistent-store-type>file</persistent-store-type> <persistent-store-dir>/mnt/wls_share</persistent-store-dir> </session-descriptor> 212.Explain about Cross-Cluster Replication in WLS? WebLogic provides the ability to replicate HTTP sessions across two clusters in separate domains:

o o o

This is most applicable to clusters that are distributed geographically. Configure a global proxy to direct clients back to the same cluster (cluster affinity). Configure a specific network channel for cross-cluster communication.

213.When cant I use WebLogic Store-and-Forward? You cant use the WebLogic Store-and-Forward service in the following situations:

Receiving from a remote destinationuse a message driven EJB or implement a client consumer directly. Sending messages to a local destinationsend directly to the local destination. Forwarding messages to prior releases of WebLogic Server. See Q. What is a messaging bridge?. Interoperating with third-party JMS products (for example, MQSeries). See Q. What is a messaging bridge?. When using temporary destinations with the JMSReplyTo field to return a response to a request.

Environment with low tolerance for message latency. SAF increases latency and may lower throughput.

214..Explain about Embedded LDAP Server?

o o

In WLS, users, groups, and authorization information is stored in an embedded LDAP server. Several properties can be set to manage the LDAP server, including: Credentials Backup settings Cache settings Replication settings

215.How will you create a Deployment Plan? Tools for creating a deployment plan: weblogic.PlanGenerator Administration Console o Goals for creating a deployment plan: To expose the external resource requirements of the application as variables in the deployment plan To expose additional configurable properties, such as tuning parameters as variables in the deployment plan WLS includes tools to accelerate deployment plan creation. The Administration Console: Generates a skeleton plan.xml if a plan folder is detected with a newly deployed application Updates plan.xml when you use the console to modify the deployment descriptor settings The weblogic.PlanGenerator Java class can also generate a skeleton plan.xml for an existing application.

216..Explain the relationship between Transaction and Resource Managers?

o o o

A transaction manager coordinates multiple resource managers. The 2PC protocol is used to coordinate the transaction. The XA protocol implements 2PC.

217..What is a topic subscription? A topic subscription can be thought of as an internal queue of messages waiting to be delivered to a particular subscriber. This internal queue accumulates copies of each message published to the topic after the subscription was created. Conversely, it does not accumulate messages that were sent before the subscription was created. Subscriptions are not sharable, only one subscriber may subscribe to a particular subscription at a time. 218.Explain about Trust and Identity in SSL?

o o o o

SSL and keystore are configured independently. For the purpose of backward compatibility, this release of Oracle WebLogic Server supports private keys and a trusted WebLogic Keystore provider. Identity: Private key and digital certificate (can now be looked up directly from the keystore, not necessarily as a stand-alone file outside the keystore) Trust:

Certificates of trusted Certificate authorities

219..How will you access SSL enabled applications?

o o

WLS uses SSL to secure HTTP and t3 communication. To use SSL, clients access WLS via the https or t3s protocols. https://localhost:7002/orderStock t3s://localhost:7002/useCreditCard

java server faces

Q1. What is JSF?

JSF stands for Java Server Faces. JSF has set of pre-assembled User Interface (UI). By this it means complex components are pre-coded and can be used with ease. It is event-driven programming model. By that it means that JSF has all necessary code for event handling and component organization. Application programmers can concentrate on application logic rather sending effort on these issues. It has component model that enables third-party components to be added like AJAX. Q2. What is required for JSF to get started? Following things required for JSF: JDK (Java SE Development Kit) JSF 1.2 Application Server (Tomcat or any standard application server) Integrated Development Environment (IDE) Ex. Netbeans 5.5, Eclipse 3.2.x, etc. Once JDK and Application Server is downloaded and configured, one can copy the JSF jar files to JSF project and could just start coding. :-) If IDE is used, it will make things very smooth and will save your time. Q3. What is JSF architecture? JSF was developed using MVC (a.k.a Model View Controller) design pattern so that applications can be scaled better with greater maintainability. It is driven by Java Community Process (JCP) and has become a standard. The advantage of JSF is that its both a Java Web user interface and a framework that fits well with the MVC. It provides clean separation between presentation and behavior. UI (a.k.a User Interface) can be created by page author using reusable UI components and business logic part can be implemented using managed beans. Q4. How JSF different from conventional JSP / Servlet Model?

JSF much more plumbing that JSP developers have to implement by hand, such as page navigation and validation. One can think of JSP and servlets as the oeassembly language? under the hood Q5. How the components of JSF are rendered? An Example In an application add the JSF libraries. Further in the .jsp page one has to add the tag library like: <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%> <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%> Or one can try XML style as well:

<?xml version="1.0"?> <jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html"> Once this is done, one can access the JSF components using the prefix attached. If working with an IDE (a.k.a Integrated Development Environment) one can easily add JSF but when working without them one also has to update/make the faces-config.xml and have to populate the file with classes i.e. Managed Beans between <faces-config> </faces-config> tags Q6. How to declare the Navigation Rules for JSF? Navigation rules tells JSF implementation which page to send back to the browser after a form has been submitted. For ex. for alogin page, after the login gets successful, it should go to Main page, else to return on the same login page, for that we have to code as: <navigation-rule> <from-view-id>/login.jsp</from-view-id> <navigation-case> <from-outcome>login</from-outcome> <to-view-id>/main.jsp<to-view-id> </navigation-case> <navigation-case> <from-outcome>fail</from-outcome> <to-view-id>/login.jsp<to-view-id> </navigation-case> </navigation-rule> from-outcome to be match with action attribute of the command button of the login.jsp as: <h:commandbutton value="Login" action="login"/> Secondly, it should also match with the navigation rule in face-config.xml as <managed-bean> <managed-bean-name>user</managed-bean-name> <managed-bean-class>core.jsf.LoginBean</managed-bean-class> <managed-bean-scope>session</managed-bean-scope> </managed-bean> In the UI component, to be declared / used as: <h:inputText value="#{user.name}"/> value attribute refers to name property of the user bean. Q7. How do I configure the configuration file? The configuration file used is our old web.xml, if we use some IDE it will be pretty simple to generate but the contents will be something like below: <?xml version=&quote;1.0&quote; encoding=&quote;UTF-8&quote;?> <web-app version=&quote;2.4&quote; xmlns=&quote;http://java.sun.com/xml/ns/j2ee&quote; xmlns:xsi=&quote;http://www.w3.org/2001/XMLSchema-instance&quote; xsi:schemaLocation=&quote;http://java.sun.com/xml/ns/j2ee http://java.sun.<context-param> <param-name>com.sun.faces.verifyObjects</param-name> <param-value>false</param-value> </context-param> <context-param>

<param-name>com.sun.faces.validateXml</param-name> <param-value>true</param-value> </context-param> <context-param> <param-name>javax.faces.STATE_SAVING_METHOD</param-name> <param-value>client</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>/faces/*</url-pattern> </servlet-mapping> <session-config> <session-timeout> 30 </session-timeout> </session-config> <welcome-file-list> <welcome-file> index.jsp </welcome-file> </welcome-file-list> </web-app> The unique thing about this file is ?servlet mapping?. JSF pages are processed by a servlet known to be part of JSF implementation code. In the example above, it has extension of .faces. It would be wrong to point your browser tohttp://localhost:8080/MyJSF/login.jsp, but it has to be http://localhost:8080/MyJSF/login.faces. If you want that your pages to be with .jsf, it can be done with small modification :-), <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> <servlet-mapping> Q8. What is JSF framework? JSF framework can be explained with the following diagram: As can be seen in Figure 1, JSF interacts with Client Devices which ties together with presentation, navigation and event handling and business logic of web tier model. Hence JSF is limited to presentation logic / tier. For Database tier i.e. Database and Web services one has to rely on other services.

of the high-level JSF framework. Q9. How does JSF depict the MVC (a.k.a Model View Controller) model? The data that is manipulated in form or the other is done by model. The data presented to user in one form or the other is done by view. JSF is connects the view and the model. View can be depicted as shown by: <h:inputText value="#{user.name}"/> JSF acts as controller by way of action processing done by the user or triggering of an event. For ex. <h:commandbutton value="Login" action="login"/> , this button event will triggered by the user on Button press, which will invoke the login Bean

as stated in the faces-config.xml file. Hence, it could be summarized as below: User Button Click -> form submission to server -> invocation of Bean class -> result thrown by Bean class caught be navigation rule -> navigation rule based on action directs to specific page. Q10. What does it mean by rendering of page in JSF? Every JSF page as described has various components made with the help of JSF library. JSF may contain h:form, h:inputText, h:commandButton, etc. Each of these are rendered (translated) to HTML output. This process is called encoding. The encoding procedure also assigns each component with a unique ID assigned by framework. The ID generated is random. Q11. What is JavaServer Faces? JavaServer Faces (JSF) is a user interface (UI) framework for Java web applications. It is designed to significantly ease the burden of writing and maintaining applications that run on a Java application server and render their UIs back to a target client. JSF provides ease-ofuse in the following ways: Makes it easy to construct a UI from a set of reusable UI components Simplifies migration of application data to and from the UI Helps manage UI state across server requests Provides a simple model for wiring client-generated events to server-side application code Allows custom UI components to be easily built and re-used Most importantly, JSF establishes standards which are designed to be leveraged by tools to provide a developer experience which is accessible to a wide variety of developer types, ranging from corporate developers to systems programmers. A "corporate developer" is characterized as an individual who is proficient in writing procedural code and business logic, but is not necessarily skilled in object-oriented programming. A "systems programmer" understands object-oriented fundamentals, including abstraction and designing for re-use. A corporate developer typically relies on tools for development, while a system programmer may define his or her tool as a text editor for writing code. Therefore, JSF is designed to be tooled, but also exposes the framework and programming model as APIs so that it can be used outside of tools, as is sometimes required by systems programmers. Q12. How to pass a parameter to the JSF application using the URL string? if you have the following URL: http://your_server/your_app/product.jsf?id=777, you access the passing parameter id with the following lines of java code: FacesContext fc = FacesContext.getCurrentInstance(); String id = (String) fc.getExternalContext().getRequestParameterMap().get("id"); From the page, you can access the same parameter using the predefined variable with name param. For example, <h:outputText value="#{param['id']}" /> Note: You have to call the jsf page directly and using the servlet mapping. Q13. How to add context path to URL for outputLink? Current JSF implementation does not add the context path for outputLink if the defined path starts with '/'. To correct this problem use #{facesContext.externalContext.requestContextPath} prefix at the beginning of the outputLink value attribute. For example: <h:outputLink value="#{facesContext.externalContext.requestContextPath}/myPage.faces"> Q14 How to get current page URL from backing bean? You can get a reference to the HTTP request object via FacesContext like this: FacesContext fc = FacesContext.getCurrentInstance(); HttpServletRequest request = (HttpServletRequest) fc.getExternalContext().getRequest(); and then use the normal request methods to obtain path information. Alternatively, context.getViewRoot().getViewId(); will return you the name of the current JSP (JSF view IDs are basically just JSP path names). Q15. How to access web.xml init parameters from java code? You can get it using externalContext getInitParameter method. For example, if you have:

<context-param> <param-name>connectionString</param-name> <param-value>jdbc:oracle:thin:scott/tiger@cartman:1521:O901DB</param-value> </context-param> You can access this connection string with: FacesContext fc = FacesContext.getCurrentInstance(); String connection = fc.getExternalContext().getInitParameter("connectionString"); Q16. How to access web.xml init parameters from jsp page? You can get it using initParam pre-defined JSF EL valiable. For example, if you have: <context-param> <param-name>productId</param-name> <param-value>2004Q4</param-value> </context-param> You can access this parameter with #{initParam['productId']} . For example: Product Id: <h:outputText value="#{initParam['productId']}"/> Q17. How to terminate the session? In order to terminate the session you can use session invalidate method. This is an example how to terminate the session from the action method of a backing bean: public String logout() { FacesContext fc = FacesContext.getCurrentInstance(); HttpSession session = (HttpSession) fc.getExternalContext().getSession(false); session.invalidate(); return "login_page"; } The following code snippet allows to terminate the session from the jsp page: <% session.invalidate(); %> <c:redirect url="loginPage.jsf" /> Q18. How to implement "Please, Wait..." page? The client-side solution might be very simple. You can wrap the jsp page (or part of it you want to hide) into the DIV, then you can add one more DIV that appears when user clicks the submit button. This DIV can contain the animated gif you speak about or any other content. Scenario: when user clicks the button, the JavaScript function is called. This function hides the page and shows the "Wait" DIV. You can customize the look-n-fill with CSS if you like. This is a working example: <%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %> <%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %> <f:loadBundle basename="demo.bundle.Messages" var="Message"/> <html> <head> <title>Input Name Page</title> <script> function gowait() { document.getElementById("main").style.visibility="hidden"; document.getElementById("wait").style.visibility="visible"; } </script> </head> <body bgcolor="white"> <f:view> <div id="main"> <h1><h:outputText value="#{Message.inputname_header}"/></h1> <h:messages style="color: red"/> <h:form id="helloForm"> <h:outputText value="#{Message.prompt}"/> <h:inputText id="userName" value="#{GetNameBean.userName}" required="true"> <f:validateLength minimum="2" maximum="20"/> </h:inputText> <h:commandButton onclick="gowait()" id="submit" action="#{GetNameBean.action}"

</h:form> </div> <div id="wait" style="visibility:hidden; position: absolute; top: 0; left: 0"> <table width="100%" height ="300px"> <tr> <td align="center" valign="middle"> <h2>Please, wait...</h2> </td> </tr> </table> </div> </f:view> </body> </html> If you want to have an animated gif of the "Wait" Page, the gif should be reloaded after the form is just submitted. So, assign the id for your image and then add reload code that will be called after some short delay. For the example above, it might be: <script> function gowait() { document.getElementById("main").style.visibility="hidden"; document.getElementById("wait").style.visibility="visible"; window.setTimeout('showProgress()', 500); } function showProgress(){ var wg = document.getElementById("waitgif"); wg.src=wg.src; } </script> .... .... .... <img id="waitgif" src="animated.gif"> Q19. How to reload the page after ValueChangeListener is invoked? At the end of the ValueChangeListener, call FacesContext.getCurrentInstance().renderResponse() Q20. How to download PDF file with JSF? This is an code example how it can be done with action listener of the backing bean. Add the following method to the backing bean: public void viewPdf(ActionEvent event) { String filename = "filename.pdf"; // use your own method that reads file to the byte array byte[] pdf = getTheContentOfTheFile(filename); FacesContext faces = FacesContext.getCurrentInstance(); HttpServletResponse response = (HttpServletResponse) faces.getExternalContext().response.setContentType("application/pdf"); response.setContentLength(pdf.length); response.setHeader( "Content-disposition", "inline; filename=\""+fileName+"\""); try { ServletOutputStream out; out = response.getOutputStream(); out.write(pdf); } catch (IOException e) { e.printStackTrace(); } faces.responseComplete(); } This is a jsp file snippet:

<h:commandButton immediate="true" actionListener="#{backingBean.viewPdf}" value="Read Q21. How to show Confirmation Dialog when user Click the Command Link? h:commandLink assign the onclick attribute for internal use. So, you cannot use it to write your own code. This problem will fixed in the JSF 1.2. For the current JSF version you can use onmousedown event that occurs before onclick. <script language="javascript"> function ConfirmDelete(link) { var delete = confirm('Do you want to Delete?'); if (delete == true) { link.onclick(); } } </script> . . . . <h:commandLink action="delete" onmousedown="return ConfirmDelete(this);"> <h:outputText value="delete it"/> </h:commandLink> Q22. What is the different between getRequestParameterMap() and getRequestParameterValuesMap() getRequestParameterValuesMap() similar to getRequestParameterMap(), but contains multiple values for for the parameters with the same name. It is important if you one of the components such as <h:selectMany>. Q23. Is it possible to have more than one Faces Configuration file? Yes. You can define the list of the configuration files in the web.xml. This is an example: <context-param> <param-name>javax.faces.CONFIG_FILES</param-name> <param-value>/WEB-INF/faces-config-navigation.xml,/WEB-INF/facesbeans.xml</param-</context-param> Note: Do not register /WEB-INF/faces-config.xml file in the web.xml . Otherwise, the JSF implementation will process it twice. Hi there, I guess the Note: column should have been meant or intended for "facesconfig.xml" file as thats the default configuration file for JSF (which is similar to strutsconfig.xml for Struts!!). faces-context.xml file sounds like the user defined config file similar to the aforementioned two xml files. Q24. How to mask actual URL to the JSF page? You'll need to implement your own version of javax.faces.ViewHandler which does what you need. Then, you register your own view handler in faces-config.xml. Here's a simple abstract ViewHandler you can extend and then implement the 3 abstract methods for. The abstract methods you override here are where you'll do your conversions to/from URI to physical paths on the file system. This information is just passed right along to the default ViewHandler for JSF to deal with in the usual way. For example, you could override these methods to add and remove the file extension of an incoming view id (like in your example), for extension-less view URIs. import java.io.IOException; import java.util.Locale; import javax.faces.FacesException; import javax.faces.application.ViewHandler; import javax.faces.component.UIViewRoot; import javax.faces.context.FacesContext; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * A facade view handler which maps URIs into actual physical views that the * underlying implementation can deal with regularly. * Therefore, all internal references to view ids, for example in faces-config, * will use the path to the physical files. Everything publicized, however, will * see a "converted" / facade url. */ public abstract class SimpleConverterViewHandler extends ViewHandler { private static final Log LOG =

LogFactory.getLog(SimpleConverterViewHandler.class); private final ViewHandler base; public SimpleConverterViewHandler(ViewHandler base) { this.base = base; } /** * Distinguishes a URI from a physical file view. * Tests if a view id is in the expected format -- the format corresponding * to the physical file views, as opposed to the URIs. * This test is necessary because JSF takes the view ID from the * faces-config navigation, and calls renderView() on it, etc. */ public abstract boolean isViewFormat(FacesContext context, String viewId); /** * Convert a private file path (view id) into a public URI. */ public abstract String convertViewToURI(FacesContext context, String viewId); /** * Convert a public URI into a private file path (view id) * note: uri always starts with "/"; */ public abstract String convertURIToView(FacesContext context, String uri); public String getActionURL(FacesContext context, String viewId) { // NOTE: this is used for FORM actions. String newViewId = convertViewToURI(context, viewId); LOG.debug("getViewIdPath: " + viewId + "->" + newViewId); return base.getActionURL(context, newViewId); } private String doConvertURIToView(FacesContext context, String requestURI) { if (isViewFormat(context, requestURI)) { return requestURI; } else { return convertURIToView(context, requestURI); } } public void renderView(FacesContext context, UIViewRoot viewToRender) throws IOException, FacesException { if (null == context || null == viewToRender) throw new NullPointerException("null context or view"); String requestURI = viewToRender.getViewId(); String newViewId = doConvertURIToView(context, requestURI); LOG.debug("renderView: " + requestURI + "->" + newViewId); viewToRender.setViewId(newViewId); base.renderView(context, viewToRender); } public UIViewRoot restoreView(FacesContext context, String viewId) { String newViewId = doConvertURIToView(context, viewId); LOG.debug("restoreView: " + viewId + "->" + newViewId); return base.restoreView(context, newViewId); } public Locale calculateLocale(FacesContext arg0) { return base.calculateLocale(arg0); } public String calculateRenderKitId(FacesContext arg0) { return base.calculateRenderKitId(arg0); } public UIViewRoot createView(FacesContext arg0, String arg1) { return base.createView(arg0, arg1); }

public String getResourceURL(FacesContext arg0, String arg1) { return base.getResourceURL(arg0, arg1); } public void writeState(FacesContext arg0) throws IOException { base.writeState(arg0); } } Q25. How to print out html markup with h:outputText? The h:outputText has attribute escape that allows to escape the html markup. By default, it equals to "true". It means all the special symbols will be replaced with '&' codes. If you set it to "false", the text will be printed out without ecsaping. For example, <h:outputText value="<b>This is a text</b>"/> will be printed out like: <b>This is a text</b> In case of <h:outputText escape="false" value="<b>This is a text</b>"/> you will get: This is a text Q26. h:inputSecret field becomes empty when page is reloaded. How to fix this? Set redisplay=true, it is false by default.

Servlets 1) Is it the "servlets" directory or the "servlet" directory? For Java Web Server:

on the file system, it's "servlets" c:\JavaWebServer1.1\servlets\DateServlet.class

in a URL path, it's "servlet" http://www.stinky.com/servlet/DateServlet

2) How do I support both GET and POST protocol from the same Servlet? The easy way is, just support POST, then have your doGet method call your doPost method:

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doPost(req, res); } 3) How do I ensure that my servlet is thread-safe? This is actually a very complex issue. A few guidelines: 1. The init() method is guaranteed to be called once per servlet instance, when the servlet is loaded. You don't have to worry about thread safety inside this method, since it is only called by a single thread, and the web server will wait until that thread exits before sending any more threads into your service() method. Every new client request generates (or allocates) a new thread; that thread calls the service() method of your servlet (which may in turn call doPost(), doGet() and so forth).

2.

3. Under most circumstances, there is only one instance of your servlet, no matter how many
client requests are in process. That means that at any given moment, there may be many threads running inside the service() method of your solo instance, all sharing the same instance data and potentially stepping on each other's toes. This means that you should be careful to synchronize access to shared data (instance variables) using the synchronized keyword. (Note that the server will also allocate a new instance if you register the servlet with a new name and, e.g., new init parameters.) 4. 5. Note that you need not (and should not) synchronize on local data or parameters. And especially you shouldn't synchronize the service() method! (Or doPost(), doGet() et al.) A simple solution to synchronizing is to always synchronize on the servlet instance itself using &quot;synchronized (this) { ... }&quot;. However, this can lead to performance bottlenecks; you're usually better off synchronizing on the data objects themselves. If you absolutely can't deal with synchronizing, you can declare that your servlet &quot;implements SingleThreadModel&quot;. This empty interface tells the web server to only send one client request at a time into your servlet. From the JavaDoc: &quot;If the target servlet is flagged with this interface, the servletprogrammer is guaranteed that no two threads will execute concurrently the service method of that servlet. This guarantee is ensured by maintaining a pool of servlet instances for each such servlet, and dispatching each service call to a free servlet. In essence, if the servlet implements this interface, the servlet will be thread safe.&quot; Note that this is not an ideal solution, since performance may suffer (depending on the size of the instance pool), plus it's more difficult to share data across instances than within a single instance. See also What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?

6.

7. To share data across successive or concurrent requests, you can use either instance variables
or class-static variables, or use Session Tracking.

8. The destroy() method is not necessarily as clean as the init() method. The server calls
destroy either after all service calls have been completed, or after a certain number of seconds have passed, whichever comes first. This means that other threads might be running service requests at the same time as your destroy() method is called! So be sure to synchronize, and/or wait for the other requests to quit. Sun's Servlet Tutorial has an example of how to do this with reference counting. destroy() can not throw an exception, so if something bad happens, call log() with a helpful message (like the exception). See the &quot;closing a JDBC connection&quot; example in Sun's Tutorial.

9.

4) What is the difference between URL encoding, URL rewriting, HTML escaping, and entity encoding? URL Encoding is a process of transforming user input to a CGI form so it is fit for travel across the network -- basically, stripping spaces and punctuation and replacing with escape characters. URL Decoding is the reverse process. To perform these operations, call java.net.URLEncoder.encode() and java.net.URLDecoder.decode() (the latter was (finally!) added to JDK 1.2, aka Java 2). Example: changing "We're #1!" into "We%27re+%231%21" URL Rewriting is a technique for saving state information on the user's browser between page hits. It's sort of like cookies, only the information gets stored inside the URL, as an additional parameter. The HttpSession API, which is part of the Servlet API, sometimes uses URL Rewriting when cookies are unavailable.

Example: changing <A HREF="nextpage.html"> into <A HREF="nextpage.html;$sessionid$=DSJFSDKFSLDFEEKOE"> (or whatever the actual syntax is; I forget offhand) (Unfortunately, the method in the Servlet API for doing URL rewriting for session management is called encodeURL(). Sigh...) There's also a feature of the Apache web server called URL Rewriting; it is enabled by the mod_rewrite module. It rewrites URLs on their way in to the server, allowing you to do things like automatically add a trailing slash to a directory name, or to map old file names to new file names. This has nothing to do with servlets. For more information, see the Apache FAQ (http://www.apache.org/docs/misc/FAQ.html#rewrite-more-config) . 5) How do I upload a file to my servlet or JSP? On the client side, the client's browser must support form-based upload. Most modern browsers do, but there's no guarantee. For example,

<FORM ENCTYPE='multipart/form-data' method='POST' action='/myservlet'> <INPUT TYPE='file' NAME='mptest'> <INPUT TYPE='submit' VALUE='upload'> </FORM> The input type &quot;file&quot; brings up a button for a file select box on the browser together with a text field that takes the file name once selected. The servlet can use the GET method parameters to decide what to do with the upload while the POST body of the request contains the file data to parse. When the user clicks the "Upload" button, the client browser locates the local file and sends it using HTTP POST, encoded using the MIME-type multipart/form-data. When it reaches your servlet, your servlet must process the POST data in order to extract the encoded file. You can learn all about this format in RFC 1867. Unfortunately, there is no method in the Servlet API to do this. Fortunately, there are a number of libraries available that do. Some of these assume that you will be writing the file to disk; others return the data as an InputStream.

Jason Hunter's MultipartRequest (available from http://www.servlets.com/) Apache Jakarta Commons Upload (package org.apache.commons.upload) "makes it easy to add robust, high-performance, file upload capability to your servlets and web applications" CParseRFC1867 (available from http://www.servletcentral.com/). HttpMultiPartParser by Anil Hemrajani, at the isavvix Code Exchange There is a multipart/form parser availailable from Anders Kristensen (http://wwwuk.hpl.hp.com/people/ak/java/,ak@hplb.hpl.hp.com) at http://wwwuk.hpl.hp.com/people/ak/java/#utils. JavaMail also has MIME-parsing routines (see the Purple Servlet References). Jun Inamori has written a class called org.apache.tomcat.request.ParseMime which is available in the TomcatCVS tree. JSPSmart has a free set of JSP for doing file upload and download. UploadBean by JavaZoom claims to handle most of the hassle of uploading for you, including writing to disk or memory. There's an Upload Tag in dotJ

Once you process the form-data stream into the uploaded file, you can then either write it to disk, write it to a database, or process it as an InputStream, depending on your needs. See How can I

access or create a file or folder in the current directory from inside a servlet? and other questions in the Servlets:Files Topic for information on writing files from a Servlet. Please note that you can't access a file on the client system directly from a servlet; that would be a huge security hole. You have to ask the user for permission, and currently form-based upload is the only way to do that. 6) How does a servlet communicate with a JSP page? The following code snippet shows how a servlet instantiates a bean and initializes it with FORM data posted by a browser. The bean is then placed into the request, and the call is then forwarded to the JSP page, Bean1.jsp, by means of a request dispatcher for downstream processing.

public void doPost (HttpServletRequest request, HttpServletResponse response) { try { govi.FormBean f = new govi.FormBean(); String id = request.getParameter("id"); f.setName(request.getParameter("name")); f.setAddr(request.getParameter("addr")); f.setAge(request.getParameter("age")); //use the id to compute //additional bean properties like info //maybe perform a db query, etc. // . . . f.setPersonalizationInfo(info); request.setAttribute("fBean",f); getServletConfig().getServletContext().getRequestDispatcher ("/jsp/Bean1.jsp").forward(request, response); } catch (Exception ex) { ... } } The JSP page Bean1.jsp can then process fBean, after first extracting it from the default request scope via the useBean action.

<jsp:useBean id="fBean" class="govi.FormBean" scope="request"/> <jsp:getProperty name="fBean" property="name" /> <jsp:getProperty name="fBean" property="addr" /> <jsp:getProperty name="fBean" property="age" /> <jsp:getProperty name="fBean" property="personalizationInfo" /> 7) What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization? Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading. Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In

that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool. 8) Can a servlet maintain a JTA UserTransaction object across multiple servlet invocations? No. A JTA transaction must start and finish within a single invocation (of the service() method). Note that this question does not address servlets that maintain and manipulate JDBC connections, including a connection's transaction handling. 9) How does the performance of JSP pages compare with that of servlets? How does it compare with Perl scripts? The performance of JSP pages is very close to that of servlets. However, users may experience a perceptible delay when a JSP page is accessed for the very first time. This is because the JSP page undergoes a "translation phase" wherein it is converted into a servlet by the JSP engine. Once this servlet is dynamically compiled and loaded into memory, it follows the servlet life cycle for request processing. Here, the jspInit() method is automatically invoked by the JSP engine upon loading the servlet, followed by the _jspService() method, which is responsible for request processing and replying to the client. Do note that the lifetime of this servlet is non-deterministic - it may be removed from memory at any time by the JSP engine for resource-related reasons. When this happens, the JSP engine automatically invokes the jspDestroy() method allowing the servlet to free any previously allocated resources. Subsequent client requests to the JSP page do not result in a repeat of the translation phase as long as the servlet is cached in memory, and are directly handled by the servlet's service() method in a concurrent fashion (i.e. the service() method handles each client request within a seperate thread concurrently.) There have been some recent studies contrasting the performance of servlets with Perl scripts running in a "real-life" environment. The results are favorable to servlets, especially when they are running in a clustered environment. 10) How do I call one servlet from another servlet? [ Short answer: there are several ways to do this, including


- Alex ]

use a RequestDispatcher use a URLConnection or HTTPClient send a redirect call getServletContext().getServlet(name) (deprecated, doesn't work in 2.1+)

It depends on what you mean by "call" and what it is you seek to do and why you seek to do it. If the end result needed is to invoke the methods then the simplest mechanism would be to treat the servlet like any java object , create an instance and call the mehods. If the idea is to call the service method from the service method of another servlet, AKA forwarding the request, you could use the RequestDispatcher object.

If, however, you want to gain access to the instance of the servlet that has been loaded into memory by the servlet engine, you have to know the alias of the servlet. (How it is defined depends on the engine.) For example, to invoke a servlet in JSDK a servlet can be named by the property

myname.code=com.sameer.servlets.MyServlet The code below shows how this named servlet can be accessed in the service method of another servlet

public void service (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... MyServlet ms=(MyServlet) getServletConfig().getServletContext().getServlet("myname"); ... } That said, This whole apporach of accessing servlets in another servlets has been deprecated in the 2.1 version of the servlet API due to the security issues. The cleaner and better apporach is to just avoid accessing other servlets directly and use the RequestDispatcher instead. 11) What are all the different kinds of servers? (Such as Web Servers, Application Servers, etc) The servers involved in handling and processing a user's request break down into a few basic types, each of which may have one or more tasks it solves. This flexibility gives developers a great deal of power over how applications will be created and deployed, but also leads to confusion over what server is able to, or should, perform a specific task. Starting at the basic level, a user is typically submitting a request to a system through a web browser. (We are conveniently ignoring all other types of clients (RMI, CORBA, COM/DCOM, Custom, etc..) for the time being for purposes of clarity.) The web request must be received by a Web Server (otherwise known as an HTTP Server) of some sort. This web server must handle standard HTTP requests and responses, typically returning HTML to the calling user. Code that executes within the server environment may be CGI driven, Servlets, ASP, or some other server-side programming language, but the end result is that the web server will pass back HTML to the user. The web server may need to execute an application in response to the users request. It may be generating a list of news items, or handling a form submission to a guest book. If the server application is written as a Java Servlet, it will need a place to execute, and this place is typically called a Servlet Engine. Depending on the web server, this engine may be internal, external, or a completely different product. This engine is continually running, unlike a traditional CGI environment where a CGI script is started upon each request to the server. This persistance gives a servlet connection and thread pooling, as well as an easy way to maintain state between each HTTP request. JSP pages are usually tied in with the servlet engine, and would execute within the same space/application as the servlets. There are many products that handle the web serving and the servlet engine in different manners. Netscape/iPlanet Enterprise Server builds the servlet engine directly into the web server and runs within the same process space. Apache requires that a servlet engine run in an external process, and will communicate to the engine via TCP/IP sockets. Other servers, such as MS IIS don't officially support servlets, and require add-on products to add that capability. When you move on to Enterprise JavaBeans (and other J2EE components like JMS and CORBA) you move into the application server space. An Application Server is any server that supplies additional

functionality related to enterprise computing -- for instance, load balancing, database access classes, transaction processing, messaging, and so on. EJB Application Servers provide an EJB container, which is the environment that beans will execute in, and this container will manage transactions, thread pools, and other issues as necessary. These application servers are usually stand-alone products, and developers would tie their servlets/JSP pages to the EJB components via remote object access APIs. Depending on the application server, programmers may use CORBA or RMI to talk to their beans, but the baseline standard is to use JNDI to locate and create EJB references as necessary. Now, one thing that confuses the issue is that many application server providers include some or all of these components in their product. If you look at WebLogic (http://www.beasys.com/) you will find that WebLogic contains a web server, servlet engine, JSP processor, JMS facility, as well as an EJB container. Theoretically a product like this could be used to handle all aspects of site development. In practice, you would most likely use this type of product to manage/serve EJB instances, while dedicated web servers handle the specific HTTP requests. 12) Should I override the service() method? No. It provides a fair bit of housekeeping that you'd just have to do yourself. If you need to do something regardless of whether the request is e.g., a POST or a GET, create a helper method and call that at the beginning of e.g., doPost() and doGet(). 13) How can my application get to know when a HttpSession is removed (when it timeouts)? Define a class, say SessionTimeoutNotifier, that implements javax.servlet.http.HttpSessionBindingListener. Create a SessionTimeoutNotifier object and add it to the user session. When the session is removed, SessionTimeoutNotifier.valueUnbound() will be called by the servlet engine. You can implement valueUnbound() to do whatever you want. 14) Why use JSP when we can do the same thing with servlets? [Original question: Why should I use JSP when there is already servlet technology available for serving dynamic content?] While JSP may be great for serving up dynamic Web content and separating content from presentation, some may still wonder why servlets should be cast aside for JSP. The utility of servlets is not in question. They are excellent for server-side processing, and, with their significant installed base, are here to stay. In fact, architecturally speaking, you can view JSP as a high-level abstraction of servlets that is implemented as an extension of the Servlet 2.1 API. Still, you shouldn't use servlets indiscriminately; they may not be appropriate for everyone. For instance, while page designers can easily write a JSP page using conventional HTML or XML tools, servlets are more suited for back-end developers because they are often written using an IDE -- a process that generally requires a higher level of programming expertise. When deploying servlets, even developers have to be careful and ensure that there is no tight coupling between presentation and content. You can usually do this by adding a third-party HTML wrapper package like htmlKona to the mix. But even this approach, though providing some flexibility with simple screen changes, still does not shield you from a change in the presentation format itself. For example, if your presentation changed from HTML to DHTML, you would still need to ensure that wrapper packages were compliant with the new format. In a worst-case scenario, if a wrapper package is not available, you may end up hardcoding the presentation within the dynamic content. So, what is the solution? One approach would be to use both JSP and servlet technologies for building application systems.

15) How do I send information and data back and forth between applet and servlet using the HTTP protocol? Use the standard java.net.URL class, or "roll your own" using java.net.Socket. See the HTTP spec at W3C for more detail. Note: The servlet cannot initiate this connection! If the servlet needs to asynchronously send a message to the applet, then you must open up a persistent socket using java.net.Socket (on the applet side), and java.net.ServerSocket and Threads (on the server side). 16) Can I get the path of the current servlet where it lives on the file system (not its URL)? Try using:

request.getRealPath(request.getServletPath()) An example may be:

out.println(request.getRealPath(request.getServletPath())); 17) How can I daisy chain servlets together such that the output of one servlet serves as the input to the next? There are two common methods for chaining the output of one servlet to another servlet : i. ii. the first method is the aliasing which describes a series of servlets to be executed the second one is to define a new MIME-Type and associate a servlet as handlers As I don't really use the second one, I'll focus on the aliasing.

To chain servlets together, you have to specify a sequential list of servlets and associate it to an alias. When a request is made to this alias, the first servlet in the list is invoked, processed its task and sent the ouptut to the next servlet in the list as the request object. The output can be sent again to another servlets. To accomplish this method, you need to configure your servlet engine (JRun, JavaWeb server, JServ ...). For example to configure JRun for servlet chaining, you select the JSE service (JRun servlet engine) to access to the JSE Service Config panel. You have just to define a new mapping rule where you define your chaining servlet. Let say /servlets/chainServlet for the virtual path and a comma separated list of servlets as srvA,srvB. So when you invoke a request like http://localhost/servlets/chainServlet, internally the servlet srvA will be invoked first and its results will be piped into the servlet srvB. The srvA servlet code should look like :

public class srvA extends HttpServlet { ... public void doGet (...) {

PrintWriter out =res.getWriter(); rest.setContentType("text/html"); ... out.println("Hello Chaining servlet"); } }

All the servlet srvB has to do is to open an input stream to the request object and read the data into a BufferedReader object as for example :

BufferedReader b = new BufferedReader( new InputStreamReader(req.getInputStream() ) ); String data = b.readLine(); b.close(); After that you can format your output with the data. It should work straigthforward with Java Web Server or Jserv too. Just look at in their documentation to define an alias name. Hope that it'll help. 18) Why there are no constructors in servlets? A servlet is just like an applet in the respect that it has an init() method that acts as a constrcutor. Since the servlet environment takes care of instantiating the servlet, an explicit constructor is not needed. Any initialization code you need to run should be placed in the init() method since it gets called when the servlet is first loaded by the servlet container. 19) How to handle multiple concurrent database requests/updates when using JDBC with servlets? All the dbms provide the facility of locks whenever the data is being modified. There can be two scenarios: 1. 2. Multiple database updates on different rows, if you are using servlets the servlets will open multiple connections for different users. In this case there is no need to do additional programming. If database updates are on the same row then the rows are locked automatically by the dbms, hence we have to send requests to the dbms repeatatively until the lock is released by dbms.

This issue is dealt with in the JDBC documentation; look up "Transactions" and "auto-commit". It can get pretty confusing. 20) What is the difference between GenericServlet and HttpServlet? GenericServlet is for servlets that might not use HTTP, like for instance FTP servlets. Of course, it turns out that there's no such thing as FTP servlets, but they were trying to plan for future growth when they designed the spec. Maybe some day there will be another subclass, but for now, always use HttpServlet.

21) How do you share session objects between servlets and JSP? Sharing sessions between a servlet and a JSP page is straight forward. JSP makes it a little easy by creating a session object and making it availabe already. In a servlet you would have to do it yourself. This is how:

//create a session if one is not created already now HttpSession session = request.getSession(true); //assign the session variable to a value. session.putValue("variable","value"); in the jsp page this is how you get the session value:

<% session.getValue("varible"); %> 22) What is a servlet? A servlet is a way of extending your web server with a Java program to perform tasks previously dealt with by CGI scripts or proprietary server extension frameworks. 23) Is there any method to unload a servlet from Web Server memory without restarting the server? There is no standard method/mechanism to unload a servlet from memory. Some servers, like JWS, provide the means to load and unload servlets from their administration module. Others, like Tomcat, require you to just replace the WAR file. 24) What distinguishes a JavaBean from a Servlet? JavaBeans are a set of rules to follow to create reusable software components, or beans. This contains properties and events. At the end you have a component which could be examined by a program (like an IDE) to allow the user of your JavaBean component to configure it and to run in its Java programs. Servlets are Java classes running in a Servlet engine implementing a particular interface: Servlet, forcing you to implement some methods (service()). The servlet is an extension of your web server where this servlet is running on and only lets you know when a user requests a GET or POST calls from a web page to your servlet. So, both have nothing in common except Java. 25) How much data we can store in a session object? Any amount of data can be stored there because the session is kept on the server side. The only limitation is sessionId length, which shouldn't exceed ~4000 bytes - this limitation is implied by HTTP header length limitation to 4Kb since sessionId may be stored in the cookie or encoded in URL (using "URL rewriting") and the cookie specification says the size of cookie as well as HTTP request (e.g. GET /document.html\n) cannot be longer then 4kb.

26) What is the difference between the doGet and doPost methods? doGet is called in response to an HTTP GET request. This happens when users click on a link, or enter a URL into the browser's address bar. It also happens with some HTML FORMs (those with METHOD="GET" specified in the FORM tag). doPost is called in response to an HTTP POST request. This happens with some HTML FORMs (those with METHOD="POST" specified in the FORM tag). Both methods are called by the default (superclass) implementation of service in the HttpServlet base class. You should override one or both to perform your servlet's actions. You probably shouldn't override service(). 27) What is the difference between encodeRedirectUrl and encodeURL? encodeURL and encodeRedirectURL are methods of the HttpResponse object. Both rewrite a raw URL to include session data if necessary. (If cookies are on, both are no-ops.) encodeURL is for normal links inside your HTML pages. encodeRedirectURL is for a link you're passing to response.sendRedirect(). It has slightly different syntax requirements too gory to get into here. 28) Can I use System.exit() in servlets? Gack! No no no no no... At best, you'll get a security exception. At worst, you'll make the servlet engine, or maybe the entire web server, quit. You don't really want to do that, huh? :-) 29) I am opening a single JDBC connection in my init() method. Do I need to synchronize on the Connection or the Statement object? You shouldn't have to. If your JDBC driver supports multiple connections, then the various createStatement methods will give you a thread-safe, reentrant, independent Statement that should work OK, even if other requests/threads are also accessing other Statements on the same Connection. Of course, crossing your fingers never hurts... Many early JDBC drivers were not re-entrant. The modern versions of JDBC drivers should work OK, but there are never any guarantees. Using connection pooling will avoid the whole issue, plus will lead to improved performance. See this FAQ for more information. 30) How can I determine the name and version number of the servlet or JSP engine that I am using? From within a servlet, you can invoke the ServletContext.getServerInfo() method as follows:

String thisServer= getServletConfig().getServletContext().getServerInfo(); If you are using JSP, you can use this expression:

<%= application.getServerInfo() %> 31) How can I get the absolute URL of a servlet/JSP page at runtime? You can get all the necessary information to determine the URL from the request object. To reconstruct the absolute URL from the scheme, server name, port, URI and query string you can use the URL class from java.net. The following code fragment will determine your page's absolute URL:

String file = request.getRequestURI(); if (request.getQueryString() != null) { file += '?' + request.getQueryString(); } URL reconstructedURL = new URL(request.getScheme(), request.getServerName(), request.getServerPort(), file); out.println(URL.toString()); 32) Why do GenericServlet and HttpServlet implement the Serializable interface? GenericServlet and HttpServlet implement the Serializable interface so that servlet engines can "hybernate" the servlet state when the servlet is not in use and reinstance it when needed or to duplicate servlet instances for better load balancing. I don't know if or how current servlet engines do this, and it could have serious implications, like breaking references to objects gotten in the init() method without the programmer knowing it. Programmers should be aware of this pitfall and implement servlets which are stateless as possible, delegating data store to Session objects or to the ServletContext. In general stateless servlets are better because they scale much better and are cleaner code. 33) How does one choose between overriding the doGet(), doPost(), and service() methods? The differences between the doGet() and doPost() methods are that they are called in the HttpServlet that your servlet extends by its service() method when it recieves a GET or a POST request from a HTTP protocol request. A GET request is a request to get a resource from the server. This is the case of a browser requesting a web page. It is also possible to specify parameters in the request, but the length of the parameters on the whole is limited. This is the case of a form in a web page declared this way in html: <form method="GET"> or <form>. A POST request is a request to post (to send) form data to a resource on the server. This is the case of of a form in a web page declared this way in html: <form method="POST">. In this case the size of the parameters can be much greater. The GenericServlet has a service() method that gets called when a client request is made. This means that it gets called by both incoming requests and the HTTP requests are given to the servlet as they are (you must do the parsing yourself). The HttpServlet instead has doGet() and doPost() methods that get called when a client request is GET or POST. This means that the parsing of the request is done by the servlet: you have the appropriate method called and have convenience methods to read the request parameters. NOTE: the doGet() and doPost() methods (as well as other HttpServlet methods) are called by the service() method.

Concluding, if you must respond to GET or POST requests made by a HTTP protocol client (usually a browser) don't hesitate to extend HttpServlet and use its convenience methods. If you must respond to requests made by a client that is not using the HTTP protocol, you must use service(). 34) How do servlets differ from RMI? What are the advantages and disadvantages of each technology? Servlets extend the server-side functionality of a website. Servlets communicate with other application(s) on that server (or any other server) and perform tasks above and beyond the "normal" static HTML document. A servlet can receive a request to get some information through EJB from one or more databases, then convert this data into a static HTML/WML page for the client to see, for example. Even if the servlet talks to many other applications all over the world to get this information, it still looks like it happened at that website. RMI (Remote Method Invocation) is just that - a way to invoke methods on remote machines. It is way for an application to talk to another remote machine and execute different methods, all the while appearing as if the action was being performed on the local machine. Servlets (or JSP) are mainly used for any web-related activity such as online banking, online grocery stores, stocktrading, etc. With servlets, you need only to know the web address and the pages displayed to you take care of calling the different servlets (or actions within a servlet) for you. Using RMI, you must bind the RMI server to an IP and port, and the client who wishes to talk to the remote server must know this IP and port, unless of course you used some kind of in-between lookup utility, which you could do with (of all things) servlets. 35) How can we use a servlet as a proxy for communications between two applets? One way to accomplish this is to have the applets communicate via TCP/IP sockets to the servlet. The servlet would then use a custom protocol to receive and push information between applets. However, this solution does have firewall problems if the system is to be used over and Internet verses an Intranet. 36) How can I design my servlet/JSP so that query results get displayed on several pages, like the results of a search engine? Each page should display, say, 10 records each and when the next link is clicked, I should see the next/previous 10 records and so on. Use a Java Bean to store the entire result of the search that you have found. The servlet will then set a pointer to the first line to be displayed in the page and the number of lines to display, and force a display of the page. The Action in the form would point back to the servlet in the JSP page which would determine whether a next or previous button has been pressed and reset the pointer to previous pointer + number of lines and redisplay the page. The JSP page would have a scriplet to display data from the Java Bean from the start pointer set to the maximum number of lines with buttons to allow previous or next pages to be selected. These buttons would be displayed based on the page number (i.e. if first then don't display previous button). 37) How do I deal with multi-valued parameters in a servlet? Instead of using getParameter() with the ServletRequest, as you would with single-valued parameters, use the getParameterValues() method. This returns a String array (or null) containing all the values of the parameter requested.

38) How can I pass data retrieved from a database by a servlet to a JSP page? One of the better approaches for passing data retrieved from a servlet to a JSP is to use the Model 2 architecture as shown below:

Basically, you need to first design a bean which can act as a wrapper for storing the resultset returned by the database query within the servlet. Once the bean has been instantiated and initialized by invoking its setter methods by the servlet, it can be placed within the request object and forwarded to a display JSP page as follows:

com.foo.dbBean bean = new com.foo.dbBean(); //call setters to initialize bean req.setAttribute("dbBean", bean); url="..."; //relative url for display jsp page ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher(url); rd.forward(req, res); The bean can then be accessed within the JSP page via the useBean tag as:

<jsp:useBean id="dbBean" class="com.foo.dbBean" scope="request"/> ... <% //iterate through the rows within dbBean and //access the values using a scriptlet %> Also, it is best to design your application such that you avoid placing beans into the session unless absolutely necessary. Placing large objects within the session imposes a heavy burden on the performance of the servlet engine. Of course, there may be additional design considerations to take care of - especially if your servlets are running under a clustered or fault-tolerant architecture. 39) How can I use a servlet to generate a site using frames? In general, look at each frame as a unique document capable of sending its own requests and receiving its own responses. You can create a top servlet (say, FrameServlet) that upon invocation creates the frame layout you desire and sets the SRC parameters for the frame tags to be another servlet, a static page or any other legal value for SRC.

---------------------- SAMPLE ---------------------public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = new PrintWriter (response.getWriter()); out.println(""); out.println("Your Title");

// // // //

definingthe three rows of Frames for the main page top : frm_1 middle : frm_2 bottom : frm_3

out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.close(); -------------------------- END -----------------------------------------Where MenuServlet and DummyServlet provide content and behavior for the frames generated by FrameServlet. 40) What is HTTP tunneling, in the general sense? HTTP tunneling is a general technique whereby arbitrary data may be sent via an HTTP connection to and from CGI scripts or Java Servlets on a Web server. This is done by serializing the data to be transmitted into a stream of bytes, and sending an HTTP message with content type "application/octet-stream". HTTP tunneling is also referred to as Firewall tunneling. 41) How do I handle FORMs with multiple form elements (e.g. radio buttons) using the same name? For radio buttons, the HTML spec assumes that a given group of buttons will have the same NAME and different VALUEs; the browser makes sure that only one button per group name will be selected (at most). So you can just call request.getParameter("groupname").

<input type="radio" name="topping" value="cheese" checked>Cheese <input type="radio" name="topping" value="pepperoni">Pepperoni <input type="radio" name="topping" value="anchovies">Anchovies If the user selects "Pepperoni" then request.getParameter("topping") will return the string "pepperoni". For lists using the <select multiple> FORM tag, multiple values can be returned for the same parameter name. When that can happen, use request.getParameterValues("param") which returns a String[] you can iterate through. It's bad form (so to speak), but you can also duplicate other element types, like

Name 1: <input type="text" name="name" value="Dick"> Name 2: <input type="text" name="name" value="Jane"> These also get returned in an array by request.getParameterValues().

42) How do I separate presentation (HTML) from business logic (Java) when using servlets? Almost anybody who has ever written a servlet can identify with this one. We all know it's bad for to embed HTML code in our java source; it's lame to have to recompile and re-deploy every time you want an HTML element to look a bit different. But what are our choices here? There are two basic options; 1. Use JSP: Java Server Pages allows you to embed Java code or the results of a servlet into your HTML. You could, for instance, define a servlet that gives a stock quote, then use the tag in a JSP page to embed the output. But then, this brings up the same problem; without discipline, your content/presentation and program logic are again meshed. I think the ideal here is to completely separate the two. 2. Use a templating/parsing system: Hmm...I know you're about to rant about re-inventing the wheel, but it's not that bad (see below). Plus, it really does pay to take this approach; you can have a group of programmers working on the Java code, and a group of HTML producers maintaining the interface. So now you probably want to know how to do it...so read on. Use SSI! Remember SSI? It hasn't gotten much attention in recent years because of embeddable scripting languages like ASP and JSP, but it still remains a viable option. To leverage it in the servlet world, I believe the best way is to use an API called SSI for Java from Areane. This API will let you emulate SSI commands from a templating system, and much more. It will let you execute any command on any system, including executing java classes! It also comes with several utility classes for creating stateful HTML form elements, tables for use with iteration, and much more. It's also open source, so it's free and you can tweak it to your heart's content! You can read the SSI for Java documentation for detailed info, but the following is an example of its use. Here's the servlet:

import import import import import

javax.servlet.*; javax.servlet.http.*; java.io.*; java.util.*; com.areane.www.ssi.*;

public class SSITemplatingServlet extends HttpServlet { private String templateFilesDirectory = "d:\\projects\\idemo\\templates\\"; //Holds path to template files /**Handles GET requests; defers every request to the POST processor*/ public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, FileNotFoundException {doPost(req, res);} /**Handles all requests. Processes the request, *saves the values, parses the file, then feeds the file to the out stream*/ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException, FileNotFoundException { HttpSession ses = req.getSession(true); Properties context = null; if((context = (Properties)ses.getValue("user.context")) == null) { //if properties doesn't already exist, create it.

context = new Properties();

//Write parameters to Properties object Enumeration paramNames = req.getParameterNames(); String curName, curVal; while(paramNames.hasMoreElements()) { curName = (String)paramNames.nextElement(); curVal = req.getParameter(curName); context.setProperty(curName, curVal); } //Save the values to the session ses.putValue("user.context", context); //Parse the page and stream to the client String templateName = req.getParameter("template"); // Get the file name of the template to use res.setContentType("text/html"); SsiPage page = SsiParser.parse(this.templateFilesDirectory + templateName); //Parsing occurs here page.write(res.getWriter(), context); //Stream to the client page = null; //clean up } }

Now, just create a template file, pass the servlet the template file name, and have at it! 43) For an HTML FORM with multiple SUBMIT buttons, how can a servlet ond differently for each button? The servlet will respond differently for each button based on the html that you have placed in the HTML page. Let's explain. For a submit button the HTML looks like <input type=submit name="Left" value="left">. A servlet could extract the value of this submit by using the getParameter("Left") from the HttpRequest object. It follows then that if you have HTML within a FORM that appears as:

<input type=submit name="Direction" value="left"> <input type=submit name="Direction" value="right"> <input type=submit name="Direction" value="up"> <input type=submit name="Direction" value="down">

Then the getParameter("Direction") from the HttpRequest would extract the value pressed by the user, either "left", "right", "up" or "down". A simple comparision in the servlet with the these values could occur and processing based on the submit button would be performed. Similiarly,for submit buttons with different names on a page, each of these values could be extracted using thegetParameter() call and acted on. However, in a situation where there are multiple

buttons, common practice would be to use one name and multiple values to identify the button pressed. 44) What is meant by the term "business logic"? "Business logic" is just a fancy way of saying "code." :-) More precisely, in a three-tier architecture, business logic is any code that is not specifically related to storing and retrieving data (that's "data storage code"), or to formatting data for display to the user (that's "presentation logic"). It makes sense, for many reasons, to store this business logic in separate objects; the middle tier comprises these objects. However, the divisions between the three layers are often blurry, and business logic is more of an ideal than a reality in most programs. The main point of the term is, you want somewhere to store the logic and "business rules" (another buzzword) of your application, while keeping the division between tiers clear and clean. 45) How can I explicitly unload a servlet or call the destroy method? In general, you can't. The Servlet API does not specify when a servlet is unloaded or how the destroy method is called. Your servlet engine (ie the implementation of the interfaces in the JSDK) might provide a way to do this, probably through its administration interface/tool (like Webshpere or JWS). Most servlet engines will also destroy and reload your servlet if they see that the class file(s) have been modified. 46) What is a servlet bean? A servlet bean is a serializable servlet that follows the JavaBeans component architecture, basically offering getter/setter methods. As long as you subclass GenericServlet/HttpServlet, you are automatically Serializable. If your web server supports them, when you install the servlet in the web server, you can configure it through a property sheet-like interface. 47) Why do we need to call super.init(config) in the init method of a servlet? Just do as you're told and you won't get hurt! :-) Because if you don't, then the config object will get lost. Just extend HttpServlet, use init() (no parameters) and it'll all work ok. From the Javadoc: init() - A convenience method which can be overridden so that there's no need to call super.init(config). 48) What is a servlet engine? A "servlet engine" is a program that plugs in to a web server and runs servlets. The term is obsolete; the preferred term now is "servlet container" since that applies both to plug-in engines and to standalone web servers that support the Servlet API.

49) Which is the most efficient (i.e. processing speed) way to create a server application that accesses a database: A Servlet using JDBC; a JSP page using a JavaBean to carry out the db access; or JSP combined with a Servlet? Are these my only choices? Your question really should be broken in two. 1-What is the most efficient way of serving pages from a Java object?. There you have a clear winner in the Servlet. Althought if you are going to change the static content of the page often is going to be a pain because you'll have to change Java code. The second place in speed is for JSP pages. But, depending on your application, the difference in speed between JSP pages and raw servlets can be so small that is not worth the extra work of servlet programming. 2-What is the most efficient way of accessing a database from Java?. If JDBC is the way you want to go the I'd suggest to pick as many drivers as you can (II,III,IV or wathever) and benchmark them. Type I uses a JDBC/ODBC bridge and usually has lousy performance. Again, go for the simplest (usually type IV driver) solution if that meets you performance needs. For database applications, the performance bottleneck is usually the database, not the web server/engine. In this case, the use of a package that access JDBC with connection pooling at the application level used from JSP pages (with or withouth beans as middleware) is the usual choice. Of course, your applications requirements may vary. 50) How can I change the port of my Java Web Server from 8080 to something else? It is very simple. JAVA WEB SERVER comes with remote Web administration tool. You can access this with a web browser. Administration tool is located on port 9090 on your web server. To change port address for web server: 1. 2. 3. 4. 5. 6. 7. Access tool (http://hostname:9090) Enter User Id/Password (by default it is admin/admin) Select service (Web service) Click on "manage" button. You will get a popup screen with all settings. Click on network tree node, On right hand side you will get text box for entering port no. Change port number with desire one. click on restart button.

51) Can I send multiple responses for a single request? No. That doesn't even make sense :-) You can, however, send a "redirect", which tells the user's browser to send another request, possibly to the same servlet with different parameters. Search this FAQ on "redirect" to learn more. 52) What is FORM based login and how do I use it? Also, what servlet containers support it? Form based login is one of the four known web based login mechanisms. For completeness I list all of them with a description of their nature: 1. HTTP Basic Authentication o An authentication protocol defined within the HTTP protocol (and based on headers). It indicates the HTTP realm for which access is being negotiated and sends passwords

with base64 encoding, therefore it is not very secure. (See RFC2068 for more information.) 2. HTTP Digest Authentication o Like HTTP Basic Authentication, but with the password transmitted in an encrypted form. It is more secure than Basic, but less then HTTPS Authentication which uses private keys. Yet it is not currently in widespread use. 3. HTTPS Authentication (SSL Mutual Authentication) o This security mechanism provides end user authentication using HTTPS (HTTP over SSL). It performs mutual (client & server) certificate based authentication with a set of different cipher suites. 4. Form Based Login o A standard HTML form (static, Servlet/JSP or script generated) for logging in. It can be associated with protection or user domains, and is used to authenticate previously unauthenticated users. o The major advantage is that the look and feel of the login screen can be controlled (in comparison to the HTTP browsers' built in mechanisms). To support 1., 3., and 4. of these authentication mechanisms is a requirement of the J2EE Specification (as of v1.2, 3.4.1.3 Required Login Mechanisms). (HTTP Digest Authentication is not a requirement, but containers are encouraged to support it.) You can also see section 3.3.11.1 of the J2EE Specs. (User Authentication, Web Client) for more detailed descriptions of the mechanisms. Thus any Servlet container that conforms to the J2EE Platform specification should support form based login. To be more specific, the Servlet 2.2 Specification describes/specifies the same mechanisms in 11.5 including form based login in 11.5.3. This section (11.5.3) describes in depth the nature, the requirements and the naming conventions of form based login and I suggest to take a look at it. Here is a sample of a conforming HTML login form:

<form method="POST" action="j_security_check"> <input type="text" name="j_username"> <input type="password" name="j_password"> </form> Known Servlet containers that support FORM-based login are:

iPlanet Application Server Tomcat (the reference implementation of the Java Servlet API)

53) How do I capture a request and dispatch the exact request (with all the parameters received) to another URL? As far as i know it depends on the location of the next target url.

If the next servlet url is in the same host, then you can use the forward method.

Here is an example code about using forward:

RequestDispatcher rd = null; String targetURL = "target_servlet_name"; ServletContext ctx = this.getServletContext(); rd = ctx.getRequestDispatcher(targetURL); rd.forward(request, response); 54) How can the data within an HTML form be refreshed automatically whenever there is a change in the database? JSP is intended for dynamically generating pages. The generated pages can include wml, html, dhtml or whatever you want... When you have a generated page, JSP has already made its work. From this moment you have a page. If you want automatic refreshing, then this should be acomplished by the technology included in the generated page (JSP will tell only what to include in the page). The browser can not be loaded by extern factors. The browser is the one who fetches url's since the http protocol is request-response based. If a server can reload a browser without its allow, it implies that we could be receiving pages which we haven't asked for from servers. May you could use applets and a ServerSocket for receiving incoming signals from the server for changed data in the DB. This way you can load new information inside the applet or try to force a page reload. [That's a nice idea -- it could use the showDocument() call to reload the current page. It could also use HTTP polling instead of maintaining an expensive socket connection. -Alex] Perhaps (if possible), could be simpler using an automatic JavaScript refreshing function that force page reload after a specified time interval. 55) What is a web application (or "webapp")? A web application is a collection of servlets, html pages, classes, and other resources that can be bundled and run on multiple containers from multiple vendors. A web application is rooted at a specific path within a web server. For example, a catalog application could be located at http://www.mycorp.com/catalog. All requests that start with this prefix will be routed to the ServletContext which represents the catalog application. 56) How can I call a servlet from a JSP page? How can I pass variables from the JSP that the servlet can access? You can use <jsp:forward page="/relativepath/YourServlet" /> or response.sendRedirect("http://path/YourServlet"). Variables can be sent as:

<jsp:forward page=/relativepath/YourServlet> <jsp:param name="name1" value="value1" /> <jsp:param name="name2" value="value2" /> </jsp:forward>

You may also pass parameters to your servlet by specifying response.sendRedirect("http://path/YourServlet?param1=val1"). 57) Can there be more than one instance of a servlet at one time ? It is important to note that there can be more than one instance of a given Servlet class in the servlet container. For example, this can occur where there was more than one servlet definition that utilized a specific servlet class with different initialization parameters. This can also occur when a servlet implements the SingleThreadModel interface and the container creates a pool of servlet instances to use. 58) How can I measure the file downloading time using servlets? ServletOutputStream out = response.getOutputStream(); String filename = getServletContext().getRealPath(request.getQueryString()); FileInputStream fin = new FileInputStream(filename); long start = System.currentTimeMillis(); byte data[] = new byte[1024]; int len = 0; while ((len = fin.read(data)) > 0) { out.write(data, 0, len); } out.flush(); long stop = System.currentTimeMills(); log("took " + (stop - start) + "ms to download " + filename); 59) What is inter-servlet communication? As the name says it, it is communication between servlets. Servlets talking to each other. [There are many ways to communicate between servlets, including

Request Dispatching HTTP Redirect Servlet Chaining HTTP request (using sockets or the URLConnection class) Shared session, request, or application objects (beans) Direct method invocation (deprecated) Shared static or instance variables (deprecated)

Search the FAQ, especially topic Message Passing (including Request Dispatching) for information on each of these techniques. -Alex] Basically interServlet communication is acheived through servlet chaining. Which is a process in which you pass the output of one servlet as the input to other. These servlets should be running in the same server. e.g. ServletContext.getRequestDispatcher(HttpRequest, HttpResponse).forward("NextServlet") ; You can pass in the current request and response object from the latest form submission to the next servlet/JSP. You can modify these objects and pass them so that the next servlet/JSP can use the results of this servlet. There are some Servlet engine specific configurations for servlet chaining. Servlets can also call public functions of other servlets running in the same server. This can be done by obtaining a handle to the desired servlet through the ServletContext Object by passing it the

servlet name ( this object can return any servlets running in the server). And then calling the function on the returned Servlet object. e.g. TestServlet test= (TestServlet)getServletConfig().getServletContext().getServlet("OtherServlet"); otherServletDetails= Test.getServletDetails(); You must be careful when you call another servlet's methods. If the servlet that you want to call implements the SingleThreadModel interface, your call could conflict with the servlet's single threaded nature. (The server cannot intervene and make sure your call happens when the servlet is not interacting with another client.) In this case, your servlet should make an HTTP request to the other servlet instead of direct calls. Servlets could also invoke other servlets programmatically by sending an HTTP request. This could be done by opening a URL connection to the desired Servlet. 60) How do I make servlet aliasing work with Apache+Tomcat? When you use Tomcat standalone as your web server, you can modify the web.xml in $TOMCAT_HOME/webapps/myApp/WEB-INF to add a url-pattern:

<web-app> <servlet> <servlet-name> myServlet </servlet-name> <servlet-class> myServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name> myServlet </servlet-name> <url-pattern> /jsp-bin/* </url-pattern> </servlet-mapping> </web-app> This will let you use: http://webserver:8080/myApp/jsp-bin/stuff.html instead of: http://webserver:8080/myApp/servlet/myServlet/stuff.html But it won't work on port 80 if you've integrated Tomcat with Apache. Graeme Wallace provided this trick to remedy the situation. Add the following to your tomcat-apache.conf (or to a static version of it, since tomcat re-generates the conf file every time it starts):

<LocationMatch /myApp/jsp-bin/* SetHandler jserv-servlet </LocationMatch This lets Apache turn over handling of the url pattern to your servlet.

61) Is there any way to determine the number of concurrent connections my servlet engine can handle? Depends on whether or not your servlet container uses thread pooling. If you do not use a thread pool, the number of concurrent connections accepted by Tomcat 3.1, for example, is 10. This you can see for yourself by testing a servlet with the Apache JMeter tool. However, if your servlet container uses a thread pool, you can specify the number of concurrent connections to be accepted by the container. For Tomcat 3.1, the information on how to do so is supplied with the documentation in the TOMCAT_HOME/doc/uguide directory. 62) What is a request dispatcher and how does it work? A RequestDispatcher object can forward a client's request to a resource or include the resource itself in the response back to the client. A resource can be another servlet, or an HTML file, or a JSP file, etc. You can also think of a RequestDispatcher object as a wrapper for the resource located at a given path that is supplied as an argument to the getRequestDispatcher method. For constructing a RequestDispatcher object, you can use either the ServletRequest.getRequestDispatcher() method or the ServletContext.getRequestDispatcher() method. They both do the same thing, but impose slightly different constraints on the argument path. For the former, it looks for the resource in the same webapp to which the invoking servlet belongs and the pathname specified can be relative to invoking servlet. For the latter, the pathname must begin with '/' and is interpreted relative to the root of the webapp. To illustrate, suppose you want Servlet_A to invoke Servlet_B. If they are both in the same directory, you could accomplish this by incorporating the following code fragment in either the service method or the doGet method of Servlet_A:

RequestDispatcher dispatcher = getRequestDispatcher("Servlet_B"); dispatcher.forward( request, response ); where request, of type HttpServletRequest, is the first parameter of the enclosing service method (or the doGet method) and response, of type HttpServletResponse, the second. You could accomplish the same by

RequestDispatcher dispatcher=getServletContext().getRequestDispatcher( "/servlet/Servlet_B" ); dispatcher.forward( request, response ); 63) What is a Servlet Context? A Servlet Context is a grouping under which related servlets (and JSPs and other web resources) run. They can share data, URL namespace, and other resources. There can be multiple contexts in a single servlet container. The ServletContext object is used by an individual servlet to "call back" and obtain services from the container (such as a request dispatcher). Read the JavaDoc for javax.servlet.ServletContext for more information. You can maintain "application global" variables by using Servlet Context Attributes.

64) Does the RequestDispatcher expect a relative URL to be relative to the originally-called servlet or to the current servlet (if different)? Since the RequestDispatcher will be passing the control (request object and response object) from the current Servlet, the relative URL must be relative to the current servlet. The originally called servlet has passed the control to the current servlet, and now current servlet is acting as controller to other resourses. 65) What is the difference between in-process and out-of-process servlet containers? The in-process Servlet containers are the containers which work inside the JVM of Web server, these provides good performance but poor in scalibility. The out-of-process containers are the containers which work in the JVM outside the web server. poor in performance but better in scalibility In the case of out-of-process containers, web server and container talks with each other by using the some standard mechanism like IPC. In addition to these types of containers, there is 3rd type which is stand-alone servlet containers. These are an integral part of the web server. 66) How is SingleThreadModel implemented in Tomcat? In other containers? [I would assume that Tomcat uses its connection thread pool, and creates a new instance of the servlet for each connection thread, instead of sharing one instance among all threads. Is that true?] The question mixes together two rather independent aspects of a servlet container: "concurrency control" and "thread pooling". Concurrency control, such as achieved by having a servlet implement the SingleThreadModel interface, addresses the issue of thread safety. A servlet will be thread-safe or thread-unsafe regardless of whether the servlet container used a thread pool. Thread pooling merely eliminates the overhead associated with the creation and destruction of threads as a servlet container tries to respond to multiple requests received simultaneously. It is for this reason that the specification document for Servlet 2.2 API is silent on the subject of thread pooling -- as it is merely an implementation detail. However, the document does indeed address the issue of thread safety and how and when to use SingleThreadModel servlets. Section 3.3.3.1 of the Servlet 2.2 API Specification document says that if a servlet implements the SingleThreadModel it is guaranteed "that only one request thread at time will be allowed in the service method." It says further that "a servlet container may satisfy this guarantee by serializing requests on a servlet or by maintaining a pool of servlet instances." Obviously, for superior performance you'd want the servlet container to create multiple instances of a SingleThreadModel type servlet should there be many requests received in quick succession. Whether or not a servlet container does that depends completely on the implementation. My experiments show that Tomcat 3.1 does indeed create multiple instances of a SingleThreadModel servlet, but only for the first batch of requests received concurrently. For subsequent batches of concurrent requests, it seems to use only one of those instances.

67) Which servlet containers have persistent session support? Specifically, does Tomcat 3.1? All servlet containers that implement the Servlet 2.2 API must provide for session tracking through either the use of cookies or through URL rewriting. All Tomcat servlet containers support session tracking. 68) Can I use JAAS as the authentication technology for servlets ? Yes, JAAS can be used as authentication technology for servlets. One important feature of JAAS is pure Java implementation. The JAAS infrastructure is divided into two main components: an authentication component and an authorization component. The JAAS authentication component provides the ability to reliably and securely determine who is currently executing Java code, regardless of whether the code is running as an application, an applet, a bean, or a servlet. 69) How can I set a servlet to load on startup of the container, rather than on the first request? The Servlet 2.2 spec defines a load-on-startup element for just this purpose. Put it in the <servlet> section of your web.xml deployment descriptor. It is either empty (<load-on-startup/>) or contains "a positive integer indicating the order in which the servlet should be loaded. Lower integers are loaded before higher integers. If no value is specified, or if the value specified is not a positive integer, the container is free to load it at any time in the startup sequence." For example,

<servlet> <servlet-name>foo</servlet-name> <servlet-class>com.foo.servlets.Foo</servlet-class> <load-on-startup>5</load-on-startup> </servlet> Some servlet containers also have their own techniques for configuring this; please submit feedback with information on these. 70) Is it possible to write a servlet that acts as a FTP server? Yes. It would spawn a thread that opens a ServerSocket, then listens for incoming connections and speaks the FTP protocol. 71) Is there a way to disable a user's ability to double-click a submit image/button (and therefore submitting duplicate data -- multiple submits)? Is there a way to do this with Javascript? Give the submit image (or button) an onClick() handler. Have the handler check if a flag is set and if not set the flag and submit the form and then clear the form. 72) What are the main differences between Servlets and ISAPI? The first difference is obviously that Servlets is the technology from Sun Microsystems and ISAPI is from Microsoft.

Other Differences are: i. ii. iii. iv. v. vi. vii. Servlet is a simple .class file and ISAPI is a DLL Servlets run in the Servlet containers and may be in-process or out of process. ISAs run in the same address space as the HTTP server Servlet container preprocesses and postprocesses the data communication between the client and server. ISAPI Filters provide the capability of pre-processing and post-processing of all data sent between the client and the server Java is the only choice for writing Servlets, VC++/MFC is used to write ISAPI code Servlets works on most of the Web servers plus third party containers can be integrated with other web servers to provide servlets on them. ISAPI works on only ISAPI-compliant Web server (for example, Microsoft Internet Information Server) Servlets can connect to the Databases through JDBC as well as jdbc-odbc bridges. ISAPI can connect to Databases through only ODBC Servlets have access to many server-side technologies like EJB and etc. ISAPI is limited in scope Multiple commands can be implemented in a servlet by using pathinfo. ISAPI allows multiple commands in one DLL, implemented as member functions of the CHttpServer object in the DLL. Content generation and content presentation can be done seperately in Servlets with the help of JSP. ISAPI code has to generate HTML code itself.

viii.
ix.

73) Can I associate a servlet with a particular mime-type, so if the client requests a file of that type, my servlet will be executed? In web.xml you can use a mime-mapping to map the type with a certain extension and then map the servlet to that extension. e.g.

<mime-mapping> <extension> zzz </extension> <mime-type> text/plain </mime-type> </mime-mapping> <servlet-mapping> <url> *.zzz </url> <servlet-name> MyServlet </servlet-name> </servlet-mapping> So, when a file for type zzz is requested, the servlet gets called. 74) What are the different cases for using sendRedirect() vs. getRequestDispatcher()? When you want to preserve the current request/response objects and transfer them to another resource WITHIN the context, you must use getRequestDispatcher or getNamedDispatcher.

If you want to dispatch to resources OUTSIDE the context, then you must use sendRedirect. In this case you won't be sending the original request/response objects, but you will be sending a header asking to the browser to issue a request to the new URL. If you don't need to preserve the request/response objects, you can use either. 75) How do I access the value of a cookie using JavaScript? You can manipulate cookies in JavaScript with the document.cookie property. You can set a cookie by assigning this property, and retrieve one by reading its current value. The following statement, for example, sets a new cookie with a minimum number of attributes:

document.cookie = "cookieName=cookieValue"; And the following statement displays the property's value:

alert(document.cookie); The value of document.cookie is a string containing a list of all cookies that are associated with a web page. It consists, that is, of name=value pairs for each cookie that matches the current domain, path, and date. The value of the document.cookie property, for instance, might be the following string:

cookieName1=cookieValue1; cookieName2=cookieValue2;

76) How do I write to a log file using JSP under Tomcat? Can I make use of the log() method for this? Yes, you can use the Servlet API's log method in Tomcat from within JSPs or servlets. These messages are stored in the server's log directory in a file called servlet.log. 77) How can I use a servlet to print a file on a printer attached to the client? The security in a browser is designed to restrict you from automating things like this. However, you can use JavaScript in the HTML your servlet returns to print a frame. The browser will still confirm the print job with the user, so you can't completely automate this. Also, you'll be printing whatever the browser is displaying (it will not reliably print plug-ins or applets), so normally you are restricted to HTML and images. [The JavaScript source code for doing this is:

<input type="button" onClick="window.print(0)" value="Print This Page">

78) How do you do servlet aliasing with Apache and Tomcat? Servlet aliasing is a two part process with Apache and Tomcat. First, you must map the request in Apache to Tomcat with the ApJServMount directive, e.g., ApJServMount/myservlet/ROOT Second, you must map that url pattern to a servlet name and then to a servlet class in your web.xml configuration file. Here is a sample exerpt:

<servlet> <servlet-name>myservlet</servlet-name> <servlet-class>com.mypackage.MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>myservlet</servlet-name> <url-pattern>/myservlet</url-pattern> </servlet-mapping> 79) I want my servlet page to redirect to a login page if the session has timed out. How can I know if my session has timed out? If the servlet engine does the time-out, following code should help you:

//assume you have a HttpServletRequest request if(request.getSession(false)==null) { //no valid session (timeouted=invalid) //code to redirect to login page } 80) Can Tomcat be configured to interpret all, or selected, .html files within a given context as JSP? Or, do JSP files have to end with a .jsp extension? yes you can do that by modifying the web.xml file. You will have to invoke the org.apache.jasper.runtime.JspServlet for all the requests having extension .html. You can do that by changing the Servlet mapping code:

<servlet-mapping> <servlet-name> jsp </servlet-name> <url>*.html</url> </servlet-mapping> And comment out the following block

<mime-mapping> <extension> html </extension> <mime-type> text/html

</mime-type> </mime-mapping> 81) What is the difference between request attributes, session attributes, and ServletContext attributes? A ServletContext attribute is an object bound into a context through ServletContext.setAttribute() method and which is available to ALL servlets (thus JSP) in that context, or to other contexts via the getContext() method. By definition a context attribute exists locally in the VM where they were defined. So, they're unavailable on distributed applications. Session attributes are bound to a session, as a mean to provide state to a set of related HTTP requests. Session attributes are available ONLY to those servlets which join the session. They're also unavailable to different JVMs in distributed scenarios. Objects can be notified when they're bound/unbound to the session implementing the HttpSessionBindingListener interface. Request attributes are bound to a specific request object, and they last as far as the request is resolved or while it keep dispatched from servlet to servlet. They're used more as comunication channel between Servlets via the RequestDispatcher Interface (since you can't add Parameters...) and by the container. Request attributes are very useful in web apps when you must provide setup information between information providers and the information presentation layer (a JSP) that is bound to a specific request and need not be available any longer, which usually happens with sessions without a rigorous control strategy. Thus we can say that context attributes are meant for infra-structure such as shared connection pools, session attributes to contextual information such as user identification, and request attributes are meant to specific request info such as query results. 82) Are singleton/static objects shared between servlet contexts? [Question continues: For example if I have two contexts on a single web server, and each context uses a login servlet and the login servlet connects to a DB. The DB connection is managed by a singleton object. Do both contexts have their own instance of the DB singleton or does one instance get shared between the two?] It depends on from where the class is loaded. The classes loaded from context's WEB-INF directory are not shared by other contexts, whereas classes loaded from CLASSPATH are shared. So if you have exactly the same DBConnection class in WEB-INF/classes directory of two different contexts, each context gets its own copy of the singleton (static) object. 83) When building web applications, what are some areas where synchronization problems arrise? In general, you will run into synchronization issues when you try to access any shared resource. By shared resource, I mean anything which might be used by more than one request. Typical examples include:

Connections to external servers, especially if you have any sort of pooling. Anything which you include in a HttpSession. (Your user could open many browser windows and make many simultaneous requests within the one session.) Log destinations, if you do your own logging from your servlets.

84) What is the difference between apache webserver, java webserver and tomcat server? Apache is an HTTP server written in C that can be compiled and run on many platforms. Java WebServer is an HTTP server from Sun written in Java that also supports Servlets and JSP. Tomcat is an open-source HTTP server from the Apache Foundation, written in Java, that supports Servlets and JSP. It can also be used as a "plug-in" to native-code HTTP servers, such as Apache Web Server and IIS, to provide support for Servlets (while still serving normal HTTP requests from the primary, native-code web server). 85) How can you embed a JavaScript within servlets / JSP pages? You don't have to do anything special to include JavaScript in servlets or JSP pages. Just have the servlet/JSP page generate the necessary JavaScript code, just like you would include it in a raw HTML page. The key thing to remember is it won't run in the server. It will run back on the client when the browser loads the generate HTML, with the included JavaScript. 86) How can I make a POST request through response.sendRedirect() or response.setStatus() and response.setHeader() methods? You can't. It's a fundamental limitation of the HTTP protocol. You'll have to figure out some other way to pass the data, such as

Use GET instead Make the POST from your servlet, not from the client Store data in cookies instead of passing it via GET/POST

87) How do I pass a request object of one servlet as a request object to another servlet? Use a Request Dispatcher. 88) I call a servlet as the action in a form, from a jsp. How can I redirect the response from the servlet, back to the JSP? (RequestDispatcher.forward will not help in this case, as I do not know which resource has made the request. request.getRequestURI will return the uri as contained in the action tag of the form, which is not what is needed.) You'll have to pass the JSP's URI in to the servlet, and have the servlet call sendRedirect to go back to the JSP. For example:

<FORM ACTION="/foo/myservlet"> <INPUT TYPE="HIDDEN" NAME="redirect" VALUE="/foo/thisjsp.jsp"> Shoe size: <INPUT NAME="shoesize"> <INPUT TYPE="SUBMIT"> </FORM> Then in the servlet...

response.sendRedirect(request.getParameter("redirect")); 89) What is the ServletConfig object, and why is it useful? The ServletConfig object is an interface. It contains the methods

getInitParameter getInitParameterNames getServletContext getServletName

You can use the methods to determine the Servlet's initialization parameters, the name of the servlets instance, and a reference to the Servlet Context the servlet is running in. getServletContext is the most valuable method, as it allows you to share information accross an application (context). 90) I have a global variable in a servlet class. What will happen to this global variable if two requests hit on the same time? What will happen is an unforeseeable event. The best way to establish a default occurrence (the servlet handles a request at a time) is to synchronize the access to the global variable or alternatively to create a servlet that implements the SingleThreadModel interface. 91) Suppose I have 2 servers, server1 and server2. How can I take data in a cookie from server1, and send it to server2? You'll have to create a (new) similar cookie on server 2. Have a ReadCookieServlet running on server1 that

Reads the cookie, using request.getCookies() Redirects to WriteCookieServlet running on server2, passing the cookie name, value and expiration date as request parameters, using response.sendRedirect().

Have a WriteCookieServlet running on server2 that

Reads the cookie name, value and expiration date request parameters, using request.getParameter(). Creates a similar cookie, using response.addCookie().

92) How can I pass data from a servlet running in one context (webapp) to a servlet running in another context? There are three ways I can think of off the top of my head:

1. Store the information you want to share in a persistant format, such as in a file system or

database. That way, any servlet that is running in a JVM that can "see" these resources can get to this information.

2. If persisting this information is not an option, you can bind this information to a context that is
3. accessible to all servlet contexts, such as the application server's context. This way, you can keep the data you want to share in memory. Use the old fashion way of passing information to a servlet - HTTP. One servlet could foward a request to another servlet and include the data that needs to be shared as parameters in the request.

93) How can I write an "error page" -- that is, a servlet or JSP to report errors of other servlets? The Servlet 2.2 specification allows you to specify an error page (a servlet or a JSP) for different kinds of HTTP errors or ServletExceptions. You can specify this in deployment descriptor of the web application as:

<error-page> <exception-type>FooException</exception-type> <location>/error.jsp</location> </error-page> where FooException is a subclass of ServletException. The web container invokes this servlet in case of errors, and you can access the following information from the request object of error servlet/JSP: error code, exception type, and a message. 94) What is the difference between ServletContext and ServletConfig? A ServletContext represents the context in a servlet container of a servlet instance operates. A servlet container can have several contexts (or web applications) at one time. Each servlet instance is running in one of these contexts. All servlets instances running in the same context are part of the same web application and, therefore, share common resources. A servlet accesses these shared resource (such as a RequestDispatcher and application properties) through the ServletContext object. This notion of a web application became very significant upon the Servlet 2.1 API, where you could deploy an entire web application in a WAR file. Notice that I always said "servlet instance", not servlet. That is because the same servlet can be used in several web applications at one time. In fact, this may be common if there is a generic controller servlet that can be configured at run time for a specific application. Then, you would have several instances of the same servlet running, each possibly having different configurations. This is where the ServletConfig comes in. This object defines how a servlet is to be configured is passed to a servlet in its init method. Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. The container, in turn, passes these parameters to the servlet via the ServetConfig. 95) Under what circumstances will a servlet be reloaded? That depends on the Servlet container. Most of the Servlet containers reload the servlet only it detects the code change in the Servlet, not in the referenced classes. In Tomcat's server.xml deployment descriptor, if you have mentioned

<Context path="/myApp" docBase="D:/myApp/webDev" crossContext="true" debug="0" reloadable="true" trusted="false" > </Context> The reloadable = true makes the magic. Every time the Servlet container detects that the Servlet code is changed, it will call the destroy on the currently loaded Servlet and reload the new code. But if the class that is referenced by the Servlet changes, then the Servlet will not get loaded. You will have to change the timestamp of the servlet or stop-start the server to have the new class in the container memory. 96) What is a Servlet Filter? A filter is basically a component that is invoked whenever a resource is invoked for which the filter is mapped. The resource can be something like a servlet, or a URL pattern. A filter normally works on the request, response, or header attributes, and does not itself send a response to the client. 97) I am using the RequestDispatcher's forward() method to redirect to a JSP. The problem is that the jsp's url is now relative to the servlet's url and all my url's in the jsp such as <img src="pic.gif"> will be corrupt. How do I solve this problem? You can use absolute urls like:

<BODY> <% String base = request.getContextPath(); %> <IMG src="<%=base%>/img/pic.gif"> </BODY> or write out a BASE tag like:

<% String base = request.getContextPath(); %> <HEAD> <BASE HREF="<%=base%>"> </HEAD> <BODY> <IMG src="img/pic.gif"> </BODY> That should take care of the problem. 98) How can I return a readily available (static) HTML page to the user instead of generating it in the servlet? To solve your problem, you can either send a "Redirect" back to the client or use a RequestDispatcher and forward your request to another page: 1. Redirect:

A redirection is made using the HttpServletResponse object:

if(condition) { response.sendRedirect("page1.html"); } else { response.sendRedirect("page2.html"); } 2. RequestDispatcher: A request dispatcher can be obtained through the ServletContext. It can be used to include another page or to forward to it.

if(condition) { this.getServletContext() .getRequestDispatcher("page1.html").forward(); } else { this.getServletContext() .getRequestDispatcher("page2.html").forward(); } Both solutions require, that the pages are available in you document root. If they are located somewhere else on your filesystem, you have to open the file manually and copy their content to the output writer. If your application server is set up in combination with a normal web server like Apache, you should use solution (1), because the the web server usually serves static files much faster than the application server. 99) What is the difference between static variables and instance variables in a servlet? According to the Java Language definition, a static variable is shared among all instances of a class, where a non-static variable -- also called an instance variable -- is specific to a single instance of that class. According to the Servlet specification, a servlet that does not declare SingleThreadModel usually has one and only one instance, shared among all concurrent requests hitting that servlet. That means that, in servlets (and other multithreaded applications), an instance variable behaves very much like a static variable, since it is shared among all threads. You have to be very careful about synchronizing access to shared data. The big difference between instance variables and static variables comes when you have configured your servlet engine to instantiate two instances of the same servlet class, but with different init parameters. In this case, there will be two instances of the same servlet class, which means two sets of instance variables, but only one set of static variables. Remember that you can store data in lots of different places in a servlet. To wit:

Local variables - for loop iterators, result sets, and so forth Request attributes - for data that must be passed to other servlets invoked with the RequestDispatcher

Session attributes - persists for all future requests from the current user only Instance variables - for data that persists for the life of the servlet, shared with all concurrent users Static variables - for data that persists for the life of the application, shared with all concurrent users -- including any other servlet instances that were instantiated with different init parameters Context attributes - for data that must persist for the life of the application, and be shared with all other servlets

100) How can I share data between two different web applications? Different servlets may share data within one application via ServletContext. If you have a compelling to put the servlets in different applications, you may wanna consider using EJBs.