Java Faqs
Java Faqs
JAVA
Abstraction: Showing the essential and hiding the non-Essential is known as Abstraction. Encapsulation: The Wrapping up of data and functions into a single unit is known as
Encapsulation. Encapsulation is the term given to the process of hiding the implementation details of the object. Once an object is encapsulated, its implementation details are not immediately accessible any more. Instead they are packaged and are only indirectly accessed via the interface of the object.
Inheritance: is the Process by which the Obj of one class acquires the properties of Objs
another Class. A reference variable of a Super Class can be assign to any Sub class derived from the Super class. Inheritance is the method of creating the new class based on already existing class , the new class derived is called Sub class which has all the features of existing class and its own, i.e sub class. Adv: Reusability of code , accessibility of variables and methods of the Base class by the Derived class.
Polymorphism: The ability to take more that one form, it supports Method Overloading &
Method Overriding.
Method overloading: When a method in a class having the same method name with different arguments (diff Parameters or Signatures) is said to be Method Overloading. This is Compile time Polymorphism. o Using one identifier to refer to multiple items in the same scope. Method Overriding: When a method in a Class having same method name with same arguments is said to be Method overriding. This is Run time Polymorphism. o Providing a different implementation of a method in a subclass of the class that originally defined the method. 1. In Over loading there is a relationship between the methods available in the same class ,where as in Over riding there is relationship between the Super class method and Sub class method. 2. Overloading does not block the Inheritance from the Super class , Where as in Overriding blocks Inheritance from the Super Class. 3. In Overloading separate methods share the same name, where as in Overriding Sub class method replaces the Super Class. 4. Overloading must have different method Signatures , Where as Overriding methods must have same Signatures. Dynamic dispatch: is a mechanism by which a call to Overridden function is resolved at runtime rather than at Compile time , and this is how Java implements Run time Polymorphism.
Dynamic Binding: Means the code associated with the given procedure call is not known
until the time of call the call at run time. (it is associated with Inheritance & Polymorphism).
system, which is called the Java Virtual machine (JVM), i.e. in its standard form, the JVM is an Interpreter for byte code. JIT- is a compiler for Byte code, The JIT-Complier is part of the JVM, it complies byte code into executable code in real time, piece-by-piece on demand basis.
o o o o o o
Interface: Interfaces can be used to implement the Inheritance relationship between the non-related classes that do not belongs to the same hierarchy, i.e. any Class and any where in hierarchy. Using Interface, you can specify what a class must do but not how it does. A class can implement more than one Interface. An Interface can extend one or more interfaces, by using the keyword extends. All the data members in the interface are public, static and Final by default. An Interface method can have only Public, default and Abstract modifiers. An Interface is loaded in memory only when it is needed for the first time. A Class, which implements an Interface, needs to provide the implementation of all the methods in that Interface. If the Implementation for all the methods declared in the Interface are not provided , the class itself has to declare abstract, other wise the Class will not compile. If a class Implements two interface and both the Intfs have identical method declaration, it is totally valid. If a class implements two interfaces both have identical method name and argument list, but different return types, the code will not compile. An Interface cant be instantiated. Intf Are designed to support dynamic method resolution at run time. An interface can not be native, static, synchronize, final, protected or private. The Interface fields cant be Private or Protected. A Transient variables and Volatile variables can not be members of Interface. The extends keyword should not used after the Implements keyword, the Extends must always come before the Implements keyword. A top level Interface can not be declared as static or final. If an Interface species an exception list for a method, then the class implementing the interface need not declare the method with the exception list. If an Interface cant specify an exception list for a method, the class cant throw an exception. If an Interface does not specify the exception list for a method, he class can not throw any exception list. The general form of Interface is Access interface name { return-type method-name1(parameter-list); type final-varname1=value; }
Abstract Class means - Which has more than one abstract method which doesnt have
method body but at least one of its methods need to be implemented in derived Class. The general form of abstract class is : abstract type name (parameter list); The Number class in the java.lang package represents the abstract concept of numbers. It makes sense to model numbers in a program, but it doesn't make sense to create a generic number object. o o o o Difference Between Interfaces And Abstract class ? All the methods declared in the Interface are Abstract, where as abstract class must have atleast one abstract method and others may be concrete. In abstract class keyword abstract must be used for method, where as in Interface we need not use the keyword for methods. Abstract class must have Sub class, where as Interface cant have sub classes. An abstract class can extend only one class, where as an Interface can extend more than one.
What are access specifiers and access modifiers ? Accesss specifiers Public Protected Private Access modifiers Public Abstract Final Static Volatile Synchronized Transient Native
Constant
Public : The Variables and methods can be access any where and any package. Protected : The Variables and methods can be access same Class, same Package & sub
class.
Private : The variable and methods can be access in same class only.
Same class Same-package & subclass Same Package & non-sub classes Public, Protected, and Private Public, Protected Public, Protected
Identifiers : are the Variables that are declared under particular Datatype. Literals: are the values assigned to the Identifiers.
Static : access modifier. Signa: Variable-Static int b; Method- static void meth(int x)
When a member is declared as Static, it can be accessed before any objects of its class are created and without reference to any object. Eg : main(),it must call before any object exit. Static can be applied to Inner classes, Variables and Methods. Local variables cant be declared as static. A static method can access only static Variables. and they cant refer to this or super in any way. Static methods cant be abstract. A static method may be called without creating any instance of the class. Only one instance of static variable will exit any amount of class instances.
Transient : access modifier Transient can be applied only to class level variables. Local variables cant be declared as transient. During serialization, Objects transient variables are not serialized. Transient variables may not be final or static. But the complies allows the declaration and no compile time error is generated.
Volatile can applied to static variables. Volatile can not be applied to final variables. Transient and volatile can not come together. Volatile is used in multi-processor environments.
Synchronized : access modifier Synchronized keyword can be applied to methods or parts of the methods only.
Synchronize keyword is used to control the access to critical code in multi-threaded programming. Declaration of access specifier and access modifiers :
Package : A Package is a collection of Classes Interfaces that provides a high-level layer of access protection and name space management.
Finalize( ) method:
All the objects have Finalize() method, this method is inherited from the Object class. Finalize() is used to release the system resources other than memory(such as file handles& network connecs. Finalize( ) is used just before an object is destroyed and can be called prior to garbage collection. Finalize() is called only once for an Object. If any exception is thrown in the finalize() the object is still eligible for garbage collection. Finalize() can be called explicitly. And can be overloaded, but only original method will be called by Ga-collect. Finalize( ) may only be invoked once by the Garbage Collector when the Object is unreachable. The signature finalize( ) : protected void finalize() throws Throwable { }
Constructor( ) :
A constructor method is special kind of method that determines how an object is initialized when created. Constructor has the same name as class name. Constructor does not have return type. Constructor cannot be over ridden and can be over loaded. Default constructor is automatically generated by compiler if class does not have once. If explicit constructor is there in the class the default constructor is not generated. If a sub class has a default constructor and super class has explicit constructor the code will not compile.
Object : Object is a Super class for all the classes. The methods in Object class as follows.
Object clone( ) final void notify( ) Int hashCode( ) Boolean equals( ) final void notify( ) Void finalize( ) String toString( ) Final Class getClass( ) final void wait( ) Class : The Class class is used to represent the classes and interfaces that are loaded by the JAVA Program.
Character : A class whose instances can hold a single character value. This class also
defines handy methods that can manipulate or inspect single-character data. constructors and methods provided by the Character class: Character(char) : The Character class's only constructor, which creates a Character object containing the value provided by the argument. Once a Character object has been created, the value it contains cannot be changed. compareTo(Character) :An instance method that compares the values held by two character objects. equals(Object) : An instance method that compares the value held by the current object with the value held by another. toString() : An instance method that converts the object to a string. charValue() :An instance method that returns the value held by the character object as a primitive char value.
String: String is Immutable and String Is a final class. The String class provides for strings
whose value will not change. One accessor method that you can use with both strings and string buffers is the length() method, which returns the number of characters contained in the string or the string buffer. The methods in String Class:toString( ) equals( ) indexOff( ) LowerCase( ) charAt( ) compareTo( ) lastIndexOff( ) UpperCase( ) getChars( ) subString( ) trim( ) getBytes( ) concat( ) valueOf( ) toCharArray( ) replace( ) ValueOf( ) : converts data from its internal formate into human readable formate. String Buffer : Is Mutable , The StringBuffer class provides for strings that will be modified; you use string buffers when you know that the value of the character data will change. In addition to length, the StringBuffer class has a method called capacity, which returns the amount of space allocated for the string buffer rather than the amount of space used. The methods in StringBuffer Class:length( ) append( ) replace( ) charAt( ) and setCharAt( ) capacity( ) insert( ) substring( ) getChars( ) ensureCapacity( ) reverse( ) setLength( ) delete( )
Wraper Classes : are the classes that allow primitive types to be accessed as Objects.
These classes Number Double Float
are similar to primitive data types but starting with capital letter. Byte Boolean Short Character Integer Long primitive Datatypes in Java : According to Java in a Nutshell, 5th ed boolean, byte, char, short, long float, double, int. Float class : The Float and Double provides the methods isInfinite( ) and isNaN( ). isInfinite( ) : returns true if the value being tested is infinetly large or small. isNaN( ) : returns true if the value being tested is not a number.
Character class : defines forDigit( ) digit( ) . ForDigit( ) : returns the digit character associated with the value of num. digit( ) : returns the integer value associated with the specified character (which is presumably) according to the specified radix.
String Tokenizer : provide parsing process in which it identifies the delimiters provided by
the user, by default delimiters are spaces, tab, new line etc., and separates them from the tokens. Tokens are those which are separated by delimiters.
Observable Class: Objects that subclass the Observable class maintain a list of observers.
When an Observable object is updated it invokes the update( ) method of each of its observers to notify the observers that it has changed state. Observer interface : is implemented by objects that observe Observable objects.
Instanceof( ) :is used to check to see if an object can be cast into a specified type with out
throwing a cast class exception.
this() : can be used to invoke a constructor of the same class. super() :can be used to invoke a super class constructor. Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private. Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors. What is reflection API? How are they implemented Reflection package is used mainlyfor the purpose of getting the class name. by useing the getName method we can get name of the class for particular application. Reflection is a feature of the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. What is heap in Java JAVA is fully Object oriented language. It has two phases first one is Compilation phase and second one is interpratation phase. The Compilation phase convert the java file to class file (byte code is only readable format of JVM) than Intepratation phase interorate the class file line by line and give the proper result. main( ) : is the method where Java application Begins. String args[ ] : receives any command line argument during runtime. System : is a predefined Class that provides access to the System. Out : is output stream connected to console. Println :displays the output. Downcasting : is the casting from a general to a more specific type, i.e casting down the hierarchy. Doing a cast from a base class to more specific Class, the cast does;t convert the Object, just asserts it actually is a more specific extended Object. Upcasting : byte can take Integer values.
Exception Exception handling Exception can be generated by Java-runtime system or they can be manually generated by code. Error-Handling becomes a necessary while developing an application to account for exceptional situations that may occur during the program execution, such as Run out of memory Resource allocation Error Inability to find a file Problems in Network connectivity. If the Resource file is not present in the disk, you can use the Exception handling mechanisim to handle such abrupt termination of program.
Exception class : is used for the exceptional conditions that are trapped by the program. An exception is an abnormal condition or error that occur during the execution of the program. Error : the error class defines the conditions that do not occur under normal conditions. Eg: Run out of memory, Stack overflow error.
Java.lang.Object +.Java.Lang.Throwable Throwable +. Java.lang.Error | +. A whole bunch of errors | Exception Error +.Java.Lang.Exception (Unchecked, Checked) +.Java.Lang.RuntimeException | +. Various Unchecked Exception | +. Various checked Exceptions. Two types of exceptions: 1. Checked Exceptions : must be declare in the method declaration or caught in a catch block. Checked exception must be handled at Compile Time. Environmental error that cannot necessarly be detected by Testing, Eg: disk full, brocken Socket, Database unavailable etc. 2. Un-checked Exceptions: Run-time Exceptions and Error, doest have to be declare.(but can be caught). Run-time Exceptions : programming errors that should be detectd in Testing , Arithmetic, Null pointer, ArrayIndexOutofBounds, ArrayStore, FilenotFound, NumberFormate, IO, OutofMemory.
} Finally : when an exception is raised, the statement in the try block is ignored, some times it is necessary to process certain statements irrespective of wheather an exception is raised or not, the finally block is used for this purpose. Throw : The throw class is used to call exception explicitly. You may want to throw an exception when the user enters a wrong login ID and pass word, you can use throw statement to do so. The throw statement takes an single argument, which is an Object of exception class.
Throw<throwable Instance> If the Object does not belong to a valid exception class the compiler gives error. Throws :The throws statement specifies the list of exception that has thrown by a method. If a method is capable of raising an exception that is does not handle, it must specify the exception has to be handle by the calling method, this is done by using the throw statement. [<access specifier>] [<access modifier>] <return type> <method name> <arg-list> [<exception-list>]
Eg: public void accept password( ) throws illegalException { System.out.println(Intruder); Throw new illegalAccesException; }
Multi Programming A multithreaded program contains two or more parts that can run concurrently, Each part a program is called thread and each part that defines a separate path of excution. Thus multithreading is a specified from of multitasking . There are two distinct types of multitasking . Process: A Process is , in essence , a program that is executing. Process-based :is heavy weight- allows you run two or more programs concurrently. Eg: you can use JAVA compiler at the same time you are using text editor. Here a program is a small unit of code that can be dispatched by scheduler . Thread-based: is Light weight- A Program can perform two or more tasks simultaneously. Creating a thread: Eg: A text editor can format at the same time you can print, as long as these two tasks are being perform separate threads. Thread: can be defined as single sequential flow of control with in a program. Single Thread : Application can perform only one task at a time. Multithreaded : A process having more than one thread is said to be multithreaded. The multiple threads in the process run at the same time, perform different task and interact with each other. Daemon Thread : Is a low priority thread which runs immediately on the back ground doing the Garbage Collection operation for the Java Run time System. SetDaemon( ) is used to create DaemonThread.
Creating a Thread : 1. By implementing the Runnable Interface. 2.By extending the thread Class.
10
Runnable Interface :
The Runnable interface consist of a Single method Run( ), which is executed when the thread is activated. When a program need it inherit from another class besides the thread Class, you need to implement the Runnable interface. Syntax: public void <Class-name> extends <SuperClass-name> implements Runnable Eg: public Class myapplet extends Japplet implements Runnable { // Implement the Class } Runnable interface is the most advantageous method to create threads because we need not extend thread Class here.
Runnable
New Thread -- Life Cycle of Thread : ---- Not Runnable ----
Dead
New Thread : When an instance of a thread class is created, a thread enters the new thread state. Thread newThread = new Thread(this); You have to invoke the Start( ) to start the thread. ie, newThread.Start( ); Runnable : when the Start( ) of the thread is invoked the thread enters into the Runnable State. Not Runnable : A thread is said to be not runnable state if it Is Sleeping Is Waiting Is being blocked by another thread. sleep(long t); where t= no: of milliseconds for which the thread is inactive. The sleep( ) is a static method because it operates on the current thread. Dead : A thread can either die natuarally or be killed. - A thread dies a natural death when the loop in the Run( ) is complete. - Assigning null to the thread Object kills the thread. - If the loop in the Run( ) has a hundred iterations , the life of the thread is a hundred iterators of the loop.
11
IsAlive( ) : of the thread class is used to determine whether a thread has been started or stopped. If isAlive( ) returns true the thread is still running otherwise running completed. Thread Priorities : are used by the thread scheduler to decide when each thread should be allowed to run.To set a thread priority, use the setpriority( ), which is a member of a thread. final void setpriority(int level) - here level specifies the new priority setting for the calling thread. The value level must be with in the range :MIN_PRIORITY = 1 NORM_PRIORITY = 5 MAX_PRIORITY = 10 You can obtain the current priority setting by calling getpriority( ) of thread. final int getpriority( ) Synchronization : Two ro more threads trying to access the same method at the same point of time leads to synchronization. If that method is declared as Synchronized , only one thread can access it at a time. Another thread can access that method only if the first threads task is completed.
method. A Synchronized statements can only be executed after a thread has acquired a lock for the object or Class reffered in the Synchronized statements. The general form is - Synchronized(object) { // statements to be Synchronized } Inter Thread Communication : To Avoid pooling , Java includes an elegant interprocess communication mechanism. Wait( ) - tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor & call notify( ). notify( ) - wake up the first thread that called wait( ) on the same Object. notifyall( ) wake up all the threads that called wait( ) on the same Object. The highest priority thread will run fast.
Serialization : The process of writing the state of Object to a byte stream to transfer
over the network is known as Serialization.
Deserialization : and restored these Objects by deserialization. Externalizable : is an interface that extends Serializable interface and sends data into
streams in compressed format. WriteExternal(Objectoutput out) ReadExternal(objectInput in) I/O Package Java.io.*; It has two methods
There are two classifications. ByteStream - console input CharacterStream File 1. ByteStream : Console Input Read( ) - one character Readline( ) one String BufferReader br = new BufferReader(new InputStreamReader(System.in));
12
2. CharacterStream : File FileInputStream - Store the contents to the File. FileOutStream - Get the contents from File. PrintWrite pw = new printwriter(System.out.true); Pw.println( ); Eg :Class myadd { public static void main(String args[ ]) { BufferReader br = new BufferReader(new InputStreamReader(System.in)); System.out.println(Enter A no : ); int a = Integer.parseInt(br.Read( )); System.out.println(Enter B no : ); int b = Integer.parseInt(br.Read( )); System.out.println(The Addition is : (a+b)); } }
Collections Collections : A collection allows a group of objects to be treated as a single unit. collection define a set of core Interfaces as follows. Collection Set Hash set Tree set List Array List Vector List Linked List Map Hash Map class Hash Table class
Sorted set
Sorted map
Collection Interface :
The CI is the root of collection hierarchy and is used for common functionality across all collections. There is no direct implementation of Collection Interface.
The Class Hash set implements Set Interface. Is used to represent the group of unique elements. Set stores elements in an unordered way but does not contain duplicate elements.
Sorted set : extends Set Interface. The class Tree Set implements Sorted set Interface.
It provides the extra functionality of keeping the elements sorted. It represents the collection consisting of Unique, sorted elements in ascending order.
List : extends Collection Interface. The classes Array List, Vector List & Linked List
implements List Interface.
13
Map Interface:basic Interface.The classesHash Map & Hash Table implements Map
interface. Used to represent the mapping of unique keys to values. By using the key value we can retrive the values. Two basic operations are get( ) & put( ) .
The Class Tree Map implements Sorted Map Interface. Maintain the values of key order. The entries are maintained in ascending order.
Collection classes:
Abstract Collection Abstract List Abstract Sequential List Linked List List Map | | Abstract List Dictonary | | Vector HashTable | | Stack Properities HashSet : Implements Set Interface. HashSet( ); The elements are not stored in sorted order. Array List Abstract Set Hash Set Tree Set Abstract Map Hash Map Tree Map
TreeSet ts=new TreeSet( ); The elements are stored in sorted ascending order. ts.add(H); Access and retrieval times are quit fast, when storing a large amount of data.
Vector : Implements List Interface. Vector implements dynamic array. Vector v = new vector( ); Vector is a growable object. V1.addElement(new Integer(1)); Vector is Synchronized, it cant allow special characters and null values.
All vector starts with intial capacity, after it is reached next time if we want to store object in vector, the vector automatically allocates space for that Object plus extra room for additional Objects.
ArrayList : Implements List Interface. Array can dynamically increase or decrease size. Array List are ment for Random accessing.
14
L1.add(R);
Map Classes: Abstract Map; Hash Map ; Tree Map Hash Map : Implements Map Interface. Hashmap() , Hashmap(Map m), Hashmap(int capacity) The Elements may not in Order. Hash Map is not synchronized and permits null values Hash Map is not serialized. Hashmap hm = new HashMap( ); Hash Map supports Iterators. hm.put(Hari,new Double(11.9)); Hash Table : Implements Map Interface. Hash Table is synchronized and does not permit null values. Hash Table is Serialized. Hashtable ht = new Hashtable( ); Stores key/value pairs in Hash Table. ht.put(Prasadi,new Double(74.6)); A Hash Table stores information by using a mechanism called hashing. In hashing the informational content of a key is used to determine a unique value, called its Hash Code. The Hash Code is then used as the index at which the data associated with the key is stored. The Transformation of the key into its Hash Code is performed automatically- we never see the Hash Code. Also the code cant directly index into h c. Tree Map : Implements Sorted Set Interface. TreeMap tm=new TreeMap( ); The elements are stored in sorted ascending order. tm.put( Prasad,new Double(74.6)); Using key value we can retrieve the data. Provides an efficient means of storing key/value pairs in sorted order and allows rapid retrivals.
Iterator: Each of collection class provided an iterator( ). By using this iterator Object, we can access each element in the collection one at a time. We can remove() ; Hashnext( ) go next; if it returns false end of list.
Iterarator Iterator itr = a1.iterator( ); While(itr.hasNext( )) { Enumerator Enumerator vEnum = v.element( ); System.out.println(Elements in Vector :); while(vEnum.hasMoreElements( ) )
System.out.println(element + );
System.out.println(vEnum.nextElement( ) + );
Collections
1.Introduction 2.Legacy Collections 1. The Enumeration Interface 2. Vector 3. Stack 4. Hashtable 5. Properties 3.Java 2 Collections 1. The Interfaces of the collections framework 2. Classes in the collections framework 3. ArrayList & HashSet 4. TreeSet & Maps
Introduction : 15
16
Methods : Object put(Object key,Object value) : Inserts a key and a value into the hashtable. Object get(Object key) : Returns the object that contains the value associated with key. boolean contains(Object value) : Returns true if the given value is available in the hashtable. If not, returns false. boolean containsKey(Object key) : Returns true if the given key is available in the hashtable. If not, returns false. Enumeration elements() : Returns an enumeration of the values contained in the hashtable. int size() : Returns the number of entries in the hashtable.
Properties Properties is a subclass of Hashtable Used to maintain lists of values in which the key is a String and the value is also a String Constructors Properties() Properties(Properties propDefault) : Creates an object that uses propDefault for its default value. Methods : String getProperty(String key) : Returns the value associated with key. String getProperty(String key, String defaultProperty) : Returns the value associated with key. defaultProperty is returned if key is neither in the list nor in the default property list . Enumeration propertyNames() : Returns an enumeration of the keys. This includes those keys found in the default property list.
Set
List
SortedMap
ListIterator
17
List Interface
ordered collection Elements are added into a particular position. Represents the sequence of numbers in a fixed order. But may contain duplicate elements. Elements can be inserted or retrieved by their position in the List using Zero based index. List stores elements in an ordered way.
Map Interface: Basic Interface.The classes Hash Map & HashTable implements Map interface. Used to represent the mapping of unique keys to values. By using the key value we can retrive the values. Two basic operations are get( ) & put( ) . boolean put(Object key, Object value) : Inserts given value into map with key Object get(Object key) : Reads value for the given key. Tree Map Class: Implements Sorted Set Interface. The elements are stored in sorted ascending order. Using key value we can retrieve the data. Provides an efficient means of storing key/value pairs in sorted order and allows rapid retrievals.
TreeMap tm=new TreeMap( ); tm.put( Prasad,new Double(74.6));
The Classes in Collections Framework Abstract Collection Abstract List Abstract Set Abstract Map
18
Array List
Hash Set
Tree Set
Hash Map
Tree Map
ArrayList
Similar to Vector: it encapsulates a dynamically reallocated Object[] array Why use an ArrayList instead of a Vector? All methods of the Vector class are synchronized, It is safe to access a Vector object from two threads. ArrayList methods are not synchronized, use ArrayList in case of no synchronization Use get and set methods instead of elementAt and setElementAt methods of vector
HashSet
Implements a set based on a hashtable The default constructor constructs a hashtable with 101 buckets and a load factor of 0.75 HashSet(int initialCapacity) HashSet(int initialCapacity,float loadFactor) loadFactor is a measure of how full the hashtable is allowed to get before its capacity is automatically increased Use Hashset if you dont care about the ordering of the elements in the collection
TreeSet
Similar to hash set, with one added improvement A tree set is a sorted collection Insert elements into the collection in any order, when it is iterated, the values are automatically presented in sorted order Maps : Two implementations for maps:
HashMap
hashes the keys The Elements may not in Order. Hash Map is not synchronized and permits null values Hash Map is not serialized. Hash Map supports Iterators.
TreeMap
uses a total ordering on the keys to organize them in a search tree The hash or comparison function is applied only to the keys The values associated with the keys are not hashed or compared. How are memory leaks possible in Java If any object variable is still pointing to some object which is of no use, then JVM will not garbage collect that object and object will remain in memory creating memory leak What are the differences between EJB and Java beans the main difference is Ejb components are distributed which means develop once and run anywhere. java beans are not distributed. which means the beans cannot be shared .
19
What would happen if you say this = null this will give a compilation error as follows cannot assign value to final variable this Will there be a performance penalty if you make a method synchronized? If so, can you make any design changes to improve the performance yes.the performance will be down if we use synchronization. one can minimise the penalty by including garbage collection algorithm, which reduces the cost of collecting large numbers of short- lived objects. and also by using Improved thread synchronization for invoking the synchronized methods.the invoking will be faster. How would you implement a thread pool public class ThreadPool extends java.lang.Object implements ThreadPoolInt This class is an generic implementation of a thread pool, which takes the following input a) Size of the pool to be constructed b) Name of the class which implements Runnable (which has a visible default constructor) and constructs a thread pool with active threads that are waiting for activation. once the threads have finished processing they come back and wait once again in the pool. This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine. However, the currently executing threads are allowed to continue till they come back to the passivePool How does serialization work Its like FIFO method (first in first out) How does garbage collection work There are several basic strategies for garbage collection: reference counting, marksweep, mark-compact, and copying. In addition, some algorithms can do their job incrementally (the entire heap need not be collected at once, resulting in shorter collection pauses), and some can run while the user program runs (concurrent collectors). Others must perform an entire collection at once while the user program is suspended (so-called stop-the-world collectors). Finally, there are hybrid collectors, such as the generational collector employed by the 1.2 and later JDKs, which use different collection algorithms on different areas of the heap How would you pass a java integer by reference to another function Passing by reference is impossible in JAVA but Java support the object reference so. Object is the only way to pass the integer by refrence. What is the sweep and paint algorithm The painting algorithm takes as input a source image and a list of brush sizes. sweep also is that it computes the arrangement of n lines in the plane ... a correct algorithm, Can a method be static and synchronized no a static mettod can't be synchronised Do multiple inheritance in Java Its not possible directly. That means this feature is not provided by Java, but it can be achieved with the help of Interface. By implementing more than one interface. What is data encapsulation? What does it buy you The most common example I can think of is a javabean. Encapsulation may be used by creating 'get' and 'set' methods in a class which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public. Encapsulation can be used to validate the data that is to be stored, to do calculations on data that is stored in a field or fields, or for use in introspection (often the case when using javabeans in Struts, for instance).
20
What is reflection API? How are they implemented Reflection package is used mainlyfor the purpose of getting the class name. by using the getName method we can get name of the class for particular application . Reflection is a feature of the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. What are the primitive types in Java According to Java in a Nutshell, 5th ed boolean, byte, char, short, long float, double, int Is there a separate stack for each thread in Java No What is heap in Java JAVA is fully Object oriented language. It has two phases first one is Compilation phase and second one is interpratation phase. The Compilation phase convert the java file to class file (byte code is only readable format of JVM) than Intepratation phase interorate the class file line by line and give the proper result. In Java, how are objects / values passed around In Java Object are passed by reference and Primitive data is always pass by value Do primitive types have a class representation Primitive data type has a wrapper class to present. Like for int - Integer , for byte Byte, for long Long etc ... How all can you free memory With the help of finalize() method. If a programmer really wants to explicitly request a garbage collection at some point, System.gc() or Runtime.gc() can be invoked, which will fire off a garbage collection at that time. Does java do reference counting It is more likely that the JVMs you encounter in the real world will use a tracing algorithm in their garbage-collected heaps What does a static inner class mean? How is it different from any other static member A static inner class behaves like any ``outer'' class. It may contain methods and fields. It is not necessarily the case that an instance of the outer class exists even when we have created an instance of the inner class. Similarly, instantiating the outer class does not create any instances of the inner class. The methods of a static inner class may access all the members (fields or methods) of the inner class but they can access only static members (fields or methods) of the outer class. Thus, f can access the field x, but it cannot access the field y. How do you declare constant values in java Using Final keyword we can declare the constant values How all can you instantiate final members Final member can be instantiate only at the time of declaration. null How is serialization implemented in Java A particular class has to implement an Interface java.io.Serializable for implementing serialization. When you have an object passed to a method and when the object is reassigned to a different one, then is the original reference lost No Reference is not lost. Java always passes the object by reference, now two references is pointing to the same object. What are the different kinds of exceptions? How do you catch a Runtime exception There are 2 types of exceptions. 1. Checked exception 2. Unchecked exception. Checked exception is catched at the compile time while unchecked exception is checked at run time.
21
JDBC How to Interact with DB? Generally every DB vendor provides a User Interface through which we can easily execute SQL querys and get the result (For example Oracle Query Manager for Oracle, and TOAD (www.quest.com) tool common to all the databases). And these tools will help DB developers to create database. But as a programmer we want to interact with the DB
22
Oracle ODBC Front End Application SQL server ODBC Sybase ODBC
ODBC API
SP API
C function calls Oracle DSN My DSN SQL Server DSN Sybase DSN Our DSN
SP API
Sybase
Advantages Single API (Protocol) is used to interact with any DB Switching from one DB to another is easy Doesnt require any modifications in the Application when you want to shift from one DB to other. What for JDBC? As we have studied about ODBC and is advantages and came to know that it provides a common API to interact with any DB which has an ODBC Service Providers Implementation written in Native API that can be used in your applications. If an application wants to interact with the DB then the options which have been explained up to now in this book are: 1. Using Native Libraries given by the DB vendor 2. Using ODBC API And we have listed there Advantages and Disadvantages. But if the application is a JAVA application then the above given options are not recommended to be used due to the following reasons 1. Native Libraries given by DB vendor a. Application becomes vendor dependent and b. The application has to use JNI to interact with Native Lib which may cause serious problem for Platform Independency in our applications.
23
P A PI
SP AP I
Sybase DB
Oracle DB
In the above show archetecture diagram the JDBC Driver forms an abstraction layer between the JAVA Application and DB, and is implemented by 3 rd party vendors or a DB Vendor. But whoever may be the vendor and what ever may be the DB we need not to worry will just us JDCB API to give instructions to JDBC Driver and then its the responsibility of JDBC Driver Provider to convert the JDBC Call to the DB Specific Call.
24
1. 2. 3. 4.
(JDBC ODBC-Bridge Driver) JDBC-ODBC Bridge Driver (Java-Native API Driver) Native API Partly JAVA Driver (Thick Driver) (Java Net Protocol Driver) Intermediate DataBase Access Server (Java Native Protocol driver) Pure JAVA Driver (Thin driver)
Type-1 : JDBC-ODBC Bridge Driver : Since ODBC is written in C-language using pointers, so JAVA doest support pointers, a java program cant communate directly with the DataBase. The JDBCODBC bridge drivertransulates JDBC API calls to ODBC API calls. Architecture
JAVA Application
DBMS
This type of Driver is designed to convert the JDBC request call to ODBC call and ODBC response call to JDBC call. The JDBC uses this interface in order to communicate with the database, so neither the database nor the middle tier need to be Java compliant. However ODBC binary code must be installed on each client machine that uses this driver. This bridge driver uses a configured data source. Advantages Simple to use because ODBC drivers comes with DB installation/Microsoft front/back office product installation JDBC ODBC Drivers comes with JDK software Disadvantages More number of layers between the application and DB. And more number of API conversions leads to the downfall of the performance. Slower than type-2 driver Where to use? This type of drivers are generaly used at the development time to test your applications. Because of the disadvantages listed above it is not used at production time. But if we are not available with any other type of driver implementations for a DB then we are forced to use this type of driver (for example Microsoft Access). Examples of this type of drivers JdbcOdbcDriver from sun Suns JdbcOdbcDriver is one of type-1 drivers and comes along with sun j2sdk (JDK). Setting environment to use this driver 1. Software ODBC libraries has to be installed.
25
SP API
DBMS
OCI Libraries
DBMS Client libraries (native) SP N/W Libra ries DBMS Server libraries (native)
This driver converts the JDBC call given by the Java application to a DB specific native call (i.e. to C or C++) using JNI (Java Native Interface). Advantages :Faster than the other types of drivers due to native library participation in socket programing. Disadvantage : DB spcifiic native client library has to be installed in the client machine. Preferablly work in local network environment because network service name must be configured in client system Where to use? This type of drivers are suitable to be used in server side applications. Not recommended to use with the applications using two tire model (i.e. client and database layers) because in this type of model client used to interact with DB using the driver and in such a situation the client system sould have the DB native library. Examples of this type of drivers 1. OCI 8 (Oracle Call Interface) for Oracle implemented by Oracle Corporation. Setting environment to use this driver Software: Oracle client software has to be installed in client machine classpath %ORACLE_HOME%\ora81\jdbc\lib\classes111.zip
26
JDBC Application
JDBC API
Net protocol
Middleware Listener
Server Listener
OCI Libraries
This type of drivers responsibility is to convert JDBC call to Net protocol (Middleware listener dependent) format and redirect the client request to Middleware Listener and middleware listener inturn uses type-1, type-2 or type-4 driver to interact with DB. Advantages: It allows the flexibility on the architecture of the application. In absence of DB vendor supplied driver we can use this driver Suitable for Applet clients to connect DB, because it uses Java libraries for communication between client and server. Disadvantages: From client to server communication this driver uses Java libraries, but from server to DB connectivity this driver uses native libraries, hence number of API conversion and layer of interactions increases to perform operations that leads to performance deficit. Third party vendor dependent and this driver may not provide suitable driver for all DBs Where to use? Suitable for Applets when connecting to databases Examples of this type of drivers:
27
Native Protocol
This type of driver converts the JDBC call to a DB defined native protocol.
DBMS
Advantage Type-4 driver are simple to deploy since there is No client native libraries required to be installed in client machine Comes with most of the Databases Disadvantages: Slower in execution compared with other JDBC Driver due to Java libraries are used in socket communication with the DB Where to use? This type of drivers are sutable to be used with server side applications, client side application and Java Applets also. Examples of this type of drivers 1) Thin driver for Oracle implemented by Oracle Corporation Setting environment to use this driver classpath %ORACLE_HOME%\ora81\jdbc\lib\classes111.zip How to use this driver Driver class name oracle.jdbc.driver.OracleDriver Driver URL jdbc:oracle:thin:@HostName:<port no>:<SID> <port no> 1521 <SID> -> ORCL 2) MySQL Jconnector for MySQL database Setting environment to use this driver classpath C:\mysql\mysql-connector-java-3.0.8-stable\mysqlconnector-java-3.0.8-stable-bin.jar How to use this driver Driver class name Driver URL com.mysql.jdbc.Driver jdbc:mysql:///test
28
Chapter 3 [JDBC Core API] In this chapter we are going to discuss about 3 versions of JDBC: JDBC 1.0, 2.0 and 3.0 Q) How JDBC API is common to all the Databases and also to all drivers? A) Fine! The answer is JDBC API uses Factory Method and Abstract Factory Design pattern implementations to make API common to all the Databases and Drivers. In fact most of the classes available in JDBC API are interfaces, where Driver vendors must provide implementation for the above said interfaces. Q) Then how JDBC developer can remember or find out the syntaxes of vendor specific classes? A) No! developer need not have to find out the syntaxes of vendor specific implementations why because DriverManager is one named class available in JDBC API into which if you register Driver class name, URL, user and password, DriverManager class in-turn brings us one Connection object. Q) Why most of the classes given in JDBC API are interfaces? A) Why abstract class and abstract methods are? Abstract class forces all sub classes to implement common methods whichever are required implementations. Only abstract method and class can do this job. Thats why most part of the JDBC API is a formation of interfaces. JDBC API comes in 2 packages java.sql.* javax.sql.* First of all I want to discuss briefly about all the list of interfaces and classes available in java.sql. package Interfaces index Driver Every JDBC Driver vendor must one sub class of this class for initial establishment of Connections. DriverManager class need to be first registered with this class before accepting URL and other information for getting DB connection. Method index Connection connect(String url, Properties info) This method takes URL argument and user name & password info as Properties object boolean acceptURL(String url) This method returns boolean value true if the given URL is correct, false if any wrong in URL boolean jdbcComplaint() JDBC compliance requires full support for the JDBC API and full support for SQL 92 Entry Level. It is expected that JDBC compliant drivers will be available for all the major commercial databases. Connection Connection is class in-turn holds the TCP/IP connection with DB. Functions available in this class are used to manage connection live-ness as long as JDBC application wants to connect with DB. The period for how long the connection exists is called as Session. This class also provides functions to execute various SQL statements on the DB. For instance the operations for DB are mainly divided into 3 types DDL (create, alter, and drop) DML (insert, select, update and delete) DCL (commit, rollback) and also call function_name (or) call procedure_name Method Index Statement createStatement() PreparedStatement prepareStatement(String preSqlOperation)
29
30
// TypeIIDriverTest,java package com.digitalbook.j2ee.jdbc; import java.sql.*; public class TypeIIDriverTest { Connection con; Statement stmt; ResultSet rs; public TypeIIDriverTest () { try { // Load driver class into default ClassLoader Class.forName ("oracle.jdbc.driver.OracleDriver"); // Obtain a connection with the loaded driver con =DriverManager.getConnection ("jdbc:oracle:oci8:@digital","scott","tiger"); // create a statement st=con.createStatement(); //execute SQL query rs =st.executeQuery ("select ename,sal from emp"); System.out.println ("Name Salary"); System.out.println ("--------------------------------"); while(rs.next()) { System.out.println (rs.getString(1)+" "+rs.getString(2)); } rs.close (); stmt.close (); con.close (); } catch(Exception e) { e.printStackTrace (); } } public static void main (String args[]) { TypeIIDriverTest demo=new TypeIIDriverTest (); } } Chapter 9 : [javax.sql package]
31
32
33
RowSetEvent As part of its internal notification process, a RowSet object creates an instance of RowSetEvent and passes it to the listener. The listener can use this RowSetEvent object to find out which rowset had the event. 2. Metadata RowSetMetaData This interface, derived from the ResultSetMetaData interface, provides information about the columns in a RowSet object. An application can use RowSetMetaData methods to find out how many columns the rowset contains and what kind of data each column can contain. The RowSetMetaData interface provides methods for setting the information about columns, but an application would not normally use these methods. When an application calls the RowSet method execute, the RowSet object will contain a new set of rows, and its RowSetMetaData object will have been internally updated to contain information about the new columns. 3. The Reader/Writer Facility A RowSet object that implements the RowSetInternal interface can call on the RowSetReader object associated with it to populate itself with data. It can also call on the RowSetWriter object associated with it to write any changes to its rows back to the data source from which it originally got the rows. A rowset that remains connected to its data source does not need to use a reader and writer because it can simply operate on the data source directly. RowSetInternal By implementing the RowSetInternal interface, a RowSet object gets access to its internal state and is able to call on its reader and writer. A rowset keeps track of the values in its current rows and of the values that immediately preceded the current ones, referred to as the original values. A rowset also keeps track of (1) the parameters that have been set for its command and (2) the connection that was passed to it, if any. A rowset uses the RowSetInternal methods behind the scenes to get access to this information. An application does not normally invoke these methods directly. RowSetReader A disconnected RowSet object that has implemented the RowSetInternal interface can call on its reader (the RowSetReader object associated with it) to populate it with data. When an application calls the RowSet.execute method, that method calls on the rowset's reader to do much of the work. Implementations can vary widely, but generally a reader makes a connection to the data source, reads data from the data source and populates the rowset with it, and closes the connection. A reader may also update the RowSetMetaData object for its rowset. The rowset's internal state is also updated, either by the reader or directly by the method RowSet.execute. RowSetWriter A disconnected RowSet object that has implemented the RowSetInternal interface can call on its writer (the RowSetWriter object associated with it) to write changes back to the underlying data source. Implementations may vary widely, but generally, a writer will do the following: Make a connection to the data source Check to see whether there is a conflict, that is, whether a value that has been changed in the rowset has also been changed in the data source Write the new values to the data source if there is no conflict Close the connection The RowSet interface may be implemented in any number of ways, and anyone may write an implementation. Developers are encouraged to use their imaginations in coming up with new ways to use rowsets. Type III Driver WebLogic BEA weblogic.jdbc.common.internal.ConnectionPool Type III Driver WebLogic BEA weblogic.jdbc.connector.internal.ConnectionPool Type II & IV driver Oracle DB - Oracle
34
JDBC: There are three types of statements in JDBC Create statement : Is used to execute single SQL statements. Prepared statement: Is used for executing parameterized quaries. Is used to run precompiled SEQL Statement. Callable statement: Is used to execute stored procedures. Stored Procedures: Is a group of SQL statements that perform a logical unit and performs a particular task. Are used to encapsulate a set operations or queries t execute on data. execute() returns Boolean value executeQuery( ) returns resultset Object executeupdate( ) returns integer value Loading the Driver: Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); Conn=DriverManager.getConnection(jdbc:odbc:dsn, username, password); ( ORACLE Driver ) Class.forName(Oracle.jdbc.driver.OracleDriver); Conn=DriverManager.getConnection(jdbc:oracle:thin:@192.168.1.105:1521:dbn, username, password); Data base connection: Public static void main(String args[]); Connection con; Statement st; Resultset rs; try { // Getting all rows from Table Class.forName(sun.jdbc.odbc.jdbcodbc); Conn=DriverManager.getConnction(jdbc.odbc.dsn, username , password); st = con.createstatement( ); rs = st.executestatement(SELECT * FROM mytable); while(rs.next()); { String s= rs.getString(1); or rs.setString(COL_A); int i = rs. getInt(2); Float f = rs.getfloat(3); Process(s,i,f); } catch(SQLException e) {} //Getting particular rows from Table st = con.createstatement( ); rs = st.executequery(SELECT * FROM mytable WHERE COL A = Prasad); while(rs.next( )); { String s = rs.getString(1); Int i = rs.getint(2); Float f = rs.getfloat(3); Process(s,i,f); } Catch(SQLException e); { } //updating a row from table. try { st = con.createstatement( ); int numupdated = st.executeupdate(UPDATE mytable SET COL_A = prasad WHERE COL_B=746); rs = st.executeupdate(); conn.close(); } catch(SQLExceptione); { }
35
36
37
5.
38
39
40
41
Web Components
Servlets Java Server Pages (JSP) Tags and Tag Libraries Whats a Servlet? Javas answer to CGI programming Program runs on Web server and builds pages on the fly When would you use servlets? Data changes frequently e.g. weather-reports Page uses information from databases e.g. on-line stores Page is based on user-submitted data e.g search engines Data changes frequently e.g. weather-reports Page uses information from databases e.g. on-line stores Page is based on user-submitted data e.g search engines Servlet Class Hierarchy javax.servlet.Servlet Defines methods that all servlets must implement init() service() destroy() javax.servlet.GenericServlet Defines a generic, protocol-independent servlet javax.servlet.http.HttpServlet To write an HTTP servlet for use on the Web doGet() doPost() javax.servlet.ServletConfig A servlet configuration object Passes information to a servlet during initialization Servlet.getServletConfig() javax.servlet.ServletContext To communicate with the servlet container Contained within the ServletConfig object ServletConfig.getServletContext() javax.servlet.ServletRequest Provides client request information to a servlet javax.servlet.ServletResponse Sending a response to the client Basic Servlet Structure import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Hello World extends HttpServlet { // Handle get request public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // request access incoming HTTP headers and HTML form data // response - specify the HTTP response line and headers // (e.g. specifying the content type, setting cookies). PrintWriter out = response.getWriter(); //out - send content to browser out.println("Hello World");
42
} }
Servlet Life Cycle Loading and Instantiation Initialization Request Handling End of Service Session Tracking Typical scenario shopping cart in online store Necessary because HTTP is a "stateless" protocol Session Tracking API allows you to look up session object associated with current request create a new session object when necessary look up information associated with a session store information in a session discard completed or abandoned sessions Session Tracking API - I Looking up a session object HttpSession session = request.getSession(true); Pass true to create a new session if one does not exist Associating information with session session.setAttribute(user,request.getParameter(name)) Session attributes can be of any type Looking up session information String name = (String) session.getAttribute(user) Session Tracking API - II getId : the unique identifier generated for the session isNew : true if the client (browser) has never seen the session getCreationTime : time in milliseconds since session was made getLastAccessedTime : time in milliseconds since the session was last sent from client getMaxInactiveInterval : # of seconds session should go without access before being invalidated . negative value indicates that session should never timeout Javax.Servlet Interface Servlet ServletRequest ServletResponce ServletConfig ServletContext SingleThreadModel Javax.Servlet.Http HttpServletRequest HttpServletResponse HttpSession Classes Genericservlet ServletInputStream ServletOutputStream ServletException UnavailableException Classes Cookie HttpServlet HttpSessionBindingEvent
43
SERVLETS 1. What is the servlet? Servlets are modules that extend request/response-oriented servers, such as Javaenabled web servers. For example, a servlet may be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company's order database. -Servlets are used to enhance and extend the functionality of Webserver. -Servlets handles Java and HTML separately. What are the uses of Servlets? A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task. What are th characters of Servlet? As Servlet are written in java, they can make use of extensive power of the JAVA API,such as networking and URL access,multithreading,databaseconnectivity,RMI object serialization. Efficient : The initilazation code for a servlet is executed only once, when the servlet is executed for the first time. Robest : provide all the powerfull features of JAVA, such as Exception handling and garbage collection. Portable: This enables easy portability across Web Servers. Persistance : Increase the performance of the system by executing features data access. What is the difference between JSP and SERVLETS Servlets : servlet tieup files to independitently handle the static presentation logic and dynamic business logic , due to this a changes made to any file requires recompilation of the servlet. - The servlet is Pre-Compile. JSP : Facilities segregation of work profiles to Web-Developer and Web-Designer , Automatically incorporates changes made to any file (PL & BL) , no need to recompile. Web-Developer write the code for Business logic whereas Web-Designer designs the layout for the WebPage by HTML & JSP. - The JSP is Post-Compile. 5. What are the advantages using servlets than using CGI? Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. It is efficient, convenient, powerful, portable, secure and inexpensive. Servlets also address the problem of doing server-side programming with platform-specific APIs. They are developed with Java Servlet API, a standard Java extension. What is the difference between servlets and applets?
2.
3.
4.
6.
44
8.
POST Method : The Post Method sends the Data as packets through a separate socket connection. The complete transaction is invisible to the client. The post method is slower compared to the Get method because Data is sent to the server as separate packates. --You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects! 9. What is the servlet life cycle? In Servlet life cycles are, init(),services(),destory(). Init( ) : Is called by the Servlet container after the servlet has been Instantiated. --Contains all information code for servlet and is invoked when the servlet is first loaded. -The init( ) does not require any argument , returns a void and throws Servlet Exception. -If init() executed at the time of servlet class loading.And init() executed only for first user. -You can Override this method to write initialization code that needs to run only once, such as loading a driver , initializing values and soon, Inother case you can leave normally blank. Public void init(ServletConfig Config) throws ServletException Service( ) : is called by the Servlet container after the init method to allow the servlet to respond to a request. -Receives the request from the client and identifies the type of request and deligates them to doGet( ) or doPost( ) for processing. Public void service(ServletRequest request,ServletResponce response) throws ServletException, IOException Destroy( ) : The Servlet Container calls the destroy( ) before removing a Servlet Instance from Service. -Excutes only once when the Servlet is removed from Server. Public void destroy( ) If services() are both for get and post methods. -So if u want to use post method in html page,we use doPost() or services() in servlet class. -if want to use get methods in html page,we can use doGet() or services() in servlet class. -Finally destory() is used to free the object. 10. What is the difference between ServletContext and ServletConfig? Both are interfaces.
45
11.
12.
If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following translation error: java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has already been obtained 13. Can I just abort processing a JSP? Yes.Because your JSP is just a servlet method,you can just put (whereever necessary) a < % return; %> 14. What is a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization? Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading. Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is nondeterministic, it may not help much even if you did add more memory and increased the size of the instance pool. If you want a servlet to take the same action for both GET and POST request, what should you do? Simply have doGet call doPost, or vice versa. Which code line must be set before any of the lines that use the PrintWriter? setContentType() method must be set before transmitting the actual document. How HTTP Servlet handles client requests? An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request. What is the Servlet Interface?
15.
16. 17.
18.
46
20.
21.
22.
a.
b.
c.
A single thread model for servlets is generally used to protect sensitive data ( bank account operations ). 23. What is servlet context and what it takes actually as parameters? Servlet context is an object which is created as soon as the Servlet gets initialized.Servlet context object is contained in Servlet Config. With the context object u can get access to specific resource (like file) in the server and pass it as a URL to be displayed as a next screen with the help of RequestDispatcher eg :ServletContext app = getServletContext(); RequestDispatcher disp; if(b==true) disp = app.getRequestDispatcher ("jsp/login/updatepassword.jsp"); else disp = app.getRequestDispatcher ("jsp/login/error.jsp"); this code will take user to the screen depending upon the value of b. in ServletContext u can also get or set some variables which u would
47
48
-The SendRedirect( ) will come to the Client and go back,.. ie URL appending will happen. Response. SendRedirect( absolute path); Absolutepath other than application , relative path - same application. When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward. 27. do we have a constructor in servlet ? can we explictly provide a constructor in servlet programme as in java program ? We can have a constructor in servlet . Session : A session is a group of activities that are performed by a user while accesing a particular website. Session Tracking :The process of keeping track of settings across session is called session tracking. Hidden Form Fields : Used to keep track of users by placing hidden fields in the form. -The values that have been entered in these fields are sent to the server when the user submits the Form. URL-rewriting : this is a technique by which the URL is modified to include the session ID of a particular user and is sent back to the Client. -The session Id is used by the client for subsequent transactions with the server. Cookies : Cookies are small text files that are used by a webserver to keep track the Users. A cookie is created by the server and send back to the client , the value is in the form of Key-value pairs. Aclient can accept 20 cookies per host and the size of each cookie can be maximum of 4 bytes each. HttpSession : Every user who logs on to the website is autometacally associated with an HttpSession Object. -The Servlet can use this Object to store information about the users Session. -HttpSession Object enables the user to maintain two types of Data. ie State and Application. 28. How to communicate between two servlets? Two ways: a. Forward or redirect from one Servlet to another. b. Load the Servlet from ServletContext and access methods. 29. How to get one Servlet's Context Information in another Servlet? Access or load the Servlet from the Servlet Context and access the Context Information 30. The following code snippet demonstrates the invocation of a JSP error page from within a controller servlet: protected void sendErrorRedirect(HttpServletRequest request, HttpServletResponse response, String errorPageURL, Throwable e) throws ServletException, IOException { request.setAttribute ("javax.servlet.jsp.jspException", e); getServletConfig().getServletContext(). getRequestDispatcher(errorPageURL).forward(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) { try { // do something } catch (Exception ex) { try {
49
JSP (JavaServer Pages) 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, Script and directives Text could be text/ html, text/ xml or text/ plain JSP engine Compiles page to servlet Executes servlets service() method Sends text back to caller Page is Compiled once Executed many times Anatomy of a JSP <%@ page language=java contentType=text/html %> <html> <body bgcolor=white> <jsp:useBean id=greeting class=com.pramati.jsp.beans.GreetingBean> <jsp:setProperty name=greeting property=*/> </jsp:userBean> The following information was saved: User Name: <jsp:getProperty name=greeting property=userName/> Welcome! </body> </html> JSP Elements Directive Elements : Information about the page Remains same between requests
50
Declarations (<%! %>) Used to declare class scope variables or methods <%! int j = 0; %> Gets declared at class- level scope in the generated servlet
51
Generated Servlet
public void _jspService(HttpServletRequest request , HttpServletResponse response) throws ServletException ,IOException { out.write("<HTML><HEAD><TITLE>Hello.jsp</TITLE></HEAD><BODY>" ); String checking = null; String name = null; checking = request.getParameter("catch"); if (checking != null) { name = request.getParameter("name"); out.write("\r\n\t\t<b> Hello " ); out.print(name); out.write("\r\n\t\t" ); }
52
Tags & Tag Libraries What Is a Tag Library? JSP technology has a set of pre- defined tags <jsp: useBean /> These are HTML like but have limited functionality Can define new tags Look like HTML Can be used by page authors Java code is executed when tag is encountered Allow us to keep Java code off the page Better separation of content and logic May Have Tags To Process an SQL command Parse XML and output HTML Automatically call into an EJB component (EJB technology- based component) Get called on every request to initialize script variables Iterate over a ResultSet and display the output in an HTML table
implements
BodyTag Interface
<%@ taglib uri=/WEB-INF/mylib.tld prefix=test %> <html><body bgcolor=white> <test:hello name=Robert /> </body> </html> public class HelloTag extends TagSupport { private String name = World; public void setName(String name) { this.name = name; } public int doEndTag() { pageContext.getOut().println(Hello + name); } } mylib.tld <taglib> <tag><name>hello</name> <tagclass>com.pramati.HelloTag</tagclass>
53
Summary
The JSP specification is a powerful system for creating structured web content JSP technology allows non- programmers to develop dynamic web pages JSP technology allows collaboration between programmers and page designers when building web applications JSP technology uses the Java programming language as the script language The generated servlet can be managed by directives
54
55
56
57
58
59
60
61
62
What are the steps required in adding a JSP Tag Libraries? 1. Create a TLD file and configure the required class Information. 2. Create the Java Implementation Source extending the JSP Tag Lib Class (TagSupport). 3. Compile and package it as loosed class file or as a jar under lib folder in Web Archive File for Class loading. 4. Place the TLD file under the WEB-INF folder. 5. Add reference to the tag library in the web.xml file.
Struts 1.1 1. Introduction to MVC a. Overview of MVC Architecture b. Applying MVC in Servlets and JSP c. View on JSP d. JSP Model 1 Architecture e. JSP Model 2 Architecture f. Limitation in traditional MVC approach g. MVC Model 2 Architecture h. The benefits i. Application flow 2. Overview of Struts Framework a. Introduction to Struts Framework b. Struts Architecture c. Front Controller Design Pattern d. Controller servlet - ActionServlet e. Action objects f. Action Form objects g. Action mappings h. Configuring web.xml file and struts-config.xml file 3. Struts a. b. c. d. View components Composite View Building page from templates Jsp:include Vs struts template mechanism Bean tags 63
66
63
5. Advanced Struts a. Accessing Application Resource File b. Use of Tokens c. Accessing Indexed properties d. Forward Vs Redirect e. Dynamic creating Action Forwards 6. Struts 1.1 a. DynaActionForm b. DynaValidatorActionForm Validating Input Data Declarative approach Using Struts Validator Configuring the Validator Specifying validation rules Client side validation c. Plugins d. I18N (InternationalizatioN) Specifying a resource bundle Generating Locale specific messages e. Tiles
Introduction to MVC(Model View Controler) Struts : Struts is an open source framework from Jakartha Project designed for developing the web applications with Java SERVLET API and Java Server Pages Technologies.Struts conforms the Model View Controller design pattern. Struts package provides unified reusable components (such as action servlet) to build the user interface that can be applied to any web connection. It encourages software development following the MVC design pattern. Overview of MVC Architecture The MVC design pattern divides applications into three components: The Model maintains the state and data that the application represents . The View allows the display of information about the model to the user. The Controller allows the user to manipulate the application .
Users
Service Interfaces
64
Business Workflows
Business Components
Business Entities
Service Agents
Data Sources
Services
In Struts, the view is handled by JSPs and presentation components, the model is represented by Java Beans and the controller uses Servlets to perform its action. By developing a familiar Web-based shopping cart, you'll learn how to utilize the ModelView-Controller (MVC) design pattern and truly separate presentation from content when using Java Server Pages. Applying MVC in Servlets and JSP Many web applications are JSP-only or Servlets-only. With JSP, Java code is embedded in the HTML code; with Servlets the Java code calls println methods to generate the HTML code. Both approaches have their advantages and drawbacks; Struts gathers their strengths to get the best of their association. Below you will find one example on registration form processing using MVC in Servlets and JSP:
Controller Servlet
If()
User Reg JSP
If()
Reg_mast er
Confirm.jsp
Error.jsp
1. In the above application Reg.jsp act as view accepts I/P from client and submits to Controller Servlet. 2. Controller Servlet validates the form data, if valid, stores the data into DB 3. Based on the validation and DB operations Controller Servlet decides to respond either Confirm.jsp or Error.jsp to clients browser. 4. When the Error.jsp is responded, the page must include all the list of errors with detailed description.
65
In Model 1 architecture the JSP page is alone responsible for processing the incoming request and replying back to the client. There is still separation of presentation from content, because all data access is performed using beans. Although the JSP Model 1 Architecture is more suitable for simple applications, it may not be desirable for complex implementations. JSP Model 2 Architecture - MVC
The Model 2 Architecture is an approach for serving dynamic content, since it combines the use of both Servlets and JSP. It takes advantages of the predominant strengths of both technologies, using JSP to generate the presentation layer and Servlets to perform process-intensive tasks. Here servlet acts as controller and is in charge of request processing and the creation of any beans or objects used by the JSP as well as deciding depending on the users actions, which JSP page to forward the request to. Note that there is no processing logic within the JSP page itself; it is simply responsible for retrieving any objects or beans that may have been previously created by the servlet, and extracting the dynamic content from that servlet for insertion within static templates. Limitation in traditional MVC approach
66
1
User Pass
Servlet
Controller
6
Servlet
Validator 4
Browser Login
7
Servlet JSP
View 5 Model
Beans
1. Client submits login request to servlet application 2. Servlet application acts as controller it first decides to request validator another servlet program which is responsible for not null checking (business rule) 3. control comes to controller back and based on the validation response, if the response is positive, servlet controller sends the request to model 4. Model requests DB to verify whether the database is having the same user name and password, If found login operation is successful 5. Beans are used to store if any data retrieved from the database and kept into HTTPSession 6. Controller then gives response back to response JSP (view) which uses the bean objects stored in HTTPSession object 7. and prepares presentation response on to the browser Overview of Struts Framework Introduction to Struts Framework The goal of this project is to provide an open source framework for building Java web applications. The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, JavaBeans, Resource Bundles, and XML, as well as various Jakarta Commons packages. Struts encourages application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm. Struts provides its own Controller component and integrates with other technologies to provide the Model and the View.
For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with Java Server Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems. For Controller, ActionServlet and ActionMapping - The Controller portion of the application is focused on receiving requests from the client deciding what business logic function is to be performed, and then delegating responsibility for producing the next phase of the user interface to an appropriate View component. In Struts, the primary component of the Controller is a servlet of class ActionServlet. This servlet is configured by defining a set of ActionMappings. An ActionMapping defines a path that is matched against the request URI of the incoming request, and usually specifies the fully qualified class name of an Action class. Actions encapsulate the business logic, interpret the
67
Strutsconfig.xml
Front Controller code Context The presentation-tier request handling mechanism must control and coordinate processing of each user across multiple requests. Such control mechanisms may be managed in either a centralized or decentralized manner. Problem The system requires a centralized access point for presentation-tier request handling to support the integration of system services, content retrieval, view management, and navigation. When the user accesses the view directly without going through a centralized mechanism, Two problems may occur: Each view is required to provide its own system services, often resulting in duplicate code. View navigation is left to the views. This may result in commingled view content and view navigation. Additionally, distributed control is more difficult to maintain, since changes will often need to be made in numerous places. Solution : Use a controller as the initial point of contact for handling a request. The controller manages the handling of the request, including invoking security services such as authentication and authorization, delegating business processing, managing the choice of an appropriate view, handling errors, and managing the selection of content creation strategies. The controller provides a centralized entry point that controls and manages Web request handling. By centralizing decision points and controls, the controller also helps reduce the amount of Java code, called scriptlets, embedded in the JavaServer Pages (JSP) page.
68
Figure: Front Controller class diagram Participants and Responsibilities Below figure shows the sequence diagram representing the Front Controller pattern. It depicts how the controller handles a request.
69
Figure: Front Controller sequence diagram Controller : The controller is the initial contact point for handling all requests in the system. The controller may delegate to a helper to complete authentication and authorization of a user or to initiate contact retrieval. Dispatcher : A dispatcher is responsible for view management and navigation, managing the choice of the next view to present to the user, and providing the mechanism for vectoring control to this resource. A dispatcher can be encapsulated within a controller or can be a separate component working in coordination. The dispatcher provides either a static dispatching to the view or a more sophisticated dynamic dispatching mechanism. The dispatcher uses the Request Dispatcher object (supported in the servlet specification) and encapsulates some additional processing. Helper : A helper is responsible for helping a view or controller complete its processing. Thus, helpers have numerous responsibilities, including gathering data required by the view and storing this intermediate model, in which case the helper is sometimes referred to as a value bean. Additionally, helpers may adapt this data model for use by the view. Helpers can service requests for data from the view by simply providing access to the raw data or by formatting the data as Web content. A view may work with any number of helpers, which are typically implemented as JavaBeans components (JSP 1.0+) and custom tags (JSP 1.1+). Additionally, a helper may represent a Command object, a delegate, or an XSL Transformer, which is used in combination with a stylesheet to adapt and convert the model into the appropriate form. View : A view represents and displays information to the client. The view retrieves information from a model. Helpers support views by encapsulating and adapting the underlying data model for use in the display. Controller Servlet Action Servlet For those of you familiar with MVC architecture, the ActionServlet represents the C - the controller. The job of the controller is to: process user requests, determine what the user is trying to achieve according to the request, pull data from the model (if necessary) to be given to the appropriate view, and select the proper view to respond to the user. The Struts controller delegates most of this grunt work to the Request Processor and Action classes.
70
processPreprocess
processActionPerfor This is the point at which your action's perform or execute method will m be called. Finally, the process method of the RequestProcessor takes the processForwardConfi ActionForward returned by your Action class, and uses to select the g next resource (if any). Most often the ActionForward leads to the presentation page that renders the response.
71
Action class The Action class defines two methods that could be executed depending on your servlet environment: public ActionForward execute(ActionMapping mapping, ActionForm form, ServletRequest request, ServletResponse response) throws Exception; public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception; Since the majority of Struts projects are focused on building web applications, most projects will only use the "HttpServletRequest" version. A non-HTTP execute() method has been provided for applications that are not specifically geared towards the HTTP protocol. The goal of an Action class is to process a request, via its execute method, and return an ActionForward object that identifies where control should be forwarded (e.g. a JSP, Tile definition, Velocity template, or another Action) to provide the appropriate response. In the MVC/Model 2 design pattern, a typical Action class will often implement logic like the following in its execute method: Validate the current state of the user's session (for example, checking that the user has successfully logged on). If the Action class finds that no logon exists, the request can be forwarded to the presentation page that displays the username and password prompts for logging on. This could occur because a user tried to enter an application "in the middle" (say, from a bookmark), or because the session has timed out, and the servlet container created a new one. If validation is not complete, validate the form bean properties as needed. If a problem is found, store the appropriate error message keys as a request attribute, and forward control back to the input form so that the errors can be corrected. Perform the processing required to deal with this request (such as saving a row into a database). This can be done by logic code embedded within the Action class itself, but should generally be performed by calling an appropriate method of a business logic bean. Update the server-side objects that will be used to create the next page of the user interface (typically request scope or session scope beans, depending on how long you need to keep these items available). Return an appropriate ActionForward object that identifies the presentation page to be used to generate this response, based on the newly updated beans. Typically, you will acquire a reference to such an object by calling findForward on either the ActionMapping object you received (if you are using a logical name local to this mapping), or on the controller servlet itself (if you are using a logical name global to the application). In Struts 1.0, Actions called a perform method instead of the now-preferred execute method. These methods use the same parameters and differ only in which exceptions they throw. The elder perform method throws SerlvetException and IOException. The new execute method simply throws Exception. The change was to facilitate the Declarative Exception handling feature introduced in Struts 1.1. The perform method may still be used in Struts 1.1 but is deprecated. The Struts 1.1 method simply calls the new execute method and wraps any Exception thrown as a ServletException. Action Form class
72
73
o Conserve Resources - As a general rule, allocating scarce resources and keeping them
across requests from the same user (in the user's session) can cause scalability problems. For example, if your application uses JDBC and you allocate a separate JDBC connection for every user, you are probably going to run in some scalability issues when your site suddenly shows up on Slashdot. You should strive to use pools and release resources (such as database connections) prior to forwarding control to the appropriate View component -even if a bean method you have called throws an exception. Don't throw it, catch it! - Ever used a commercial website only to have a stack trace or exception thrown in your face after you've already typed in your credit card number and clicked the purchase button? Let's just say it doesn't inspire confidence. Now is your chance to deal with these application errors - in the Action class. If your application specific code throws expections you should catch these exceptions in your Action class, log them in your application's log (servlet.log("Error message", exception)) and return the appropriate ActionForward.
It is wise to avoid creating lengthy and complex Action classes. If you start to embed too much logic in the Action class itself, you will begin to find the Action class hard to understand, maintain, and impossible to reuse. Rather than creating overly complex Action classes, it is generally a good practice to move most of the persistence, and "business logic" to a separate application layer. When an Action class becomes lengthy and procedural, it may be a good time to refactor your application architecture and move some of this logic to another conceptual layer; otherwise, you may be left with an inflexible application which can only be accessed in a web-application environment. Struts should be viewed as simply the foundation for implementing MVC in your applications. Struts provides you with a useful control layer, but it is not a fully featured platform for building MVC applications, soup to nuts. The MailReader example application included with Struts stretches this design principle somewhat, because the business logic itself is embedded in the Action classes. This should be considered something of a bug in the design of the example, rather than an intrinsic feature of the Struts architecture, or an approach to be emulated. In order to demonstrate, in simple terms, the different ways Struts can be used, the MailReader application does not always follow best practices. Action mapping implementation In order to operate successfully, the Struts controller servlet needs to know several things about how each request URI should be mapped to an appropriate Action class. The required knowledge has been encapsulated in a Java class named ActionMapping, the most important properties are as follows:
o o o o o o
type - Fully qualified Java class name of the Action implementation class used by this mapping. name - The name of the form bean defined in the config file that this action will use. path - The request URI path that is matched to select this mapping. See below for examples of how matching works and how to use wildcards to match multiple request URIs. unknown - Set to true if this action should be configured as the default for this application, to handle all requests not handled by another action. Only one action can be defined as a default within a single application. validate - Set to true if the validate method of the action associated with this mapping should be called. forward - The request URI path to which control is passed when this mapping is invoked. This is an alternative to declaring a type property.
74
75
76
77
78
79
80
PlugIn Configuration Struts PlugIns are configured using the <plug-in> element within the Struts configuration file. This element has only one valid attribute, 'className', which is the fully qualified name of the Java class which implements the org.apache.struts.action.PlugIn interface. For PlugIns that require configuration themselves, the nested <set-property> element is available. This is an example using the Tiles plugin: <plug-in className="org.apache.struts.tiles.TilesPlugin" > <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml"/> </plug-in> Data Source Configuration Besides the objects related to defining ActionMappings, the Struts configuration may contain elements that create other useful objects. The <data-sources> section can be used to specify a collection of DataSources [javax.sql.DataSource] for the use of your application. Typically, a DataSource represents a connection pool to a database or other persistent store. As a convenience, the Struts DataSource manager can be used to instantiate whatever standard pool your application may need. Of course, if your persistence layer provides for its own connections, then you do not need to specify a data-sources element. Since DataSource implementations vary in what properties need to be set, unlike other Struts configuration elements, the data-source element does not pre-define a slate of properties. Instead, the generic set-property feature is used to set whatever properties your implementation may require. Typically, these settings would include: A driver class name A url to access the driver A description And other sundry properties. <data-source type="org.apache.commons.dbcp.BasicDataSource"> <!-- ... set-property elements ... --> </data-source> In Struts 1.2.0, the GenericDataSource has been removed, and it is recommended that you use the Commons BasicDataSource or other DataSource implementation instead. In practice, if you need to use the DataSource manager, you should use whatever DataSource implementation works best with your container or database. For examples of specifying a data-sources element and using the DataSource with an Action, see the Accessing a Database HowTo.
81
82
83
84
85
Struts The core of the Struts framework is a flexible control layer based on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various Jakarta Commons packages. Struts encourages application architectures based on the Model 2 approach, a variation of the classic Model-View-Controller (MVC) design paradigm. Struts provides its own Controller component and integrates with other technologies to provide the Model and the View. For the Model, Struts can interact with standard data access technologies, like JDBC and EJB, as well as most any third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as Velocity Templates, XSLT, and other presentation systems. The Struts framework provides the invisible underpinnings every professional web application needs to survive. Struts helps you create an extensible development environment for your application, based on published standards and proven design patterns. What is the difference between Struts 1.0 and Struts 1.1 The new features added to Struts 1.1 are 1. RequestProcessor class 2. Method perform() replaced by execute() in Struts base Action Class 3. Changes to web.xml and struts-config.xml 4.Declarative exception handling 5.Dynamic ActionForms 6.Plug-ins 7.Multiple Application Modules 8.Nested Tags 9.The Struts Validator 10.Change to the ORO package 11.Change to Commons logging 12.Removal of Admin actions 13. Deprecation of the GenericDataSource Explain Struts navigation flow A client requests a path that matches the Action URI pattern. The container passes the request to the ActionServlet. If this is a modular application, the ActionServlet selects the appropriate module. The ActionServlet looks up the mapping for the path. If the mapping specifies a form bean, the ActionServlet sees if there is one already or creates one. If a
86
87
88
89
What is Action Class? The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (command) passes the parameterized class to Action Form using the execute() method. 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. Write code of any Action Class? Here is the code of Action Class that returns the ActionForward object. 1. import javax.servlet.http.HttpServletRequest; 2. import javax.servlet.http.HttpServletResponse; 3. import org.apache.struts.action.Action; 4. import org.apache.struts.action.ActionForm; 5. import org.apache.struts.action.ActionForward; 6. import org.apache.struts.action.ActionMapping; 7. 8. public class TestAction extends Action 9. { 10. public ActionForward execute( 11. ActionMapping mapping, 12. ActionForm form, 13. HttpServletRequest request, 14. HttpServletResponse response) throws Exception 15. { 16. return mapping.findForward(\"testAction\"); 17. } 18. } What is ActionForm? An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is
90
91
92
Component architecture Specification to write components using Java Specification to component server developers Contract between developer roles in a components-based application project The basis of components used in distributed transaction-oriented enterprise applications. The Componentized Application : Application now consists of several re-usable components. Instances of components created at run-time for a client. Common object for all instances of the component, usually called the Factory Object EJB calls it Home Object Common place where client can locate this Home Object Objects located from a remote client through JNDI (Java Naming and Directory Interface) service. Application Server provides JNDI based naming service Implementation of Bean, Home and Remote Complete Life Cycle Management Resource pooling - beans, db connections, threads... Object persistence Transaction management Secured access to beans Scalability and availability EJB: Core of J2EE Architecture
Business logic
JSP Servlets
Bea ns
HTML client
http
J2EE Server
rmi
Java Client
93
EJB Architecture Roles : Appointed for Responsibilities Six roles in application development and deployment life cycle Bean Provider Application Assembler Server Provider Container Provider Deployer System Administrator Each role performed by a different party. Product of one role compatible with another. Creating the Bean Instance Look up for the Home Object through JNDI Get the reference Call create() method The server generates the code for remote access using RMI (Remote Method Invocation). The RMI code in the form of stub and skeleton: : establishes connection, marshals/unmarshals places remote method calls Bean Instance
94
Component Server
Client
Bean
95
Client-view contract
Bean Instance
Component Contract
Client
Client View Contract
Bean class files, interfaces Bean class files, interfaces Deployment descriptor Deployment descriptor Client-view contract :
EJB-jar
Contract between client and container Uniform application development model for greater re-use of components View sharing by local and remote programs The Client can be: another EJB deployed in same or another container a Java program, an applet or a Servlet mapped to non-Java clients like CORBA clients Component contract : Between an EJB and the container it is hosted by This contract needs responsibilities to be shared by: the bean provider the container provider Container providers responsibilities Bean providers responsibilities
Bean providers responsibility : Implement business methods in the bean Implement ejbCreate, ejbPostCreate and ejbRemove methods, and ejbFind method (in the case of bean managed persistence) Define home and remote interfaces of the bean Implement container callbacks defined in the javax.ejb.Session bean interface optionally the javax.ejb.SessionSynchronization interface Implement container callbacks defined in javax.ejb.EntityBean interfaces for entities
96
Bean Varieties Three Types of Beans: Session Beans - Short lived and last during a session. Entity Beans - Long lived and persist throughout. Message Driven Beans Asynchronous Message Consumers Asynchronous. Session Beans A session object is a non-persistent object that implements some business logic running on the server. Executes on behalf of a single client. Can be transaction aware. Does not represent directly shared data in the database, although it may access and update such data. Is relatively short-lived. Is removed when the EJB container crashes. The client has to re-establish a new session object to continue computation Types of Session Beans
97
(CartHome)
JNDI : used to locate Remote Objects created by bean. portableRemoteObject Class : It uses an Object return by Lookup( ). narrow( ) -> Call the create( ) of HomeInterface. IntialContext Class : Lookup( ) -> Searches and locate the distributed Objects. Session Beans Local Home Interface : object that implements is called a session EJBLocalHome object. Create a new session object. Remove a session object. Session Beans Remote Home Interface object that implements is called a session EJBHome object. Create a session object Remove a session object Session Beans Local Interface Instances of a session beans remote interface are called session EJBObjects business logic methods of the object. Session Beans Local Home Interface instances of a session beans local interface are called session EJBLocalObjects business logic methods of the object Creating an EJB Object Home Interface defines one or more create() methods Arguments of the create methods are typically used to initialize the state of the created session object public interface CartHome extends javax.ejb.EJBHome
98
} cartHome.create(John, 7506); EJBObject or EJBLocalObject Client never directly accesses instances of a Session Beans class Client uses Session Beans Remote Interface or Remote Home Interface to access its instance The class that implements the Session Beans Remote Interface or Remote Home Interface is provided by the container. Session Object Identity Session Objects are meant to be private resources of the client that created them Session Objects, from the clients perspective, appear anonymous Session Beans Home Interface must not define finder methods Session Object Identity Stateful Session Beans : A stateful session object has a unique identity that is assigned by the container at the time of creation. A client can determine if two object references refer to the same session object by invoking the isIdentical(EJBObject otherEJBObject) method on one of the references. Stateless Session Beans : All session objects of the same stateless session bean, within the same home have the same object identity assigned by the container. isIdentical(EJBObject otherEJBObject) method always returns true.
Container Responsibilities : Manages the lifecycle of session bean instances. Notifies instances when bean action may be necessary . Provides necessary services to ensure session bean implementation is scalable and can support several clients. Activation and Passivation :
99
Entity Beans Long Live Entity Beans! A component that represents an object-oriented view of some entities stored in a persistent storage like a database or an enterprise application. From its creation until its destruction, an entity object lives in a container. Transparent to the client, the Container provides security, concurrency, transactions, persistence, and other services to support the Entity Beans functioning Cainer Managed Persistence versus Bean Managed Persistence Multiple clients can access an entity object concurrently Container hosting the Entity Bean synchronizes access to the entity objects state using transactions Each entity object has an identity which usually survives a transaction crash Object identity is implemented by the container with help from the enterprise bean class Multiple enterprise beans can be deployed in a Container Remote Clients : Accesses an entity bean through the entity beans remote and remote home interfaces Implements EJBObject and EJBHome Interfaces Location Independent Potentially Expensive, Network Latency Useful for coarse grained component access Local Clients : Local client is a client that is collocated with the entity bean and which may be tightly coupled to the bean. Implements EJBLocalObject and EJBLocalHome Interfaces Same JVM Enterprise bean can-not be deployed on a node different from that of its client Restricts distribution of components. Better supports fine-grained component access Locating the Entity Bean : Location of EJB Container is usually transparent to Client
100
the
101
102
103
104
EJB What is the difference between normal Java object and EJB Java Object:it's a reusable componet EJB:is reusable and deployable component which can be deployed in any container EJB : is a distributed component used to develop business applications. Container provides runtime environment for EJBs. EJB is an Java object implemented according EJB specification. Deployability is a feature. What is the difference between JavaBean and EJB Java Beans : is intra-process component, JavaBeans is particularly well-suited for asynchronous, intra-application communications among software EJB : is an Inter-Process component What is EJB ? Enterprise Java Bean is a specification for server-side scalable,transactional and multiuser secure enterprise-level applications. It provides a consistant component architecture for creating distributed n-tier middleware. Enterprise JavaBeans (EJB) is a technology that based on J2EE platform. EJBs are server-side components. EJB are used to develop the distributed, transactional and secure applications based on Java technology. What is Session Bean. What are the various types of Session Bean SessionBeans: They are usually associated with one client. Each session bean is created and destroyed by the particular EJB client that is associated with it. These beans do not survive after system shutdown. These Session Beans are of two types:
105
106
107
108
109
What are the various isolation levels in a transaction and differences between them There are three isolation levels in Transaction. They are 1. Dirty reads 2.Non repeatable reads 3. Phantom reads. Dirty Reads: If transaction A updates a record in database followed by the transaction B reading the record then the transaction A performs a rollback on its update operation, the result that transaction B had read is invalid as it has been rolled back by transaction A. NonRepeatable Reads :If transaction A reads a record, followed by transaction B updating the same record, then transaction A reads the same record a second time, transaction A has read two different values for the same record. Phantom Reads :If transaction A performs a query on the database with a particular search criteria (WHERE clause), followed by transaction B creating new records that satisfy the search criteria, followed by transaction A repeating its query, transaction A sees new, phantom records in the results of the second query. What are the various transaction attributes and differences between them There are six transaction attributes that are supported in EJB. 1. Required - T1---T1 0---T1 2. RequiresNew T1---T2 0---T1 3. Mandatory - T1---T1 0---Error 4. Supports - T1---T1 0---0 5. NotSupported - T1---0
110
6. Never -
What is the difference between activation and passivation Activation and Passivation is appilicable for only Stateful session bean and Entity bean. When Bean instance is not used for a while by client then EJB Container removes it from memory and puts it in secondary storage (often disk) so that the memory can be reused. This is called Passivation. When Client calls the bean instance again then Container takes the passivated bean from secondary storage and puts it in memory to serve the client request. This is called Activation. What is Instance pooling pooling of instances. in stateless session beans and Entity Beans server maintains a pool of instances.whenever server got a request from client, it takes one instance from the pool and serves the client request. What is the difference between HTTPSession and Stateful Session Bean From a logical point of view, a Servlet/JSP session is similar to an EJB session. Using a session, in fact, a client can connect to a server and maintain his state. But, is important to understand, that the session is maintained in different ways and, in theory, for different scopes. A session in a Servlet, is maintained by the Servlet Container through the HttpSession object, that is acquired through the request object. You cannot really instantiate a new HttpSession object, and it does not contains any business logic, but is more of a place where to store objects. A session in EJB is maintained using the SessionBeans. You design beans that can contain business logic, and that can be used by the clients. You have two different session beans: Stateful and Stateless. The first one is somehow connected with a single client. It maintains the state for that client, can be used only by that client and when the client "dies" then the session bean is "lost". A Stateless Session Bean does not maintain any state and there is no guarantee that the same client will use the same stateless bean, even for two calls one after the other. The lifecycle of a Stateless Session EJB is slightly different from the one of a Stateful Session EJB. Is EJB Containers responsability to take care of knowing exactly how to track each session and redirect the request from a client to the correct instance of a Session Bean. The way this is done is vendor dependant, and is part of the contract. What is the difference between find and select methods in EJB select method is not there in EJBs A select method is similar to a finder method for Entity Beans, they both use EJB-QL to define the semantics of the method. They differ in that an ejbSelect method(s) are not exposed to the client and the ejbSelect method(s) can return values that are defined as cmp-types or cmr-types. What are the optional clauses in EJB QL Three optional clauses are available in EJB Ql. 1. SELECT 2. FROM 3. WHERE The EJB QL must always contain SELECT and FROM clauses. The WHERE clause is optional. The FROM clause provides declarations for the identification variables based on abstract schema name, for navigating through the schema. The SELECT clause uses these
111
112
<ejb-jar> <enterprise-bean> </Session> <ejb-name>Statefulfinacialcalcu</ejb-name> <home>fincal.stateful.fincalc</home> <remote> fincal.stateful.fincalc </remote> <ejb-Class> fincal.stateful.fincalcEJB <ejb-Class> <session-type> Stateful </session-type> <transaction-type> Container </transaction-type> </Session> </enterprise-bean> <assembly-descriptor> <container-transaction> <method> <ejb-name> Statefulfinacialcalcu </ejb-name> <method-name> * </method-name> </method> <transaction-attribute> supports </transaction-attribute> </container-transaction>
113
114
115
running
in
transaction
by
calling
Is there a way to get the original exception object from inside a nested or wrapped Exception (for example an EJBException or RemoteException) Absolutely yes, but the way to do that depends on the Exception, since there are no standards for that. Some examples: When you have an javax.ejb.EJBException, you can use the getCausedByException() that returns a java.lang.Exception. A java.rmi.RemoteException there is a public field called detail of type java.lang.Throwable With a java.sql.SQLException you need to use the method getNextException() to get the chained java.sql.SQLException. When you have an java.lang.reflect.InvocationtargetException, you can get the thrown target java.lang.Throwable using the getTargetException() method. Can undefined primary keys are possible with Entity beans?If so, what type is defined? Yes,undefined primary keys are possible with Entity Beans.The type is defined as java.lang.Object. When two entity beans are said to be identical?Which method is used to compare identical or not?
116
Questions
1)A developer successfully creating and tests a stateful bean following deployment, intermittent "NullpointerException" begin to occur, particularly when the server is hardly loaded. What most likely to related problem. a) setSessionContext b) ejbCreate c) ejbPassivate d) beforeCompletion e) ejbLoad 2)2 example implementations os Proxy are RMI & EJb 3)If an RMI parameter implements java.rmi.Remote, how is it passed "on-the-wire?" Choice 1 : It can never be passed. Choice 2 : It is passed by value. Choice 3 : It cannot be passed because it implements java.rmi.Remote. Choice 4 : It cannot be passed unless it ALSO implements java.io.Serializable. Choice 5 : It is passed by reference. ans)2 4)public synchronized void txTest(int i) { System.out.println("Integer is: " + i); } What is the outcome of attempting to compile and execute the method above, assuming it is implemented in a stateful session bean? Choice 1 : Run-time error when bean is created Choice 2 : The method will run, violating the EJB specification. 117
Choice 3 : Compile-time error for bean implementation class Choice 4 : Compile-time error for remote interface Choice 5 : Run-time error when the method is executed 5)What is the CORBA naming service equivalent of JNDI? Choice 1 : Interface Definition Language Choice 2 : COS Naming Choice 3 : Lightweight Directory Access Protocol Choice 4 : Interoperable Inter-Orb Protocol Choice 5 : Computer Naming Service ans)2
ans)2
6)InitialContext ic = new InitialContext(); TestHome th = (TestHome) ic.lookup("testBean/TestBean"); TestRemote beanA = th.create(); TestRemote beanB = th.create(); TestRemote beanC = th.create(); beanC.remove(); TestRemote beanD = th.create(); TestRemote beanE = th.create(); beanC = th.create(); Given the above code, container passivates which bean instance first if the container limited the bean pool size to four beans and used a "least-recently-used" algorithm to passivate? Choice 1 : Bean A Choice 2 : Bean B Choice 3 : Bean C Choice 4 : Bean D Choice 5 : Bean E 7)Which one of the following phenomena is NOT addressed by read-consistency? A.Phantom read b.Cached read c.Dirty read d.Non-repeatable read e.Fuzzy read ans)b,e 8)Which one of the following methods is generally called in both ejbLoad() and ejbStore()? a getEJBObject() b getHandle() c remove() d getEJBHome() e getPrimaryKey() ans)e 9)public void ejbCreate(int i) { System.out.println("ejbCreate(i)"); } Given a currently working stateless session bean, what will be the outcome upon deploying and executing the bean if you added the above unique method to the implementation class of a stateless session bean (and made no other changes)? a Compile time error during stub/skeleton generation b Compile time error for home interface c Code will compile without errors. d Compile time error for remote interface e Compile time error for bean implementation ans)a 10)Given the above code in your stateless session bean business method implementation, and the transaction is container-managed with a Transaction Attribute of TX_SUPPORTS, which one of the following is the first error generated? a Error when compiling home interface b Error while generating stubs and skeletons c NullPointerException during deployment 118
ans)b
11)Which one of the following is the result of attempting to deploy a stateless session bean and execute one of the method M when the bean implementation contains the method M NOT defined in the remote interface? a Compile time error for remote interface b Compile time error for bean implementation c Compile time error during stub/skeleton generation d Code will compile without errors. e Compile time error for home interface ans)d 12)Which one of the following characteristics is NOT true of RMI and Enterprise Java Beans? a They must execute within the confines of a Java virtual machine (JVM). b They serialize objects for distribution. c They require .class files to generate stubs and skeletons. d They do not require IDL. e They specify the use of the IIOP wire protocol for distribution. ans)a 13. Which one of the following is the result of attempting to deploy a stateless session bean and execute one of the method M when the bean implementation contains the method M NOT defined in the remote interface? a Compile time error for remote interface b Compile time error for bean implementation c Compile time error during stub/skeleton generation d Code will compile without errors. e Compile time error for home interface 14. If a unique constraint for primary keys is not enabled in a database, multiple rows of data with the same primary key could exist in a table. Entity beans that represent the data from the table described above are likely to throw which exception? a NoSuchEntityException b FinderException c ObjectNotFoundException d RemoveException e NullPointerException 15. A developer needs to deploy an Enterprise Java Bean, specifically an entity bean, but is unsure if the bean container is able to create and provide a transaction context. Which attribute below will allow successful deployment of the bean? a BeanManaged b RequiresNew c Mandatory d Required e Supports 16. What is the outcome of attempting to compile and execute the method above, assuming it is implemented in a stateful session bean? a Compile-time error for remote interface b Run-time error when bean is created c Compile-time error for bean implementation class d The method will run, violating the EJB specification. e Run-time error when the method is executed 119
17. Which one of the following is the result of attempting to deploy a stateless session bean and execute one of the method M when the bean implementation contains the method M NOT defined in the remote interface? a Compile time error for remote interface b Compile time error for bean implementation c Compile time error during stub/skeleton generation d Code will compile without errors. e Compile time error for home interface 18. If a unique constraint for primary keys is not enabled in a database, multiple rows of data with the same primary key could exist in a table. Entity beans that represent the data from the table described above are likely to throw which exception? a NoSuchEntityException b FinderException c ObjectNotFoundException d RemoveException e NullPointerException 19. There are two Enterprise Java Beans, A and B. A method in "A" named "Am" begins execution, reads a value v from the database and sets a variable "X" to value v, which is one hundred. "Am" adds fifty to the variable X and updates the database with the new value of X. "Am" calls "Bm", which is a method in B. "Bm" begins executing. "Bm" reads an additional value from the database. Based on the value, "Bm" determines that a business rule has been violated and aborts the transaction. Control is returned to "Am".Requirement: If "Bm" aborts the transaction, it is imperative that the original value be read from the database and stored in variable X. Given the scenario stated? a A-RequiresNew, b A-Mandatory, c A-RequiresNew, d A-NotSupported, e A-RequiresNew, above, which Transaction Attributes will most likely meet the requirements B-Mandatory B-RequiresNew B-Supports B-RequiresNew B-RequiresNew
20.) If an RMI parameter implements java.rmi.Remote, how is it passed "on-the-wire?" Choice 1 : It can never be passed. Choice 2 : It is passed by value. Choice 3 : It cannot be passed because it implements java.rmi.Remote. Choice 4 : (Correct) It cannot be passed unless it ALSO implements java.io.Serializable. Choice 5 : It is passed by reference. 21.) public synchronized void txTest(int i) { System.out.println("Integer is: " + i); } What is the outcome of attempting to compile and execute the method above, assuming it is implemented in a stateful session bean? Choice 1 : Run-time error when bean is created Choice 2 : The method will run, violating the EJB specification. Choice 3 : (Correct) Compile-time error for bean implementation class Choice 4 : Compile-time error for remote interface Choice 5 : Run-time error when the method is executed 22.) What is the CORBA naming service equivalent of JNDI? 120
: : : : :
Interface Definition Language (Correct) COS Naming Lightweight Directory Access Protocol Interoperable Inter-Orb Protocol Computer Naming Service
InitialContext ic = new InitialContext(); TestHome th = (TestHome) ic.lookup("testBean/TestBean"); TestRemote beanA = th.create(); TestRemote beanB = th.create(); TestRemote beanC = th.create(); beanC.remove(); TestRemote beanD = th.create(); TestRemote beanE = th.create(); beanC = th.create(); Given the above code, container passivates which bean instance first if the container limited the bean pool size to four beans and used a "least-recently-used" algorithm to passivate? Choice 1 Bean A Choice 2 Bean B Choice 3 Bean C Choice 4 (Correct, Since only Statefull session bean and Entity Bean can be passivated, and Entitybean can not call as th.create() normally, I take it as statefull session bean) Bean D Choice 5 Bean E ------------------------Which one of the following phenomena is NOT addressedby read-consistency? a Phantom read (Correct) b Cached read c Dirty read d Non-repeatable read e Fuzzy read -------------------------Which one of the following methods is generally called in both ejbLoad() and ejbStore()? a getEJBObject() b getHandle() c remove() d getEJBHome() e getPrimaryKey() (Correct) 121
I am Chandra, Programmer Analyst and I have been working with CTS since 3yrs. I am basically java/j2ee resource. I am coming from Tech vertical early I was in Health verticals
122