Está en la página 1de 147

Java Technoloies

Nazar Babu

1

Java Technoloies

Nazar Babu

2

Java Technoloies
CONTENTS
Core Java

4 20 23 26 33 41 47 68 80 89 116 133 141 149

Exception Handling

Multi Threading

Collection Framework

JDBC Concept

All Packages

Servlets

JSP

Struts

Hibernate FAQs

EJB Concept

Design Patterns Concept

Database Concept

Security Concept

Nazar Babu

3

Or Hiding the information from others is called as Encapsulation. (vii) The << and >> are not overloaded for I/O operations Q) Opps concepts Polymorphism Ability to take more than one form. Nazar Babu 4 . Encapsulation Wrapping of data and function into a single unit called encapsulation. in java we achieve this using Method Overloading (compile time polymorphism). (v) Java does not support multiple inheritance. (iii) Java does not perform any automatic type conversions that result in a loss of precision (iv) All the code in a Java program is encapsulated within one or more classes. (Or) Nothing but data hiding. Method overriding (runtime polymorphism) Inheritance Is the process by which one object acquires the properties of another object. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses. Java does not have global variables or global functions. Q) Object creation? Object is constructed either on a memory heap or on a stack. Dynamic binding is nothing but late binding. This memory remains allocated throughout the life cycle of the object. Q) class & object? class  class is a blue print of an object Object  instance of class. the memory allocated to the object is eligible to be back on the heap. Dynamicbinding Code associated with a given procedural call is not known until the time of the call at runtime. like the variables declared under private of a particular class are accessed only in that class and cannot access in any other the class. Memory heap generally the objects are created using the new keyword. Java does not support destructors. (vi) Java does not have the delete operator. Since pointers do not exist in Java. (ii) Java does not support operator overloading. Abstraction Nothing but representing the essential futures without including background details. When the object is no more referred. Pointers are inherently insecure and troublesome. but rather. Therefore. add the finalize() function. Ex:. Some heap memory is allocated to this newly created object.all java programs. Or Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse.Java Technoloies CORE JAVA Q) What is difference between Java and C++? A) (i) Java does not support pointers.

Java Technoloies Stack During method calls. Translating a java program into byte code helps makes it much easier to run a program in a wide variety of environment. Access Modifiers  A. Private Same class Same package Subclass Same package non-subclass Different package subclass Different package nonsubclass Q) Default Values long Int Short Byte -2^63 to 2^63 –1  0L -2^31 to 2^31 –1 0 -2^15 to 2^15 –1 0 -2^7 to 2^7 –1 0 double float Boolean char 0.0d 0. Defaults. These objects are created on stack. methods and classes. Q) System. Q) Transient & volatile Transient --> The transient modifier applies to variables only. which actually executes Java programs. Protected. it compiles byte code into executable code in real time. the object are variable will not persist. Transient variables are not serialized.io. Volatile --> value will be changed unexpectedly by the other part of the program.S gives access privileges to outside of application (or) others.println()  println() is a methd of java. Private. final cannot be modified at any point of time. objects are created for method arguments and method variables. JVM is an interpreter for byte code.System class.printWriter. "it tells the compiler a variable may change asynchronously due to threads" Q) Access Specifiers & Access modifiers? Access Specifiers  A.lang. will increase the performance of the interpretations.M which gives additional meaning to data.  “out” is an instance variable of java.  JRE is an implementation of the Java Virtual Machine. Nazar Babu 5 .out.  JVM is an interpreter for byte code  JIT (Just In Time) is a part of JVM. they are Public.0f false 0 to 2^7 –1  null character (or) ‘\u 0000’ No No No No No Public Yes Yes Yes Yes Yes Protected Yes Yes Yes Yes No No modifier Yes Yes Yes No No Q) Byte code & JIT compiler & JVM & JRE & JDK  Byte code is a highly optimized set of instructions.

Q) Public static void main (String [] args)  We can overLoad the main() method.  If I do not provide the String array as the argument to the method? Program compiles but throws a runtime error "NoSuchMethodError". But at runtime throws an error "NoSuchMethodError". variable passed in the method are called parameters.Java Technoloies  JDK is bundle of software that you can use to develop Java based software. Nazar Babu 6 .  Protected static void main(). Constructor is called immediately after the object is created before the new operator completes. Tools provided by JDK is (i) javac – compiler (ii) java – interpretor (iii) jdb – debugger (iv) javap Disassembles (v) appletviewer – Applets (vi) javadoc . Constructor has no return type not even void. static void main(). Hence there is not conflict amongst the multiple classes having main method. The compiler says that the main method is already defined in the class.lang.  If no arguments on the command line. values passed to those variables are called arguments. private static void main() are also valid. These are java. While starting the application we mention the class name to be run. Q) Does Java pass method arguments by value or by reference? Java passes all arguments by value. constructor has same name has class name. Q) Constructor The automatic initialization is performed through the constructor. While using those methods. this() is used to invoke a constructor of the same class. Q) Can I have multiple main methods in the same class? A) No the program fails to compile.package. not by reference Q) Arguments & Parameters While defining method.  We can write “static public void” instead of “public static void” but not “public void static”.documentation generator (vii) javah 'C' header file generator Q) Wrapper classes Primitive data types can be converted into objects by using wrapper classes.  What if the main method is declared as “Private”? The program compiles properly but at runtime it will give "Main method not public." Message  What if the static modifier is removed from the signature of the main method? Program compiles. We can pass the parameters to the constructor. The JVM will look for the Main method only in the class whose name you have mentioned. String array of Main method will be empty or null? It is empty. Super () is used to invoke a super class constructor. But not null.  Variables can have the same name as a method or a class Q) Can an application have multiple classes having main() method? A) Yes it is possible.

}} Class B extends A { B(){ System.out. instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program. final. private or have no access modifier  Constructor can not use the modifiers abstract.out.C is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory.  You cannot use this() and Super() in the same constructor. synchronized or strictfp  Constructor can be overloaded. we cannot override. the finalize() method is called by garbage collector when it determines no more references to the object exists. } o/p:. static.lang. protected. User program cann't directly free the object from memory. native. it is good idea to explicitly assign null into a Nazar Babu 7 .Object.println(“friend”). Every class inherits finalize() method from java. Class A( A(){ System. }} Class print { Public static void main (String args []){ B b = new B().println(“hello”).hello friend Q) Diff Constructor & Method Constructor Use to instance of a class No return type Same name as class name “This” refer to another constructor in the same class “Super” to invoke the super class constructor “Inheritance” cannot be inherited We can “overload” but we cannot “overridden” Will automatically invoke when an object is created Method Grouping java statement Void (or) valid return type As a name except the class method name. In Java. Refers to instance of class Execute an overridden method in the super class Can be inherited Can be inherited Method has called explicitly Q) Garbage collection G.Java Technoloies  Constructor can use the access modifiers public. begin with lower case.

JVM tries to recycle the unused objects. these resources are freed before the object is going to destroy. Garbage collection is a low-priority thread. overriding is not possible for that method. via an uncaught exception or an explicit return statement. Finally.exit() in try block will not allow finally code to execute Finalize: . Because of final class never allows any class to inherit it. Any time a method is about to return to the caller from inside try/catch block. but there is no guarantee when all the objects will garbage collected. We can declare final method in abstract class suppose of it is abstract too. if an object holding some non-java resource such as file handle (or) window character font. An object also becomes eligible when its reference is set to null. If an exception is thrown. Finalize Final: .Java Technoloies variable when no more in use. the finally block will execute even if no catch statement match the exception. Once to declare a variable as final it cannot occupy memory per instance basis. Q) Final. G.C cannot be forced explicitly.gc(). G. then there is no used to declare like that. Q) How an object becomes eligible for Garbage Collection? A) An object is eligible for garbage collection when no object refers to it. Integer i = new Integer(7). calling System.e.Finally create a block of code that will be executed after try catch block has completed. i = null. Finally block will execute whether or not an exception is thrown. Q) Can we declare abstract method in final class? A) It indicates an error to declare abstract method in final class. JVM may do garbage collection if it is running short of memory.some times an object need to perform some actions when it is going to destroy.C is a low priority thread in java.gc() and Runtime. the finally clause is also execute. Finally: . The objects referred by method variables or local variables are eligible for garbage collection when they go out of scope.gc() does NOT force the garbage collection but only suggests that the JVM may make an effort to do garbage collection. Nazar Babu 8 .When we declare a sub class a final the compiler will give error as “cannot subclass final class” Final to prevent inheritance and method overriding. Q) Can we declare final method in abstract class? A) If a method is defined as final then we can’t provide the reimplementation for that final method in its derived classes i. Using System.  Final class cannot have static methods  Final class cannot have abstract methods (Because of final class never allows any class to inherit it)  Final class can have a final method. The call System.

• Methods declared as final cannot be overridden.  Only member method can be overriden. • If the superclass method is protected.  The throws clause of the overriding method may only include exceptions that can be thrown by the superclass method. including its subclasses. • If the superclass method is public. or public. • If the superclass method is package. the overriding method may be protected or public. protected. } } class Child extends Parent{ int i = 10. order of parameter & return type are different then the methods are said to be overloaded.  The access modifier for the overriding method may not be more restrictive than the access modifier of the superclass method. void amethod(){ Nazar Babu 9 .Java Technoloies Q) Superclass & Subclass A super class is a class that is inherited whereas subclass is a class that does the inheriting Q) How will u implement 1) polymorphism 2) multiple inheritance 3) multilevel inheritance in java? A) Polymorphism – overloading and overriding Multiple inheritances – interfaces. the overriding method must be public.println("in Parent"). • Overloaded methods do not have any restrictions on what return type of Method (Return type are different) (or) exceptions can be thrown. Overriding (Runtime polymorphism) When a method in a subclass has the same name. return type & parameters as the method in the super class then the method in the subclass is override the method in the super class. • Overloading is used while implementing several methods that implement similar behavior but for different data types.out. Q) Overloading & Overriding? Overloading (Compile time polymorphism) Define two or more methods within the same class (or) subclass that share the same name and their number of parameter. the overriding method may be packagage. • If the superclass methods is private. That is something to worry about with overriding. it is not inherited and overriding is not an issue. not member variable class Parent{ int i = 0. void amethod(){ System. Multilevel inheritance – extending class.

i+" ").i+" "). In other words they are class variables.println("in Child").  When a member is declared a static it can be accessed before any object of its class are created.Java Technoloies System.out.  Static methods is called by the static methods only.  If you do not specify an initial value to an instance & Static variable a default value will be assigned automatically. but static methods cannot call ordinary methods. } } class Test{ public static void main(String[] args){ Parent p = new Child(). each instance has a variable stored in separate memory location.out.print("i="+p. c.  Static methods are implicitly "final". Further it may not invoke instance (non-static) methods of that class unless it provides them with some object. only its static variables. Q) Class variable & Instance variable & Instance methods & class methods Instance variable  variables defined inside a class are called instance variables with multiple instance of class. p. It may not access the instance variables of that class. an ordinary method can call the static methods. not instance variables.  Instance variables declared as static are essentially global variables. Q) Static block Static block which exactly executed exactly once when the class is first loaded into JVM. because overriding is only done based on the type of the objects  They cannot refer “this” are “super” in any way.amethod ().  Static methods cant be overriden to non-static methods. they cannot refer this or super. Q) Static variable & Static method Static variables & methods are instantiated only once per class. Before going to the main method the static block will execute. Static methods can be referenced with the name of the class. Nazar Babu 10 . the value of that variable changes for all instances of that class.  Methods declared as static have some restrictions they can access only static data.i=0 in Child i=10 in Child Q) Final variable Once to declare a variable as final it cannot occupy memory per instance basis. System. If you change the value of a static variable in a particular object. System. they can only call other static data. Child c = new Child().print("i="+c.amethod(). } } o/p: .out.

lang. StringBuffer is mutable which means that its value can be changed. super() must always be the first statements executed inside a subclass constructor. Q) Static methods cannot access instance variables why? Static methods can be invoked before the object is created. The primary difference between member classes and nested top-level classes Nazar Babu 11 . This means a public member class acts similarly to a nested top-level class.intValue(). Q) What are different types of inner classes? A) Nested top-level classes. Instance variables are created only when the new object is created. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package.Java Technoloies Class variables  you want a variable to be common to all classes then we crate class variables. Q) Conversions String to Int Conversion: int I = integer. StringBuffer represent growable and writeable character sequence. the compiler treats the class just like any other top-level class. Class methods  we create class methods to allow us to call a method without creating instance of the class. Since there is no possibility to the static method to access the instance variables. Java.If you declare a class within a class and specify the static modifier. Top-level inner classes implicitly have access only to static variables.floatValue().9).inner. outer.valueOf(23.StringBuffer is also a final class hence it cannot be sub classed. All of these are of the nested top-level variety. Q) String & StringBuffer String is a fixed length of sequence of characters. in order to use that methods we need to first create objects of the class.valueOf(10). It allocates room for 16-addition character space when no specific length is specified. Int to String Conversion :String arg = String. float f = float. To declare a class method use the “static” key word . Q) Super() Super() always calling the constructor of immediate super class. Member classes . int x = integer.. There can also be inner interfaces. e. To create a class variable put the “static” keyword before the variable name. StringBuffer cannot be overridden the equals() method.parseInt(“433”).Member inner classes are just like other member methods and member variables and access to the member class is restricted. just like methods and variables. String is immutable.g. Instance variables are called called as non-static variables.valueOf(“24”). Instance methods  we define a method in a class.

final method (but there is no use).  By default the methods & variables will take the access modifiers is <default>. Again note that the class itself is declared abstract.  An “abstract method” also declared private. private and static are not usable.  A class with an abstract method. Their visibility is only within the block of their declaration. which is accessibility as package. specific to a block of code.C can contain concrete methods. Declaring such a class abstract indicates that the implementation is somehow incomplete and is meant to serve as a super class for one or more subclasses that will complete the implementation. we cannot directly instantiate the abstract classes. private. A.  An abstract class can have instance methods that implement a default behavior. final. Because local classes are not members the modifiers public. you cannot provide a constructor. Any sub class of an Abstract class must either implement all the abstract methods in the super class or be declared itself as Abstract.Local classes are like local variables. otherwise a compile time error would have occurred.  Inner class inside method cannot have static members or blocks Q) Which circumstances you use Abstract Class & Interface? --> If you need to change your design make it an interface.  Abstract class have visibility public. A. Nazar Babu 12 . protected.  An abstract method declared in a non-abstract class.C are excellent candidates inside of application framework.  You cannot declare “abstract constructor” and “abstract static method”. strictfp. Local classes . In order for the class to be useful beyond the declaration block.  Compile time error occur if an attempt to create an instance of an Abstract class. protected. As anonymous classes have no name. --> Abstract class provide some default behaviour.Anonymous inner classes extend local inner classes one level further. which should be very faster.C allow single inheritance model. synchronized. it would need to implement a more publicly available interface. Q) Abstract Class Any class that contain one are more abstract methods must also be declared as an abstract. there can be no object of an abstract class.  A class can be declared abstract even if it does not actually have any abstract methods.  Abstract class can have static.Java Technoloies is that member classes have access to the specific instance of the enclosing class. native. Anonymous classes . protected. A.

Walking. } } Q) Interface Interface is similar to class but they lack instance variable. animals are capable of doing different things like flying.println(“Bark! Bark”). digging.callmetoo(). When an operation is performed in a different way it is a good candidate for an abstract method. But these are some common operations performed by all animals. their methods are declared with out any body. Interfaces are designed to support dynamic method resolution at run time. Nazar Babu 13 .println(“moo! moo”). All methods in interface are implicitly abstract. Interface methods have no implementation.out. Public Abstarctclass Animal{ Public void eat(food food) { } public void sleep(int hours) { } public abstract void makeNoise() { } public Dog extends Animal { public void makeNoise() { System. } } public Cow extends Animal { public void makeNoise() { System. but in a different way as well. b.Java Technoloies Abstract class A{ Public abstract callme().callme(). } } Q) When we use Abstract class? A) Let us take the behaviour of animals.out. b. Void callmetoo(){ } } class B extends A( void callme(){ } } class AbstractDemo{ public static void main(string args[]){ B b = new B(). even if the abstract modifier is omitted.

14f.  A class can only extend one other class. private.  A compile time error occurs if an interface has a simple name the same as any of it's enclosing classes or interfaces.  All Variables are implicitly final. inner interfaces may be declared private and protected but only if they are defined in a class.  Interface can extend more than one interface. float y) { return(x*y). Interface A { final static float pi = 3. even if the public modifier is omitted.  An Interface can only declare constants and instance methods. public. abstract method declarations.  All methods of an interface are implicitly Abstract. native or synchronized.Java Technoloies Interfaces are useful for? a) eclaring methods that one or more classes are expected to implement b) Capturing similarities between unrelated classes without forcing a class relationship.  An interface methods cannot be declared protected. strictfp. } } Nazar Babu 14 .  An interface body may contain constant declarations. static fields.  Interface can be extended & implemented. a. } } class test{ public static void main(String args[]) { A a = new B().compute(). inner classes and inner interfaces. c) Determining an object's programming interface without revealing the actual body of the class. } class B implements A { public float compute(float x. Why Interfaces? “ one interface multiple methods “ signifies the polymorphism concept.  Interface has visibility public.  top-level interfaces may only be declared public. Public. but cannot implement default behavior.  A class may implements more than one interface.

Delegation means that you include an instance of another class as an instance variable. rather than a new class. Methods declared inside interface are without any body. It has 2 methods writeExternal(objectOutput out). An Interface cannot.Making a programme to flexible to run in a specific locale called Localization. but cannot implement default behavior.  An A. private.  An A. protected.C can have any visibility: public. and it is harder to re-use (because it is not a subclass). An Interface visibility must be public (or) none. Localization -. there can be no objects of an abstract class. Q) What is the difference between Interface and class?  A class has instance variable and an Interface has no instance variables.  Objects can be created for classes where as objects cannot be created for interfaces. it makes you write more code. It is often safer than inheritance because it forces you to think about each message you forward. Q) What are some alternatives to inheritance? A) Delegation is an alternative to inheritance. It has two methods. An Interface cannot. and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense.Java Technoloies Q) Diff Interface & Abstract Class?  A. Q) What is the difference between Abstract class and Class?  Classes are fully defined. because the instance is of a known class. Externalizable  is an Interface that extends Serializable Interface.C can have nonabstract methods. readExternal(objectInput in). Nazar Babu 15 . On the other hand.C can define constructor.C can have instance methods that implement a default behavior.  All methods defined inside class are concrete. An Interface can only declare constants and instance methods. Q) Serializable & Externalizable Serializable --> is an interface that extends serializable interface and sends data into streams in compressed format. writeExternal(ObjectOuput out) and readExternal(ObjectInput in) Q) Internalisation & Localization Internalisation -.  An A.  An A.C must have subclasses whereas interface can't have subclasses  An A.  An A. All methods of an Interface are abstract. Abstract classes are not fully defined (incomplete class)  Objects can be created for classes.C can have instance variables. And sends data into Streams in Compressed Format. Interface contains no implementation code.Making a programme to flexible to run in any locale called internalisation. and forward messages to the instance.C may have some executable methods and methods left unimplemented.

(iv) Ex: . Method level. Q) Diff = = and . equals ()  method compare the characters in the string object. this is useful when ever you want to save the state of your programme to a persistence storage area. once a thread enter a monitor.public Synchronized void main(String args[]) But this is not the right approach because it means servlet can handle one request at a time. String s1 = "Amit". Nazar Babu 16 . Q) Synchronization Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time. (i) Ex: . all other threads must wait until that thread exist the monitor. String s2 = "Amit".Synchronizing a function: public synchronized void Method1 () { } (i) Ex: . StringBuffer sb1 = new StringBuffer("Amit"). String s3 = new String("abcd"). (Or) When 2 are more threads need to access the shared resources they need to some way ensure that the resources will be used by only one thread at a time.equals()? A) ==  Compare object references whether they refer to the sane instance are not. Object level. Block level Q) Monitor A monitor is a mutex.Java Technoloies Q) Serialization Serialization is the process of writing the state of the object to a byte stream. String ss1 = "Amit". String s4 = new String("abcd").Synchronizing a block of code inside a function: public myFunction (){ synchronized (this) { } } (iii) Ex: .public Synchronized void service() Servlet handle one request at a time in a serialized manner Q) Different level of locking using Synchronization? A) Class level. This process which is achieved is called synchronization. StringBuffer sb2= new StringBuffer("Amit").

p. Try{ p = r. is only used to read something from the network.totalMemory(). String s2 = new String("abc"). You can get a reference to the current Runtime object by calling the static method Runtime.equals(sb2)).exce(“notepad”).  F String s1 = "abc".getRuntime().equals(s2)).  T (s3. Mem1 = r.  F (sb1. Serializable. URL url = new URL(protocol name.openConnection().getRuntime() Runtime r = Runtime.  T ((s3==s4)).yahoo.equals(s2))  T Q) Marker Interfaces (or) Tagged Interfaces :An Interface with no methods.  F (sb1. SingleThread Model. port. host name. Q) URL & URLConnection URL is to identify a resource in a network. eg.  F (s1.waiFor() } Nazar Babu 17 . url specifier) URLConnection can establish communication between two programs in the network. Q) Execute other programs You can use java to execute other heavy weight process on your multi tasking operating system. several form of exec() method allow you to name the programme you want to run.equals(ss1)). s1 == s2  F s1.Java Technoloies (sb1==sb2).equals(s4)). Q) URL Encoding & URL Decoding URL Encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex Characters and URL Decoding is the reverse process converting all Hex Characters back their normal form. URL hp = new URL(“www. Runtime r = Runtime. Q) Runtime class Runtime class encapsulate the run-time environment. You cannot instantiate a Runtime object.freeMemory(). Process p = null. Cloneable. Is called marker Interfaces. URLConnection con = hp.com”). Mem1 = r.  T ((s1==s2)).getRuntime() Long mem1.

Q) Java pass arguments by value are by reference? A) By value Nazar Babu 18 . error output of the java runtime are stored in the in.A a = new A(). err variables. Q) Native Methods Native methods are used to call subroutine that is written in a language other than java. Ex:.instanceOf A. This interface having one method compare the invoking object with the object. Q) Cloneable Interface Any class that implements the cloneable interface can be cloned.Java Technoloies Q) System class System class hold a collection of static methods and variables. Cloning is a dangerous action. Q) InstanceOf Instanceof means by which your program can obtain run time type information about an object. methods & modifier of class. a.Reflect (package) Reflection is the ability of software to analyse it self. this interface defines no methods. For sorting comparable interface will be used. Ex:. constructor. It is used to indicate that a class allow a bit wise copy of an object to be made. The standard input. output.lang. out. to obtain information about the field. You need this information to build software tools that enables you to work with java beans components. Methods in this class are static Class forName(String name) throws ClassNotFoundException getClassLoader() getField() getMethods() getInterface() getClass() getConstructor() getDeclaredFields() getDeclearedMethods() getSuperClass() Q) java.int compareTo(Object obj) Q) Class Class encapsulate the run-time state of an object or interface. Q) Clone Generate a duplicate copy of the object on which it is called. Q) Comparable Interface Classes that implements comparable contain objects that can be compared in some meaningful manner. this subroutine exist as executable code for the CPU.

S java V. Q) Bin & Lib in jdk? Bin contains all tools such as javac.Java Technoloies Q) Java lack pointers how do I implements classic pointer structures like linked list? A) Using object reference. Only disadvantage is user needs a M. which includes “jexegentool”. Exe Micro soft provided sdk for java. appletviewer and awt tool. Q) java. Nazar Babu 19 .Exec” form.M installed. Lib contains API and all packages. This converts class file into a “.

E Bound. try-catch is used to catching an exception that are thrown by the java runtime system. Throws  A Throws clause list the type of exceptions that a methods might through.E Virtual Machine Error Compile time. throws try  This is used to fix up the error. which eventually results in the termination of the program in which it is thrown.E Arithmetic. Q) Can an exception be rethrown? A) Yes.Java Technoloies Exception Handling Object Throwable Error AWT Error Exception OutOfMemory. Q) What happens if an exception is not caught? A) An uncaught exception results in the uncaughtException() method of the thread's ThreadGroup being invoked.E StirngIndexoutOfBound Q) Diff Exception & Error Exception and Error both are subclasses of the Throwable class. ExceptionException is generated by java runtime system (or) by manually. Q) try.Ex (checked) EOF. Error Will stop the program execution.E NullPointer. an exception can be rethrown. throw. An exception is a abnormal condition that transfer program execution from a thrower to catcher.E Exception Indexoutof Nazar Babu 20 .E Runtime (Unchecked) FilenotFound. Throw  is used to throw an exception explicitly. to prevent the program from automatically terminating.E ArrayIndexoutOfBound. catch. StackOverFlow. Error is a abnormal system condition we cannot handle these.

ArrayIndexOutOfbound --> For accessing an array element by providing an index values <0 or > or equal to the array size. NosuchField Exception --> A request field does not exist. ClassNotfound Exception --> class not found. eg. Errors often cannot be. Instantion Exception --> Attempt to create an object of an Abstract class or Interface. IllegalArgument Exception --> Illegal argument is used to invoke a method. however. StringIndexOutOfBoundsException thrown by String's charAt() method· Checked exceptions must be caught at compile time.FileInputStream's read() method· Unchecked exceptions are RuntimeException and any of its subclasses. Checked Exceptions ClassNotFoundException NoSuchMethodException NoSuchFieldException InterruptedException IllegalAccessException CloneNotSupportedException Un checked exception ArithmeticException ArrayIndexOutOfBoundException ClasscastException IllegalArgumentException IllegalMonitorSateException IllegalThreadStateException IndexOutOfBoundException NullPointerException NumberFormatException StringIndexOutOfBounds OutOfMemoryError --> Signals that JVM has run out of memory and that the garbage collector is unable to claim any more free memory. client programmers may not even know that the exception could be thrown. Q) Checked & UnChecked Exception :Checked exception is some subclass of Exception. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown.F in the interpreter. With an unchecked exception. StringIndexOutOfbound --> For accessing character of a string or string buffer with index values <0 or > or equal to the array size. Nullpointer Exception --> If attempt to made to use a null object. Arithmetic Exception --> such as divide by zero. IOException thrown by java. StackOverFlow --> Signals that a stack O. In fact. the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause.Java Technoloies Q) What happens if a try-catch-finally statement does not 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. NosuchMethod Exception --> A request method does not exist. Runtime exceptions do not need to be. ArrayStore Exception --> Assignment to an array element of an incompatible types. Class Error and its subclasses also are unchecked. Nazar Babu 21 . ClasscastException --> Invalid casting.io. eg. NumberFormat Exception --> Invalid conversition of string to numeric format.

This process of shifting control is known as primitive multi tasking. understood. As each exception is caught and converted to a higher-level exception for rethrowing. you call the “sendError” method. Two methods and two constructors were added to Throwable. it's added to the chain. Q) What is exception chaining? A) An exception chain is a list of all the exceptions generated in response to a single root exception. with protocol version and a success or error code. a thread with higher priority is executed first than the thread with lower priority. Q) Primitive multi tasking If the threads of different priorities shifting the control depend on the priority i. This causes the server to respond with status line.e. getLocalizedMessage().Java Technoloies Q) Methods in Exceptions? A) getMessage(). getCause returns the exception that caused the current exception. while the last two digits do not have categories Numbe Type Description r 1xx Informational Requested received. printStackTrace(). and initCause returns the current exception. This provides a complete record of how an exception is handled The chained exception API was introduced in 1..4. The first digit of the status code defines the class of response. Throwable) Throwable(Throwable) The Throwable argument to initCause and the Throwable constructors is the exception that caused the current exception. and accepted 3xx Redirection Further action must be taken in order to complete the request 4xx Client Error The request contains bad syntax or cannot be fulfilled 5xx Server Error The server failed to fulfil valid request Nazar Babu 22 . continuing to process 2xx Success The action was successfully received. Throwable getCause() Throwable initCause(Throwable) Throwable(String. toString(). Q) Http Status Codes To inform the client of a problem at the server end.

Main. wait  wait for a thread until some specific condition occurs (Or) Tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify(). In case of suspend. stop( )  The thread move to dead state. (iii) A Program can contain more than one thread. When daemon thread remains the program exist.sleep(milliseconds. Process is a sub program will perform some specific actions. Q) Sleep(). it has no other role normally a daemon thread carry some background program. (ii) Thread is a lightweight task. (I) Process is a heavy weight task and is more cost. nanoseconds). thread will be suspended by calling the lock on the object. which is of low cost. (v) A program under execution is called as process. suspend(). Q) Yield( ) Yield method temporarily stop the callers thread and put at the end of queue to wait for another turn to be executed.Java Technoloies Multi Threading Q) What threads will start when you start the java program? A) Finalizer. notifyAll(). Reference Handler.  Thread.  Thread. notify(). Q) Thread Priority Nazar Babu 23 . Signal dispatcher. notifyAll( ) wakes up all the threads that called wait() on the same object.sleep(milliseconds). Q) Multi Threading Multithreading is the mechanism in which more than one thread run independent of each other within the process. wait(). Q) Diff process and threads? A) Thread is a smallest unit of dispatchable code. resume() sleep  sleep for a thread until some specific amount of time. Resume will restart from where it is suspended. It is used to make other threads of the same priority have the chance to run. Q) Daemon Thread Daemon thread is one which serves another thread. stop(). Q) Thread Thread is a smallest unit of dispatchable code. notify( )  wakes up the first thread that called wait() on the same object. suspend( ) & resume( )  To pass and restart the execution of a thread. the highest priority thread will run first. join( )  wait for a thread to terminate.

MAX_PRIORITY). Keep in mind though that the use of the stop() method of Thread is deprecated and should be avoided.stop(). Q) What is the use of start() function in starting a thread? why we do not use the run() method directly to run the thread?  Start method tell the JVM that it needs to create a system specific thread. block level Nazar Babu 24 . not a separate thread of execution. } class HiLo{ public static void main(Stirng args[]){ Thread.t. Public clicker(int p){ T = new Thread(this) t.start().start().setPriority(p). } lo.sleep(1000). method level. Q) Thread Priorities Class A implements Runnable{ Thread t.start(). Clicker hi = new Clicker(Thread. After creating the system resources it passes the runnable object to it to execute the run() method. lo. try{ hi. it cannot be restarted.join().  Calling run() method directly has the thread execute in the same as the calling object.currentThread(). } public void run(){ } public void stop(){ } public void start(){ t.setPriority(Thread. Hi.stop(). } try{ thread. hi.NORM_PRIORITY-2).NORM_PRIORITY+2). Clicker lo = new Clicker(Thread.t. Q) What are the different levels of locking using ‘Synchronize’ key word? A) Class level. Lo. object level.join().Java Technoloies MIN_PRIORITY = 1 NORM_PRIORITY = 5 MAX_PRIORITY = 10 Q) Can I restart a stopped thread? A) Once a thread is stopped.

Java Technoloies Q) Which attribute are thread safe? Multi Threaded Objective Model Local variables Instance variables Class variables Request attributes Session attributes Context attributes Y N N Y N N Single threaded Model Y Y N Y N N Nazar Babu 25 .

Iterator iterator().L is a replacement for Vector. When ever there is a lot of insertion & deletion we have to go for L. void clear(). Abstract List  Extends Abstract collection & Implements List Interface.L allow “random access”. void clear(). in expensive insertion and deletion from the middle of the list. Collection c). It will allow duplicate elements. Methods>>void add (int index. Object [] toArray(). int latIndexOf(Object element). Abstract Set  Extends Abstract collection & Implements Set interface.L is accessed via a reference to the Collection Interfaces Collection List Set Sorted Set Map Iterator Legacy classes Dictionary Hash Table Stack Vector Properties Legacy interface Enumerator Nazar Babu 26 .L. A. int indexOf(Object element).L internal node traversal from the start to the end of the collection is significantly faster than Linked List traversal.L allow rapid random access to element but slow for insertion and deletion from the middle of the list. Object element). A.L provide optimal sequence access. Linked List  Extends AbstactSequentialList and implements List interface. ArrayList support dynamic array that grow as needed. ArrayList is a variable length of array of object references. L. object get(int index). Collection c). Object remove(int index). boolean addAll(Collection c). boolean addAll(int index. int size(). boolean add(Object o). boolean addAll(Collection c). Array List  Array List extends AbstractList and implements the List interface. L. A. Methods>> void add (int index. boolean addAll(int index.Java Technoloies Collections Frame Work Q) Collection classes Abstract collection Abstract List Abstract Set Array List Linked List Hash set Tree Set Hash Map Tree Map Abstract Sequential List Collection Classes Abstract collection  Implements most of the collection interfaces. boolean add(Object o). Object element). Searching is very faster. relatively slow for random access.  A. Object remove(int index).

Java Technoloies
first node of the list. Each subsequent node is accessed via a reference to the first node of the list. Each subsequent node is accessed via the link-reference number stored in the previous node. Methods>> void addFirst(Object obj), addLast(Object obj), Object getFirst(), Object getLast(),void add (int index, Object element), boolean add(Object o), boolean addAll(Collection c), boolean addAll(int index, Collection c), Object remove(int index), Object remove(Object o), void clear(), object get(int index), int indexOf(Object element), int latIndexOf(Object element), int size(), Object [] toArray(). Hash Set  Extends AbstractSet & Implements Set interface, it creates a collection that uses HashTable for storage, H.S does not guarantee the order of its elements, if u need storage go for TreeSet. It will not allow duplicate elements Methods>>boolean add(Object o), Iterator iterator(), boolean remove(Object o), int size(). Tree Set  Extends Abstract Set & Implements Set interface. Objects are stored in sorted, ascending order. Access and retrial times are quite fast. It will not allow duplicate elements Methods>> boolean add(Object o), boolean addAll(Collection c), Object first(), Object last(), Iterator iterator(), boolean remove(Object o). Hash Map  Extends Abstract Map and implements Map interface. H.M does not guarantee the order of elements, so the order in which the elements are added to a H.M is not necessary the order in which they are ready by the iterate. H.M permits only one null values in it while H.T does not  HashMap is similar to Hashtable. Tree Map  implements Map interface, a TreeMap provides an efficient means of storing key/value pairs in sorted order and allow rapid retrieval. Abstract Sequential List  Extends Abstract collection; use sequential access of its elements. Collection Interfaces Collection  Collection is a group of objects, collection does not allow duplicate elements. Methods >> boolean add(Object obj), boolean addAll(c), int Size(), Object[] toArray(), Boolean isEmpty(), Object [] toArray(), void clear().Collection c), Iterator iterator(), boolean remove(Object obj), boolean removeAll(Collection Exceptions >> UnSupportedPointerException, ClassCastException. List  List will extend Collection Interface, list stores a sequence of elements that can contain duplicates, elements can be accessed their position in the list using a zero based index, (it can access objects by index).

Nazar Babu

27

Java Technoloies
Methods >> void add(int index, Object obj), boolean addAll(int index, Collection c), Object get(int index), int indexOf(Object obj), int lastIndexOf(Object obj), ListIterator iterator(), Object remove(int index), Object removeAll(Collection c), Object set(int index, Object obj). Set  Set will extend Collection Interface, Set cannot contain duplicate elements. Set stored elements in an unordered way. (it can access objects by value). Sorted Set  Extends Set to handle sorted sets, Sorted Set elements will be in ascending order. Methods >> Object last(), Object first(), compactor compactor(). Exceptions >> NullPointerException, ClassCastException, NoSuchElementException. Map  Map maps unique key to value in a map for every key there is a corresponding value and you will lookup the values using keys. Map cannot contain duplicate “key” and “value”. In map both the “key” & “value” are objects. Methods >> Object get(Object k), Object put(Object k, Object v), int size(), remove(Object object), boolean isEmpty() Iterator  Iterator makes it easier to traverse through the elements of a collection. It also has an extra feature not present in the older Enumeration interface - the ability to remove elements. This makes it easy to perform a search through a collection, and strip out unwanted entries. Before accessing a collection through an iterator you must obtain one if the collection classes provide an iterator() method that returns an iterator to the start of the collection. By using iterator object you can access each element in the collection, one element at a time. Methods >> boolean hasNext(), object next(),void remove() Ex:- ArayList arr = new ArrayList(); Arr.add(“c”); Iterator itr = arr.iterator(); While(itr.hashNext()) { Object element = itr.next(); } List Iterator  List Iterator gives the ability to access the collection, either forward/backward direction Legacy Classes Dictionary  is an abstract class that represent key/value storage repository and operates much like “Map” once the value is stored you can retrieve it by using key.

Nazar Babu

28

Java Technoloies
Hash Table  HashTable stores key/value pairs in hash table, HashTable is synchronized when using hash table you have to specify an object that is used as a key, and the value that you want to linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored with the table. Use H.T to store large amount of data, it will search as fast as vector. H.T store the data in sequential order. Methods>> boolean containsKey(Object key), boolean containsValue(Object value), Object get(Object key), Object put(Object key, Object value) Stack  is a sub class of vector, stack includes all the methods defined by vector and adds several of its own. Vector  Vector holds any type of objects, it is not fixed length and vector is synchronized. We can store primitive data types as well as objects. Default length of vector is up to 10. Methods>> final void addElement(Object element), final int size(), final int capacity(), final boolean removeElementAt(int index), final void removeAllElements(). Properties  is a subclass of HashTable, it is used to maintain the list of values in which the “key/value” is String. Legacy Interfaces Enumeration  Define methods by which you can enumerate the elements in a collection of objects. Enumeration is synchronized. Methods>> hasMoreElements(),Object nextElement(). Q) Which is the preferred collection class to use for storing database result sets? A) LinkedList is the best one, benefits include: 1. Retains the original retrieval order. 2. Has quick insertion at the head/tail 3. Doesn't have an internal size limitation like a Vector where when the size is exceeded a new internal structure is created. 4. Permits user-controlled synchronization unlike the pre-Collections Vector which is always synchronized ResultSet result = stmt.executeQuery("..."); List list = new LinkedList(); while(result.next()) { list.add(result.getString("col")); } If there are multiple columns in the result set, you'll have to combine them into their own data structure for each row. Arrays work well for that as you know the size, though a custom class might be best so you can convert the contents to the proper type when extracting from databse, instead of later. Q) Efficiency of HashTable - If hash table is so fast, why don't we use it for everything? A) One reason is that in a hash table the relations among keys disappear, so that certain operations (other than search, insertion, and deletion) cannot be easily implemented. For example, it is hard to traverse a hash table according to the order of the key. Another reason is that when no good hash function can be found for a

Nazar Babu

29

If many entries are to be put into a Hashtable.M permits null values in it while H. Both are interface. The load factor should be between 0. List Iterator extends Iterator to allow bi-directional traversal of a list and modification of the elements. Enumeration is a legacy interface. If you want to convert back to a collection implementation. linked list. // Convert from a collection to an array Object[] array = c.0.  Iterator in the H. which returns an array of objects. ‘ hasPrevious()’.P is part of new collection framework. If two or more different keys have the same hash value these entries are stored as a linked list under the same index. we can store primitive data types as well as class objects. creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table. All entries of the Hashtable are stored in an array of Entry objects with the hash value of the key serving as the index. Q) Diff HashTable & HashMap  Both provide key/value to access the data. or tree). Iterator having 3 methods ‘boolean hasNext()’. Iterator is collection interface that extends from ‘List’ interface. Hashtable has two parameters that affect its efficiency: its capacity and its load factor. Q) How does a Hashtable internally maintain the key-value pairs? A) The Hashtable class uses an internal (private) class named Entry to hold the keyvalue pairs.and back again? The collection interface define the toArray() method. ‘object next()’. Q) Array Array of fixed length of same data type. List Iterator It is an interface.T is one of the collection original collection classes in java. you could manually traverse each element of the array and add it using the add(Object) method.the ability to remove elements there is one method “void remove()”.Java Technoloies certain application. Iterator also has an extra feature not present in the older Enumeration interface .P is fail-safe while the enumerator for the H. H. not declared.  H.toArray().  Arrays are initialized to the default value of their type when they are created. the capacity is increased by calling the rehash method. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity.M is not. ‘void remove()’. the time and space cost is even higher than other data structures (array. Nazar Babu 30 .T does not. at the expense of larger expected time per lookup. Enumeration having 2 methods ‘Boolean hasMoreElements()’ & ‘Object NextElement()’.  H.T is synchronized and H. The H. Methods are ‘hasNext()’. Q) Converting from a Collection to an array . Larger load factors use memory more efficiently. even if they are local variables Q) Diff Iterator & Enumeration & List Iterator Iterator is not synchronized and enumeration is synchronized.0 and 1.T is not.

Java Technoloies // Convert back to a collection Collection c2 = new HashSet(). Set set = hmap. indx < args.iterator().</option> <% hmap =(HashMap)request.Select Standard WorkFlow&gt. i < array.startsWith("-") ) i. // Use the remove method of iterator if (! param.get(key)%></option> <% } } %> </select> Q) Retrieving data from a collection? public class IteratorDemo { public static void main(String args[]) { Collection c = new ArrayList().length. if( hmap.next(). // PRE : Collection has all parameters while (i."> <option value="">&lt.keySet().hasNext()) { Integer key = (Integer)it. Iterator it = set.add(array[i]). // Add every parameter to our array list for (int indx = 0. for(int i = 0.getAttribute("stdwf").iterator().add(args[indx]). while(it. } // Examine only those parameters that start with Iterator i = c. } Q) How do I look through each element of a HashMap? A) <select id="swf" name="swf" onChange="showStandardWF()" style="width:175px. %> <option value="<%=key%>"><%=(String)hmap.hasNext()) { String param = (String) i.size().length. Nazar Babu 31 .next(). indx++) { c.remove(). i++) { c2.size() != 0){ int len = hmap.

sort(theArray). } } } Q) How do I sort an array? A) Arrays class provides a series of sort() methods for sorting arrays. while (i2. Arrays. however. theComparator). Nazar Babu 32 .println ("Param : " + i2.iterator().Java Technoloies } // POST: Collection only has parameters that start with // Demonstrate by dumping collection contents Iterator i2 = c.next()). it is an array of objects that don't implement the Comparable interface then you need to provide a custom Comparator to help you sort the elements in the array.out.hasNext()) { System.sort(theArray. If. If the array is an array of primitives (or) an array of a class that implements Comparable then you can just call the method directly: Arrays.

Also added the ability to update a referenced object through the Ref object. 5.to control how prepared statements are pooled and reused by connections.Added methods to allow a string to identify the parameter to be set for a CallableStatement object.0 new features? A) 1. 8. Retrieval of auto-generated keys: . and updateRef methods to the ResultSet interface.sql.Added the interface ParameterMetaData. Nazar Babu 33 . 10. updateArray.Added methods to retrieve the object referenced by a Ref object. 3.Added of the updateBlob. Holdable cursor support: . which contains new methods to set. Retrieval of parameter metadata: . BOOLEAN data type: . Reuse of prepared statements by connection pools: .forName will do while loading drivers? A) Will create an instance of the driver and register with the DriverManager. ARRAY and REF types: . which describes the number. Transaction Savepoint support: . 12. These properties can be used to describe how PooledConnection objects created by DataSource objects should be pooled. Connection pool configuration :. CLOB.Java Technoloies JDBC Q) What Class. 7.Added the ability to specify the of holdability of a ResultSet object. release.Added a means of retrieving values from columns containing automatically generated values. updateClob. 6.Defined a number of properties for the ConnectionPoolDataSource interface. Passing parameters to CallableStatement objects by name: .Added the Savepoint interface. Updating of columns containing BLOB. BOOLEAN is logically equivalent to BIT. 9.Added the new method getMoreResults(int). Q) JDBC 3. 4. Multiple open ResultSet objects: .Added methods to allow the data contained in Blob and Clob objects to be altered.BOOLEAN. 11.Types. type and properties of parameters to prepared statements.Added the data type java. or roll back a transaction to designated savepoints. Making internal updates to the data in Blob and Clob objects: . 2. Retrieving and updating the object referenced by a Ref object: .

Java Technoloies
Q) JDBC Drivers o o o o Tier JDBC-ODBC Bridge Driver Native API - Partly Java Driver Network protocol - All Java Driver Native Protocol - Pure Java Driver

Description JDBC access via most ODBC drivers, some ODBC binary code and client code must be loaded on each client machine. This driver is Two JDBC-ODBC commonly used for prototyping. The JDBCODBC Bridge is JDBC driver which implements JDBC operations by translating them to ODBC operations. This driver converts JDBC calls to database Native API - Partly Java Two specific native calls. Client requires database driver specific libraries. ThreeNetwork protocol - All This driver converts JDBC calls into DBMS Java Driver independent network protocol that is sent to the middleware server. This will translate this DBMS independent network protocol into DBMS specific protocol, which is sent to a particular database. The results are again rooted back to middleware server and sent back to client. Native protocol - All They are pure java driver, they communicate Two Java driver directly with the vendor database. Q) JDBC connection import java.sql.*; public class JDBCSample { public static void main(java.lang.String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (ClassNotFoundException e) { System.out.println("Unable to load Driver Class"); return; } try { Connection con = DriverManager.getConnection("jdbc:odbc:companydb","", ""); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT FIRST_NAME FROM EMPLOYEES"); while(rs.next()) { System.out.println(rs.getString("FIRST_NAME")); } rs.close(); stmt.close(); con.close(); }

Driver mechanism

Nazar Babu

34

Java Technoloies
catch (SQLException se) { System.out.println("SQL Exception: " + se.getMessage()); }

} }

Q) 4th type driver class.forName(“oracle.jdbcdriver.oracledriver”); connection con = driverManager.getConnection(“JDBC:oracle:thin:@hostname:portno:oracleservice”,” uid”, “pwd”); Q) Steps to connect to JDBC? A) 1. First thing is using jdbc you have to establish a connection to the data base this is 2 steps process (i) you must load the jdbc driver (ii) then make a connection, to do this we can call the getConnection() method of driver manager class. 2. To execute any sql commands using jdbc connection you must first create a statement object to create this call statement st = con.createSteatement(). This is done by calling the createStatement() method in connection interface. Once the statement is created you can executed it by calling execute() method of the statement interface. Q) Resultset Types rs.beforeFirst()  goto 1st record rs.afterLast()  goto last record isFirst() / isLast() res.absolute(4)  will got 4th record in result set. rs.deleteRow() rs.updateRow(3,88)  value in column 3 of resultset is set to 88. rs.updateFloat() rs.relative(2) Q) Transactional Savepoints Statement stmt = conn.createStatement (); Int rowcount = stmt.executeUpdate ("insert into etable (event) values ('TMM')"); Int rowcount = stmt.executeUpdate ("insert into costs (cost) values (45.0)"); Savepoint sv1 = conn.setSavePoint ("svpoint1"); // create save point for inserts Int rowcount = stmt.executeUpdate ("delete from employees"); Conn.rollback (sv1); // discard the delete statement but keep the inserts Conn.commit; // inserts are now permanent Q) Updating BLOB & CLOB Data Types rs.next(); Blob data = rs.getClob (1); Rs.close(); // now let's insert this history into another table stmt.setClob (1, data); // data is the Clob object we retrieved from the history table int InsertCount = stmt.executeUpdate("insert into EscalatedIncidents (IncidentID, CaseHistory, Owner)" + " Values (71164, ?, 'Goodson') ");

Nazar Babu

35

Java Technoloies
Q Retreiving / Storing / Updating Array of Objects Array a = rs.getArray(1); Pstmt.setArray(2, member_array); Rs.updateArray(“last_num”,num); Q) How to execute no of queries at one go? A) By using a batchUpdate's (i.e. throw addBatch() and executeBatch()) in java.sql.Statement interface or by using procedures. Q) Batch Updates CallableStatement stmt = con.prepareCall(“{call employeeInfo (?)}”); stmt.addBatch("INSERT INTO employees VALUES (1000, 'Joe Jones')"); stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')"); // submit a batch of update commands for execution int[] updateCounts = stmt.executeBatch(); Q) Multiple Resultset A) The methods getMoreResults, getUpdateCount, and getResultSet can be used to retrieve all the results. CallableStatement cstmt = connection.prepareCall(procCall); boolean retval = cstmt.execute(); if (retval == false) { } else { ResultSet rs1 = cstmt.getResultSet(); retval = cstmt.getMoreResults(Statement.KEEP_CURRENT_RESULT); if (retval == true) { ResultSet rs2 = cstmt.getResultSet(); rs2.next(); rs1.next(); } } CLOSE_ALL_RESULTS All previously opened ResultSet objects should be closed when calling getMoreResults().

CLOSE_CURRENT_RESULT The current ResultSet object should be closed when calling getMoreResults(). KEEP_CURRENT_RESULT The current ResultSet object should not be closed when calling getMoreResults().

Q) Diff execute() ,executeUpdate() and executeQuery() ? A) execute() returns a boolean value, which may return multiple results. executeUpdate() is used for nonfetching queries, which returns int value and tell how many rows will be affected. executeQuery() is used for fetching queries, which returns single ResulSet object and never return Null value. Q) How to move the cursor in scrollable resultset? Type of a ResultSet object:TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE, TYPE_SCROLL_SENSITIVE, CONCUR_READ_ONLY and CONCUR_UPDATABLE.

Nazar Babu

36

// rowNum should be 4 rs. Delete: uprs. JDBC is a low level pure java API used to execute SQL statements.getRow().createStatement(ResultSet. Q) What is necessity of JDBC in JDBC-ODBC bridge? A) The purpose of JDBC is to link java API to the ODBC.getRow(). rs. ODBC return high level “c” API so the JDBC converts “c” level API to java API.updateRow(). Q) JDBC connection pool When you are going to caret a pool of connection to the database. ResultSet. Q) Why you need JDBC if ODBC is available? A) ODBC is purely written in “c” so we cannot directly connect with java. COLUMN_2 FROM TABLE_NAME"). // cursor is on the fourth row int rowNum = rs. int rowNum = rs. rs. } Q) How to “Update” & “Delete” a resultset programmatically? Update: Statement stmt = con.CONCUR_UPDATABLE). otherwise.createStatement(ResultSet.absolute(5). Calls from java to native “c” code have number of drawbacks in the security.55).TYPE_SCROLL_SENSITIVE.relative(-3). // rowNum should be 1 rs.//update last row's data uprs. uprs. the data will be lost. Q) Can we establish the connection with ODBC itself? A) Yes.executeQuery("SELECT COLUMN_1. 25. // will delete row 5. float salary = rs.updateFloat("COLUMN_2".deleteRow().. uprs.previous()) { String name = rs. ResultSet rs = stmt.CONCUR_READ_ONLY).absolute(4).getFloat("COLUMN_2").//don't miss this method. implementation and robustness. Nazar Babu 37 .last().getString("COLUMN_1").afterLast(). int rowNum = rs. (i) ODBC is not appropriate for direct use from java because it uses “c” interfaces. This will give access to a collection of already opened data base connections. ResultSet uprs = stmt. while (srs.executeQuery("SELECT COLUMN_1. using java native classes we have to write a program.getRow(). which will reduce the time it takes to service the request and you can service “n” number of request at once.relative(2). uprs.Java Technoloies Statement stmt = con. ResultSet.TYPE_SCROLL_SENSITIVE.. COLUMN_2 FROM TABLE_NAME"). // rowNum should be 3 //.

InOut  both. Callable statement will call a single stored procedure. CallableStatement CST = con.setInt (1.S are partially compiled statements placed at server side with placeholders? Before execution of these statements user has to supply values for place holders. they perform multiple queries and updates without network traffic. types.executeUpdate (“create table “+ uname+ “(sno int.ParseInt (dis. In  used to send information to the procedure. Q) Is the JDBC-ODBC Bridge multi-threaded? A) No.S used to retrieve data by invoking stored procedures. P. DataInputStream dis = new DataInputStream (“System. Out  used to retrieve information from data base. Int enum = Integer.registerOutParameter (2. it will increase performance of application. These are used by n-number of clients.prepareCall (“{CALL procedure-name (??)}”).readLine ()). Q) Statements in JDBC Statement  Does not take any arguments. ResultSet rs = pst.prepareStatement ("SELECT * FROM EMP WHERE deptno=?"). Int n = st. sentby varchar (10). stored procedure are program units placed at data base server side for reusability. so they can run faster than the dynamic sql.setInt (1. The JDBC-ODBC Bridge does not support concurrent access from different threads. enum).S is precompiled statements once we compile the statements and send it to the server for later use. In this statement it will check syntax error and execute it every time (it will parse every time). dno). Callable statement  C.in”). PreparedStatement PST = con. Int dno = Integer.readLine ()). cst.Java Technoloies Q) Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? A) No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.cretaeStatement ().execute (). pst. Nazar Babu 38 .ParseInt (dis. DataInputStream dis = new DataInputStream (“System. subject varchar (15)”). The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC Q) Dynamically creating Tables Statement st = con. cst.in”).executeQuery ().VARCHAR) Resultset rs = cst. Prepare statement  P. Stored procedure is precompiled in RDBMS.

Connection. getColumnType(). getTables(). ResultSet. Similarly.getMessage()). GetBinaryStream()  used to read images. trying to retrieve a warning on a statement after it has been closed or on a result set after it has been closed will cause an exception to be thrown.getMetaData(). Nazar Babu 39 . ""). Q) Database MetaData You need some information about the “data base” & “dictionary” we use this . getProcedures().println("SQLState: " + warning. and ResultSet objects. this is the largest interface in java.println("Message: " + warning. System.Connection interface Q) Retrieving very large values from database? A) getASSCIISteram()  read values which are character in nature. Methods  getColumnCount(). getTables(). Q) SQL Warnings Warnings may be retrieved from Connection.getWarnings(). Q) ResultSetMetaData It is used to find out the information of a table in a data base.getWarnings() Statement. ResultSet rs= dbmd.Java Technoloies Q) In which interface the methods commit() & rollback() savepoint() defined ? A) Java.print("Vendor error code: ").getConnection(jdbcURL. if (warning != null) { while (warning != null) { System.sql package Connection con = DriverManager.out.getSQLState()). getDriverName(). Trying to retrieve a warning on a connection after it has been closed will cause an exception to be thrown. primary key of a table we use this. getProcedureColumns(). get MinorVersion().getWarnings(). getColumnLabel().getMetaData(). ResultSet rs = stmt. System. Serialized Form SQLWarning warning = stmt. Methods  getColumns().executeQuery("SELECT * FROM "+ table). getTableName().sql. DatabaseMetaData dbmd = con.To find out tables.getxxx(). getColumnName(). stored procedure names. Statement. "". getMajorVersion().getWarnings().out. Note that closing a statement also closes a result set that it might have produced. columns in a table. ResultSetMetaData rsmd = rs. getTableTypes().out.

fis. END. warning = warning.executeUpadate(). Int ch.out. sub programs are naming PL/SQL blocks that can take parameters to be invoked. ResultSet rs = st. Update accounts set balance = bal where account_id = id.03. Oracle executes triggers automatically when ever a given SQL operation effects the table.gif”). :name) end Q) Stored Images into a table Public class img { Public static void main(String args[]){ Class.gif”).setBinaryStream(1.getErrorCode()).next(). we can associate 12 data base triggers with in a given table.write(ch). Preparestatement pst = con.println(warning.getNextWarning(). } Retrieve Image Statement st = con. Bal: = bal + bal * 0. Pst.getBinaryStream(1). InputStream is = rs. } } Q) Procedure Procedure is a subprogram will perform some specific action.forName(). Int I = pst. FileOutPutStream fos = new FileOutPutStream(“g2.getConnection().read(1))!=!-1) { fos. bal IN OUT FLOAT) IS BEGIN select balance into bal from accounts where account_id = id. Q) Trigger Trigger is a stored PL/SQL block associated with a specific database table.executeQuery(“select * from img”). fis. While((ch=is.Java Technoloies System.available).prepareStatement(“insert into image value(?)). FileInputStream fis = new FileInputStream(“a. Connection con = DriverManager.CreateStatement(). } Nazar Babu 40 . Rs. Create/Replace trigger before Insert (or) Delete (or) Update on emp for each row Begin Insert into table-name values(:empno. create (or) replace procedure procedure-name (id IN INTEGER .

Methods: void notify() void notifyAll() Object clone() Sting toString() boolean equals(Object void wait() object) void finalize() void wait(long milliseconds.servlet Package Interfaces Servlet ServletConfig ServletContext ServletRequest ServletResponse SingleThreadModel ServletContextListener ServletContextAttributeList ener ServletContextInitialization parameters ServletRequestAttributeList ener ServletRequestListner Filter FilterChain FilterConfig RequestDispatcher Classes GenericServlet ServletInputStream ServletOutputStream ServletContextAttribut eEvent Exceptions ServletExceptio n UnavaliableExc eption Nazar Babu 41 . Object class is a super class of all other class. int nanoseconds) int hashcode() Q) throwable class Methods: String getMessage() String toString() Void printStackTrace() Throwable fillInStackTrace() Q) Javax.Java Technoloies All Packages Q) Thread Class Methods: getName() run() getPriority() Sleep() isAlive() Start() join() Q) Object class All other classes are sub classes of object class.

public abstract void log(Exception exception. public abstract Enumeration getParameterNames(). int len) ServletOutputStream (C) public void print(String s) throws IOException. public abstract String getServerInfo(). public abstract String getServletInfo(). public abstract void service(ServletRequest req. String msg). public abstract String getRemoteAddr().Java Technoloies GenericServlet (C) public void destroy(). public abstract int getServerPort(). public abstract String getParameter(String name). public String getInitParameter(String name). public abstract ServletConfig getServletConfig(). ServletContext (I)  public abstract Object getAttribute(String name). Nazar Babu 42 . int off. public void log(String msg). public abstract String[] getParameterValues(String name). public ServletConfig getServletConfig(). public void println() throws IOException. ServletResponse res) ServletInputStream (C) public int readLine(byte b[]. ServletContextAttributeEvent (C)  public void attributeAdded(ServletContextAttributeEvent scab) public void attributeRemoved(ServletContextAttributeEvent scab) public void attributeReplaced(ServletContextAttributeEvent scab) Servlet (I)  public abstract void destroy(). public abstract String getServerName(). public abstract Enumeration getServlets(). public abstract Servlet getServlet(String name) throws ServletException. public abstract Enumeration getInitParameterNames(). public ServletContext getServletContext(). public abstract Enumeration getServletNames(). public abstract void service(ServletRequest req. public abstract void init(ServletConfig config) throws ServletException. public abstract ServletContext getServletContext(). public abstract String getRealPath(String path). public abstract String getRemoteHost(). public String getServletInfo(). public Enumeration getInitParameterNames(). public abstract String getRealPath(String path). ServletRequest (I)  public abstract Object getAttribute(String name). ServletResponse res) ServletConfig (I)  public abstract String getInitParameter(String name). public void init(ServletConfig config) throws ServletException.

public abstract void setContentType(String type). Classes Cookies HttpServlet (Abstarct Class) HttpUtils HttpSessionBindingEven t Exceptions ServletException UnavaliableExcep tion Nazar Babu 43 .Http Package Interfaces HttpServletRequest HttpServletResponse HttpSession HttpSessionListener HttpSessionActivationLis tener HttpSessionAttributeList ener HttpSessionBindingListe ner HttpSessionContext (deprecated) Filter ServletContextListener (I)  public void contextInitialized(ServletContextEvent event) public void contextDestroyed(ServletContextEvent event) ServletContextAttributeListener (I) public void attributeAdded(ServletContextAttributeEvent scab) public void attributeRemoved(ServletContextAttributeEvent scab) public void attributeReplaced(ServletContextAttributeEvent scab) ServletContextInitilazation parameters  Cookies (C)  public Object clone().4 ServletResponse (I)  public abstract String getCharacterEncoding(). Q) Javax. String getValue().servlet.4 public String getLocalAddr(). public int getLocalPort().4 public int getRemotePort(). public abstract PrintWriter getWriter() throws IOException. String getName(). int getVersion().4 public String getLocalName(). public abstract void setContentLength(int len). // servlet 2. // servlet 2. // servlet 2. String getPath(). public public public public public int getMaxAge(). // servlet 2.Java Technoloies RequestDispatcher getRequestDispatcher(String path).

String value). HttpServletRequest (I)  public abstract Cookie[] getCookies(). public abstract void addDateHeader(String header. public abstract boolean isRequestedSessionIdValid(). long value). protected void service(HttpServletRequest req. HttpServletResponse res) protected void doTrace(HttpServletRequest req. ServletResponse res) protected void doDelete (HttpServletRequest req. public abstract String getQueryString(). HttpServletResponse res) protected void doPost(HttpServletRequest req. HttpServletResponse res) protected void doGet (HttpServletRequest req. setPath(String uri). public HttpSession getSession(). public abstract String encodeUrl(String url). public abstract HttpSession getSession(boolean create). public abstract String getRemoteUser(). public abstract String getRequestURI(). HttpServletResponse res) protected long getLastModified(HttpServletRequest req). public abstract void setHeader(String name. public abstract String encodeRedirectUrl(String url). int value). HttpServletResponse (I)  public abstract void addCookie(Cookie cookie). String msg) throws IOException. public abstract String getHeader(String name). HttpServletResponse res) HttpSessionbindingEvent (C)  public String getName(). public abstract boolean isRequestedSessionIdFromCookie(). public abstract String getServletPath(). setValue(String newValue). HttpServlet (C)  public void service(ServletRequest req.Java Technoloies public public public public void void void void setMaxAge(int expiry). int value). public abstract void addIntHeader(String header. setVersion(int v). public abstract void setIntHeader(String header. public abstract String getRequestedSessionId(). public abstract void sendError(int sc. public abstract boolean isRequestedSessionIdFromUrl(). public abstract void sendRedirect(String location) throws IOException. Nazar Babu 44 . HttpServletResponse res) protected void doPut(HttpServletRequest req. public abstract Enumeration getHeaderNames(). HttpServletResponse res) protected void doOptions(HttpServletRequest req.

sql Package Interfaces Connection CallableStatement Driver Classes DriverManager Date TimeStamp Exceptions ClassNotFoundException Instantiation Exception Nazar Babu 45 .valueBound(HttpSessionBindingEvent event) public void HttpSessionBindingListener. public setMaxInactiveIntervel(). Object value). public remove Attribute(String name. public abstract String[] getValueNames(). public abstract void removeValue(String name). public abstract String getId(). Object value). public abstract Object getValue(String name). public abstract HttpSessionContext getSessionContext(). ServletResponse response. FilterChain chain) public FilterConfig getFilterConfig() public void setFilterConfig (FilterConfig filterConfig) Q) java. HttpSessionListener (I)  public void sessionCreated(HttpSessionEvent event) public void sessionDestroyed(HttpSessionEvent event) HttpSessionAttributeListener (I)  public void attributeAdded(ServletContextAttributeEvent scab) public void attributeRemoved(ServletContextAttributeEvent scab) public void attributeReplaced(ServletContextAttributeEvent scab) HttpSessionBindingListener (I)  public void HttpSessionBindingListener. public getAttribute(String name. Object value). public abstract long getLastAccessedTime(). HttpSession (I)  public abstract long getCreationTime(). public abstract void invalidate(). public setAttribute(String name. public void setStatus(). public abstract void putValue(String name. long value).Java Technoloies public abstract void setDateHeader(String header.valueUnbound(HttpSessionBindingEvent event) HttpSessionActivationListener (I)  public void sessionDidActivate(HttpSessionEvent event) public void sessionWillpassivate(HttpSessionEvent event) Filter (i)  public void doFilter (ServletRequest request. public abstract boolean isNew(). Object value).

E String. ClassLoader IlleAcess.E. Float.sql Package Interfaces Classes Exceptions ConnectionEventListener ConnectionEvent ConnectionPoolDataSource RowsetEvent DataSource PooledConnection RowSet RowSetListener RowSetMetaDate RowSetReader/Writer XAConnection XADataSource Q) java. Boolean. StringBuffer NoSuchField. ArithmeticException.lang Package Interfaces Classes Exceptions Cloneable Double. SQLOutput. Character.E Thread. BufferOutputStream BufferReader.E. IllegalArgument. RunTime. Void IllegalSate. CharacterArayWriter DataInputStream.IO Package Interfaces DataInputstream DataOutputstream ObjectInputStream ObjectOutputstrea m Serializable Externializable Classes BufferInputstream. ThreadGroup NumberFormat. SQLPermission Savepoint Q) javax. ClassNotFound. Byte. ByteArrayOutputstream CharacterarrayReader. NullPointer.E Comparable Process. Integer.E. Short.E Runnable Class. Long. FileWriter ObjectInputStream. NoSuchMethod. ObjectOutputStream Exceptions Time Types SQL Exception.E Q) java. ArrayIndexOutOfBoundOf. ClassCast.E. SQL Warnings Nazar Babu 46 . Blob SQLInput. BufferWriter ByteArrayInputStream.E.Java Technoloies PreparedStatement ResultSet ResultSetMetaData Statement DatabaseMetaData Array ParameterMetaData Clob. DataOutputStream Filereader.

All servlet containers must support HTTP as a protocol for requests and responses.Java Technoloies SERVLETs Class path: set path= c:\j2sdk1.c:\servlet. rd. A servlet container also contains and manages servlets through their lifecycle. decodes MIME-based requests. servlet container internally creates a 'servlet' & executes it.RequestDispatcher rd=ServletContext.jar. Q) Generally Servlets are used for complete HTML generation. A servlet container can be built into a host Web server. Ex: . Servlets will be loaded in the Address space of web server.html”) in the servlet code we can mix the partial static HTML Directory page. In general this servlet will be deleted immediately to create & execute a servlet base on a JSP we can use following command.4. but additional request/response-based protocols such as HTTPS (HTTP over SSL) may be supported.2\bin set classpath= c:\ j2sdk1. what method do you use? A) Using 'RequestDispather. This servlet is called as 'Temporary servlet'. and formats MIME-based responses. If you want to generate partial HTML's that include some static text as well as some dynamic text.jsp Q) What is the difference between Server and Container? A) A server provides many services to the clients. Q) What is Temporary Servlet? A) When we sent a request to access a JSP. or installed as an add-on component to a Web Server via that server’s native extension API.include(“xx.bat  shortcut Q) Servlet Servlet is server side component.response).include(request.2\lib\tools. Nazar Babu 47 .html”). Q) Servlet Container The servlet container is a part of a Web server (or) Application server that provides the network services over which requests and responses are sent. Java weblogic.jar C:\Tomcat5\bin\startup. Servlets are durable objects means that they remain in memory specially instructed to be destroyed. Here a container holds a set of objects.4. a servlet is small plug gable extension to the server and servlets are used to extend the functionality of the java-enabled server.jspc—keepgenerated *.getRequestDispatcher(“xx. servlet/jsp container.  Servlet are loaded 3 ways 1) When the web sever starts 2) You can set this in the configuration file 3) Through an administration interface. A server may contain one or more containers such as ejb containers.

instead of init(). to initialize servlet? A) Yes.html. Q) Can we use the constructor. Q) Can we leave init() method empty and insted can we write initilization code inside servlet's constructor? A) No. your Servlet's destroy () method will be called. Q) Why there is no constructor in servlet? A) A servlet is just like an applet in the respect that it has an init() method that acts as a constructor. ServletResponse res) throws ServletException. this will call only once. So ServletConfig will not be accessible in the constructor. That no longer applies. There’s nothing to stop you. . IOException public void destroy ()  The Web server when loading the servlet calls the init method once. such as | . . because the container passes the ServletConfig object to the servlet only when it calls the init method. The original reason for init() was that ancient versions of Java couldn’t dynamically invoke constructors with arguments. an initialization code you need to run should e place in the init().gif) | +WEB-INF/-+ | + classes/(Java classes.jpg.Java Technoloies Q) Servlet Life cycle Public void init (ServletConfig config) throws ServletException public void service (ServletRequest req. ServletException  Signals that some error occurred during the processing of the request and the container should take appropriate measures to clean up the request. Servlets) | + lib/(jar files) | Nazar Babu 48 . so there was no way to give the constructur a ServletConfig.jsp. . (The init method typically establishes database connections. since it get called when the servlet is first loaded. but servlet containers still will only call your no-arg constructor.) Any request from client is handled initially by the service () method before delegating to the doXxx () methods in the case of HttpServlet. Q) Directory Structure of Web Applications? A) WebApp/(Publicly available files. IOException  Signals that Servlet is unable to handle requests either temporarily or permanently. This allows you to free any resources you may have got hold of in your Servlet's init () method. If u put “Private” modifier for the service() it will give compile time error. of course you can use. But you shouldn’t. So you won’t have access to a ServletConfig or ServletContext.  When your application is stopped (or) Servlet Container shuts down.

TestFilter</filter-class> <init-param> <param-name>locale</param-name> <param-value>US</param-value> </init-param> </filter> <filter-mapping> <filter-name>Test Filter</filter-name> <servlet-name>TestServlet</servlet-name> </filter-mapping> <!-.Defines application events listeners --> <listener> <listener-class> listeners.jdbc.Java Technoloies + web.Defines WebApp initialization parameters.odbc.Defines servlets --> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>servlets.xml: <web-app> <!-.tld) | + weblogic.Defines filters and specifies filter mapping --> <filter> <filter-name>Test Filter</filter-name> <filter-class>filters.xml / (taglib.HelloServlet</servlet-class> <init-param> <param-name>driverclassname</param-name> <param-value>sun.JdbcOdbcDriver</param-value> </init-param> <init-param> <param-name>dburl</param-name> Nazar Babu 49 .xml WAR-> WARfile can be placed in a server’s webapps directory Q) Web.--> <context-param> <param-name>locale</param-name> <param-value>US</param-value> </context-param> <!-.MySessionCumContextListener </listener-class> </listener> <!-.MyServletContextListener</listener-class> </listener> <listener> <listener-class> listeners.

tld</taglib-location> </taglib> <!-.com/testlib</taglib-uri> <taglib-location>/WEB-INF/tlds/testlib.SQLException</exception-type> <location>sqlexception.jsp</location> </error-page> <taglib> <taglib-uri>http://abc. --> <role-name>manager</role-name> <!-.Defines servlet mappings --> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>*. --> <session-config> <session-timeout>30</session-timeout> <session-config> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> <! -.role-name is used in HttpServletRequest.isUserInRole(String role) method.Error page -.Java Technoloies <param-value>jdbc:odbc:MySQLODBC</param-value> </init-param> <security-role-ref> <!-.> <error-page> <error-code>404</error-code> <location>notfoundpage.hello</url-pattern> </servlet-mapping> <!--specifies session timeout as 30 minutes.sql. --> <role-link>supervisor</role-link> </security-role-ref> </servlet> <!-.tld</taglib-location> </taglib> <taglib> <taglib-uri>/examplelib</taglib-uri> <taglib-location>/WEB-INF/tlds/examplelib.only POST method is protected --> <http-method>POST</http-method> <web-resource-collection> <web-resource-name>Another Protected Area</web-resource-name> Nazar Babu 50 .role-link is one of the role-names specified in security-role elements.jsp</location> </error-page> <error-page> <exception-type>java.

auth-method can be: BASIC. passes these parameters to the servlet via the ServetConfig. FORM. Most servlet containers provide a way to configure a servlet at runtime (usually through flat file) and set up its initial parameters.odbc. The container.hello</url-pattern> </web-resource-collection> <!-. calls the servlet's service() method at the specified times. in turn. 18:00</run-at> </servlet> Q) ServletConfig Interface & ServletContex Interfaces ServletConfig  ServletConfig object is used to obtain configuration data when it is loaded.html</form-login-page> <form-error-page>/formerror. To run the servlet every 6 hours.jsp</form-error-page> </form-login-config> </login-config> </web-app> Q) Automatically start Servlet? A) If present. or CLIENT-CERT --> <auth-method>FORM</auth-method> <realm-name>sales</realm-name> <form-login-config> <form-login-page>/formlogin.jdbc.JdbcOdbcDriver</param-value> </init-param> <init-param> <param-name>dburl</param-name> <param-value>jdbc:odbc:MySQLODBC</param-value> </init-param> </servlet> </web-app> -------------------------------------- Nazar Babu 51 .HelloWorld'> <run-at>0:00. This object defines how a servlet is to be configured is passed to a servlet in its init method. 12:00. The value is a list of 24-hour times when the servlet should be automatically executed. 6:00. Ex:<web-app> <servlet> <servlet-name>TestServlet</servlet-name> <servlet-class>TestServlet</servlet-class> <init-param> <param-name>driverclassname</param-name> <param-value>sun. <run-at> lets servlet writers execute periodic tasks without worrying about creating a new Thread.Java Technoloies <url-pattern>*. you could use: <servlet servlet-name='test. There can be multiple ServletConfig objects in a single web application. DIGEST.

Where as Stateful Session bean is a type of bean. To receive notification events. appContext. In cases where the container is distributed over many virtual machines. To receive notification Nazar Babu 52 . Q) Servlet Listeners (i) ServletContextListener void contextDestroyed (ServletContextEvent sce) void contextInitialized (ServletContextEvent sce) Implementations of this interface receive notifications about changes to the servlet context of the web application they are part of.username. } ServletContext ServletContext is also called application object. req.productIdsInCart). which can also maintain the state of the client in Application servers.getConnection(dbURL.getParameter(paramName)).getAttribute(paramName). URL namespace. a Web application will have an instance of the ServletContext for each JVM. They can share data.forName(driverClassName). based on RMI-IIOP. which are based on Http protocol. appContext.getInitParameter("driverclassname").getInitParameter("dburl"). ServletContext is used to obtain information about environment on which a servlet is running. String driverClassName = config. Servlet Context is a grouping under which related servlets run. (ii) ServletContextAttributeListener (I) void attributeAdded (ServletContextAttributeEvent scab) void attributeRemoved (ServletContextAttributeEvent scab) void attributeReplaced (ServletContextAttributeEvent scab) Implementations of this interface receive notifications of changes to the attribute list on the servlet context of a web application.setAttribute(paramName.password). Q) How to add application scope in Servlets? A) In Servlets Application is nothing but ServletContext Scope. dbConnection = DriverManager.Java Technoloies public void init() { ServletConfig config = getServletConfig().setAttribute("productIdsInCart". There is one instance object of the ServletContext interface associated with each Web application deployed into a container. Class. Q) Can we store objects in a session? A) session. ServletContext appContext = servletConfig. String dbURL = config. the implementation class must be configured in the deployment descriptor for the web application. and other resources.removeAttribute("productIdsInCart"). There can be multiple contexts in a single servlet container. Q) Diff between HttpSeassion & Stateful Session bean? Why can't HttpSessionn be used instead of of Session bean? A) HttpSession is used to maintain the state of a client in webservers.getServletContext(). session.

servlet. a database connection may begin a transaction when bound to a session and end the transaction when unbound.HttpSessionBindingEvent argument provides access to the name under which the object is being bound (or unbound) with the getName() method: public String HttpSessionBindingEvent. (iv) HttpSession Binding Listener (** If session will expire how to get the values) Some objects may wish to perform an action when they are bound (or) unbound from a session. the implementation class must be configured in the deployment descriptor for the web application.HttpSessionBindingListener interface is notified when it is bound (or) unbound from a session. (iii) HttpSessionAttributeListener (I) public void attributeAdded(HttpSessionBindingEvent se) public void attributeRemoved(HttpSessionBindingEvent se) public void attributeReplaced(HttpSessionBindingEvent se) This listener interface can be implemented in order to get notifications of changes to the attribute lists of sessions within this web application.getName() The HttpSessionBindingEvent object also provides access to the HttpSession object to which the listener is being bound (or unbound) with getSession() : public HttpSession HttpSessionBindingEvent.getSession() Nazar Babu 53 . For example. valueBound() and valueUnbound(). The javax. (ii) HttpSessionActivationListener (I) public void sessionWillPassivate(HttpSessionEvent se) public void sessionDidActivate(HttpSessionEvent se) Objects that are bound to a session may listen to container events notifying them that sessions will be passivated and that session will be activated. Any object that implements the javax. that must be implemented: Methods: public void HttpSessionBindingListener.Java Technoloies events.valueBound(HttpSessionBindingEvent event) public void HttpSessionBindingListener. The interface declares two methods. the implementation class must be configured in the deployment descriptor for the web application. Q) HttpListeners (i) HttpSessionListener (I) public void sessionCreated(HttpSessionEvent event) public void sessionDestroyed(HttpSessionEvent event) Implementations of this interface are notified of changes to the list of active sessions in a web application.valueUnbound(HttpSessionBindingEvent event) valueBound()  method is called when the listener is bound into a session valueUnbound()  is called when the listener is unbound from a session.http. To receive notification events.http.servlet.

When a servlet container receives a request for a resource. // Add a CustomBindingListener } } ============= class CustomBindingListener implements HttpSessionBindingListener { ServletContext context. The filter. } public void valueUnbound(HttpSessionBindingEvent event) { context.setContentType("text/plain"). HttpSession session = req. public CustomBindingListener(ServletContext context) { this.getSession(true). the servlet container routes the request to the filter instead of routing it to the resource. it checks whether a filter is associated with this resource.getWriter ().context = context. and then filters the data being passed between them.listener".getName() + " to " + event. • It passes on the request (modified or unmodified) to the next filter in the chain • It routes the request to a different resource. It acts as a guard. } } Q) Filter Filter is an object that intercepts a message between a data source and a data destination.getId()).log("UNBOUND as " + event.getSession(). after processing the request. IOException { res.getSession(). HttpServletResponse res) throws ServletException. new CustomBindingListener(getServletContext())).getId()). session. PrintWriter out = res.getName() + " from " + event. preventing undesired information from being transmitted from one point to another. If a filter is associated with the resource. } public void valueBound(HttpSessionBindingEvent event) { context.log("BOUND as " + event.Java Technoloies ========= public class SessionBindings extends HttpServlet { public void doGet(HttpServletRequest req. Examples of Filtering Components • Authentication filters • Logging and auditing filters • Image conversion filters • Data compression filters • Encryption filters • Tokenizing filters • Filters that trigger resource access events • MIME-type chain filters • Caching filters • XSL/T filters that transform XML content Nazar Babu 54 .putValue("bindings. does one of three things: • It generates the response itself and returns it to the client.

doFilter (request. ServletResponse response.Java Technoloies The javax. public void doFilter (ServletRequest request.filterConfig = filterConfig. } public void setFilterConfig (FilterConfig filterConfig) { this.println ("IOException raised in SimpleFilter"). response). } } Filter and the RequestDispatcher version 2. Q) Session Tracking Session tracking is the capability of the server to maintain the single client sequential list. By using the new <dispatcher>INCLUDE / FORWARD</dispatcher> element in the deployment descriptor.out & System. Nazar Babu 55 . like a hit counter for instance.err goes to 'server side' and is visible in error logs and/or on console.4 of the Java Servlet specification is the ability to configure filters to be invoked under request dispatcher forward() and include() calls.servlet. Q) Are Servlets multithread? A) Yes. ServletResponse response. } } public FilterConfig getFilterConfig() { return this. Q) What happens to System. FilterChain chain) public FilterConfig getFilterConfig() public void setFilterConfig (FilterConfig filterConfig) Ex:public class SimpleFilter implements Filter { private FilterConfig filterConfig. but u can use static variable to store and present information that is common to all threads. // for Filter Chain } catch (IOException io) { System. Each thread of your servlet runs as if a single user were accessing using it alone.out. err output in a Servlet? A) System. FilterChain chain) { try { chain.Filter interface defines three methods: public void doFilter (ServletRequest request.out goes to 'client side' and is seen in browser. while System.filterConfig. the servlet container allocates a thread for each new request for a single servlet.

we send less amount of data through GET. doPost().servlet. In generic we cannot maintain the state of next page only main state of current page. you can catch servlet errors and give custom error pages for them. Q) Can I catch servlet exception and give my own error message? (or) custom error pages? A) Yes. To make a servlet chain open your browser and give the alias name in URL. where one servlet output is piped to the next servlet output. The are 2 ways (i) Servlet Aliasing (ii) HttpRequest Servlet Aliasing  allow you to setup a single alias name for a comma delimited list of servlets. Nazar Babu 56 .  Http servlet can override doGet(). Q) Diff CGI & Servlet  Servlet is thread based but CGI is process based.Java Technoloies Q) Servlet chaining Is a technique in which two are more servlets cooperating in servicing a single client sequential request. you can use a RequestDispatcher to forward the request to an error page. If a servlet relies upon system or network resources that may not be available for unexpected reasons. CGI is platform dependent and servlet is platform independent. The amount of information limited is 240-255 characters (or 1kb in length). doDelete(). Generic servlet will implements all networking protocol  Http is stateless protocol. POST is to post the html data.servlet package.  Generic is from javax. generic servlet will override Service() method only. Q) Diff Http & Generic Servlet  HttpServlet class extends Generic servlet .  Get is to get the posted html data. but if there are exceptional conditions you can anticipate. Q) Diff GET & POST  GET & POST are used to process request and response of a client. Q) HttpTunnelling Is a method used to reading and writing serializes objects using a http connection.  CGI allow separate process for every client request. so Generic servlet is parent and HttpServlet is child. which mean each request is independent of previous one. You are creating a sub protocol inside http protocol that is tunneling inside another protocol.  A protocol is said to be stateless if it has n memory of prior connection.  Using POST we can send large amount of data through hidden fields. HttpServlet is from javax.  GET method is the part of URL. HttpRequest construct a URL string and append a comma delimited list of servlets to the end. doGet(). it would be better for your application to address these directly and try to avoid them in the first place. doTrace().  Http implements all Http protocols.  Http servlet extra functionality is capable of retrieving Http header information.Http package.

This header's value specifies the number of seconds to display the page before pulling the next one.lang. } Web. Server push Server push because the server sends. With server push. URL=http://home. <META HTTP-EQUIV="Refresh" CONTENT="5.URL=/servlet/stockquotes/"> Nazar Babu 57 . "3.RuntimeException </exception-type> <location> /err/RuntimeException. If no URL is given. try { // SQL operation } catch (SQLException se) { dispatcher. the socket connection between the client and the server remains open until the last page has been sent.com"). "3").Java Technoloies RequestDispatcher dispatcher = null. Client pull information is sent to the client using the Refresh HTTP header.jsp). response).xml <error-page> <error-code> HTTP error code (404) <error-code> <exception-type> java.forName(). and it optionally includes a URL string that specifies the URL from which to pull. It's called client pull because the client is responsible for pulling the content from the next page.jsp </location> </error-page> Q) How many ways we can instantiate a class? A) Class.forward(request. with one major difference: the browser actually displays the content from the first page and waits some specified amount of time before retrieving and displaying the content from the next page. a sequence of response pages to the client. the same URL is used. Here's a call to setHeader() that tells the client to reload this same servlet after showing its current content for three seconds: setHeader("Refresh".getRequestDispatcher(/err/SQL.netscape. And here's a call that tells the client to display Netscape's home page after the three seconds: setHeader("Refresh".newInstance() and new keyword Q) Client pull & Server push? Client pull Client pull is similar to redirection. request. or pushes.

they should be added to the response before you send any content. and they can limit each cookie's size to 4096 bytes. subject to certain rules. 300 total per user. hidden form fields define constant variables for a form. cookies are often used for session tracking. URL rewriting is another way to support anonymous session tracking. every local URL the user might click on is dynamically modified. it saves the cookie and thereafter sends the cookie back to the server each time it accesses a page on that server. When a browser receives a cookie. With URL rewriting. Nazar Babu 58 . or rewritten. You include hidden form fields with HTML like this: <FORM ACTION="/servlet/MovieFinder" METHOD="POST"> <INPUT TYPE=hidden NAME="zip" VALUE="94040"> <INPUT TYPE=hidden NAME="level" VALUE="expert"> </FORM> In a sense. To a servlet receiving a submitted form.Java Technoloies Q) How can a servlet refresh automatically if some new data has entered the database? A) You can use client side refresh are server push Q) How can i upload File using a Servlet? <FORM ENCTYPE="multipart/form-data" method=post action="/utils/FileUploadServlet"> <INPUT TYPE="file" NAME="currentfilename"> <INPUT TYPE="submit" VALUE="upload"> </FORM> Q) Session Tracking techniques (i) URL Rewriting (ii) Hidden form Field (iii) Persistence Cookies (iv) Session Tracking API (v) User Authorization URL Rewriting URL rewriting is a technique in which the requested URL is modified with the session id. Because cookies are sent using HTTP headers. Browsers are only required to accept 20 cookies per site. Because a cookie's value can uniquely identify a client. http://server:port/servlet/Rewritten?sessionid=123 added parameter Hidden form Field Hidden form fields are HTML input type that are not displayed when read by the browser. there is no difference between a hidden field and a visible field. Persistence Cookie A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser. They are sent back to the server when the form that contains them is submitted. to include extra information.

"123").setMaxAge(int seconds) method:  Zero means to delete the cookie  + value is the maximum number of seconds the cookie will live.length.value means the cookie will not be stored beyond this browser session (deleted on browser close) Session Tracking API In Java the javax. This will return the session for this user or create one if one does not already exist. A servlet retrieves cookies by calling the getCookies () method of HttpServletRequest: public Cookie[] HttpServletRequest. } } Deleting the Cookies <% Cookie killMyCookie = new Cookie("mycookie". A session object is created through the HttpServletRequest using the getSession() method: HttpSession session = request. Nazar Babu 59 . getCookies(). getValue().Java Technoloies Sending cookies from a servlet Cookie cookie = new Cookie ("ID". killMyCookie. if (cookies != null) { for (int i = 0. res. It allows a session object to be created for each user session. String value = cookies [i]. The code to fetch cookies looks like this: Reading browser cookies from a Servlet Cookie [] cookies = req. killMyCookie. null).addCookie (cookie).servlet. before it expires  . i < cookies. response.addCookie(killMyCookie). getName ().putValue("valueName". %> You can set the maximum age of a cookie with the cookie. Values can be stored for a user session using the HttpSession method putValue(): session.http.setPath("/"). i++) { String name = cookies [i].HttpSession API handles many of the details of session tracking. valueObject). then allows for values to be stored and retrieved for each session.setMaxAge(0).getSession(true).getCookies() This method returns an array of Cookie objects that contains all the cookies sent by the browser as part of the request or null if no cookies were sent.

either until user closes the browser or user remains idle for the session expiration time. value " + i + " is " + paramValues[i]. for (int i = 0. // Removing Valuefrom Session Object Nazar Babu 60 . while (params. when you create a session the server saves the session ID on the clients machine as a cookie. Internally if the amount of data being saved in Session exceeds the predefined limit. session. If the data to be store is very huge.out.getValue(MyIdentifier1). The user is required to enter a user name and password. The only limit is the Session ID length (Identifier). The container generates a session ID. } } Q) Session Session is a persistence network connection between client and server that facilitate the exchange of information between client and server.println("\nParameter name is " + paramName). session. i < paramValues. which should not exceed more than 4K. Values can also be removed using removeValue(String valueName) User Authorization Servers can be set up to restrict access to HTML pages (and servlets).removeValue(MyIdentifier1).getParameterNames(). When a user makes another request the user name can be used to add new items to their cart using the hashtable.getParameterValues(paramName).putValue ("MyIdentifier1". while a array of all value names can be retrieved using getValueNames().hasMoreElements()) { paramName = (String) params. For example.getSession(true). most of the servers write it to a temporary cache on Hard disk.length. // Prints value of Count session.toString()). As such there is no limit on the amount of information that can be saved in a Session Object. String[] paramValues = null.putValue ("MyIdentifier2".Java Technoloies Session objects can be retrieved using getValue(String name). count2). Servlets can use the username authorisation sent with request to keep track of user data. paramValues = request. Once they are verified the client re-sends the authorisation with requests for documents to that site in the http header. Q) Retrieving query parameters names? Enumeration params = request.nextElement(). System. // If “True” means creating a session if session is not there // if “False” means session is not created should one does not exist HttpSession session = req.println(". count1). // Storing Value into session Object session. a hashtable can be set up to contain all the data for a particular user. rather than saving it in session. Only the RAM available on the server machine is the limitation. String paramName = null. A session object created for each user persists on the server side. then it's preferred to save it to a temporary file onto hard disk.out. i++) { System.

notice that the session will time out rather than directly triggering session invalidate.xml Q) Cookie advantages & Disadvantages Advantages Persistence offer efficient way to implement session tracking for each client request a cookie can be automatically provide a clients session id.Java Technoloies Invalidating a Session There are 6 different ways to invalidate the session. then it referred to as Multiple Windows. But the quick alternative would be. Cookies are stored in a plain text format so every one can view and modify them. 4  calling invalidate() 5  if server cashes 6  put <session-timeout> in web. if cookies are disable also we can maintain sessions using URLRewriting. 2.  Cookies are store at client side so some clients may disable cookies so we may not sure that the cookies which we are maintaining may work or not. Sessions properties are maintained across all these windows. Q) Advantages of Sessions over Cookies & URLRewriting?  Sessions are more secure and fast because they are stored at server side. you may avoid "view source" (so that people can't see the hidden field). else user had disabled the option to accept cookies. in this case how can we proceed? A) 1. Browser only requires accepting 20 cookies per page and they can limit the cookie size to 4096 bytes. (from servlet) write the next page with a hidden field containing a unique ID that serves as "session ID".setMaxInactiveIntervel(int sec) 2  Session will automatically expire after a certain time of inactivity 3  User closes browser window. So next time when the user clicks submit. If you use applet. We can put maximum 300 cookies for entire application. then it was successfully saved. It cannot work if the security level set too high in browser. Some times browser does not accept cookies. after sending the required data to the users browser. 1  Httpsession. But sessions has to be used combindly with cookies (or) URLRewriting for maintaining client id that is session id at client side. redirect the response to a different Servlet which would try to read back the cookie. Q) If the cookies at client side are disabled then session don't work. Your applet reads back an ID from the servlet and use that from then on to make further requests Q) How to confirm that user's browser accepted the Cookie? A) There's no direct API to directly verify that user's browser accepted the cookie. Disadvantage The biggest problem with cookies is that browser do not always accept cookies. if we open a new Window. If this Servlet is able to read back the cookie. Nazar Babu 61 .  In URLRewriting we cannot maintain large data because it leads to network traffic and access may be become slow. you can retrieve the hidden field. Where in sessions will not maintain the data which we have to maintain instead we will maintain only the session id. Q) Diff between Multiple Instances of Browser and Multiple Windows? How does this affect Sessions? A) From the current Browser window.

Nazar Babu 62 . This is referred to as Multiple Instances of Browser.  Instead. but at the cost of increased resource requirements as more servlet instances are loaded at any given time.Java Technoloies even though they are operating in multiple windows. SingleThreadModel provides easy thread safety. “encodeURL” is for normal links inside your HTML pages. by either double clicking on the Browser Shortcut then we are creating a new Instance of the Browser. In this model no two threads will execute concurrently the service method of the servlet. Q) Why do you need both GET & POST methods in servlets? A) A single servlet can be called from different HTML pages. Q) encodeURL & encodeRedirectURL These are methods of HttpResponse object. browser name. to accomplish this each thread uses a free servlet instance from the servlet pool.sendRedirect(). if we open a new Browser. the server ensures that each instance of the servlet handles only one service request at a time. so different method calls can be possible. version and information about the machine on which it is running. public interface SingleThreadModel { } Q) Request Headers User-agent: . (or) If a servlet implements this interface. “encodeRedirectURL” is for a link your passing to response. So Sessions are not maintained across these windows. Q) SingleThread model SingleThreadModel is a tag interface with no methods. So any servlet implementing this can be considered thread safe and it is not required synchronize access to its variables.getHeader(“user-agent”).Gives the information about client software. request. Here each Browser window is considered as different client. Servers implement this functionality by maintaining a pool of servlet instances and dispatching incoming requests to free servlets within the pool.

getServletContext().forward("NextServlet") .Java Technoloies Q) Servlet output . rd.getRequestDispatcher (“/. servletResponse res){ ServletContext sc = getServletContext(). RequestDispatcher rd = sc. including Request Dispatching HTTP Redirect Servlet Chaining Servlet1 ServletContext sc = getServletContext(). Servlet2 Public void service(servletRequest req. Ex:. } Basically interServlet communication is acheived through servlet chaining./srevlet2”) . (The server cannot intervene and make sure your call happens when the servlet is not interacting with another client. otherServletDetails= Test. it is communication between servlets. your servlet should make an HTTP request to the other servlet instead of direct calls./srevlet1”) .to . There are some Servlet engine specific configurations for servlet chaining. your call could conflict with the servlet's single threaded nature.ServletContext. You can modify these objects and pass them so that the next servlet/JSP can use the results of this servlet. 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).getRequestDispatcher (“/..getServlet("OtherServlet"). You must be careful when you call another servlet's methods. These servlets should be running in the same server. Ex:. res).) In this case. RequestDispatcher rd = sc. [There are many ways to communicate between servlets.another Servlet? Inter-servlet communication? A) As the name says it.forward(req. Servlets talking to each other. If the servlet that you want to call implements the SingleThreadModel interface.TestServlet test= (TestServlet)getServletConfig(). Nazar Babu 63 .getServletDetails(). Servlets can also call public functions of other servlets running in the same server. This could be done by opening a URL connection to the desired Servlet.include(req. rd. HttpResponse). Which is a process in which you pass the output of one servlet as the input to other. You can pass in the current request and response object from the latest form submission to the next servlet/JSP. And then calling the function on the returned Servlet object.getRequestDispatcher(HttpRequest.. res). Servlets could also invoke other servlets programmatically by sending an HTTP request.

getNamedDispatcher() Nazar Babu 64 . specifying the HTTP request and response objects as arguments.getRequestDispatcher("/jsp/mypage.RequestDispatcher interface. f. Complete the following steps in your code to use this mechanism: 1) Get a servlet context instance from the servlet instance: ServletContext sc = this. See "Passing Data Between a JSP Page and a Servlet" below for information.servlet. response).getRequestDispatcher() context. } } The jsp page Bean1. you can optionally make data available to the JSP page through attributes of the HTTP request object. f.forward(request.include(request. Prior to or during this step.forward(req.j sp”).setAttribute(“fBean”. Q) context.getServletContext(). res).(Or) ----------------------------------------You can invoke a JSP page from a servlet through functionality of the standard javax.getParameter(“addr”)).setName(req.Java Technoloies Q) Servlet – to.getRequestDispatcher(“/jsp/Bean1.FormBean f = new govi. f.getRequestDispatcher() request.setAdress(req.f).formBean” scope=”request” /> <jsp:getProprety name=”fBean” property=”name” /> <jsp:getProprety name=”fBean” property=”addr” /> -----------------------------------------.jsp can then process fBean. getServletConfig(). response). } catch(Exception ex).getServletContext(). HttpServletResponse res){ Try{ govi. Note that the forward() method clears the output buffer.formBean(). <jsp:useBean id=”fBean” class=”govi. req.JSP/Servlet communicate? (or) How Servlet invoke a JSP page? public void doPost(HttpServletRequest req. The functionality of these methods is similar to that of jsp:include and jsp:forward actions.setPersonalizationInfo(info). The include() method only temporarily transfers control. 3) Invoke the include() or forward() method of the request dispatcher.getParameter(“name”)).jsp"). 2) Get a request dispatcher from the servlet context instance. execution returns to the invoking servlet afterward. specifying the pagerelative or application-relative path of the target JSP page as input to the getRequestDispatcher() method: RequestDispatcher rd = sc. rd. / rd.

then you must use sendRedirect. the URL in the address bar doesn’t change. —> You must use 2) ServletRequest.getRequestDispatcher("/HelloWorldExample").include (request. but you will be sending a header asking to the browser to issue a request to the new URL. } } } RequestDispatcher dispatcher = getServletContext(). Nazar Babu 65 .getRequestDispatcher( / ) Absolute paths. Return.forward(re quest. Q) How can I pass data from a servlet running in one context (webapp) to a servlet running in another context? A) You can bind this information to a context that is accessible to all servlet contexts.  If you want to dispatch to resources OUTSIDE the context. IOException { try { getServletConfig() .getRequestDispatcher(Relative Path) —> The path may be Relative. } else{ dispatcher. but cannot extend outside current servlet context. 3) ServletRequest. and is in the web. } catch (Exception ex) { ex. HttpServletResponse res) throws ServletException. you must use getRequestDispatcher (or) getNamedDispatcher.getNamedDispatcher(String name) —> This name is the name of the servlet for which a dispatcher is requested. getRequestDispatcher () / getNamedDispatcher?  When you want to preserve the current request/response objects and transfer them to another resource WITHIN the context. The client looses path information when it receives a forwarded request.printStackTrace (). response). it can extend outside current servlet context. response). } Q) Different cases for using sendRedirect () vs.Java Technoloies 1) ServletContext.getRequestDispatcher(path).xml file Ex :public class ServletToServlet extends HttpServlet { public void doGet (HttpServletRequest req. if (dispatcher == null) { out.println (path + “not available"). In this case you won't be sending the original request/response objects. such as the application server's context. you can keep the data you want to share in memory. This way.getServletContext().

The former returns the path to the script including any extra path information following the name of the servlet. doPost( ) and service( ) ) of the servlet.Java Technoloies Q) How can I share data between two different web applications? A) Different servlets may share data within one application via ServletContext. this.user = user. user. i < initialConnections.getConnection(dbURL.put(DriverManager. ServletKiller.FALSE). Q) How do servlets handle multiple simultaneous requests? A) The server has multiple threads that are available to handle requests. String user. If you have a compelling to put the servlets in different applications. private String dbURL. http://www. When a request comes in. i++) { connections.com/servlets/HelloServlet/jdata/useri URL nfo?pagetype=s3&pagenum=4 GetRequestURI GetServletPath GetPathInfo GetQueryString servlets/HelloServlet/jdata/userinfo servlets/HelloServlet/ /jdata/userinfo pagetype=s3&pagenum=4 Q) How can i stress test my Servlets? A) following products to stress test your Servlets. connections = new Hashtable(). For this reason. the latter strips the extra path info. E-Load.int initialConnections. Boolean. password). this. JMeter from Apache Q) Connection pool class public class ConnectionPool { private Hashtable connections. ClassNotFoundException { Class.javasoft. this.getRequestURI() / req. user. which calls a service method (for example: doGet(). } } public Connection getConnection() throws SQLException { Nazar Babu 66 . a single servlet object can have its service methods called by many threads at once.forName(driverClassName).dbURL = dbURL. String password.getServletPath(). this.increment = increment. Q) How do i get the name of the currently executing script? A) req. int increment) throws SQLException. it is assigned to a thread. String driverClassName. Web Application Stress Tool. public ConnectionPool(String dbURL. password.password = password. // Put our pool of Connections in the Hashtable // The FALSE value indicates they're unused for(int i = 0. private int increment.

// For production use.setAutoCommit(true). for(int i = 0.nextElement().get(con). Enumeration cons = connections.getConnection(dbURL.keys().put(con.FALSE). } catch(SQLException e) { // Problem with the connection. such as executing a simple query. there were no free connections. return con.hasMoreElements()) { con = (Connection)cons. Boolean. Enumeration cons = connections. Boolean b = (Boolean)connections.put(DriverManager.keys().FALSE) { // So we found an unused connection. replace it. user. } // Update the Hashtable to show this one's taken connections. // We've got to make more. Test its integrity with a quick setAutoCommit(true) call. con = DriverManager. } } } // If we get here.Java Technoloies Connection con = null. if (b == Boolean. user. try { con.getConnection(dbURL. } public void returnConnection(Connection returned) { Connection con. } // Recurse to get one of the new connections.hasMoreElements()) { con = (Connection)cons. while (cons.put(con. return getConnection(). Boolean. synchronized (connnections) { while(cons.TRUE). password). more testing should be performed. i++) { connections. } } } } Nazar Babu 67 . Boolean.FALSE). if (con == returned) { connections. i < increment. password). break.nextElement().

Java Technoloies JSP Why JSP Technology? •Servlets are good at running logic –Not so good at producing large amounts of output –out.write() is ugly •JSP pages are great at producing lots of textual output –Not so good at lots of logic –<% %> is ugly How does it Work ? •“JSP page” –Mixture of text. We can also include “Static” files using this directive. Page directive defines information that will be globally available for that page Page Directive Nazar Babu 68 . text/ xml or text/ plain •“JSP engine” –‘Compiles’ page to servlet –Executes servlet’s service() method •Sends text back to caller •Page is –Compiled once –Executed many times Directives: <%@ Page language="java" extends="className" import="className" session="true| false" buffer="8KB" autoFlush="true/false" isThreadSafe="true/false" info="text" errorPage="jspUrl" isErrorPage="true/false" contentType="mimeType” %> XML syntax: <Jsp: directive. Script and directives –Text could be text/ html.page file=” ” /> Include JSP are Servlet at compile time meaning that only once parsed by the compiler.include file=” ” /> <Jsp: directive.page import=” ” /> <%@ include file="relative URL" %> XML syntax: Include Directive <Jsp: directive. it will act as a “C” "#include" pulling in the text of the included file and compiling it as if it were part of the including file.

and it Includes a static file or sends a request to a dynamic file. Jsp Include includes the JSP are Servlet at request time. value pairs. <Jsp: getProperty> <Jsp: param> <Jsp: include> <Jsp: include page="relativeURL " flush="true" > <Jsp: param name="username" value="jsmith" /> </jsp: include> <Jsp: forward page="{relativeURL| <%=expression %>}" > <jsp: param name="paramName" value="paramValue"/> </jsp: forward> Gets the value of a bean property so that you can display it in a result page. When ever the client request will come it will take the request and process the request and the request to be forward to another page and it will also forward <Jsp: forward> Nazar Babu 69 . jsp:plugin. This is used to conjunction with jsp:include..” version=”1. <Jsp: useBean> <Jsp: setProperty> Sets a property value or values in a bean. It is used to provide other tags with additional information in the form of name. Actions: <Jsp: useBean id="beanInstanceName" scope="page|request|session| application” class=""/ type="" bean Name=" "</jsp: useBean> <Jsp: setProperty name="beanInstanceName” property="*" |"propertyName” param="paramName" value="{string | <%= expression %>}" /> <Jsp: getProperty name="beanInstanceName" property="propertyName" /> <Jsp: param name="beanInstanceName" value=" parameterValue " /> UseBean tag is used to associate a java bean with jsp.Java Technoloies <%@ taglib uri="uriToTagLibrary" prefix="prefixString" %> Taglib Directive XML syntax: <Jsp: root xmlns:prefix1=”http://. it is not parsed by the compiler. jsp:forward.2” /> </Jsp: root> Taglib directive enables you to create your own custom tags.

http. setAttribute.Objects accessible from pages belonging to the same session as the one in which they were created. It will work at server side. Session javax.Java Technoloies the http parameters of the previous page to the destination page.servlet. setAttribute Not typically used by JSP page authors Session .Servlet Context .Refers to the response sent to the client. applicatio n getAttribute.JSP 1.servlet. <Jsp: plugin> <Jsp: plugin type="bean/applet" code="classFileName" codebase="classFileDirectoryName" name="instanceName" archive="” align="" height=" " width=" " hspace=" " vspace=" </jsp: plugin> Implicit Objects Objects Type / purpose Request Subclass of javax. Page Sum useful methods getAttribute. getParameterName s. followed by execution of applet or java bean component specified in tag.Objects accessible from pages processing the request where they were created. It is also passed to the _jspService() method. getRealPath. javax.Refers to the current request passed to the _jspService() method Response Subclass of javax.http. getParameterValue s. getParameter. then using the session keyword results in a fatal translation time error.servlet. getAttribute.http.Use it to find information about the servlet engine and the servlet environment. This action is used to generate client browser specific html tags that ensures the java plug in software is available. Application . Scope Request .servlet. getMimeType.HttpS ession .Objects accessible from pages belonging to the same application.2 specification states that if the session directive is set to false. getId.Servl etResponse . setAttribute Nazar Babu 70 .Servl etRequest .

ServletCo nfig . getLocalizedMessa ge. setAttribute. from which you can display it. getRemaining getInitParameter.Objects accessible only within jsp pages where it was created. .Object.Provides certain convenience methods and stores references to the implicit objects.Available for pages that set the page directive attribute isErrorPage to true. printStackTrace. getAttributeNames InScope.lang.Refers to the current instance of the servlet generated from the JSP page. java.Java Technoloies Out javax. the output is stored in the out object. getAttribute. getMessage.servlet. XML syntax: Scriptlet <Jsp: scriptlet> Date today = new Date(). If the scriptlet produces output. . flush. Page Not typically used by JSP page authors exception Page findAttribute.The initialization parameters given in the deployment descriptor can be retrieved from this object.lang. . clearBuffer. getBufferSize. java.PageC ontext. when the JSP engine processes the client request.servlet.JspWri ter .jsp. </jsp: scriptlet> Nazar Babu 71 . getInitParameterN ames Config Page page pageCont ext Page . toString Sum useful methods A scriptlet can contain variable (or) method declarations (or) expressions. javax. Scripting Elements: Type / purpose Elements <% Java_code %> Page clear. getAttributesScope .Throwable.jsp. javax.servlet.Refers to the output stream of the JSP page. It can be used for exception handling. Scriptlets are executed at request time.

</jsp: Declaration> Ex: <%= (new java. } %> XML syntax: <jsp: declaration> int counter=0.util. Q) MVC A declaration declares one or more variables (or) methods for use later in the JSP source file. %> <%! private void processAmount () { . Explicit objects are typically JavaBean instances declared and created in jsp:useBean action statements. converted to a String. This is used for “Global declaration”.comment --%> Q) Diff Explicit Objects & Implicit Objects Explicit Explicit objects are declared and created within the code of your JSP page. %> <%! int accountnumber=23468. accessible to that page and other pages according to the scope setting you choose.<%= expression %> --> Hidden Comment  Documents the JSP file.toLocaleString() %> XML syntax: <jsp: expression> // ------</jsp: expression> Html comment  Creates a comment that is sent to the client in the viewable page source. and inserted where the expression appears in the JSP file. Ex: <%-. Comments are removed from the viewable source of your HTML files by using only JSP comment tags. Declaration Expressions Comments An expression tag contains a scripting language expression that is evaluated. b. c.. HTML comments remain visible when the user selects view source in the browser. <jsp:useBean id="pageBean" class="mybeans. but is not sent to the client. Ex: <! -.NameBean" scope="page" /> Implicit Implicit objects are created by the underlying JSP mechanism and accessible to Java scriptlets (or) expressions in JSP pages according to the inherent scope setting of the particular object type.Java Technoloies Ex: <%! int a. Nazar Babu 72 .Date())..

If page1. it will execute at “server side”. passing it the request and the response objects. It cannot forward the http parameters of the previous page.Java Technoloies Model: .Until the session timeout (or) session id invalidate. jspDestroy( )  container calls this when it decides take the instance out of service.forward() res. res) RequestDispatcher.Life of container (or) explicitly killed Q) Life-cycle of JSP Page translation Jsp compilation Load class Create Instance jspInit( ).  Major benefits of using the MVC design pattern is separate the view & model this make it is possible to create are change views with out having to change the model. Q) WebApplication scopes? A) Request.sendRedirect(url) when ever the client request will come just it will take the request and the request to be forwarded to another page. and is called only once for a servlet instance. It is called before any other method. Application :. res) PageContext.jsp.Controller is a servlet that performs necessary manipulations to the model.sendRedirect(url) <jsp:forward> RequestDispatcher. It is the last method called n the servlet instance. _jspservice( )  container calls _jspservice() for each request. res) in forward req. _jspservice( ).include(req.jsp. the browser's address bar be updated to show page2.jsp redirects to page2. 3) The jsp formats the model for display and send the html results back top the web browser. Request :. Q) RequestDispatcher.model is a java bean/entity bean that represent the data being transmitted are received Controller: . Application. res.forward(req. This will work at “client side”. Nazar Babu 73 .forward(req. Session. jspDestroy( ) jspInit( )  container calls the jspInit() to initialize to servlet instance.  Destroy is not called if the container crashes.Life time is until the response is return to the user Session :.  1) The browser makes a request to the controller servlet 2) Servlet performs necessary actions to the java bean model and forward the result to the jsp view.  jspInit() & jspDestroy() called only once so we cannot override these methods. res would be passed to the destination URL and the control will return back to the same method.is a screen representation of the model. View: .

The included page is inserted into the current page or output stream at the indicated point. the advantage is that you can point to any resource(whether on the same domain or some other domain).jsp. where the fwd. that means this route is made by the servlet engine at the server level only. res) public class BookStoreServlet extends HttpServlet { public void doGet(HttpServletRequest req.getRequestDispatcher("/bookstore. for eg if sendRedirect was called at www. HttpServletResponse res) throws ServletException.include() and <jsp:include> both include content. Ex -. call was made. IOException { // Get the dispatcher.forward(request. it's like any other Http request being generated by your browser. the browser uses this header to make another fresh request. In the case of forward() call.sendError(response.forward() and RequestDispatcher.html"). } else { // Send the user the bookstore's opening page dispatcher.html in this case) cannot be found res.jsp.SC_NO_CONTENT).Java Technoloies PageContext. also the request and response objects remain the same both from where the forward call was made and the resource which was called. response).sendRedirect() operations updates the browser history. res.com. res) RequestDispatcher. if (dispatcher == null) { // No dispatcher means the resource (bookstore. PageContext. RequestDispatcher. The difference between the two is that sendRedirect always sends a header back to the client/browser.com then it can also be used to redirect a call to a resource on www.of RequestDispatcher.mydomain.forward(req. resources from the server. it gets the main page to the user RequestDispatcher dispatcher = config.include(req. no headers are sent to the browser which makes this very efficient. It will execute at “server side” so the browser unaware of the changes. Forward operations are faster because all processing is done at server side. can only be requested for.forward() are effectively the same. it will also forward the http parameters of the previous page to the destination page.theserverside. this header then contains the resource(page/servlet) which you wanted to be redirected. the browser address bar will still show page1. thus sendRedirect has a overhead as to the extra remort trip being incurred.jsp redirects to page2. <Jsp: forward> Forwards a client request to an HTML file/JSP file/servlet for processing.getServletContext(). When ever the client request will come it will take the request and process the request and the request to be forward to another page. } Nazar Babu 74 . But the major diff between the two is that forward just routes the request to the new resources which you specify in your forward call. It will execute at “server side”.forward is a helper method that calls the RequestDispatcher method. the above is not true. If page1.

Q) Diff Jsp & Servlet Internally when jsp is executed by the server it get converted into the servlet so the way jsp & servlet work is almost similar. The browser will normally interpret this response by initiating a new request to the redirect URL given in the response.  In jsp we can easily separate the P. if you indicate that it is an error-processing page. forward()  does not involve the client's browser. (Or) includes a jsp/servlet at compile time meaning only once parsed by the compiler. If you want the browser to initiate a new request to a different servlet/jsp. if you want to hide the fact that you're handling the browser request with multiple servlets/jsp.jsp"> include a jsp/servlet at request time it is not parsed by the compiler. and all of the servlets/jsp are in the same web application. but in servlet both are combined. use forward() or include(). pulling in the text of the included file and compiling it as if it were part of the including file.jsp” %> <%@include file="abc.forward( ) sendRedirect()  sends a redirect response back to the client's browser. The included file can be any type (including HTML or text).jsp.  One servlet object is communicate with many number of objects.jsp\" %> redirects the browser to the JSP page error. Within error. Nazar Babu 75 . but jsp it is not possible.jsp"%> directive acts like C "#include". For ex. For example: <%@ page errorPage=\"error. and hands it off to another servlet/jsp to handle.jsp if an uncaught exception is encountered during request processing. <jsp:include page="abc.sendRedirect( ) & req. You can make a page “thread-safe” and have it serve client requests in a singlethreaded fashion by setting the page tag’s is Thread Safe attribute to false: <%@ page is ThreadSafe=”false” %> Q) How does JSP handle runtime exceptions? A) You can use the errorPage attribute of the page directive to have uncaught runtime exceptions automatically forwarded to an error processing page.L with B. It just takes browser's current request.Java Technoloies Q) Diff res. use sendRedirect (). The client doesn't know that they're request is being handled by a different servlet/jsp than they originally called.L. via the directive: <%@ page isErrorPage=\"true\" %>. Q) Can JSP be multi-threaded? How can I implement a thread-safe JSP page? A) By default the service() method of all the JSP execute in a multithreaded fashion. Q) Diff <%@ include file="file" %> & <jsp:include page=”abc. or if the servlet/jsp you want to forward to is not in the same web application.

setHeader("Pragma".create().). accHome = (AccountHome)PortableRemoteObject. If your users to increase in the future. Q) What's a better approach for enabling thread-safe servlets & JSPs? SingleThreadModel Interface or Synchronization? A) SingleThreadModel technique is easy to use."no-store"). javax.doWhatever(. foo. all the unserviced requests are queued until something becomes free.AccountHome. and works well for low volume sites.Java Technoloies Q) How do I prevent the output of my JSP or Servlet pages from being cached by the Web browser? And Proxy server? A) Web browser caching <% response.AccountHome.setHeader("Cache-Control"."private").narrow(ref. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool.lookup("java: comp/env/ejb/AccountEJB").sendRedirect("http://path/YourServlet?param1=val1"). public void jspInit() { InitialContext cntxt = new InitialContext( )..*. you may be better off implementing explicit synchronization for your shared data Also.to-EJB Session Bean communication? <%@ page import="javax.Account" %> <%! AccountHome accHome=null."no-cache"). %> Nazar Babu 76 .setDateHeader ("Expires".. acct.rmi. note that SingleThreadModel is pretty resource intensive from the server's perspective.PortableRemoteObject.naming.class). %> Proxy server caching response. Variables also 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. response. foo.sendRedirect("http://path/YourServlet"). In that case. Object ref= cntxt. 0). response. Q) Invoking a Servlet from a JSP page? Passing data to a Servlet invoked from a JSP page? A) Use <jsp:forward page="/relativepath/YourServlet" /> (or) response. Q) JSP.setHeader("Cache-Control". } %> <% Account acct = accHome.

Java Technoloies
Q) How do you pass an InitParameter to a JSP? <%! ServletConfig cfg =null; public void jspInit(){ ServletConfig cfg=getServletConfig(); for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();) { String name=(String)e.nextElement(); String value = cfg.getInitParameter(name); System.out.println(name+"="+value); } } %> Q) How to view an image stored on database with JSP? <%@ page language="java" import="java.sql.*,java.util.*"%> <% String image_id = (String) request.getParameter("ID"); if (image_id != null){ try { Class.forName("interbase.interclient.Driver"); Connection con = DriverManager.getConnection("jdbc:interbase://localhost/D:/examp/Database /employee.gdb","java","java"); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM IMMAGINE WHERE IMMAGINE_ID = " + image_id); if (rs.next()) { String dim_image = rs.getString("IMMAGINE_DIMENSIONE"); byte [] blocco = rs.getBytes("IMMAGINE_IMMAGINE"); response.setContentType("image/jpeg"); ServletOutputStream op = response.getOutputStream(); for(int i=0;i<Integer.parseInt(dim_image);i++) { op.write(blocco[i]); } } rs.close(); stmt.close(); con.close(); } catch(Exception e) { out.println("An error occurs : " + e.toString()); } } %>

Nazar Babu

77

Java Technoloies
Q) How do I pass values from a list box (with multiple selects) to a Java Bean? Consider the following HTML, which basically allows the user to select multiple values by means of a checkbox: What's your favorite movie? <form method=post action=Movies.jsp> <input type=checkbox name=faveMovies value="2001: A Space Odyssey"> 2001: A Space Odyssey <input type=checkbox name=faveMovies value="The Waterboy"> The Waterboy <input type=checkbox name=faveMovies value="The Tin Drum"> The Tin Drum <input type=checkbox name=faveMovies value="Being John"> Being John Malkovich <input type=submit> </form> To handle HTML elements like checkboxes and lists which can be used to select multiple values, you need to use a bean with indexed properties (arrays). The following bean can be used to store the data selected from the above check box, since it contains an indexed property movies: package foo; public class MovieBean { private String[] movies; public MovieBean() { String movies[] = new String[0]; } public String[] getMovies() { return movies; } public void setMovies(String[] m) { this.movies = m; } } Although a good design pattern would be to have the names of the bean properties match those of the HTML input form elements, it need not always be the case, as indicated within this example. The JSP code to process the posted form data is as follows: <html> <body> <%! String[] movies; %> <jsp:useBean id="movieBean" class="foo.MovieBean"> <jsp:setProperty name="movieBean" property="movies" param="faveMovies" /> </jsp:useBean> <% movies = movieBean.getMovies(); if (movies != null) { out.println("You selected: <br>"); out.println("<ul>"); for (int i = 0; i < movies.length; i++) {

Nazar Babu

78

Java Technoloies
out.println ("<li>"+movies[i]+"</li>"); } out.println("</ul>"); } else out.println ("Don't you watch any movies?!"); %> </body></html> Q) Tag Libraries These all methods are callback methods. Tag methods: doStartTag() Body Tag : doAfterBody()

doEndTag()

Nazar Babu

79

independent developers. The Controller receives the request from the browser. custom tags. Client tier parameters are automatically transmitted to the business logic bean. 10. 3. Removal of Admin actions.Plug-ins. The end result is a cooperative. 4.action. And controller receives the UI tier parameters.xml and struts-config.0 & 1. 11. Controller and business logic beans are tightly coupled.xml file.Change to Commons logging. 5. 6. Controller and business logic are loosely coupled and controller has nothing to do with the project/ business logic as such. suitable for development teams. ``semi-complete'' application that can be specialized to produce custom applications Q) Why do we need Struts? A) Struts combines Java Servlets.Nested Tags. invoke a business operation and coordinating the view to return to the client.The Struts Validator Change to the ORO package. synergistic platform.ActionServlet is the called the ActionServlet.RequestProcessor class. Q) How to Configure Struts? Before being able to use Struts. So Model2 is a project specific model and MVC is project independent. Declarative exception handling. and business logic is java bean. 12.xml. 7. one for each application should suffice Q) ActionServlet (controller) The class org. Q) Diff Struts1. 9. 8.Deprecation of the GenericDataSource Q) What is the difference between Model2 and MVC models? In model2.xml) that specifies action mappings for the application while it's possible to define multiple controllers in the web. Java ServerPages.Method perform() replaced by execute() in Struts base Action Class. This is done in the web. you must set up your JSP container so that it knows to map all appropriate requests with a certain file extension to the Struts action servlet. and message resources into a unified framework. controller is servlet. and everyone in between. Q) Action Class The Action Class is part of the Model and is a wrapper around the business logic. Controller is responsible for handling all the requests. Changes to web. In Struts Framework this class plays the role of controller. it reads a configuration file (struts-config. When the control is initialized. All the requests to the server goes through the controller. The purpose of Action Class is to translate the HttpServletRequest to the Nazar Babu 80 .1? 1.Multiple Application Modules. 2.xml file that is read when the JSP container starts.apache.struts.Java Technoloies Struts Q) Framework? A) A framework is a reusable. we have client tier as jsp. But in MVC. commonly called as ActionForm.Dynamic ActionForms.

servlet.roledesc = "". import javax.struts. Ex: package com. public class BillingAdviceAction extends Action { public ActionForward execute(ActionMapping mapping.servlet.apache. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. It is advisable to perform all the database related stuffs in the Action Class. } public void setProjectid(String projectid) { this.required”)). HttpServletResponse response) throws Exception { BillingAdviceVO bavo = new BillingAdviceVO(). private String projectname. return (mapping. } } Q) Action Form An ActionForm is a JavaBean that extends org.form.HttpServletResponse. } public ActionErrors validate(ActionMapping mapping. BillingAdviceForm baform = (BillingAdviceForm)form.action.name. this. Ex: package com. if(getProjectName() == null || getProjectName().setAttribute("projects". ActionForm form. BillingAdviceDAO badao = new MySqlBillingAdviceDAO(). 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.odccom. } public void reset(ActionMapping mapping.ActionForm. public String getProjectid() { return projectid. }} Nazar Babu 81 .length() < 1){ errors. ArrayList projects = badao. request. import javax.getProjects(). HttpServletRequest request) { ActionErrors errors = new ActionErrors().add(“name”. In the Action Class all the database/business processing are done.findForward("success")).odccom.struts. we need to Subclass and overwrite the execute() method.http. new ActionError(“error. 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.action.projectid = projectid.http. To use the Action.projects).currid = "".struts. } return errors. HttpServletRequest request. public class BillingAdviceForm extends ActionForm { private String projectid.Java Technoloies business logic.HttpServletRequest. HttpServletRequest request){ this. DAOFactory factory = new MySqlDAOFactory().

configuring Validator's two configuration files. The controller creates an instance of the Action class if one does not already exist. The ActionForm should perform any input validation that can be done and return any detected errors to the controller. Nazar Babu 82 . public ActionForward execute( ActionMapping mapping. The frame work will create only a single instance of each Action class. Enabling the Validator plug-in: This makes the Validator available to the system.R. HttpServletRequest request request) } Q) execute Is called by the controller when a request is received from a client.properties” file these files contains the messages that can be used in struts project. purpose of this method is to reset all of the forms data members and allow the object to be pooled for rescue. HttpServletRequest request) Q) What is Validator? Why will you go for Validator? Validator is an independent framework.D can be added in struts-config. with validator you use an xml configuration file to declare the validations that should be applied to each form bean. 4.D file are simple “. The M. Create Message Resources for the displaying the error message to the user.Java Technoloies Q) Message Resource Definition file M. HttpServletResponse response) Q) Validate: This method is called by the controller after the values from the request has been inserted into the ActionForm.xml file through <message-resource> tag ex: <message-resource parameter=”MessageResource”> Q) Reset :This is called by the struts framework with each request. and creating Form Beans that extend the Validator's ActionForm subclasses. Using Validator Framework Using the Validator framework involves enabling the Validator plug-in. Developing the Validation rules We have to define the validation rules in the validation. Applying the rules: We are required to add the appropriate tag to the JSP for generation of JavaScript. HttpServletRequest request. Validator supports both “server-side and client-side” validations where form beans only provide “server-side” validations.xml for the address form. Struts Validator Framework uses this rule for generating the JavaScript for validation. Public ActionErrors validate(ActionMapping mapping. Flowing steps: 1. Instead of coding validation logic in each form bean’s validate() method. struts still comes packaged with it. public class TestAction extends ActionForm{ public void reset(ActionMapping mapping. ActionForm form. 3. 2.R.

Java Technoloies Enabling the Validator Plug-in Validator framework comes packaged with Struts.struts. org.xml file. The Validator Framework uses two XML configuration files validator-rules.required"> <javascript> <![CDATA[ function validateRequired(form) { ]]> </javascript> </validator> </global> </form-validation> Q) How struts validation is working? Validator uses the XML file to pickup the validation rules to be applied to a form.ValidatorPlugIn"> <set-property property="pathnames" value="/technology/WEB-INF/validatorrules.http. Q) What is Tiles? A) Tiles is a framework for the development user interface. Nazar Babu 83 . To enable Validator.ValidatorAction.validator. Upon initialization.commons. The validation.struts. <plug-in className="org.struts. Email Address validation and more. org. Validator-rules.validator. such as Required.xml.ActionErrors.action.validator. javax.xml.apache.Field.FieldChecks" method="validateRequired" methodParams="java.xml"/> </plug-in> This definition tells Struts to load and initialize the Validator plug-in for your application. In case we need special validation rules not provided by the validator framework. These are reusable and used in validation. In XML validation requirements are defined applied to a form.lang.xml defines the standard validation routines.apache. add the following plug-in definition to your application's struts-config.xml defines the validations applied to a form bean. Validator is not enabled by default.xml & validation.Object.apache. org. Tiles is enables the developers to develop the web applications by assembling the reusable tiles.commons. Maximum length.xml. /WEB-INF/validation. we can plug in our own custom validations into Validator.servlet. Minimum Length.HttpServletRequest" msg="errors. The validator-rules.apache. Date Validation. To define the form specific validations.apache. the plug-in loads the comma-delimited list of Validator config files specified by the pathnames property.xml <form-validation> <global> <Validator name="required" classname="org.validator.

2. So that it is available to all the pages that for a part of the request Q) How would struts handle “messages” required for the application? A) Messages are defined in a “. Q) How to call ejb from Struts? 1…use the Service Locator patter to look up the ejbs. looping over object collections for repetitive generation of output text. Create layout JSPs.empname”/> Nazar Babu 84 . Struts-logic tag library -> can manage conditional generation of output text. ActionForward etc.properties file in WEBINF/classes folder and define in struts-config. and application flow management. Struts-tiles tag library -> This will allow you to define layouts and reuse those layouts with in our site.xml. To make these messages available to the application. Q) How you will save the data across different pages for a particular client request using Struts? A) If the request has a Form object. Action. call request.xml <message-resource parameter=”title. Struts-template tag library -> contains tags that are useful in creating dynamic JSP templates for pages which share a common format.empname”/> and in order to display a message in a jsp would use this <bean:message key=”title. 3. Struts-bean tag library -> provides substantial enhancements to the basic capability provided by . ActionMapping.properties” file as name value pairs.Using validators Q) What are the core classes of struts? A) ActionForm.getSession and use session. though that will persist through the life of the session until altered. Develop the web pages using layouts. the data may be passed on through the Form object across pages.Java Technoloies 1. -The “exceptions” can be wrapped across different layers to show a user showable exception. Or within the Action class. 2…Or you can use InitialContext and get the home interface. Struts-nested tag library -> Q) How you will handle errors & exceptions using Struts? -To handle “errors” server side validation can be used using ActionErrors classes can be used. You need to place the . (Or) Create an appropriate instance of ActionForm that is form bean and store that form bean in session scope.setAttribute(). . Q) What are the various Struts tag libraries? Struts-html tag library -> used for creating dynamic HTML user interfaces and forms. Add the Tiles Tag Library Descriptor (TLD) file to the web.

action form is used to populate the html tags in jsp using struts custom tag. We are going to use a subclass of DynaActionForm called a DynaValidatorForm which provides greater functionality when used with the validation framework. In struts 1.struts.1 dyna action form is introduced. The dyna action form bloats up with the struts-config.if the formbean is a subclass of ActionForm.lang.xml? A) Yes you can I have more than one.basically this simplifies coding DynaActionForm which allows you to configure the bean in the struts-config.lang.apache.set("age".validate().String"/> <form-property name="age" type="java. but usually only one is needed Q) Can I have more than one struts-config. 2. <servlet> <servlet-name>action</servlet-name> <servlet-class>org.0.This can be used to develop using xml. the change in action class is needed. if you need to define a property: formBean.struts.validator.ActionServlet</servlet-class> Nazar Babu 85 . getters but in strutsconfig.lang. Q) Struts how many “Controllers” can we have? A) You can have multiple controllers. To avoid the chages in struts 1.DynaValidatorForm"> <form-property name="name" type="java. In order to get fields out of the DynaActionForm you would do: String age = (String)formBean. we can provide reset().String"/> <form-property name="department" type="java.when the java code changes.String"/> </form-bean> </form-beans> </struts-config> This DynaValidatorForm is used just like a normal ActionForm when it comes to how we define its use in our action mappings."33").gettters whereas if the formbean is a subclass to DynaActionForm we need not provide setters. Where as we have to create Actionform class with getter and setter methods which are to be populated from the form 3.xml we have to configure the properties in using . The only 'tricky' thing is that standard getter and setters are not made since the DynaActionForms are backed by a HashMap. Similarly.apache. There is no need to write actionform class for the DynaActionForm and all the variables related to the actionform class will be specified in the struts-config.xml file.xml based definetion. <struts-config> <form-beans> <form-bean name="employeeForm" type="org.lang.String" initial="2" /> <form-property name="flavorIDs" type="java.String[]"/> <form-property name="methodToCall" type="java.action.lang.setters(to hold the values).Java Technoloies Q) What is the difference between ActionForm and DynaActionForm? A) 1.xml.get("age").

xml file.xml <struts-config> <data-sources> <data-source> <set-property property=”key” value=”” url=”” maxcount=”” mincount=”” user=”” pwd=”” > </data-source> <data-sources> <!— describe the instance of the form bean-. } If the user want to call any methods.Java Technoloies <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config. HttpServletResponse response) throws Exception { Return some thing. he would do something in struts-config.xml</param-value> </init-param> <! — module configurations -. } public ActionForward update(ActionMapping mapping.reumann.jsp" /> </action> Q) Struts-config. ActionForm form. Public class StudentAction extends DispatchAction { public ActionForward read(ActionMapping mapping.> <form-beans> <form-bean name="employeeForm" type="net.struts.EmployeeForm"/> </form-beans> Nazar Babu 86 .StudentAction" name="StudentForm" <b>parameter=”methodToCall”</b> scope="request" validate="true"> <forward name="success" path="/Home. HttpServletResponse response) throws Exception { Return some thing. HttpServletRequest request. ActionForm form. we can create any number of methods in Action class and instruct the action tag in struts-config.xml</param-value> </init-param> </servlet> Q) Can you write your own methods in Action class other than execute() and call the user method directly? A) Yes. <action path="/somepage" type="com.xml file to call that user methods. HttpServletRequest request.> <init-param> <param-name>config/exercise</param-name> <param-value>/WEB-INF/exercise/struts-config.odccom.action.

xml: Is a configuration file describe the deployment elements.> <message-resources parameter="ApplicationResources" null="false" /> <!—Validator plugin  <plug-in className="org.ActionServlet</servlet-class> <!—Resource Properties --> <init-param> <param-name>application</param-name> <param-value>ApplicationResources</param-value> Nazar Babu 87 .> <controller processorClass=”” bufferSize=” ” contentType=”” noCache=”” maxFileSize=””/> <!— message resource properties -.SetUpEmployeeAction" name="employeeForm" scope="request" validate="false"> <forward name="continue" path="/employeeForm.apache.xml "/> </plug-in> </struts-config> Q) Web.validator.jsp"/> </global-forwards> <!— describe an action instance to the action servlet-.action.> <action-mappings> <action path="/setUpEmployeeForm" type="net.xml.struts.reumann. <web-app> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.reumann.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.TilesPlugIn"> <set-property property="definitions-config" value="/WEB-INF/tiles-defs.jsp"/> </action> <action path="/insertEmployee" type="net.InsertEmployeeAction" name="employeeForm" scope="request" validate="true" input="/employeeForm.Java Technoloies <!— to identify the target of an action class when it returns results -.struts.apache.apache. /WEB-INF/validation.jsp"/> </action> </action-mappings> <!— to modify the default behaviour of the struts controller-.> <global-forwards> <forward name="error" path="/error.xml"/> </plug-in> <!—Tiles plugin  <plug-in className="org.tiles.jsp"> <forward name="success" path="/confirmation.struts.

tld</taglib-location> </taglib> <!—Using Filters --> <filter> <filter-name>HelloWorldFilter</filter-name> <filter-class>HelloWorldFilter</filter-class> </filter> <filter-mapping> <filter-name>HelloWorldFilter</filter-name> <url-pattern>ResponseServlet</ url-pattern > </filter-mapping> </web-app> Nazar Babu 88 .tld</taglib-location> </taglib> <!—Tiles tag libs --> <taglib> <taglib-uri>/tags/struts-tiles</taglib-uri> <taglib-location>/WEB-INF/struts-tiles.tag libs --> <taglib> <taglib-uri>struts/bean-el</taglib-uri> <taglib-location>/WEB-INF/struts-bean-el.Java Technoloies </init-param> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.jsp</welcome-file> </welcome-file-list> <!-.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-.The Welcome File List --> <welcome-file-list> <welcome-file>index.tld</taglib-location> </taglib> <taglib> <taglib-uri>struts/html-el</taglib-uri> <taglib-location>/WEB-INF/struts-html-el.Action Servlet Mapping --> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>/do/*</url-pattern> </servlet-mapping> <!-.

Apart from this. lazy associations fetching 3. ORM is the automated persistence of objects in a Java application to the tables in a relational database.What is Hibernate? 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 files. polymorphism.Why do you need ORM tools like hibernate? The main advantage of ORM like hibernate is that it shields developers from messy SQL.What does ORM consists of ? An ORM solution consists of the followig four pieces: • • • • API for performing basic CRUD operations API to express ries refering to classes Facilities to specify metadata Optimization facilities : dirty checking. 5.What is ORM ? ORM stands for object/relational mapping.) 2)Light objects mapping (JDBC) 3)Medium object mapping 4)Full object Mapping (composition. 2.inheritance.Java Technoloies Hibernate 1.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.What are the ORM levels ? The ORM levels are: 1)Pure relational (stored procedure. 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 • • Nazar Babu 89 . persistence by reachability) 4.

Typical mapping file look as follows: 8. Nazar Babu 90 .cfg.Java Technoloies • o A lot less code to write Improved portability o ORM framework generates database-specific SQL for you 6.cfg.What are the most common methods of Hibernate configuration? The most common methods of Hibernate configuration are: • • Programmatic configuration XML configuration (hibernate.What are the important tags of hibernate.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 7.xml? An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that should be executed to process this rest.What is the need for Hibernate xml mapping file? Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects.xml) 9.

openSession(). It allows you to create query objects to retrieve persistent objects. • • • • • Session interface SessionFactory interface Configuration interface Transaction interface Query and Criteria interfaces 11. It is a single-threaded.What role does the Session interface play in Hibernate? The Session interface is the primary interface used by Hibernate applications. you can store and retrieve persistent objects and control transactions. Session session = sessionFactory.Java Technoloies 10. Using these interfaces. Session interface role: • • Wraps a JDBC connection Factory for Transaction Nazar Babu 91 .What are the Core interfaces are of Hibernate framework? The five core interfaces are used in just about every Hibernate application. short-lived object representing a conversation between the application and the persistent store.

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.How do you map Java Objects with Database tables? • • First we need to write Java domain objects (beans with setter and getter).lang.buildSessionFactory().String"/> <property column="USER_PASSWORD" length="255" name="userPassword" not-null="true" type="java. 13. Write hbm.test.String"/> </class> </hibernate-mapping> Nazar Babu 92 . update. where we map java class to table and database columns to Java class variables. 15. This language. the Hibernate query Language (HQL).Java Technoloies • Holds a mandatory (first-level) cache of persistent objects. and retrieve objects from a database. It will automatically load all hbm mapping files Create session factory from configuration object Get one session from this session factory Create HQL Query Execute query to get list containing Java objects 14. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work SessionFactory sessionFactory = configuration.What role does the SessionFactory interface play in Hibernate? The application obtains Session instances from a SessionFactory.xml.lang. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. The variables should be same as database columns.What is Hibernate Query Language (HQL)? Hibernate offers a query language that embodies a very powerful and flexible mechanism to query.User" table="user"> <property column="USER_NAME" length="255" name="userName" not-null="true" type="java. There is typically a single SessionFactory for the whole application—created during application initialization. used when navigating the object graph or looking up objects by identifier 12. is an object-oriented extension to SQL. store. Example : <hibernate-mapping> <class name="com.

Java Technoloies 16.Define cascade and inverse option in one-many mapping? cascade .Long"> <generator class="sequence"> <param name="table">SEQUENCE_NAME</param> <generator> </id> 19. get() : load() get() If you are not sure that the object Only use the load() method if you are sure exists. then use one of the get() that the object exists.lang.enable operations to cascade to child entities. If the one–to– many was marked as inverse. load() method will throw an exception if the get() method will return null if the unique id is not found in the database. 17.getParent). If the one–to–many was marked as non–inverse then a child–>parent relationship would be created. so when persisting a parent who has a collection of children. hibernate would create a child–>parent relationship (child. 18.What’s the difference between load() and get()? load() vs. unique id is not found in the database.mark this collection as the "inverse" end of a bidirectional association. should you ask the parent for its list of children. Example:<id column="USER_ID" name="id" type="java.What does it mean to be inverse? It informs hibernate to ignore that end of the relationship. methods. load() just returns a proxy by default and get() will database won’t be hit until the proxy is first immediately. invoked. and merge() if you want to merge your modifications at any time without consideration of the state of the session. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored. or ask the children who the parents are? 20. cascade="all|none|save-update|delete|all-delete-orphan" inverse .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. hit the database Nazar Babu 93 .How do you define sequence generated primary key in hibernate? Using <generator> tag.

createCriteria(Employee. Nazar Babu 94 .NAME LIKE :name </sql-query> Invoke Named Query : List people = session.class) .setString("TomBrady".setMaxResults(50) .What do you mean by Named – SQL query? Named SQL queries are defined in the mapping xml document and called wherever required.add(Restrictions.like("name".list().name} FROM Employee EMP WHERE emp.Java Technoloies 21.empid}. name) .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> 23. emp.like("address". "a%") ) .addOrder(Order.EMP_ID AS {emp. Example: <sql-query name = "empdetails"> <return alias="emp" class="com.EMP_NAME AS {emp.list(). 22. emp.Explain Criteria API ? Criteria is a simplified API for retrieving entities by composing Criterion objects.Employee"/> SELECT emp.test. "Boston")) .add(Restrictions.EMP_ADDRESS AS {emp.address}.asc("name") ) . 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.getNamedQuery("empdetails") .

orm. what should we do? In Hibernate configuration file set as follows: <property name="show_sql">true</property> 28. Common functions are simplified to single method calls.Define HibernateTemplate? org.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. 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 Nazar Babu 95 .hibernate.If you want to see the Hibernate generated SQL statements on console.What is component mapping in Hibernate? • • • • A component is an object saved as a value. a Spring Template class simplifies interactions with Hibernate Session. 25.Java Technoloies 24.springframework. 27. 29. 26. we can switch databases. The expression can be defined using the formula attribute of the element. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.What are the benefits does HibernateTemplate provide? The benefits of HibernateTemplate are : • • • • HibernateTemplate. Sessions are automatically closed. Hibernate will generate appropriate hql queries based on the dialect defined. Exceptions are automatically caught and converted to runtime exceptions.What are derived properties? The properties that are not mapped to a column.How do you switch between relational databases without code changes? Using Hibernate SQL Dialects . but calculated at runtime by evaluation of an expression are called derived properties.

What is the advantage of Hibernate over jdbc? Hibernate Vs. being read from database using java comparator.What is the difference between sorted and ordered collection in hibernate? sorted collection vs. more efficient way to sort it . Nazar Babu 96 . developer has to write code solution to map Java classes to to map an object model's data database tables. it will be more efficient way to sort it. 31. Hibernate itself takes representation to a relational data model care of this mapping using XML files so and its corresponding database schema.Java Technoloies Example: 30. If your collection is not large. order collection :sorted collection order collection A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. after the data sorting this collection when retrieval. The Order collection is sorting a collection by sorting occurs in the memory of JVM specifying the order-by clause for which running Hibernate. developer does not need to write code for this. JDBC :JDBC Hibernate Hibernate is flexible and powerful ORM With JDBC. it will be If your collection is very large.

Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code. mapping between Java objects and database tables is done manually. It improves With JDBC. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. It relieves programmer from manual handling of persistent data. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. with Transparent Persistence. Developer has to find out the efficient way to access database. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. caching is maintained by performance if client application reads hand-coding. Hibernate. Relational tuples are moved to this cache as a result of query. Application using JDBC to handle persistent data (database tables) having database specific code in large amount. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code. This check this defined field Hibernate updates has to be added by the developer. same data many times for same write. it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. If there is change in Database or in any table then the only need to change XML file properties. It also selects an effective way to perform a database manipulation task for an application.e. i.Java Technoloies With JDBC. Hibernate also supports native SQL statements. Hibernate provides this mapping itself. due to every user has updated data. cache is set to application work space. to select effective query from a number of queries to perform same task. JDBC supports only native Structured Query Language (SQL). So with JDBC. The actual mapping between tables and application objects is done in XML files. version field of database table every Nazar Babu 97 . As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-toobject/object-to-table. Hibernate enables developer to define In JDBC there is no check that always version type field to application. hence reducing the development time and maintenance cost. With JDBC.

or ask the children who the parents are? 35. Nazar Babu 98 .What are the Collection types in Hibernate ? • • • • • Bag Set List Array Map 33. 34. A theta-style join in the WHERE clause.Define cascade and inverse option in one-many mapping? cascade . So if two users retrieve same tuple and then modify it and one user save this modified tuple to database. 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. so when persisting a parent who has a collection of children. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data. cascade="all|none|save-update|delete|all-delete-orphan" inverse . version is automatically updated for this tuple by Hibernate.Java Technoloies time relational tuple is updated in form of Java class object to that table.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.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.enable operations to cascade to child entities. should you ask the parent for its list of children.What is Hibernate proxy? The proxy attribute enables lazy initialization of persistent instances of the class. 32.

What do you mean by fetching strategy ? A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. 42. 38. Immutable classes. This feature is called transactional write-behind. Fetch strategies may be declared in the O/R mapping metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object. 37. 41. or over-ridden by a particular HQL or Criteria query. This specifies that instances of the class are (not) mutable.. • • 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. 40. 39. 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.What is transactional write-behind? Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user.How can a whole class be mapped as immutable? Mark the class as mutable="false" (Default is true). may not be updated or deleted by the application.Java Technoloies 36. when an object is loaded.What are Callback interfaces? Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example.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.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.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. Nazar Babu 99 .

0 Annotations used to support Attribute Oriented Programming Defines EJB QL for expressing queries Support Entity Relationships through Java 5. Bidirectional relationships are implemented by two unidirectional relationships Provides callback support through Entity Listener and Callback methods Entity Relationships are bidirectional or unidirectional 45. Query.Java Technoloies saved.0 :Hibernate Session–Cache or collection of loaded objects relating to a single unit of work XDoclet Annotations used to support Attribute Oriented Programming Defines HQL for expressing queries to the database Supports Entity Relationships through mapping files and annotations in JavaDoc EJB 3.0 annotations Provides a Persistence Manager API Provides and Entity Manager exposed via the Session. interceptor. 43. Criteria.0 & Hibernate? Hibernate Vs EJB 3. or deleted.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 Nazar Babu 100 . Hibernate applications don't need to implement these callbacks.0 Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit Java 5.What are the differences between EJB 3. and validatable interfaces Entity Relationships are unidirectional. but they're useful for implementing certain kinds of generic functionality.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 44. Interface for managing CRUD and Transaction API operations for an Entity Provides callback support through lifecycle.

Delete) operations on objects of persistent classes Should have a language or an API for specifying queries that refer to the classes and the properties of classes An ability for specifying mapping metadata It should have a technique for ORM implementation to interact with transactional objects to perform dirty checking.Java Technoloies 1. Pure relational ii. Nazar Babu 101 .What is ORM? ORM stands for Object/Relational mapping. Full object mapping 5. 3. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database using the metadata that describes the mapping between the objects and the database.What is a meant by light object mapping? The entities are represented as classes that are mapped manually to the relational tables. Medium object mapping iv. lazy association fetching.What does an ORM solution comprises of? • • • • It should have an API for performing basic CRUD (Create. 2. Update. 6. including the user interface. inheritance. Read. and other optimization functions 4.What are the different levels of ORM quality? There are four levels defined for ORM quality. and collections. i. The code is hidden from the business logic using specific design patterns. This lets the users to develop persistent classes following objectoriented principles such as association.What is Hibernate? Hibernate is a powerful. This approach is successful for applications with a less number of entities. polymorphism.What is a pure relational ORM? The entire application. high performance object/relational persistence and query service. composition. Light object mapping iii. It works by transforming the data from one representation to another. is designed around the relational model and SQL-based relational operations.

Vendor independence . 9. 7.Hibernate reduces the burden of developer by providing much of Maintainability . polymorphism and persistence. MyPersistanceClass mpc = new MyPersistanceClass ("Sample App"). This approach is most known to all. metadata-driven data models. session. 10. persistent classes do not inherit any special base class or have to implement a special interface. i. Nazar Babu 102 . application will be reduced and it is easy to maintain.openSession().commit(). But in hibernate. Performance . By automated object/relational persistence it even reduces the LOC.What is meant by full object mapping? Full object mapping supports sophisticated object modeling: composition. If it is automated persistence then it still increases the performance.How does hibernate code looks like? Session session = getSessionFactory(). it provides more optimization that works all the time there by increasing the performance.What is a meant by medium object mapping? The application is designed around an object model. Productivity .close(). The SQL code is generated at build time.save(mpc). the LOC for the the functionality and let the developer to concentrate on business logic.Irrespective of the different types of databases that are there.As hibernate provides most of the functionality. iii.Java Technoloies or applications with common. ii. inheritance. And the associations between objects are supported by the persistence mechanism. The persistence layer implements transparent persistence. 8. Out of which the following are the most important one.beginTransaction(). and queries are specified using an object-oriented expression language. iv. tx. Transaction tx = session. Efficient fetching strategies and caching strategies are implemented transparently to the application.What are the benefits of ORM and Hibernate? There are many benefits from these. This is best suited for medium-sized applications with some complex transactions.Hand-coded persistence provided greater performance than automated one. Used when the mapping exceeds 25 different database products at a time. session. But this is not true all the times. hibernate provides a much easier way to develop a cross platform application.

usually the information is provided in an xml document.0.Show Hibernate overview? Nazar Babu 103 . how properties of the user defined persistence classes' map to the columns of the relative tables in database.dtd"> <hibernate-mapping> <class name="sample.sourceforge.Java Technoloies The Session and Transaction are the interfaces provided by hibernate.MyPersistanceClass" table="MyPersitaceTable"> <id name="id" column="MyPerId"> <generator class="increment"/> </id> <property name="text" column="Persistance_message"/> <many-to-one name="nxtPer" cascade="all" column="NxtPerId"/> </class> </hibernate-mapping> Everything should be included under <hibernate-mapping> tag. among other things.What is a hibernate xml mapping document and how does it look like? In order to make most of the things work in hibernate. 11. 12. There are many other interfaces besides this. The document defines. <?xml version="1. This is the main tag for an xml mapping document.net/hibernate-mapping-2. This document is called as xml mapping document.0"?> <!DOCTYPE hibernate-mapping PUBLIC "http://hibernate.

What the Core interfaces are of hibernate framework? There are many benefits from these.This is an optional interface but the above three interfaces are mandatory in each and every application. The instance of this interface is used by the application in order to specify the location of hibernate specific mapping documents.This is a factory that delivers the session objects to hibernate application. Session Interface .Used for transaction management Transaction interface . it provides a way so that user can include other interfaces and implement those interfaces for user desire functionality. iv. saved or deleted.This interface allows the user to perform queries and also control the flow of the query execution. These interfaces are called as Extension interfaces. 16. iii. v. JTA transaction. There is no need to implement callbacks in hibernate applications.used for JDBC connection management TransactionFactory interface .What are the Extension interfaces that are there in hibernate? • • • • • There are many extension interfaces provided by hibernate. ii. Transaction Interface . but they're useful for implementing certain kinds of generic functionality. SessionFactory Interface . Like when an object is loaded. i. Hibernate sessions are not thread safe.used to create proxies ConnectionProvider interface . Generally there will be a single SessionFactory for the whole application and it will be shared among all the application threads.Used for transaction management Nazar Babu 104 . The instances of this interface are lightweight and are inexpensive to create and destroy.Java Technoloies 13. This interface abstracts the code from any kind of transaction implementations such as JDBC transaction.What are Callback interfaces? These interfaces are used in the application to receive a notification when some object events occur. Query and Criteria Interface . 15.This interface is used to configure and bootstrap hibernate. 14. ProxyFactory interface . Configuration Interface . Out of which the following are the most important one.What are Extension interfaces? When the built-in functionalities provided by hibernate is not sufficient enough.This is the primary interface used by hibernate applications.

18. security levels and all are defined.provides caching techniques and strategies CacheProvider interface .xml The filename varies here.Java Technoloies • • • • • • TransactionManagementLookup interface . After configuring this instance is used to create the SessionFactory by calling the method buildSessionFactory().What do you create a SessionFactory? Configuration cfg = new Configuration(). cfg.In this kind of environment everything from database connections. transaction boundaries.provides ORM strategies IdentifierGenerator interface .hbm. Weblogic and WebSphere. SessionFactory sessions = new Nazar Babu 105 .What are different environments to configure hibernate? There are mainly two types of environments in which the configuration of hibernate application differs. 20.setProperties( System.xml").xml".What is the file extension you use for hibernate mapping file? The name of the file should be like this : filename.getProperties() ).Used in transaction management. Managed environment . Tomcat is one of the best examples that provide this kind of environment.What is meant by Method chaining? Method chaining is a programming technique that is supported by many hibernate interfaces.same as Cache interface ClassPersister interface . Non-managed environment . we need to create an instance of Configuration and use that instance to refer to the location of the configuration file. SessionFactory sessions = cfg. This is less readable when compared to actual java code.addResource("myinstance/MyConfig. This is just a convention and it's not mandatory.buildSessionFactory(). But this is the best practice to follow this extension.This kind of environment provides a basic configuration template. Look how a SessionFactory is created when we use method chaining. And it is not mandatory to use this format. The extension of these files should be ".used for primary key generation Dialect abstract class .provides SQL support 17. Cahce interface .hbm. i. 19. First.hbm. An example of this kind of environment is environment provided by application servers such as JBoss. ii. cfg.

setProperties( System.connection.properties file. Java types and SQL types. 24. At this moment the application will automatically detect and read this hibernate.What should SessionFactory be placed so that it can be easily accessed? As far as it is compared to J2EE environment.manager_lookup_class = net.What is object/relational mapping metadata? ORM tools require a metadata format for the application to specify the mapping between classes and tables. 25. So when the Configuration object is created.hibernate. if the SessionFactory is placed in JNDI then it can be easily accessed and shared between different threads and various components that are hibernate aware. Hibernate applications works efficiently with POJOs rather then simple java classes.sf. hibernate.hibernate. It also allows the user to express in native SQL. associations and foreign keys.xml").addResource("myinstance/MyConfig.dialect = net.hibernate.dialect.What does hibernate. properties and columns.transaction.factory_class = net. Besides they can also have some business logic related to that property. Nazar Babu 106 .JBossTransactionManagerLookup hibernate.transaction.JTATransactionFactory hibernate.properties file.buildSessionFactory(). This information is called the object/relational mapping metadata.What is HQL? HQL stands for Hibernate Query Language.transaction.transaction.datasource = java:/comp/env/jdbc/AuctionDB hibernate. 21.What are POJOs? POJO stands for plain old java objects. It defines the transformation between the different data type systems and relationship representations.sf.Java Technoloies Configuration().session_factory_name in the hibernate.properties file consist of? This is a property file that should be placed in application class path. 23.getProperties() ).sf. Hibernate allows the user to express queries in its own portable SQL extension and this is called as HQL.hbm. hibernate is first initialized. You can set the SessionFactory to a JNDI by configuring a property hibernate. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean.PostgreSQLDialect 22.

Objects stored in a relational database are identical if they represent the same row or. which compares object identity. or method-level metadata attributes. i.5. 28.AMOUNT) from type="big_decimal"/> • • Typical and most common property mapping <property name="description" column="DESCRIPTION" type="string"/> Controlling inserts and updates <property name="name" column="NAME" type="string" insert="false" update="false"/> 27. share the same table and primary key value. iii.Java Technoloies 26. This can be checked by using the = = operator.Object. as defined by in the JVM.What is Attribute Oriented Programming? XDoclet has brought the concept of attribute-oriented programming to Java. Database identity . BID b where b.What are the different types of property and class mappings? • Typical and most common property mapping <property name="description" column="DESCRIPTION" type="string"/> Or <property name="description" type="string"> <column name="DESCRIPTION"/> </property> • Derived properties <property name="averageBidAmount" formula="( select AVG(b. the equals( ) method.ITEM_ID = ITEM_ID )" Nazar Babu 107 .Objects are equal if they have the same value. the Java language had no support for annotations. now XDoclet uses the Javadoc tag format (@attribute) to specify class-.lang. Object identity -Objects are identical if they reside in the same memory location Object equality . This kind of programming that works on attributes is called as Attribute Oriented Programming. ii. Until JDK 1. field-. Classes that don't explicitly override this method inherit the implementation defined by java. These attributes are used to generate hibernate mapping file automatically when the application is built.What are the different methods of identifying an object? There are three methods by which an object can be identified. equivalently.

Q: What is SessionFactory interface? A: The application obtains Session instances from a SessionFactory. Table per concrete class. SessionFactory instances are not lightweight and typically one instance is created for the whole application. Q: What role does the Session interface play in Hibernate? A: The Session is a persistence manager that manages operation like storing and retrieving objects. Object-oriented technology supports the building of applications out of networks of objects with both data and behavior. Relational technology supports the storage of data in tables and manipulation of that data using data manipulation language (DML). Coming to hibernate associations. Because the underlying paradigms are different the two technologies do not work seamlessly. Q: What is Hibernate? A: Hibernate is a java-based Object/relational mapping(ORM) tool. using metadata that describes the mapping between the objects and the database. Table per subclass. If the application accesses multiple databases. They are not threadsafe. 3. 30. Table per class hierarchy. it needs one per database Q: What is Configuration interface? A: The application uses a Configuration instance to specify the location of mapping Nazar Babu 108 . Q: What are ORM tools? A: ORM tools provide automated solutions for the Object/relational paradigm mismatch problem. These are bi-directional associations. Instances of Session are inexpensive to create and destroy. whereas relational paradigm on mathematical principles.Java Technoloies 29. Q: What is Object/relational paradigm mismatch? A: Object-Oriented paradigm is based on software engineering principles.What are managed associations and hibernate associations? Associations that are related to container management persistence are called managed associations.What are the different approaches to represent an inheritance hierarchy? 1. 2. these are unidirectional. hence the name Object/relational paradigm mismatch.

xml Q: What are the most common methods of configuring Hibernate? A: 1. Q: How can the mapping files be configured in Hibernate? A: 1. Including <property> elements in hibernate. Nazar Babu 109 .cfg. where is the single created instance placed in J2EE environments? A: Usually it is bound to JNDI.xml in the classpath.hbm. However. By placing hibernate.xml are in the classpath? A: The settings of the XML configuration file will override the settings used in the properties.properties and hibernate. Q: What happens when both hibernate. Q: Does hibernate require persistent classes to implement Serializable? A: Hibernate doesn't require that persistent classes implement Serializable.Java Technoloies documents and Hibernate-specific properties and then creates the SessionFactory. And getter and setter methods for all the instance variables. it will bind itself automatically if hibernate.properties file in the classpath.cfg.xml using the <mapping> elements. Q: Since SessionFactory instances are not lightweight. Q: How can Hibernate be configured to access a instance variable directly and not through a setter method? A: By mapping the property with access="field" in Hibernate metadata. what interfaces/classes must the persistent classes (classes that are mapped to database tables) implement/extend? A: NONE. 2. they can be regular POJOs. Mapping files can be added to Configuration in the application code or. Q: What is the naming convention for Hibernate XML mapping file extensions? A: . Q: How to set Hibernate to log all generated SQL to the console? A: By setting the hibernate.newInstance().cfg. serialization is necessary. Q: In hibernate. They can be configured in hibernate.session_factory_name is set to the name of directory node. it requires a constructor with no arguments for every persistent class. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.show_sql property to true. when objects are stored in an HttpSession or passed by value using RMI. Q: What methods must the persistent classes implement in Hibernate? A: Since Hibernate instantiates persistent classes using Constructor. 2.

Q: How do you achieve table-per-class hierarchy while mapping classes in Hibernate? A: By using several <subclass> elements one for each sub-class inside the <class> element. Q: How can a whole class be mapped as immutable? A: By using the mutable="false" attribute in the class mapping. this is called dirty checking. which are compared by identity. by using multiple <class> elements. Nazar Babu 110 . Q: What is the root level element in a hibernate mapping file? A:<hibernate-mapping> Q: Is it possible to declare mappings for multiple classes in one mapping file? A: Yes. For this reason you should return exactly the same collection instance as Hibernate passed to the setter method to prevent unnecessary database updates. but calculated at runtime by evaluation of an expression are called derived properties. A <joinedsubclass> element may contain other <joined-subclass> elements. An important note here is. The expression can be defined using the formula attribute of the <property> element. But. Q: How are the individual properties mapped to different table columns? A: By using multiple <property> elements inside the <class> element.Java Technoloies Q: What is dirty checking in Hibernate? A: Hibernate automatically detects object state changes in order to synchronize the updated state with the database. Q: What are derived properties? A: The properties that are not mapped to a column. the recommended practice is to use one mapping file per persistent class. except for Collections. Q: How can you make a property be read from the database but not modified in anyway (make it immutable)? A: By using the insert="false" and update="false" attributes. Q: How do you achieve table-per-subclass while mapping classes in Hibernate? A: By using <joined-subclass> element inside the <class> element. Hibernate will compare objects by value. The <subclass> class element can in turn contain other <subclass> elements. Q: What is the use of dynamic-insert and dynamic-update attributes in a class mapping? A: They tell hibernate whether to include unmodified properties in SQL INSERT and SQL UPDATE.

iBatis works well when you need to intergate with an existing database.when u use hibernate u can make lazy=true or lazy=false. e.What is different between Hibernate and iBatis? Ans: 1. 1.xml file in Hibernate Ans: To make the application developemnt more productive.Java Technoloies Q: Does hibernate allow mixing table-per-class hierarchy and table-per-subclass strategies? A: No..SQLQuery sq = (SQLQuery) session. its saves development time and also mainly it deals with Objects(POJO) .TEST_PROC3( ? ) }While I can get stored proc output if there is no input to TEST_PROC3. . Hibernate works well when you control the data model. Sample code is below. With IBatis you will get full control on SQL but hibenate deals with relationships of tables..sq.. so this improves performance. 5..Why Hibernate came in to picture Anybody tell me please. .. among other advantages. and .tell me about the mapping and . 2. you can easily switch the database like MySql .getNamedQuery("findSearchResultsListSP"). hibernate loads collection elements ONLY when actually you ask for them.Execute Stored procedure in Hibernate How to invoke a stored procedure in Hibernate and pass in a parameter?I have { ? = call myservice.. 4.Lazy initialisation (what is lazy initialisation in hibernate ) Ans: when loading an obj that has a collection.What J2EE design problems does Hibernate solves apart from Data Base independency and being an ORM What J2EE design problems does Hibernate solves apart from Data Base independency and being an ORM tool? Nazar Babu 111 .xml file is nuthing but mapping between database column and POJO variable.Call it in your code.. 3. where exactly Hibernate is used. call Ans: You can declare it as Named queiries in one of your mapping files and give unique name. 2.addEntity("documentTypeCod e". you cannot have a <joined-subclass> inside <subclass> and vice versa.g.

securiry etc as well. 8. Where as in Hibernate we can able to establishes the connections to more than One Data Base... Nazar Babu 112 . Very nice in ..... The subclass has all the methods of the parent.. 7..Which is ... the proxy loads up the real object from the DB and calls the method for you. Only thing we need to write one more configuration file.What is the difference between and merge and update Ans: Update():. In detail Go thru.EJB infact use the container services(EJB container) like transaction...hibernate. Ans: HQL provides four ways of expressing (inner and outer) joins:1) An ordinary join in the from clause2) A fetch join in the from clause3) A theta-style join in the where clause4) An implicit association join . relations. object. and when any of the methods are accessed. these relational mappings are done by using the hibernates utilities such as list.What is Hibernate proxy? Ans: Proxies are created dynamically by subclassing your object at runtime. www.. bags. 11.Why Hibernate is advantageous over Entity Beans & JDBC? Ans: Hibernate and EJB have different purpose. 12.How are joins handled using HQL. 1 to many. 9.What is the difference between hibernate and spring JDBC template? List any advantages and disadvantages What is the difference between hibernate and spring JDBC template? List any advantages and disadvantages 10..then use update to save the data in hibernateMerge():-if you want to save your modificatiions at any time with out knowing abot ..How does Hibrnate maintain relations of RDBMS Ans: Those are .Java Technoloies 6... many to many...  2) Entity Beans does not support .if you are sure that the session does not contains an already persistent instance with the same identifier.What is the main difference between Entity Beans and Hibernate ? Ans: 1) In Entity Bean at a time we can interact with only one data Base. many to one.org .EJB is for writing business logic as well and provide Database independency just as hibernate provide for us. set.

evict .Spring is a framework for enterprise applications with default APIs for presentation. lock . 20. 17.What is the difference between beans and hibernate(which one is good)? Ans: Its is one of the most popular ORM technology available to date in the market. middle tier and presistence APIs . 16. replicate.. There are many alternatives to implement persistence. save_update. 18.Id before the appropriate field in POJO with @Column @Id@Column(name="user_id") . refresh .Java Technoloies 13.netbeans.How to create primary key using hibernate? Ans: We can also specify primary key using annotations in the POJO using:@javax.. delete.What is the advantage of Hibernate over jdbc? Ans: 1) Hiberante is not tightly tied with any underlaying database.where as . Persistence is once of the fundamental concepts of application developement.2 . ..What is database persistence?How well it is implemented in Hibernate Ans: Preserving the data inside a database is database persistence... There is no persistency on bean hibernate provides the service to make the bean persistent so that we can make use of it.What is the use of cascade in hbm file? Ans: cascade specifies which operations should be casecaded from the parent object to the associated object. In hibernate .Where as JDBC is tighlty tield with the underlaying database.What is the latest version of Hibernate using in current industry? Ans: Hibernate 3. 15.http://www.How to use hibernate in NetBeans IDE? Ans: Add the hibernate related jar files into lib directory of any web application using net beans. all .. Nazar Babu 113 .. merge...Java bean is a simple resuble component..What is the difference between hibernate and Spring Ans: Hibernate is ORM tool used for data persistency. Object/relational mapping (ORM) is the technique that Hibernate . middle tiers and presistence layers and allows to integrate with various presentations.persistence. delete_orphan... 14.. The meaningfull values would be persist .org/kb/41/hibernate.. 19..html ."Write Once presist anywhere" using hibernate can achieved by changing the dialect in configuration xml file..

26. please lets keep it out..Why do you need ORM tools like hibernate? Ans: Basically we need Hibernate like tools for the purpose of developing the application in short period of time.How do you handle the situation where persistence class attribute name is one of the reserved keyword How do you handle the situation where persistence class attribute name is one of the reserved keyword in database. JPA is a specification . There we use lazy loading to avoid that .How JPA and hibernate are related as per EJB 3 specifications? Ans: first things first . 23. It will make serious performance issues. 24... its nt a frame work .}public class Name{chat initial... .What is the main advantage of using the hibernate than using the sql Ans: Hibernate is based on object oriented concept like java. The product like Hibernate used for the productivity.In Jdbc we have to mannualy handle exception and every time we need to open/cose the connection.. e..as for the answer ..What is lazy fetching in hibernate Ans: There are two types of Loading in application. Nazar Babu 114 .eg)public class person{private Name name.name=name.i have just seen ppl venting thier personal grudge over java / jpa or whatever over this forum.}..not an entity reference..g..... In eager loading we will fetch all the values from the Persistent storage and cache it. 27. When large amount of data have to handle that time instead of using JDBC we used Hibernate. so it has better compatibility with java than sql. resultset whatever .. user ? Will this cause any issue while hibenrate executes SQL statements behind the scene? 25. Eager loading and Lazy loading.String .public Name getName(){ return name. 22.Java Technoloies 21..What is the difference between sorted and orderd collection in hibernate? Ans: A component is an object saved as a value.suns official sacceptence that jpa is a failure..}public void setName(Name name){this.create/close the statement . 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 .What is component mapping in hibernate? Ans: A component is a contained object that is persisted as a value type .

1 and when to use Hibernate? Explain with scenarios.1 and Hibernate. is better?Explain with reason.1? Q2: Which one.1? Q2: Which one. I am using hibernate. Q1: What is the difference between Hibernate and EJB 2. among EJB 2.Java Technoloies Q1: What is the difference between Hibernate and EJB 2.1 and Hibernate. among EJB 2. Q3: When to use EJB 2.What is the use In Data(POJO) class primary key is sending as an argument with I am using hibernate.What is the use In Data(POJO) class primary key is sending as an argument with constructor? Nazar Babu 115 .

S is a generalized server for running more than one application like ejb.  Many small changes: support for the latest versions of Java specifications.S provides runtime environment for server side components. security.  A. jsp and servlets. AVG. transaction services.1?  Message-driven beans (MDBs): can now accept messages from sources other than JMS. SUM. an EJB can easily access a Web service using the new service reference.  A. rmi.S and process the business logic and send the output to the W. they provide middleware services such as resource pooling and network. but W. failover.  W. clustering. Q) What is enterprise java bean? Why ejb? A) It’s a collection of java classes and xml descriptor files bundled together as a unit.Java Technoloies EJB Q: What is the J2EE? The J2EE is a set of coordinated specifications and practices that together enable solutions for developing.S understands and supports only HTTP protocol whereas an Application Server supports HTTP. XML schema. TCP/IP and many more protocols. and MOD.  W.S which it turns send to the client. security.S takes only the Http request.  Support for Web services: stateless session beans can be invoked over SOAP/HTTP. The java classes must provide certain rules and call back methods as per ejb specifications.  EJB timer service: a new event-based mechanism for invoking EJBs at specific times. COUNT. scalability. MIN. caching.S cannot process Http request. It takes the client request and send response back to the client and the connection is closed. Also. MAX. Q) Application server & Web server  A. and message destinations. response paradigm. Q) New in EJB 2. W.  A.S manage transactions. load-balancing ejb is the right choice. persistence. Q) What does Container contain? Nazar Babu 116 .S cannot help in this regards. but takes the forwarded request from W. deploying and managing multi-tier server-centric applications. resource pooling.  EJB query language (EJB-QL): many new functions are added to this language: ORDER BY.S is for request. When the application is so complex and requires certain enterprise level services such as concurrency.

E.S. S. S. Stateful bean will be destroyed once the client has gone (or after session time out) If the business process spans multiple invocations there by requiring a conversational then S. S. Life Cycle Management Q) SessionBeans Session beans are not persistence there are short lived beans.B can retain their state on the behalf of individual client. Database connection pooling) 5.B will be ideal choice. Support for Security 3. other words component developer must write the code to translate your in-memory fields into an underlying Nazar Babu 117 . the E. Stateful Session Bean Statefull session bean is a bean that is designed to service business process that span multiple methods request/transaction.B are persistence objects.B it self is not a persistence objects. Bean managed Persistence & Container managed Persistence  B. Stateful bean will be given individual copy for every user. E. Support for Transaction Management.B can be reconstructed in memory again by simple reading the data back in from the database. it remains in the pooled state. If the business last only for a single method call. Support for Persistence 4.B are permanent so if any machine crashes.B can perform database operations but S. There should be one and only one create method that to without any argument in the home interface.S.B are suitable Stateless session bean cannot have instance variable EjbRemove() method does not destroy the bean . There can be one or more create methods with or without arguments in the Home Interface. Stateless session bean instance can be pooled. Q) Statefull Session Bean & Stateless Session Bean Stateless Session Bean Stateless session bean these are single request business process is one that does not require state to be maintained across method invocation. business rules and workflow.P is an entity bean that must be persisted by hand.S. E. Instance Pooling. Stateful session bean will have instance variable and state is maintained in these instance variables Stateful bean can be destroyed by calling the ejbRemove() method Q) Entity Bean Entity beans are permanent business entities because their state is saved in permanent data storage. 2. Stateless bean will not be destroyed after client has gone. Therefore “n” number of beans can cater to n+1 number of clients. Statefull session bean do not have pooling concept. S. Stateless session bean cannot hold the state.B contain data related logic.B are business process objects they implements business logic. Support for management of multiple instances (Instance passivation.Java Technoloies A) 1.

B because the container is simply uses object serialization to persist S. requiring a conversational state if so the state full model fits very nicely.B are effective when working with one row at a time cause of lot of N.P your ejb container will implement the finder methods. rather than processing a serialized sequence of method calls. The E. updating multiple rows from database. client access message beans through the beans JMS interface (java. Q) When to choose Statefull & Stateless Session bean? A) Does the business process span multiple method invocations.B for application logic.D and then loads and initializes declared beans. The transactions in C.M. rollback. begin are transactions In B.P are TX-Support.Java Technoloies data store.message message) Q) Diff Statefull Session & Entity Bean? Both S. another enterprise bean. Q) Diff MDB & Stateless Session beans? .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 MDB. fetching. He findByPK() in C.P return void because the method is internally implemented.B container establish a connection with the message provide(MOM server).MDB’s process multiple JMS messages asynchronously.P for C. Clients interact with MDB’s only indirectly.P findByPK() return a reference to the actual bean object.  S. TX-NotSupport.B are efficient when client wants to access database directly. In this commit. When EJB application server starts it parse the D.B are effective when application want to access one row at a time. server side.B process messages asynchronously are deliver via JMS. You handle these persist operations your self. S.M.B’s are stateless. you place your data base calls in ejbLoad() and ejbStore().D. an application client. transaction aware components used for asynchronous JMS messages.M.W traffic.  You do not have to do anything to synchronize with database.I.B fields.MDB have no H. In entity bean deployment descriptor you specify which fields that the container should manage.M. .messageListerner) which exposes a single method.D. Q) When to choose Session Bean & Entity Bean?  E. It acts as a JMS message listener which JMS messages. by sending a message to a JMS Queue or Topic. In case of M.B & E.JMS.B undergo passivation and activation. Finder methods only for B.S. and therefore cannot be directly accessed by internal or external clients. M. TX-require. If your business process last for a single method call the stateless paradigm will better suite needed. Q) When to choose CMP & BMP? Nazar Babu 118 . .D. instances cannot be created or removed as a result of client requests or other API calls.S. or by a JMS application. We do not need these callbacks for S.S. Public void onmessage(javax.JMS. if many rows needed to be fetched using session bean can be better alternative. Q) Message Driven Bean  M.M.B have a separate ejbStore() callback for saving state during passivation & a separate ejbLoad() callback for loading state during activation.I / R.  E. the messages may be sent by any J2ee component.

M is a persistence mechanism of persistence objects than simple object serialization. the compiler will not return an error because there is no ejbCreate() method. Bean managed is also used when the persistence data storage is not a relational database. Q) Can a Session Bean be defined without ejbCreate() method? The ejbCreate() methods is part of the bean's lifecycle.jar” file. To keep informed of changes in transation status.B maintain data consistency by updating their fields each time a transaction is committed.D contains information for all the beans in the “ejb.Java Technoloies CMP is used when the persistent data store is a relational database and there is “one to one” mapping between a data represented in a table in the relational database and the ejb object. O.B implements the SessionSynchronization interface. Bean managed persistence is used when there is no “one to one” mapping of the table and a complex query retrieving data from several tables needs to be performed to construct an ejb object. it is possible using Handle. so. whether stateful or stateless.S. In cases where create() method is not provided. . A stateful session bean instance typically can't survive system failures and other destructive events. Q) Object-Relational Mapping Mapping of objects to relational database is a technology called O. Remember that ejbCreate() is essentially analogous to a constructor for ejb. Q) ejbCreate() In stateless session bean can have only one ejbCreate() method it must take no arguments.D enables ejb container to provide implicit services to enterprise bean components. . D. Because the stateless session bean has no client specific variables. these services can gain your bean with out coding. while the session bean class must contain exactly one ejbCreate() method.S.D is a XML file.Stateful Session Beans can have arguments (more than one create method). a S. Stateful beans can contain multiple ejbCreate() as long as they match with the home interface definition Q) Can I develop an Entity Bean without implementing the create() method in the home interface? As per the specifications. also without arguments. Q) Can't stateful session beans persistent? Is it possible to maintain persistence temporarily in stateful sessionbeans? A) Session beans are not designed to be persistent. there can be 'ZERO' or 'MORE' create() methods defined in an Entity Bean. Yes. Container then calls methods of this interface as it initiates and completes transactions involving the bean. Q) How do Stateful Session beans maintain consistency across transaction updates? A) S.The home interface of a Stateless Session Bean must have a single create() method with no arguments. D.R. the only Nazar Babu 119 .M. it initializes an instance internal state variable. Q) Deployment Descriptor D.R.

In general. create or instantiate an object (which has instance variable equal to number of columns to be stored) each time and add the object to vector that stores. the javax.Context is for the purpose of 'NAMING' [by the way of referring to] an object. The life of a Stateless Session bean for a client is just till the execution of the method that the client would have called on the bean…after the execution of that method if the client calls another method. you can create an instance of a bean based on the data present in the table. Q) How can you capture if findBy method returns more than one row? A) If finder method returns more than one row. the EJBContext (SessionContext and EntityContext). Once this is known. It's much like the RMI Naming. There is EntityContext too which is also and EJBContext object that'll be provided to an EntityBean for the purpose of the EntityBean accessing the container details.Context is an interface that provides methods for binding a name to an object.isIdentical method. In those cases. Where as. Where as SessionContext is an EJBContext object that is provided by the EJB container to a SessionBean in order for the SessionBean to access the information and/or services or the container. one can use the 'getPrimaryKey()' to get a remote reference to that bean. a set a columns that uniquely identify a single row in that table. Nazar Babu 120 . i. All one needs to know is the primary key of that table. and to access particular information and/or service.InitialContext is a Context and provides implementation for methods available in the Context interface. which can further be used to invoke business methods. dbase connection. Vector stores only the memory address not object reference. references to an EJBObject and so on can be maintained. Q) Can a Stateless Session Bean maintain state? A) Yes. For ex states such as socket connection. AppletContext and ServletContext help the corresponding Java objects in knowing about its 'context' [environment in which they run]. Q) Diff Context.e. InitialContext & SessionContext & EntityContext javax. A Stateless Session bean can contain no-client specific state across clientinvoked methods.Java Technoloies way to access the bean is by knowing its primary key. javax. So every time when you instantiate and store object into vector a separate memory address will be allocated and the same is stored in the vector.bind() method. Q) How do you determine whether two entity beans are the same? A) By invoking the EntityBean. So the container very well knows that a bean has finished its life for a client and can put it back in the pool.naming.naming. then a different bean is taken from the pool. and by acquiring a handle to it by using its corresponding finder method. Q) Can i call remove() on a Stateless Session bean? A) Yes. This method should be implemented by the entity bean developer to determine when two references are to the same object.naming.

S.ejb. So release all resources here.SessionBean extends javax. The container then calls the ejbActivate() method. Consider applying the DAO design pattern to accomplish this. Acquire all the required resources for the bean in this method.C is your beans gateway to interact with the container. The container should release all resources held by the bean.ie write the bean to some temp storage.ejb. public abstract void ejbPassivate(). public abstract void ejbLoad().EnterpriseBean { public abstract void ejbActivate(). This is accomplished with multiple Entity beans handling to each database and a single session bean to manage a transaction with the Entity bean. its said to be activated. public abstract void setEntityContext(EntityContext ctx).EntityBean extends javax.C query the container about your current transactional state.etc. If you choose Container-Managed Persistence(CMP). public abstract void ejbRemove(). Q) Session Bean CallBack methods? public interface javax. public abstract void setSessionContext(SessionContext ctx). the container can passivate some of them . public abstract void unsetEntityContext(). Q) Can EJB handle transaction across multiple databases? A) The transaction manager in EJB handling transaction across multiple databases. your security state. } Nazar Babu 121 . close socket connections. Just before passivating. public abstract void ejbPassivate(). public abstract void ejbCreate().. ie get socket connection ejbRemove() container wants to remove your bean instance it will call this method. map the bean to tables manually. use the vendors object/relational mapping tool to specify the mapping between your object state and the persistence schema. public abstract void ejbStore(). the container calls the ejbPassivate() method. i.ejb. } SessionContext  S.ejb. ejbActivate( )  When a passiavted bean is called.Java Technoloies Q) How can I map a single Entity Bean to multiple tables? A) If you use Bean-Managed Persistence(BMP).e. public abstract void ejbRemove().EnterpriseBean { public abstract void ejbActivate(). ejbCreate() ejbPassivate( )  If too many beans are instantiated. Q) Entity Bean CallBack methods? public interface javax.

Statefull. EAR file will contain D.Java Technoloies Q) EJBContext Rollback Methods EJBContext interface provides the methods setRollbackOnly() & getRollbackOnly(). Properties props = System. Q) Conversational & Non-conversational Conversational is an interaction between the bean and client. Context ctx = new InitialContext(props). you must provide nick name for your beans H. Use JNDI to locate the Home Interface of the other bean. that will allow you to remotely access to all its methods and members.lookup(“MyHome”). Q) ejbCretae( ) & ejbPostCreate( )  ejbCreate() is called just before the state of the bean is written to the persistence storage. and then acquire an instance. MyHome home = (MyHome)ctx.O are physically located some where on the N. JAR  All EJB classes should package in a JAR file. The remote interface is your link to the bean.W to some directory service to look for the H. Q) EAR.B can hold conversational with client that may span multiple method requests. Q) How can I call one EJB from inside of another EJB? A) EJB can be clients of another EJB’s it just works. ejb modules. Container will use this nick name. stateless session bean is a bean that do not hold multi method conversation with clients. All web components pages. EAR file contain all the JAR & WAR files. WAR. Q) JNDI to locate Home Objects H.B cannot hold state. After this method is completed a new record is created and written.O.create(). gif. Client will use this nick name to identify the H. beans. This can be used to avoid executing work that wouldn't be committed anyway.S.S.W. As you can see there are two distinct elements (the container and beans) and you need two different interfaces for accessing to both of them.O. perhaps in the address space of the Ejb Container. getRollbackOnly( )  method returns true if the current transaction has been marked for rollback. applets. Why cant it be in one? The home interface is your way to communicate with the container.getProperties(). classes should be packaged into WAR file. setRollbackOnly( )Once a bean invokes the setRollbackOnly() method.  ejbPostCreate() is called after the bean has been written to the database and the bean data has been assigned to an Ejb object. the current transaction is marked for rollback and cannot be committed by any other participant in the transaction--including the container. For client to locate H. MyRemoteInterface remote = home. we will specify the nice name in the Deployment descriptor.O. Note that each JAR. servlets. WAR. locating even removing one or more beans. JNDI goes over the N. that is who is responsible of creating. Stateless.O it wants. Nazar Babu 122 .D Q) What is the need of Remote and Home interface. html.

the container calls the ejbPassivate() method. the container can passivate some of them . A bean has not yet instantiated when it is in the Does Not Exist Sate. So release all resources here. ejbActivate( ) When a passiavted bean is called. Once a container creates one are more instance of a Stateful Session bean it sets them in a Method Ready State.newInstance()). the context is passed (setSessionContext()) and finally the bean is created with the ejbCreate(). ejbPassivate( ) If too many beans are instantiated. Just before passivating. Like Stateless beans. The container then calls the ejbActivate() method. its said to be activated.. ie get socket connection Life cycle of a Stateless Session Bean : - - A S.ie. When the EJB container needs one are more beans.ie write the bean to some temp storage.S. In this state it can serve requests from its clients.newInstance()). Nazar Babu 123 . Method Ready Pool and Passivated states.Java Technoloies Q) Life cycle Life cycle of a Stateful Session Bean - - - Stateful session bean has 3 states Does Not Exist. Acquire all the required resources for the bean in this method. a new instance is created(Class. it creates and set then in the Method Ready Pool Sate. The container should release all resources held by the bean. then it is set its context (setSessionContext()) and finally calls the ejbCreate() method.close socket connections.B has only two states: Does Not Exist and Method Ready Pool. This happens through the creation of a new instance(Class.Etc. A bean has not yet instantiated when it is in the Does Not Exist Sate.

. the container calls the ejbPassivate() method.B data base data loaded into it and it does not hold any bean specific resources (socket & database connections) .ie write the bean to some temp storage. The container then calls the ejbActivate() method. if a client call ejbremove() method. At this point your E. The container grabs the beans instance from the pool and the instance ejbCreate() method is called.ejbPassivate( ) If too many beans are instantiated. .B is in a pool of other E.close socket connections.Bean instance “Dose not exist” state represent entity bean instance that has not been instantiated yet. ie get socket connection - Nazar Babu 124 .If the container wants to reduce it’s pool size it can destroy your bean by calling unsetEntityContext() on your bean. ie.Java Technoloies The ejbRemove() method is called to move a bean from the Method Ready Pool back to Does Not Exist State.To create a new instance container calls the newInstance() on entity bean class. Just before passivating.E. Acquire all the required resources for the bean in this method. . .B does not have any E. its said to be activated.After step 2 E.etc.ejbActivate( ) When a passiavted bean is called.B to be kicked back to pool..When the client wants to create some new data base data it calls a create() method on entity beans HomeObject. So release all resources here. Life cycle of Entity bean .Bs. The container should release all resources held by the bean. the container can passivate some of them . . .

First.Java Technoloies Life cycle of M.D. The Method-Ready Pool MDB instances enter the Method-Ready Pool as the container needs them. three operations are performed on it. it is not an instance in the memory of the system. (The actual behavior of the server depends on the implementation. the bean instance is instantiated Nazar Babu 125 .B Does Not Exist When an MDB instance is in the Does Not Exist state. it has not been instantiated yet. Transitioning to the Method-Ready Pool When an instance transitions from the Does Not Exist state to the Method-Ready Pool. In other words. more can be created and added to the pool. it may create a number of MDB instances and enter them into the Method-Ready Pool.) When the number of MDB instances handling incoming messages is insufficient. When the EJB server is first started.

and phantom reads are prevented.Java Technoloies when the container invokes the Class. TRANSACTION_READ_COMMITTED The transaction cannot read uncommitted data. Dirty-reads are prevented. The MessageDrivenContext reference may be stored in an instance field of the MDB.newInstance() method on the MDB class. The MDB has only one ejbCreate() method. The ejbCreate() method is invoked only once in the life cycle of the MDB. the setMessageDrivenContext() method is invoked by the container providing the MDB instance with a reference to its EJBContext. Nazar Babu 126 . Q) Transaction Isolation levels TRANSACTION_READ_UNCOMMITTED The transaction can read uncommitted data. Dirty reads and nonrepeatable reads are prevented. the data has been changed. but upon reading the data. This can arise when another concurrently executing transaction modifies the data being read. data that is being changed by a different transaction cannot be read. Q) Diff Phantom & Un-repeatable Un-repeatable occurs when existing data is changed. TRANSACTION_REPEATABLE_READ The transaction cannot change data that is being read by a different transaction. Dirty reads. Un-repeatable read  When a component reads some data from a database. When you using programmatically transaction. Dirty-read  When your application reads data from a database that has not been committed to permanent storage yet. where as phantom read occurs when new data is inserted that does not exist before. Dirty reads. which takes no arguments. Q) Transaction Attributes TX_BEAN_MANAGED  Then your bean programmatically controls its own transaction boundaries. phantom reads can occur. you issue the begin. Second. Phantom-read  Phantom is a new set of data that magically appears in a database between two databases read operations. This isolation level is the most restrictive. and phantom reads can occur. nonrepeatable reads and phantom reads can occur. Bean methods with this isolation level have the same restrictions as Read Committed and can only execute repeatable reads. nonrepeatable reads. commit & abort statements. Bean methods with this isolation level cannot read uncommitted data. nonrepeatable reads. Bean methods with this isolation level can read uncommitted change. the no-argument ejbCreate() method is invoked by the container on the bean instance. different transactions can neither read nor write the same data. Finally. TRANSACTION_SERIALIZABLE The transaction has exclusive read and update privileges to data.

If there is a transaction already underway when your bean called. It guarantees that your bean should run in a transaction. Isolation  Protect concurrently executing transaction from seeing each other incomplete results.If you write a bank account data to a database. Q) ACID Properties When you properly use transaction your operations will execute ACID properties.When you transfer money from one bank account to another you want to add funds to one account and remove funds from the other transaction and you want both operations to occur or neither to occur. There is no way your bean can be called if there is not a transaction already running. The lock guarantee that no other updates can interfere. the bean runs with no transaction at all.Java Technoloies TX_NOT_SUPPORTED  If you set this your bean cannot be involved in a transaction at all. Ex: . TX_SUPPORTS  When a client call this it runs only in a transaction if the client had one running already. the container starts one for you. Consistency  Guarantees that a transaction will leave the system state to be consistent after a transaction completes. If there is no transaction running. it then joins that transaction. TX_REQUIRED  If you want your bean to always run in a transaction. that transaction is suspended during the bean invocation. TX_REQUIRES_NEW  If you always want a new transaction to begin when your bean is called we should use this. The container then launches a new transaction and delegate the call to the bean. Ex: . If no transaction.A bank system state could be consist if the rule “bank account balance must always be +ve”. Atomicity  Guarantees that many operations are bundled together and appears as one contiguous unit of work. the permanent data can be reconstructed by reapplying the steps in the log. Ex:. the transaction may obtain locks on the bank account record (or) table. Nazar Babu 127 . Durability  Resources keep a transactional log for resources crashes. If there is a transaction already running your bean joins in on that transaction. TX_MANDATORY  Is a safe transaction attribute to use.

xml.Uses EJB container in web logic server to manage transactions. The file structure of war file is: /-| | WEB-INF | | | |-. In this setup.Use same connection pool on multiple servers. War file)? Each web application should be contained in a war (web archive) file.e Jar. application components can be deployed on a number of JVM’s.Does not use any memory preferred for large documents. since objects 6. Tree of nodes 2.Objects are to be created 5. Programmatically easy.Access multiple resources. Q) Clustering In J2ee container can be distributed.backward navigation is not possible Q) Hot deployment Hot Deployment in Web Logic is he acts of deploying.Java Technoloies Q) Diff SAX & DOM DOM 1. Occupies more memory preferred for small XML documents 3. Q How to deploy in J2EE (i. 3.classes (Folder containing servlets and JSPs | | META-INF | | | |-.Faster at runtime 4. re-deploying and un-deploying EJBs while the server is still running.Need to write code for creating objects are to referred 6.XML (Deployment descriptor) | |-. a distributed container consists of number of JVM’s running on one are more host machines. .MF | | all utility files and resources like error pages etc. Subject to the type of loading strategy and the type of the component the container can distributed the load of incoming request to one of these JVM’s. Slower at runtime 4. Stored as objects 5. Nazar Babu 128 . such as database & JMS during transactions. War files are nothing but a jar file containing atleast one descriptor called web. Q) When should I use TxDataSource instead of Datasource? If your application (or) environment meets the following criteria you should use . .Sequence of events 2.MANIFEST.WEB. DOM creates a tree structure in memory SAX 1. .Includes multiple database updates with single transaction. Easy of navigation 7.Uses JTA .

xml | | jar and war files.0"?> <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems.titan.MANIFEST.dtd"> <ejb-jar> <description> This Deployment includes all the beans needed to make a reservation: TravelAgent. ProcessPayment.sun.xml. Reservation. Inc.MANIFEST. Q) Deployment descriptor of EJB (ejb-jar.xml) <?xml version="1. Both jar and war files are placed inside a ear (enterprise archive) file.//DTD Enterprise JavaBeans 1.ejb-jar.travelagent.1//EN" "http://java.com/j2ee/dtds/ejb-jar_1_1.> Nazar Babu 129 . </session> <entity> <ejb-name>CustomerBean</ejb-name> <remote>com.Customer</remote> .MF | |-.TravelAgent</remote> . </description> <enterprise-beans> <session> <ejb-name>TravelAgentBean</ejb-name> <remote>com. The structure of an ear file is /-| | META-INF | | | |-.. Cruise.xml | | all classes as in a normal jar file.titan.customer. </entity> </enterprise-beans> <! – Transactions in EJB -. and Cabin.application. Q) How do you configure a session bean for bean-managed transactions? A) By set transaction-attribute in the xml file or in the deployment descriptor. The jar file contains all standard files like manifest and atleast one additional file called ejb-jar..Java Technoloies Each enterprise bean is stored in a jar file. The structure of a jar file is: /-| | META-INF | | | |-...MF | |-. Customer.

.xml</type-storage> </persistence-type> <db-is-shared>true</db-is-shared> <persistence-use> <type-identifier>WebLogic_CMP_RDBMS</type-identifier> <type-version>5.0</type-version> </persistence-use> </persistence> <entity-clustering> <home-is-clusterable>true</home-is-clusterable> </entity-clustering> </entity-descriptor> <transaction-descriptor> <trans-timeout-seconds>30</trans-timeout-seconds> </transaction-descriptor> <enable-call-by-reference>true</enable-call-by-reference> <jndi-name>demo.xml <weblogic-ejb-jar> <weblogic-enterprise-bean> <ejb-name>demo.Story</ejb-name> <entity-descriptor> <entity-cache> <max-beans-in-cache>100</max-beans-in-cache> <idle-timeout-seconds>600</idle-timeout-seconds> <read-timeout-seconds>0</read-timeout-seconds> <concurrency-strategy>Database</concurrency-strategy> </entity-cache> <lifecycle> <passivation-strategy>default</passivation-strategy> </lifecycle> <persistence> <delay-updates-until-end-of-tx>true</delay-updates-until-end-of-tx> <finders-load-bean>true</finders-load-bean> <persistence-type> <type-identifier>WebLogic_CMP_RDBMS</type-identifier> <type-version>5.Java Technoloies <assembly-descriptor> <container-transaction> <method> <ejb-name>EJBName</ejb-name> <method-name>methodName / *</method-name> </method> <trans-attribute>Required</trans-attribute> </container-transaction> </assembly-descriptor> .1.StoryHome</jndi-name> </weblogic-enterprise-bean> </weblogic-ejb-jar> Nazar Babu 130 .0</type-version> <type-storage>META-INF/weblogic-rdbms11-persistence600.1. </ejb-jar> Q) Weblogic-ejb-jar..

} Q) Entity Bean Example Home. public int add(int a. public interface Home extends javax. public String hello(){ System. public abstract void ejbRemove().out.protableRemoteObject. HelloHome home = (HelloHome) javax. System.println(“hello()”).create().CreateException. HelloHome.ejb.println(hello.out. } Home Interface public interface HelloHome extends javax. public HomeObj findByPrimaryKey(String a) throws RemoteException.lookup(“HelloHome”).EJBHome { public String hello() throws RemoteException.RemoteException.rmi. Context ctx = new InitialContext(props).remove().narrow(obj.EJBObject { public String hello() throws java.ejb. javax. public void ejbCreate().Java Technoloies Q) Session Bean Example Remote Interface public interface Hello extends javax.EJBHome { Hello create() throws java.SessionBean { private SessionContex ctx.class).RemoteException. } Nazar Babu 131 .java (Home Interface) package test.rmi.rmi.ejb. Hello.getProperties().ejb. FinderException. public abstract void setSessionContext(SessionyContext ctx).hello()). int b) throws RemoteException. } Client public class HelloClient { public static void main(String args[ ]) properties props = system. public abstract void ejbActivate(). Hello hello = home. public abstract void ejbPassivate(). } Bean Class public class HelloBean implements javax. Return “hello world”. Object obj = ctx.ejb.

pw.ejb.home.add(7.entity.lookup("ejb/home"). } catch (Exception e) { throw new ServletException(e).AbstractEntityBean { public String ejbHomeHello() { return "Hello. 1) + "").ejb.getWriter(). home = (Home) env. import javax.EJBObject { } HelloBean.lookup("java:comp/env"). try { pw. } public int ejbHomeAdd(int a.*.add(1.println("7 + 1 = " + home. pw. 3) + ""). import javax. ServletResponse res) throws IOException. public void init() throws ServletException { try { Context env = (Context) new InitialContext(). ServletException { PrintWriter pw = res.java (Remote Interface) package test. } } Client package test.*. public class HomeServlet extends GenericServlet { Home home.Java Technoloies HelloObj. int b) { return a + b. } public String ejbFindByPrimaryKey(String key) throws FinderException { throw new FinderException("no children"). } catch (Exception e) { throw new ServletException(e).println("1 + 3 = " + home. public class HelloBean extends com. } } } Nazar Babu 132 .java (Bean class) package test.println("message: " + home. world".caucho.naming. } } public void service(ServletRequest req.hello() + ""). public interface HelloObj extends javax.ejb.

Service to Worker: Combines a Dispatcher component with the Front Controller and View Helper patterns. The Transfer Object Assembler uses Transfer Objects to retrieve data from various business objects and other objects that define the model or part of the model. Patterns provide a ready-made solution that can be adapted to different problems as necessary. Composite Entity :It model. Message Driven beans can be used to implement Service Activator for message based enterprise applications. Service Activator: Service Activator enables asynchronous access to enterprise beans and other business services. Transfer Object Assembler: It is used to build the required model or submodel. deferring many activities to View processing.Java Technoloies Design Patterns J2EE Design Patterns Pattern Name ? Intercepting Filter ? Front Controller ? View Helper ? Composite view ? Service to Worker ? Dispacther View Business Tier ? Business Delegate ? Value Object ? Session Façade ? Composite Entity ? Value Object Assembler ? Value List Handler ? Service Locator Integration Tier ? Data Access Object ? Service Activator Q) What is a Desing Pattern? Why use patterns? Tier Presentation Tier A) A pattern describes a proven solution to a recurring design problem. The Service Activator is a JMS Listener and delegation service that creates a message façade for the EJBs. In EJB2. and manage a set of interrelated persistent objects rather than representing them as individual fine-grained entity beans. Nazar Babu 133 . It receives asynchronous client requests and messages.0. A Composite Entity bean represents a graph of objects. represent. On receiving a message. Q) J2EE Design Patterns? Dispatcher View: Combines a Dispatcher component with the Front Controller and View Helper patterns. the Service Activator locates and invokes the necessary business methods on the business service components to fulfill the request asynchronously.

Java Technoloies Q) What is architectural design pattern? A) Describe MVC2 & Front Controller. jsps etc) can access entity beans directly. J2EE compatible server binds these resources/services to the JNDI server so that the clients can lookup those resources/services through JNDI lookup process from anywhere in the network. Front Controller It will dispatch the request to the correct resource. This technique maintains a cache of service objects and looks up the JNDI only first time for a service object. JMS ConnectionFactory 4. DataSource objects 3. Service Locator To access different resources/services. Session Façade EJB clients (swing. servlets. If EJB clients access entity beans directly over the network. JNDI lookup process is expensive because clients need to get network connection to the JNDI server if the JNDI server is located on a different machine and need to go through lookup process every time. JMS Topic/Queue etc. Centralized controller for managing and holding of a request. this is redundant and expensive. All these services need to bind to the JNDI services and the clients need to lookup JNDI to get those services. The solution for the redundant and expensive JNDI lookup process problem is to cache those service objects when the client performs JNDI lookup first time and reuse that service object from the cache second time onwards for other clients. The resources/services can be 1. Clients have to go through JNDI lookup process every time to work with these services. EJBHome objects 2. it takes more network calls and Nazar Babu 134 .

Here the servlet calls multiple entity beans directly to accomplish a business process. If you use synchronous session and entity beans in such situations. the client does not have to bother about return value. The EJB client accesses session bean (Facade) instead of entity beans through coarse grained method call to accomplish a business process. Nazar Babu 135 . Message Facade Session bean and entity bean methods execute synchronously that means the method caller has to wait till a value is returned. they take a long time to process methods and clients have to wait till the method returns a value. The solution for avoiding number of network calls due to directly accessing multiple entity beans is to wrap entity beans with session bean (Facade). In some situations like sending hundred's of mails or firing a batch process or updating processes. thereby increasing the number of network calls.Java Technoloies imposes network overhead.

use asynchronous message driven beans. This synchronous execution takes a long time and has an impact on performance when the method process is huge.getName(). there are three network calls from client to the remote object because every method call is remote method call. // send Value Object through network Nazar Babu 136 .setCity("Austin"). Value Object (DTO-DataTransfer Object) When a client calls a remote method there will be process of marshalling. remoteObject. network calls and unmarshalling involved for the remote method invocation.setName("Ravi"). For example if you call fine grained method like this. If you choose fine-grained approach when calling methods remotely. person.getState(). so that client does not have to wait for a return value. If a client uses asynchronous messaging then the client need not wait for a return value but can continue its flow of execution after sending the message.getCity(). The solution for avoiding many network calls due to fine-grained method calls is to use coarse-grained approach. there will be a significant network overhead involved. To avoid blocking of a client. remoteObject.Java Technoloies The client has to wait till all the eight synchronous steps complete. For example: // Create a Value Object and fill that object locally PersonInfo person = new PersonInfo(). person. remoteObject.

let ValueObjectFactory hold different ValueObjects as placeholders and respond with a single ValueObject for a client request. Value Object is an object that is passed over the network rather than passing each attributes separately thus increasing performance by reducing network calls.Java Technoloies remoteObject. Here. ValueObjectFactory For a single request. To reduce the network traffic due to accessing multiple components by a client for a single request.getPersonInfo(person). there is only one network call instead of three network calls and PersonInfo object is a Value Object. a client might need to access multiple server side components such as different session beans and entity beans. In such situations the client accesses multiple components over the network. this increases the network traffic and has an impact on the performance. The following figure illustrates the coarse grained approach that is passing a Value Object through network. Nazar Babu 137 .

DAO encapsulates JDBC access logic. Its intent is to ensure that a class has only one instance. and a PC is connected to a single keyboard 1. and to provide a global point of access to it. Return small quantity of data multiple times iteratively rather than returning large amount of data at once to the client. so that outside class can not access this constructor. There are many situations in which a singleton object is necessary: a GUI application must have a single mouse. If an application returns huge queried data to the client.Create a Private constructor. 1. an operating system can only have one window manager. Nazar Babu 138 .Java Technoloies Value List Handler (DAO) J2EE applications generally have the search facility and have to search huge data and retrieve results. the client takes long time to retrieve that large data and if that application uses entity bean to search data. And declare a private static reference of same class. Use Data Access Objects (DAO) rather than Entity beans 2. it calls ValueListHandler that is in turn responsible for caching data and returning data to the client iteratively. ValueListHandler caches list of Value objects that are retrieved through DAO. When client wants to search data. so that other classes can't create a new instance. an active modem needs one and only one telephone line. Singleton  You can achieve this by having the private constructor in the class. it has an impact on.

Q). because it limits unnecessary and potentially costly round trips over the network.D uses a component called the Lookup Service. The delegate may cache results and references to remote business services. I would require a single connection object for all the users coming in.Write a public Factory method which creates an object. private Singleton (){ } public static Singleton getSingleton() { if (ref == null) ref = new Singleton ().D acts as a client-side business abstraction and hides the implementation of the business services. Assign this object to private static Reference and return the object public class Singleton { private static Singleton ref. The BusinessDelegate uses a LookupService to locate the required BusinessService component. return ref. ex while designing database connection pool. Why Factory Pattern is used and an example? A) Factory pattern is used in place where the implementation varies over time.Java Technoloies 2. Q). Factory pattern suggest creating many different instances from interfaces. B. Interfaces Nazar Babu 139 . not a separate one for each user. Caching can significantly improve performance. The client requests the BusinessDelegate to provide access to the underlying business service. The Lookup Service is responsible for hiding the underlying implementation details of the business service lookup code. such as lookup & access details of the EJB architecture. } } Business Delegate The B. Where do you use singleton pattern and why? A) If I require a single instance of an object in a particular JVM.

as and when the event occurs. Q). Nazar Babu 140 . Where do you use visitor pattern and why? A) If I want to defrag business logic in different sets of modules and the final processing requires all these module to be included in a particular fashion. Q) What is the difference between J2EE design patterns and the Gang of Four patterns? A) The GOF design patterns apply generically to any object-oriented programming language. Q). J2EE design patterns address common problems encountered in designing J2EE architecture. look and feel of the application changes to Window style. ex: If the OS is Windows.Java Technoloies are the one that faces client and implementation of those methods come from factory depending on a specific condition. and list grows over time and it is hardly possible to call /notify each and every listeners at design time. This course presents the key J2EE design patterns required when implementing a J2EE system. What problem an observer pattern solves? A) If a particular event has to be notified to many objects. We use observer pattern . It is something like visiting many modules one at a time. for Linux it is Metal and for machintosh it will be different. just to register many objects listening to a particular event and getting notified automatically. Visitor pattern generally calls a visit method of these modules /objects and all the different logic stored in different modules and call one by one.

Eliminate any non-full dependence of data item on record keys. delete DDL  create. alter. The foreign key constraints are used to enforce referential integrity. Removes Transitive dependency. I. drop. Ie If X is the primary key in a table. revoke. Drops the indexes Nazar Babu 141 .Eliminate any transitive dependence of data items on P. (ii) 2nd normal form: . The check constraints are used to enforce domain integrity. update. as the check constraints. rollback. Another major difference is that. A foreign key in one table points to a primary key in another table.K’s.e.F is achieved when all repeating groups are removed.Java Technoloies Database Concepts Q) DML  insert. where are unique creates a nonclustered index by default. truncate. TCL  commit. Q) Diff Primary key and a Unique key? What is foreign key? A) Both primary key and unique enforce uniqueness of the column on which they are defined.e. NOT NULL constraint enforces that the column will not accept null values. But by default primary key creates a clustered index on the column. and P. DQL  select DCL  grant. (iii) 3rd normal form: . i. (i) 1st normal form: . Dropping : (Table structure + Data are deleted). primary key doesn't allow NULLs. big table is broken into many small tables. savepoint. Q) Diff Delete & Truncate? A) Rollback is possible after DELETE but TRUNCATE remove the table permanently and can’t rollback. rename. such that each table has a primary key. The not null constraints are used to enforce domain integrity.K should be defined. Truncate will remove the data permanently we cannot rollback the deleted data. CHECK constraint is used to limit the values that can be placed in a column. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value.1st N. Then Z does not depend directly on primary key. Suppose Z depends only on Y and Y depends on X. The columns in a table which is not completely dependant on the primary key are taken to a separate table. Invalidates the dependent objects. Q) Normalization Normalization is the process of simplifying the relationship between data elements in a record. Foreign key constraint prevents any actions that would destroy link between tables with the corresponding data values. Y & Z are columns in the same table. but unique key allows one NULL only. So remove Z from the table to a look up table.

You use the LONG RAW datatype to store binary data (or) byte strings.Java Technoloies Truncating : (Data alone deleted). except that LONG RAW data is not interpreted by PL/SQL.sal<=t2. empssn) not in (select min (empid). Performs an automatic commit.sal)) from tab t2 where t1. The maximum length of a LONG RAW value is 32760 bytes. except that the maximum length of a LONG value is 32760 bytes. COUNT (EMPSSN) EMPSSN ----------------------2 555-55-5555 2 555-58-5555 SQL> delete from employee where (empid. Q) Diff Function & Procedure Function is a self-contained program segment. empssn from employee group by empssn). Q) How to find out duplicate rows & delete duplicate rows in a table? A) MPID EMPNAME EMPSSN ----. Nazar Babu 142 . Q) Diff LONG & LONG RAW? A) You use the LONG datatype to store variable-length character strings. Q) Select the nth highest rank from the table? A) Select * from tab t1 where 2=(select count (distinct (t2. empName and salary for month November? A) Select emp. empssn from employee group by empssn having count (empssn) > 1. LONG RAW data is like LONG data. function will return a value but procedure not.sal) Q) a) Emp table where fields empName. Doesn’t perform automatic commit Q) Diff Varchar and Varchar2? A) The difference between Varchar and Varchar2 is both are variable length but only 2000 bytes of character of data can be store in varchar where as 4000 bytes of character of data can be store in varchar2.empId and month=November. month. Amount from emp. empName. empId.-------------------1 Jack 555-55-5555 2 Mike 555-58-5555 3 Jack 555-55-5555 4 Mike 555-58-5555 SQL> select count (empssn).empId=salary. salary where emp. Procedure is sub program will perform some specific actions.empId. Amount these 2 tables he wants EmpId. address b) Salary table where fields EmpId. Faster than delete Delete : (Data alone deleted). The LONG datatype is like the VARCHAR2 datatype.

views. suppliers. drop [public] synonym [schema . Example: Drop public synonym suppliers. Q) What is an alias and how does it differ from a synonym? A) An alias is an alternative to a synonym. stored procedures. Oracle assumes that you are referring to your own schema. Example demonstrates how to create a synonym called suppliers. Force -. you could always use the or replace phrase as follows: Create or replace public synonym suppliers for app.means that the synonym is a public synonym and is accessible to all users.] object_name.] synonym_name for [schema. If this phrase is omitted. users of other schemas can reference the table called suppliers without having to prefix the table name with the schema named app. Now. and other database objects Syntax: Create [or replace] [public] synonym [schema. then you don't specify a schema. Schema -.phrase allows you to drop a public synonym.phrase will force Oracle to drop the synonym even if it has dependencies.allows you to recreate the synonym (if it already exists) without having to issue a DROP synonym command.Java Technoloies Q) Oracle/PLSQL: Synonyms? A) A synonym is an alternative name for objects such as tables.] Synonym_name [force]. designed for a distributed environment to avoid having to use the location qualifier of a table or view. It can be one of the following: Table Package View sequence Function materialized view java class schema object Synonym stored procedure user-defined object example: Create public synonym suppliers for app. For example: Select * from suppliers. Dropping a synonym It is also possible to drop a synonym. Q) What are joins? Inner join & outer join? Nazar Babu 143 . It is probably not a good idea to use the force phrase as it can cause invalidation of Oracle objects.is the appropriate schema. If you have specified public. sequences. If this synonym already existed and you wanted to redefine it. public -. This drop statement would drop the synonym called suppliers that we defined earlier. The alias is not dropped when the table is dropped. Public -. object_name -.is the name of the object for which you are creating the synonym. suppliers. or replace -.

outer join includes rows from tables when there are no matching values in the tables. • RIGHT JOIN or RIGHT OUTER JOIN. When there is a match between the tables. the select list columns from the other table contain null values. All rows from the right table are returned. Diff join and a Union? A) A join selects columns from 2 or more tables. • FULL JOIN or FULL OUTER JOIN. When a row in the left table has no matching rows in the right table. you can retrieve data from two or more tables based on logical relationships between the tables Inner Join: . Union & Union All? A) The UNION ALL command is equal to the UNION command. A union selects rows.id(+).mid=b. The UNION command eliminate duplicate values. Q) Explain a scenario when you don’t go for normalization? Nazar Babu 144 . Outer Join: . except that UNION ALL selects all values.returns all rows from both tables where there is a match. Null values are returned for the left table any time a right table row has no matching row in the left table. A right outer join is the reverse of a left outer join. Any time a row has no match in the other table. A full outer join returns all rows in both the left and right tables. not just the ones in which the joined columns match. Q.Java Technoloies A) By using joins. • LEFT JOIN or LEFT OUTER JOIN The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause.name.name from employee a. Q. when using the UNION command all selected columns need to be of the same data type. It cannot eliminate duplicate values. the entire result set row contains data values from the base tables. employee b where a. the associated result set row contains null values for all select list columns coming from the right table. b. > SELECT E_Name FROM Employees_Norway UNION ALL SELECT E_Name FROM Employees_USA Q) Is the foreign key is unique in the primary table? A) Not necessary Q) Table mentioned below named employee ID NAME MID 1 CEO Null 2 VP CEO 3 Director VP Asked to write a query to obtain the following output CEO Null VP CEO Director VP A) SQL> Select a.

select_table2. [ FROM from_clause ] [ WHERE where_expression ] [ GROUP BY expression1.. but not stored separately. from_clause ::= select_table1 RIGHT [OUTER] JOIN select_table2 ON expr ... > SELECT DISTINCT city FROM supplier..... Q) What is Referential integrity? A) R... SUM("col_nam2") FROM "tab_name" GROUP BY "col_nam1" Nazar Babu 145 . Q) Diff GROUP BY & ORDER BY? A) Group by controls the presentation of the rows. i. . ... order by controls the presentation of the columns for the results of the SELECT statement..I refers to the consistency that must be maintained between primary and foreign keys.Java Technoloies A) If we r sure that there wont be much data redundancy then don’t go for normalization.. Q) Diff HAVING CLAUSE & WHERE CLAUSE? A) Having Clause is basically used only with the GROUP BY function in a query. order_column_expr2.. Q) SELECT statement syntax? A) SELECT [ DISTINCT | ALL ] column_expression1. from_clause ::= select_table1 [INNER] JOIN select_table2 . Q) COUNT function? A) The COUNT function returns the number of rows in a query > SELECT COUNT (*) as "No of emps" FROM employees WHERE salary > 25000. column_expression2. from_clause ::= select_table1 LEFT [OUTER] JOIN select_table2 ON expr . . unions and nested selects are used to retrieve data. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. Q) What is a view? Why use it? A) A view is a virtual table made up of data from base tables and other views. select_table ::= table_name [ AS ] [ table_alias ] select_table ::= ( sub_select_statement ) [ AS ] [ table_alias ] order_column_expr ::= expression [ ASC | DESC ] Q) DISTINCT clause? A) The DISTINCT clause allows you to remove duplicates from the result set.. > SELECT "col_nam1". ] column_expression ::= expression [ AS ] [ column_alias ] from_clause ::= select_table1. . Q) What techniques are used to retrieve data from more than one table in a single SQL statement? A) Joins.e... ] [ HAVING having_expression ] [ ORDER BY order_column_expr1. expression2. every foreign key value must have a corresponding primary key value.

and each index is given a name. Nazar Babu 146 . but can reference columns in a table listed in the from list of the outer query. The % sign is used as a wildcard. Unique Index : A unique index means that two rows cannot have the same index value. ALL. Allows to check if at least a value of the list satisfies condition. A NULL in a column means no entry has been made in that column. one can use the predicates IN. Q) What is a NULL value? What are the pros and cons of using NULLS? A) NULL value takes up one byte of storage and indicates that a value is not present as opposed to a space or zero value. COUNT and DISTINCT. >CREATE INDEX PersonIndex ON Person (LastName. the value returned is True otherwise the value returned is False. DESC] Q) What keyword does an SQL SELECT statement use for a string search? A) The LIKE keyword allows for string searches. If the subquery returns a result. If you want to index the values in a column in descending order. According to the conditions which one wants to express." Q) Index? Types of indexes? A) Locate rows more quickly and efficiently. ANY. Q) What are some sql Aggregates and other Built-in functions? A) AVG. Allows to check if condition is realized for all the values of the list. duplicate values are allowed. Q) Predicates IN. The users cannot see the indexes. MIN.Java Technoloies > SELECT "col_nam" FROM "tab_nam" [WHERE "condition"] ORDER BY "col_nam" [ASC. None of them have used a reference from outside the subquery. you can add the reserved word DESC after the column name: >CREATE INDEX PersonIndex ON Person (LastName DESC) If you want to index more than one column you can list the column names within the parentheses. >CREATE UNIQUE INDEX index_name ON table_name (column_name) When the UNIQUE keyword is omitted. It is possible to create an index on one (or) more columns of a table. FirstName) Q) Diff subqueries & Correlated subqueries? A)subqueries are self-contained. ALL or EXISTS. correlated subquery cannot be evaluated as an independent query. they are just used to speed up queries. EXISTS? A) Sub query can return a subset of zero to n values. IN ANY ALL EXISTS The comparison operator is the equality and the logical operation between values is OR. A data value for the column is "unknown" or "not available. ANY. SUM. MAX.

The verifier checks that the instructions cannot perform actions that are obviously damaging. applying a different san box to each program. which can be loaded into JVM. Nazar Babu 147 .Java Technoloies Security Concepts Q) Java Security Model Byte code verifier Which examine the byte code of a class before executing. Digest Authentication  In this the user id and password does not send across the network instead send a digest representation of password. creating S. the server decode the string and looks in the data base for match.W socket.M.M is a class that controls weather a specific operation are permitted. which can be loaded into JVM. ClassLoader ClassLoader. You can also define a set of sand boxes. In this the user id and password are sent by the client in base-64 encoded string. Security manager Restrict access to potentially dangerous operations. ClassLoader keeps the record of classes. S. If it finds a match grant access to the requested resource. perform N. S.W multi cast etc… Q) Basic Authentication & Digest Authentication Basic Authentication  Is a security model in this the client must authenticate itself with user id and password for each resource to access.M provides a sand box in which applet run. which restrict access to the classes.M will perform operations like opening N. S.