Complete Java&J2 EE
Complete Java&J2 EE
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 Obj’s
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 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).
Bite code: Is a optimized set of instructions designed to be executed by Java-run time system,
which is called the Java Virtual machine (JVM), i.e. in its standard form, the JVM is an
Interpreter for byte code.
You have Downloaded this file from kamma-Sangam Yahoo Group 1
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.
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 tow interfaces both have identical method name and argument list, but
different return types, the code will not compile.
An Interface can‘t 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 can‘t 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 can‘t specify an exception list for a method, the class can‘t throw an exception.
If an Interface does not specify the exception list for a method, he class can not throw any
exception list.
You have Downloaded this file from kamma-Sangam Yahoo Group 2
The general form of Interface is
Access interface name {
return-type method-name1(parameter-list);
type final-varname1=value;
}
-----------------------
Marker Interfaces : Serializable, Clonable, Remote, EventListener,
Java.lang is the Package of all classes and is automatically imported into all Java Program
Interfaces: Clonable , Comparable, Runnable
Abstract Class: Abstract classes can be used to implement the inheritance relationship
between the classes that belongs same hierarchy.
Classes and methods can be declared as abstract.
Abstract class can extend only one Class.
If a Class is declared as abstract , no instance of that class can be created.
If a method is declared as abstract, the sub class gives the implementation of that class.
Even if a single method is declared as abstract in a Class , the class itself can be declared as
abstract.
Abstract class have at least one abstract method and others may be concrete.
In abstract Class the keyword abstract must be used for method.
Abstract classes have sub classes.
Combination of modifiers Final and Abstract is illegal in java.
Abstract Class means - Which has more than one abstract method which doesn‘t have method
body but at least one of its methods need to be implemented in derived Class.
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.
Identifiers : are the Variables that are declared under particular Datatype.
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 can‘t be declared as static.
A static method can access only static Variables. and they can‘t refer to this or super in any
way.
Static methods can‘t 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.
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
connec‘s.
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.
You have Downloaded this file from kamma-Sangam Yahoo Group 5
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.
isUpperCase(char) : A class method that determines whether a primitive char value is
uppercase.
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 are similar to primitive data types but starting with capital letter.
Number Byte Boolean
Double Short Character
Float 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.
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.
Garbage Collection : When an object is no longer referred to by any variable, java automatically
reclaims memory used by that object. This is known as garbage collection.
System.gc() method may be used to call it explicitly and does not force the garbage collection
but only suggests that the JVM may make an effort to do the Garbage Collection.
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.
Exception
Exception handling
Exception can be generated by Java-runtime system or they can be manually generated by code.
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.
2. Un-checked Exceptions: Run-time Exceptions and Error, does‘t 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.
Errors: Virtual mechine error – class not found , out of memory, no such method , illegal access to
private field , etc.
Catch: This is a default exception handler. since the exception class is the base class for all the
exception class, this handler id capable of catching any type of exception.
The catch statement takes an Object of exception class as a parameter, if an exception is thrown the
statement in the catch block is executed. The catch block is restricted to the statements in the
proceeding try block only.
Try {
// statements that may cause exception
}
catch(Exception obj)
{
}
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.
You have Downloaded this file from kamma-Sangam Yahoo Group 9
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 species 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>]
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 .
Thread-based: is Light weight- A Program can perform two or more tasks simultaneously.
Creating a thread:
Eg: A text editor can formate at the same time you can print, as long as these two tasks are being
perform separate treads.
Creating a Thread :
1. By implementing the Runnable Interface.
2. By extending the thread Class.
Thread Class : Java.lang.Threadclass is used to construct and access the individual threads in a
multithreaded application.
Syntax: Public Class <class name> extends Thread { }
The Thread class define several methods .
o Getname() – obtain a thread name.
o Getname() – obtain thread priority.
o Start( ) - start a thread by calling a Run( ).
o Run( ) - Entry point for the thread.
o Sleep( ) - suspend a thread for a period of time.
o IsAlive( ) - Determine if a thread is still running.
o Join( ) - wait for a thread to terminate.
Runable Interface : The Runnable interface consist of a Single method Run( ), which is
executed when the thread is activated.
When a program need ti inherit from another class besides the thread Class, you need to
implement the Runnable interface.
You have Downloaded this file from kamma-Sangam Yahoo Group 11
Syntax: public void <Class-name> extends <SuperClass-name> implements Runnable
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.
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.
IsAlive( ) : of the thread class is used to determine wheather 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 ne
allowed to run.To set a thread priority, use te setpriority( ), which is a member of a thread.
final void setpriority(int level) - here level specifies the new priority seting for the calling
thread.
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 strems in
compressed format. It has two methods
WriteExternal(Objectoutput out)
ReadExternal(objectInput in)
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[ ])
You have Downloaded this file from kamma-Sangam Yahoo Group 13
{
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
Set Interface: extends 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.
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 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( ) .
Sorted Map : extends Map Interface. 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 Array List Hash Set Tree Set Hash Map Tree Map
Sequential
List
Linked List
List Map
| |
Abstract List Dictonary
| |
Vector HashTable
| |
Stack Properities
HashSet : Implements Set Interface. HashSet hs=new HashSet( );
The elements are not stored in sorted order. hs.add(―m‖);
Iterarator Enumerator
Iterator itr = a1.iterator( ); Enumerator vEnum = v.element( );
While(itr.hashNext( )) System.out.println(―Elements in Vector :‖);
{ while(vEnum.hasMoreElements( ) )
Object element = itr.next( ); System.out.println(vEnum.nextElement( ) + ― ―);
System.out.println(element + ― ―);
}
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 :
•Does your class need a way to easily search through thousands of items quickly?
• Does it need an ordered sequence of elements and the ability to rapidly insert and remove
elements in the middle of the sequence?• Does it need an array like structure with random-access
ability that can grow at runtime?
List Map
| |
Abstract List Dictonary
| |
Vector HashTable
| |
Stack Properities
VECTOR :
Vector implements dynamic array. Vector v = new vector( );
Vector is a growable object. V1.addElement(new Integer(1));
Vector is Synchronized, it can‘t allow special characters and null values.
Vector is a variable-length array of object references.
Vectors are created with an initial size.
When this size is exceeded, the vector is automatically enlarged.
When objects are removed, the vector may be shrunk.
Methods :
Object push(Object item) : Pushes an item onto the top of this stack.
Object pop() : Removes the object at the top of this stack and returns that object as the value of
this function. An EmptyStackException is thrown if it is called on empty stack.
boolean empty() : Tests if this stack is empty.
Object peek() : Looks at the object at the top of this stack without removing it from the stack.
int search(Object o) : Determine if an object exists on the stack and returns the number of pops
that would be required to bring it to the top of the stack.
HashTable :
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));
Hashtable is a concrete implementation of a Dictionary.
Dictionary is an abstract class that represents a key/value storage repository.
A Hashtable instance can be used store arbitrary objects which are indexed by any other
arbitrary object.
A Hashtable stores information using a mechanism called hashing.
You have Downloaded this file from kamma-Sangam Yahoo Group 17
When using a Hashtable, you specify an object that is used as a key and the value (data) that
you want linked to that key.
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
Strng 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.
Collection :
A collection allows a group of objects to be treated as a single unit.
The Java collections library forms a framework for collection classes.
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.
Two fundamental interfaces for containers:
You have Downloaded this file from kamma-Sangam Yahoo Group 18
• Collection
boolean add(Object element) : Inserts element into a collection
Set Interface: extends 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.
identical to Collection interface, but doesn‘t accept duplicates.
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.
expose the comparison object for sorting.
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.
Abstract Collection
Abstract Array List Hash Set Tree Set Hash Map Tree Map
Sequential
List
Linked List
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 don‘t 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
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.
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.
What is a memory footprint? How can you specify the lower and upper limits of the RAM
used by the JVM? What happens when the JVM needs more memory?
when JVM needs more memory then it does the garbage collection, and sweeps all the
memory which is not being used.
can we declare multiple main() methods in multiple classes. ie can we have each main
method in its class in our program?
YES
About ODBC
What is ODBC
ODBC (Open Database Connectivity) is an ISV (Independent software vendor product)
composes of native API to connect to different databases through via a single API called ODBC.
Open Database Connectivity (ODBC) is an SQL oriented application programming interface
developed by in collaboration with IBM and some other database vendors.
ODBC comes with Microsoft products and with all databases on Windows OS.
ODBC Architecture
“C”
function Sybase ODBC
SP API Sybase
calls
Oracle DSN
Oracle ODBC
Oracle
My DSN
Advantages
Single API (Protocol) is used to interact with any DB
Switching from one DB to another is easy
You have Downloaded this file from kamma-Sangam Yahoo Group 24
Doesn‘t 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 Provider‘s 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.
2. And the second option given was using ODBC API which can solve the 1.a problem but
again this ODBC API is also a Native API, so we have to use JNI in our Java
applications which lead to the 1.b described problem.
And the answer for these problems is JDBC (Java Data Base Connectivity) which provides a
common Java API to interact with any DB.
What is JDBC
As explained above JDBC standards for Java Data Base Connectivity. It is a specification
given by Sun Microsystems and standards followed by X/Open SAG (SQL Access Group) CLI
(Call Level Interface) to interact with the DB.
Java programing language methods. The JDBC API provides database-independent connectivity
between the JAVA Applications and a wide range of tabular data bases. JDBC technology
allows an application component provider to:
Perform connection and authentication to a database server
Manage transactions
Moves SQL statements to a database engine for preprocessing and
execution
Executes stored procedures
Inspects and modifies the results from SELECT statements
JDBC API
JDBC API is divided into two parts
1. JDBC Core API
2. JDBC Extension or Optional API
JDBC Core API (java.sql package)
This part of API deals with the following futures
1. Establish a connection to a DB
2. Getting DB Details
3. Getting Driver Details
4. maintaining Local Transaction
5. executing query‘s
6. getting result‘s (ResultSet)
7. preparing pre-compiled SQL query‘s and executing
8. executing procedures & functions
JDBC Ext OR Optional API (javax.sql package)
This part of API deals with the following futures
You have Downloaded this file from kamma-Sangam Yahoo Group 25
1. Resource Objects with Distributed Transaction Management support
2. Connection Pooling.
These two parts of Specification are the part of J2SE and are inherited into J2EE i.e. this
specification API can be used with all the component‘s given under J2SE and J2EE.
JDBC Architecture:
JDBC Application
JDBC
API
JDBC Driver
SP SP SP
API API API
In the above show archetecture diagram the JDBC Driver forms an abstraction layer
between the JAVA Application and DB, and is implemented by 3rd 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 it‘s the responsibility of
JDBC Driver Provider to convert the JDBC Call to the DB Specific Call.
And this 3rd party vendor or DB vendor implemented Drivers are classified into 4-Types namely
Types Of Drivers :
Architecture
DBMS
Interface
DBMS Server
Libraries
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 application‘s.
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).
SP
N/W
Librari
DBMS DBMS
es Server
OCI libraries (native)
Libraries
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
layer‘s) 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
path %ORACLE_HOME%\ora81\bin
How to use this driver
Driver class name oracle.jdbc.driver.OracleDriver
Driver URL jdbc:oracle:oci8:@TNSName
Note: TNS Names of Oracle is available in Oracle installed folder
%ORACLE_HOME%\Ora81\network\admin\tnsnames.ora
2. Weblogic Jdriver for Oracle implemented by BEA Weblogic:
Setting environment to use this driver
Oracle client software has to be installed in client machine
weblogicoic dll‘s has to be set in the path
classpath d:\bea\weblogic700\server\lib\weblogic.jar
path %ORACLE_HOME%\ora81\bin;
d:\bea\weblogic700\server\bin\<subfolder><sub folder> is
o oci817_8 if you are using Oracle 8.1.x
o oci901_8 for Oracle 9.0.x
o oci920_8 for Oracle 9.2.x
You have Downloaded this file from kamma-Sangam Yahoo Group 28
How to use this driver
Driver class name weblogic.jdbc.oci.Driver
Driver URL jdbc:weblogic:oracle:HostName
Architecture :
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:
1. IDS Server (Intersolv) driver available for most of the Databases
Setting environment to use this driver
Software: IDS software required to be downloaded from the following URL
[ http://www.idssoftware.com/idsserver.html -> Export Evaluation ]
classpath C:\IDSServer\classes\jdk14drv.jar
path
How to use this driver
Driver class name ids.sql.IDSDriver
Driver URL jdbc:ids://localhost:12/conn?dsn='IDSExamples'
Architecture
JDBC DBMS Interface
JDBC Type IV
Application JDBC Native Protocol Server Listener
API Driver
DBMS
API
DBMS
This type of driver converts the JDBC call to a DB defined native protocol.
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.
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?
You have Downloaded this file from kamma-Sangam Yahoo Group 30
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. That‘s‘ why most part of the
JDBC API is a formation of interfaces.
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)
CallableStatement prepareCall(String callToProc())
You have Downloaded this file from kamma-Sangam Yahoo Group 31
Statement
Statement class is the super class in its hierarchy. Provides basic functions to execute query
(select) and non-related (create, alter, drop, insert, update, delete) query operations.
Method Index
int executeUpdate(String sql)
This function accepts non-query based SQL operations; the return value int tells that how many
number of rows effected/updated by the given SQL operation.
ResultSet executeQuery(String sql)
This function accepts SQL statement SELECT and returns java buffer object which contains
temporary instance of SQL structure maintaining all the records retrieved from the DB. This
object exists as long as DB connection exist.
boolean execute()
This function accepts all SQL operations including SELECT statement also.
PreparedStatement
PreparedStatement class is sub classing from Statement class. While connection class
prepareStatement function is creating one new instance this class, function takes one String
argument that contains basic syntax of SQL operation represented with ―?‖ for IN parameter
representation. In the further stages of the JDBC program, programmer uses setXXX(int index,
datatype identifier) to pass values into IN parameter and requests exdcute()/ exuecteUpdate()
call.
Method Index
setInt(int index, int value) – similar functions are provided for all other primitive
parameters
setString(int index, String value)
setObject(int index, Object value)
setBinaryStream(int index, InputStream is, int length)
CallableStatement
ResultSet ResultSetMetaData DatabaseMetaData
BLOB CLOB REF
SavePoint Struct
SQLInput SQLOutput SQLData
// 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)
You have Downloaded this file from kamma-Sangam Yahoo Group 33
{
e.printStackTrace ();
}
}
public static void main (String args[])
{
TypeIIDriverTest demo=new TypeIIDriverTest ();
}
}
Connection Pooling
Connections made via a DataSource object that is implemented to work with a middle tier
connection pool manager will participate in connection pooling. This can improve the
performance dramatically because creating a new connection is very expensive.
Connection Pool provides following features:
Substantial improvement in the performance of DB application can be accomplished by
pre-caching the DB connection objects
CPM supplied DB connections are remote enable
CPM supplied DB connections are cluster aware
CPM supplied DB connections supports DTM (distributed TXs)
CPM supplied DB connections are not actual DB Connection objects, in turn they are
remote object, hence even though client closes DB connection using con.close() the
actual connection may not be closed instead RMI connection between client to CPM are
closed
CPM supplied DB connection objects are serializable, hence client from any where in the
network can access DB connections
The classes and interfaces used for connection pooling are:
1. ConnectionPoolDataSource
2. PooledConnection
3. ConnectionEvent
4. ConnectionEventListener
Connection Pool Manager resided on middle tier system uses these classes and interfaces
behind the scenes. When the ConnectionPooledDataSource object is called on to create
PooledConnection object, the connection pool manager will register as a
ConnectionEventListener object with the new PooledConnection object. When the connection is
closed or there is an error, the connection pool manager (being listener) gets a notification that
includes a ConnectionEvent object.
Distributed Transactions
As with pooled connections, connections made via data source object that is implemented
to work with the middle tier infrastructure may participate in distributed transactions. This gives
an application the ability to involve data sources on multiple servers in a single transaction.
The classes and interfaces used for distributed transactions are:
XADataSource
XAConnection
These interfaces are used by transaction manager; an application does not use them directly.
The XAConnection interface is derived from the PooledConnection interface, so what
applies to a pooled connection also applies to a connection that is part of distributed transaction.
A transaction manager in the middle tier handles everything transparently. The only change in
application code is that an application cannot do anything that would interfere with the
transaction manager‘s handling of the transaction. Specifically application cannot call the
methods Connection.commit or Connection.rollback and it cannot set the connection to be in
auto-commit mode.
You have Downloaded this file from kamma-Sangam Yahoo Group 35
An application does not need to do anything special to participate in a distributed
transaction. It simply creates connections to the data sources it wants to use via the
DataSource.getConnection method, just as it normally does. The transaction manager manages
the transaction behind the scenes. The XADataSource interface creates XAConnection objects,
and each XAConnection object creates an XAResource object that the transaction manager uses
to manage the connection.
Rowsets
The RowSet interface works with various other classes and interfaces behind the scenes.
These can be grouped into three categories.
1. Event Notification
o RowSetListener
A RowSet object is a JavaBeansTM component because it has properties and participates in the
JavaBeans event notification mechanism. The RowSetListener interface is implemented by a
component that wants to be notified about events that occur to a particular RowSet object. Such
a component registers itself as a listener with a rowset via the RowSet.addRowSetListener
method.
o When the RowSet object changes one of its rows, changes all of it rows, or moves its cursor, it
also notifies each listener that is registered with it. The listener reacts by carrying out its
implementation of the notification method called on it.
o 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.
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.
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 –
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 pre-compiled
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
executeupdate( ) – returns resultset Object
executeupdate( ) – returns integer value
WebRowSetImpl - This is very similar to the CachedRowSetImpl (it is a child class) but it also
includes methods for converting the rows into an XML document and loading the RowSet with
an XML document. The XML document can come from any Stream or Reader/Writer object.
This could be especially useful for Web Services.
What are the steps for connecting to the database using JDBC
Using DriverManager:
1. Load the driver class using class.forName(driverclass) and class.forName() loads the driver
class and passes the control to DriverManager class
2. DriverManager.getConnection() creates the connection to the databse
Using DataSource.
DataSource is used instead of DriverManager in Distributed Environment with the help of JNDI.
1. Use JNDI to lookup the DataSource from Naming service server.
3. DataSource.getConnection method will return Connection object to the database
2.Prepared Statement :For a runtime / dynamic query .Where String is a dynamic query you
want to execute
3. Callable Statement (Use prepareCall) : //For Stored procedure Callable statement, where sql
is stored procedure.
try
{
Connection conn = DriverManager.getConnection("URL",'USER"."PWD");
Don't forget all the above statements will throw the SQLException, so we need to use try catch
for the same to handle the exception.
•Servlets
•Java Server Pages (JSP)
•Tags and Tag Libraries
What‘s a Servlet?
•Java‘s 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
•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
You have Downloaded this file from kamma-Sangam Yahoo Group 45
•ServletConfig.getServletContext()•javax.servlet.ServletRequest
–Provides client request information to a servlet
•javax.servlet.ServletResponse
–Sending a response to the client
}
}
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
Javax.Servlet.Http Classes
HttpServletRequest Cookie
HttpServletResponse HttpServlet
HttpSession HttpSessionBindingEvent
HttpSessionContext HttpUtils
HttpSessionBindingListener -
Exceptions
ServletException
UnavailableException
SERVLETS
8. What are the differences between GET and POST service methods?
Get Method : Uses Query String to send additional information to the server.
-Query String is displayed on the client Browser.
Query String : The additional sequence of characters that are appended to the URL ia called
Query String. The length of the Query string is limited to 255 characters.
-The amount of information you can send back using a GET is restricted as URLs can only be
1024 characters.
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().
You have Downloaded this file from kamma-Sangam Yahoo Group 48
Init( ) : Is called by the Servlet container after the servlet has ben 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 Sevice.
-Excutes only once when the Servlet is removed from Server.
Public void destroy( )
Servlet Context(): The ServletContext interface provides information to servlets regarding the
environment in which they are running. It also provides standard way for servlets to write events
to a log file.
ServletContext defines methods that allow a servlet to interact with the host server. This
includes reading server-specific attributes, finding information about particular files located on
the server, and writing to the server log files. I f there are several virtual servers running, each
one may return a different ServletContext.
getMIMEType( ) , getResourse( ), getContext( ),getServerInfo( ),getServletContetName( )
11. Can I invoke a JSP error page from a servlet?
Yes, you can invoke the JSP error page and pass the exception object to it from within a
servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception
object as a javax.servlet.jsp.jspException request attribute. However, note that you can do this
from only within controller servlets.
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
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 non-deterministic, it may not help much
even if you did add more memory and increased the size of the instance pool.
15. 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.
16. 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.
19. When a servlet accepts a call from a client, it receives two objects. What are they?
ServeltRequest: which encapsulates the communication from the client to the server.
ServletResponse: which encapsulates the communication from the servlet back to the
Client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.
20. What information that the ServletRequest interface allows the servlet access to?
Information such as the names of the parameters passed in by the client, the protocol
(scheme) being used by the client, and the names of the remote host that made the request and
the server that received it. The input stream, ServletInputStream.Servlets use the input stream to
get data
from clients that use application protocols such as the HTTP POST and PUT methods.
21. What information that the ServletResponse interface gives the servlet methods for replying
to the client?
You have Downloaded this file from kamma-Sangam Yahoo Group 50
It Allows the servlet to set the content length and MIME type of the reply. Provides an
output stream, ServletOutputStream and a Writer through which the servlet can send the reply
data.
22. Difference between single thread and multi thread model servlet
A servlet that implements SingleThreadModel means that for every request, a single servlet
instance is created. This is not a very scalable solution as most web servers handle multitudes of
requests. A multi-threaded servlet means that one servlet is capable of handling many requests
which is the way most servlets should be implemented.
a. A single thread model for servlets is generally used to protect sensitive data ( bank account
operations ).
b. Single thread model means instance of the servlet gets created for each request recieved. Its not
thread safe whereas in multi threaded only single instance of the servlet exists for what ever # of
requests recieved. Its thread safe and is taken care by the servlet container.
c. A servlet that implements SingleThreadModel means that for every request, a single servlet
instance is created. This is not a very scalable solution as most web servers handle multitudes of
requests. A multi-threaded servlet means that one servlet is capable of handling many requests
which is the way most servlets should be implemented.
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
like to retreive in next screen.
eg
context.setAttribute("supportAddress", "[email protected]");
Better yet, you could use the web.xml context-param element to
designate the address, then read it with the getInitParameter method
of ServletContext.
26. What is difference between forward() and sendRedirect().. ? Which one is faster then
other and which works on server?
Forward( ) : javax.Servlet.RequestDispatcher interface.
-RequestDispatcher.forward( ) works on the Server.
-The forward( ) works inside the WebContainer.
-The forward( ) restricts you to redirect only to a resource in the same web-Application.
-After executing the forward( ), the control will return back to the same method from where the
forward method was called.
-the forward( ) will redirect in the application server itself, it does‘n come back to the client.
- The forward( ) is faster than Sendredirect( ) .
To use the forward( ) of the requestDispatcher interface, the first thing to do is to obtain
RequestDispatcher Object. The Servlet technology provides in three ways.
1. By using the getRequestDispatcher( ) of the javax.Servlet.ServletContext interface , passing a
String containing the path of the other resources, path is relative to the root of the
ServletContext.
RequestDispatcher rd=request.getRequestDispatcher(“secondServlet”);
Rd.forward(request, response);
-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
You have Downloaded this file from kamma-Sangam Yahoo Group 52
request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower
than forward.
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.
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>
JSP Elements
•Directive Elements : –Information about the page
–Remains same between requests
You have Downloaded this file from kamma-Sangam Yahoo Group 54
–E.g., scripting language used
•Action Elements : –Take action based on info required at request-time
•Standard
•Custom (Tags and Tag Libraries)
•Scripting Elements
–Add pieces of code to generate output based on conditions
Directives
•Global information used by the ―JSP engine‖
•Of form <%@ directive attr_ list %>
•Or <jsp: directive. directive attr_ list />
–Directive could be
•Page
•Include
•Taglib
–E. g.,
<%@ page info=― written by DevelopMentor‖ %>
<jsp: directive. page import=― java. sql.*‖ />
<%@ include file =―\ somefile. txt‖ %>
<%@ taglib uri = tags prefix=― foo‖ %>
Actions Within a JSP Page
•Specifies an action to be carried out by the ―JSP engine‖
•Standard or custom
–Standard must be implemented by all engines
–Custom defined in tag libraries
•Standard actions ‗scoped‘ by ‗jsp‘ namespace
•Have name and attributes
<jsp: useBean id=― clock‖ class=― java.util.Date‖ />
<ul> The current date at the server is:
<li> Date: <jsp: getProperty name=―clock‖ property=―date‖ />
<li> Month: <jsp: getProperty name=―clock‖ property=―month‖ />
</ul>
Scriptlets
•Of form <% /* code goes here*/ %>
–Gets copied into _ jspService method of generated servlet
•Any valid Java code can go here
CODE: OUTPUT
<% int j; %> <value> 0</ value>
<% for (j = 0; j < 3; j++) {%> <value> 1</ value>
<value> <value> 2</ value>
You have Downloaded this file from kamma-Sangam Yahoo Group 55
<% out. write(""+ j); %>
</ value><% } %>
Generated Servlet…
public void _jspService(HttpServletRequest request ,
HttpServletResponse response)
throws ServletException ,IOException {
You have Downloaded this file from kamma-Sangam Yahoo Group 56
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" );
}
out.write("\r\n\t\t<FORM METHOD='POST' action="
+"\"Hello.jsp\">\r\n\t\t\t<table width=\"500\" cell―……………………………..
}
}
BodyTag BodyTagSupport
Interface class
mylib.tld
<taglib> ……
<tag><name>hello</name>
<tagclass>com.pramati.HelloTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute><name>name</name></attribute>
</tag>
</taglib>
How Tag Handler methods are invoked :
<prefix:tagName
attr1=―value1‖ ------------ setAttr1(―value1‖)
attr2=―value2‖ ------------ setAttr2(―value2‖)
> ------------ doStartTag()
This tags's body
</ prefix:tagName>------------ doEndTag()
•Implementation of JSP page will use the tag handler for each ‗action‘ on page.
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
•JSP components can be used as the view in the MVC architecture
•Authors using JSP technology are not necessarily programmers using Java technology
•Want to keep ―Java code‖ off a ―JSP Page‖
•Custom actions (tag libraries) allow the use of elements as a replacement for Java code
What are Custom tags. Why do you need Custom tags. How do you create Custom tag
1) Custom tags are those which are user defined.
2) Inorder to separate the presentation logic in a separate class rather than keeping in jsp page
we can use custom tags.
3) Step 1 : Build a class that implements the javax.servlet.jsp.tagext.Tag interface as follows.
Compile it and place it under the web-inf/classes directory (in the appropriate package
structure).
package examples;
import java.io.*; //// THIS PROGRAM IS EVERY TIME I MEAN WHEN U REFRESH
THAT PARTICULAR CURRENT DATE THIS CUSTOM TAG WILL DISPLAY
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class ShowDateTag implements Tag {
private PageContext pageContext;
private Tag parent;
public int doStartTag() throws JspException {
return SKIP_BODY; }
public int doEndTag() throws JspException {
try {
pageContext.getOut().write("" + new java.util.Date());
} catch (IOException ioe) {
throw new JspException(ioe.getMessage());
}
return EVAL_PAGE; }
public void release() {
}
public void setPageContext(PageContext page) {
this.pageContext = page;
}
public void setParent(Tag tag) {
this.parent = tag;
}
public Tag getParent() {
return this.parent; } }
Step 2:Now we need to describe the tag, so create a file called taglib.tld and place it under the
web-inf directory."http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> 1.0 1.1
myTag http://www.mycompany.com/taglib My own tag library showDate
examples.ShowDateTag Show the current date
Step 3 : Now we need to tell the web application where to find the custom tags, and how they
will be referenced from JSP pages. Edit the web.xml file under the web-inf directory and insert
the following XML fragement.http://www.mycompany.com/taglib /WEB-INF/taglib.tld
Step 4 : And finally, create a JSP page that uses the custom tag.Now restart the server and call
up the JSP page! You should notice that every time the page is requested, the current date is
You have Downloaded this file from kamma-Sangam Yahoo Group 59
displayed in the browser. Whilst this doesn't explain what all the various parts of the tag are
for (e.g. the tag description, page context, etc) it should get you going. If you use the tutorial
(above) and this example, you should be able to grasp what's going on! There are some methods
in context object with the help of which u can get the server (or servlet container) information.
Apart from all this with the help of ServletContext u can implement ServletContextListener
and then use the get-InitParametermethod to read context initialization parameters as the basis of
data that will be made available to all servlets and JSP pages.
What are the implicit objects in JSP & differences between them
There are nine implicit objects in JSP.
1. request : The request object represents httprequest that are trigged by service( ) invocation.
javax.servlet
4. session : the session object represents the session created by the current user.
javax.Servlet.http.HttpSession
5. application : the application object represents servlet context , obtained from servlet
configaration . javax.Servlet.ServletContext
6. out : the out object represents to write the out put stream .
javax.Servlet.jsp.jspWriter
7. Config :the config object represents the servlet config interface from this page,and has scope
attribute. javax.Servlet.ServletConfig
8. page : The object is th eInstance of page implementation servlet class that are processing the
current request.
java.lang.Object
9. exception : These are used for different purposes and actually u no need to create these
objects in JSP. JSP container will create these objects automatically.
java.lang.Throwable
Example:
If i want to put my username in the session in JSP.
JSP Page: In the about page, i am using session object. But this session object is not declared in
JSP file, because, this is implicit object and it will be created by the jsp container.
If u see the java file for this jsp page in the work folder of apache tomcat, u will find these
objects are created.
What is jsp:usebean. What are the scope attributes & difference between these attributes
page, request, session, application
What is difference between scriptlet and expression
What is Declaration
Declaration is used in JSP to declare methods and variables.To add a declaration, you must use
the sequences to enclose your declarations.
How do I have the JSP-generated servlet subclass my own custom servlet class, instead of
the default?
One should be very careful when having JSP pages extend custom servlet classes as
opposed to the default one generated by the JSP engine. In doing so, you may lose out on any
advanced optimization that may be provided by the JSPengine. In any case, your new superclass
has to fulfill the contract with the JSPngine by: Implementing the HttpJspPage interface, if the
protocol used is HTTP, or implementing JspPage otherwise Ensuring that all the methods in the
Servlet interface are declared final Additionally, your servlet superclass also needs to do the
following:
The service() method has to invoke the _jspService() method
The init() method has to invoke the jspInit() method
The destroy() method has to invoke jspDestroy()
If any of the above conditions are not satisfied, the JSP engine may throw a translation error.
Once the superclass has been developed, you can have your JSP extend it as follows:
<%@ page extends="packageName.ServletName" %<
How can I set a cookie and delete a cookie from within a JSP page?
A cookie, mycookie, can be deleted using the following scriptlet:
<%
//creating a cookie
Cookie mycookie = new Cookie("aName","aValue");
response.addCookie(mycookie);
//delete a cookie
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);
%>
How can I enable session tracking for JSP pages if the browser has disabled cookies?
We know that session tracking uses cookies by default to associate a session identifier with
a unique user. If the browser does not support cookies, or if cookies are disabled, you can still
enable session tracking using URL rewriting. URL rewriting essentially includes the session ID
within the link itself as a name/value pair. However, for this to be effective, you need to append
the session ID for each and every link that is part of your servlet response. Adding the session
ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL()
associates a session ID with a given URL, and if you are using redirection,
response.encodeRedirectURL() can be used by giving the redirected URL as input. Both
encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the
browser; if so, the input URL is returned unchanged since the session ID will be persisted as a
cookie.
Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp,
interact with each other. Basically, we create a new session within hello1.jsp and place an object
within this session. The user can then traverse to hello2.jsp by clicking on the link present within
the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session
and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link
used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to
the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with
You have Downloaded this file from kamma-Sangam Yahoo Group 63
cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you
should see the maintenance of the session across pages. Do note that to get this example to work
with cookies disabled at the browser, your JSP engine has to support URL rewriting.
hello1.jsp
<%@ page session="true" %>
<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
<a href='<%=url%>'>hello2.jsp</a>
hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is "+i.intValue());
How do I use a scriptlet to initialize a newly instantiated bean?
A jsp:useBean action may optionally have a body. If the body is specified, its contents will be
automatically invoked when the specified bean is instantiated. Typically, the body will contain
scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not
restricted to using those alone. The following example shows the "today" property of the Foo
bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP
expression within the jsp:setProperty action.
How do I prevent the output of my JSP or Servlet pages from being cached by the
browser?
You will need to set the appropriate HTTP header attributes to prevent the dynamic content
output by the JSP page from being cached by the browser. Just execute the following scriptlet at
the beginning of your JSP pages to prevent them from being cached at the browser. You need
both the statements to take care of some of the older browser versions.
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
You have Downloaded this file from kamma-Sangam Yahoo Group 64
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
How do you prevent the Creation of a Session in a JSP Page and why?
By default, a JSP page will automatically create a session for the request if one does not exist.
However, sessions consume resources and if it is not necessary to maintain a session, one should
not be created. For example, a marketing campaign may suggest the reader visit a web page for
more information. If it is anticipated that a lot of traffic will hit that page, you may want to
optimize the load on the machine by not creating useless sessions.
What is the page directive is used to prevent a JSP page from automatically creating a
session:
<%@ page session="false">
Is it possible to share an HttpSession between a JSP and EJB? What happens when I
change a value in the HttpSession from inside an EJB?
You can pass the HttpSession as parameter to an EJB method, only if all objects in
session are serializable.This has to be consider as "passed-by-value", that means that it's read-
only in the EJB. If anything is altered from inside the EJB, it won't be reflected back to the
HttpSession of the Servlet Container.The "pass-byreference" can be used between EJBs Remote
Interfaces, as they are remote references. While it IS possible to pass an HttpSession as a
parameter to an EJB object, it is considered to be "bad practice (1)" in terms of object oriented
design. This is because you are creating an unnecessary coupling between back-end objects
(ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb's api.
Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics),
create a class that acts as a value object (or structure) that holds all the data you need to pass
back and forth between front-end/back-end. Consider the case where your ejb needs to support a
non-http-based client. This higher level of abstraction will be flexible enough to support it. (1)
Core J2EE design patterns (2001)
Can you make use of a ServletOutputStream object from within a JSP page?
No. You are supposed to make use of only a JSPWriter object (given to you in the form of the
implicit object out) for replying to clients. A JSPWriter can be viewed as a buffered version of
the stream object returned by response.getWriter(), although from an implementational
perspective, it is not. A page author can always disable the default buffering for any page using a
page directive as:
<%@ page buffer="none" %>
Struts 1.1
1. Introduction to MVC
a. Overview of MVC Architecture 63
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 66
a. Introduction to Struts Framework
b. Struts Architecture
c. Front Controller Design Pattern
d. Controller servlet - ActionServlet
e. Action objects
f. Action Form objects
You have Downloaded this file from kamma-Sangam Yahoo Group 68
g. Action mappings
h. Configuring web.xml file and struts-config.xml file
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
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.
You have Downloaded this file from kamma-Sangam Yahoo Group 69
The Controller allows the user to manipulate the application .
C O S Users
o
m
p
e
e
c
m r u
u a r
n t i
UI Components
i i t
c o y
a n
UI Process Components
t a
i l
o m
n a
n Service Interfaces
a
g
Business Business Business
e Workflows Components Entities
m
e
n
t
Data Access Logic Service Agents
Components
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 Model-View-
Controller (MVC) design pattern and truly separate presentation from content when using Java
Server Pages.
Below you will find one example on registration form processing using MVC in Servlets and
JSP:
Controller Servlet
If() Reg_mast
User er
If()
You have Downloaded this file from kamma-Sangam Yahoo Group 70
Reg 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 client‘s browser.
4. When the Error.jsp is responded, the page must include all the list of errors with detailed
description.
5. The above shown application architecture is the model for MVC.
6. IF MVC Model 2 wants to be implemented in your application business logic and model
operations must be separated from controller program.
View on JSP
The early JSP specification follows two approaches for building applications using JSP
technology. These two approaches are called as JSP Model 1 and JSP Model 2 architectures.
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.
Pass 6 3
4
Beans
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 outcome, and ultimately dispatch
control to the appropriate View component to create the response.
The Struts project was launched in May 2000 by Craig McClanahan to provide a standard MVC
framework to the Java community. In July 2001.
In the MVC design pattern, application flow is mediated by a central Controller. The
Controller delegates‘ requests - in our case, HTTP requests - to an appropriate handler. The
handlers are tied to a Model, and each handler acts as an adapter between the request and the
Model. The Model represents, or encapsulates, an application's business logic or state. Control is
usually then forwarded back through the Controller to the appropriate View. The forwarding can
be determined by consulting a set of mappings, usually loaded from a database or configuration
file. This provides a loose coupling between the View and Model, which can make applications
significantly easier to create and maintain.
Struts Architecture
Request.jsp J2EE
Struts- Component
Action config.xml (EJB)
Servlet
ActionForm
Success
Response DB
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.
Centralizing control in the controller and reducing business logic in the view promotes code
reuse across requests. It is a preferable approach to the alternative-embedding code in multiple
views-because that approach may lead to a more error-prone, reuse-by-copy- and-paste
environment.
Structure
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.
Action class
The Action class defines two methods that could be executed depending on your servlet
environment:
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
You have Downloaded this file from kamma-Sangam Yahoo Group 77
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.
o Only Use Local Variables - The most important principle that aids in thread-safe coding is to
use only local variables, not instance variables, in your Action class. Local variables are
created on a stack that is assigned (by your JVM) to each request thread, so there is no need to
worry about sharing them. An Action can be factored into several local methods, so long as all
variables needed are passed as method parameters. This assures thread safety, as the JVM
handles such variables internally using the call stack which is associated with a single Thread.
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
You have Downloaded this file from kamma-Sangam Yahoo Group 79
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.
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 type - Fully qualified Java class name of the Action implementation class used by this mapping.
o name - The name of the form bean defined in the config file that this action will use.
o 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.
o 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.
o validate - Set to true if the validate method of the action associated with this mapping should be
called.
o forward - The request URI path to which control is passed when this mapping is invoked. This
is an alternative to declaring a type property.
The controller uses an internal copy of this document to parse the configuration; an Internet
connection is not required for operation.
The outermost XML element must be <struts-config>. Inside of the <struts-config> element,
there are three important elements that are used to describe your actions:
<form-beans>
<global-forwards>
<action-mappings>
<form-beans>
This section contains your form bean definitions. Form beans are descriptors that are used to
create ActionForm instances at runtime. You use a <form-bean> element for each form bean,
which has the following important attributes:
name: A unique identifier for this bean, which will be used to reference it in
corresponding action mappings. Usually, this is also the name of the request or session
attribute under which this form bean will be stored.
type: The fully-qualified Java classname of the ActionForm subclass to use with this
form bean.
<global-forwards>
This section contains your global forward definitions. Forwards are instances of the
ActionForward class returned from an ActionForm's execute method. These map logical names
to specific resources (typically JSPs), allowing you to change the resource without changing
references to it throughout your application. You use a <forward> element for each forward
definition, which has the following important attributes:
name: The logical name for this forward. This is used in your ActionForm's execute
method to forward to the next appropriate resource. Example: homepage
path: The context relative path to the resource. Example: /index.jsp or /index.do
redirect: True or false (default). Should the ActionServlet redirect to the resource instead
of forward?
<action-mappings>
This section contains your action definitions. You use an <action> element for each of the
mappings you would like to define. Most action elements will define at least the following
attributes:
path: The application context-relative path to the action.
type: The fully qualified java classname of your Action class.
name: The name of your <form-bean> element to use with this action
Other often-used attributes include:
parameter: A general-purpose attribute often used by "standard" Actions to pass a
required property.
roles: A comma-delimited list of the user security roles that can access this mapping.
For a complete description of the elements that can be used with the action element, see the
Struts Configuration DTD and the ActionMapping documentation.
If not specified, the default forwardPattern is consistent with the previous behavior of
forwards. [$M$P] (optional)
inputForward - Set to true if you want the input attribute of <action> elements to be the
name of a local or global ActionForward, which will then be used to calculate the
ultimate URL. Set to false to treat the input parameter of <action> elements as a module-
relative path to the resource to be used as the input form. [false] (optional)
locale - Set to true if you want a Locale object stored in the user's session if not already
present. [true] (optional)
maxFileSize - The maximum size (in bytes) of a file to be accepted as a file upload. Can
be expressed as a number followed by a "K", "M", or "G", which are interpreted to mean
kilobytes, megabytes, or gigabytes, respectively. [250M] (optional)
multipartClass - The fully qualified Java class name of the multipart request handler
class to be used with this module.
[org.apache.struts.upload.CommonsMultipartRequestHandler] (optional)
nocache - Set to true if you want the controller to add HTTP headers for defeating
caching to every response from this module. [false] (optional)
pagePattern - Replacement pattern defining how the page attribute of custom tags using
it is mapped to a context-relative URL of the corresponding resource. This value may
consist of any combination of the following:
o $M - Replaced by the module prefix of this module.
o $P - Replaced by the "path" attribute of the selected <forward> element.
o $$ - Causes a literal dollar sign to be rendered.
o $x - (Where "x" is any character not defined above) Silently swallowed, reserved
for future use.
If not specified, the default pagePattern is consistent with the previous behavior of URL
calculation. [$M$P] (optional)
processorClass - The fully qualified Java class name of the RequestProcessor subclass
to be used with this module. [org.apache.struts.action.RequestProcessor] (optional)
tempDir - Temporary working directory to use when processing file uploads. [{the
directory provided by the servlet container}]
This example uses the default values for several controller parameters. If you only want default
behavior you can omit the controller section altogether.
<controller
processorClass="org.apache.struts.action.RequestProcessor"
debug="0"
contentType="text/html"/>;
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,
The Struts configuration file
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>
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.
Configuring your application for modules
Very little is required in order to start taking advantage of the Struts module feature. Just go
through the following steps:
1. Prepare a config file for each module.
2. Inform the controller of your module.
3. Use actions to refer to your pages.
Module Configuration Files
Back in Struts 1.0, a few "boot-strap" options were placed in the web.xml file, and the bulk of
the configuration was done in a single struts-config.xml file. Obviously, this wasn't ideal for a
team environment, since multiple users had to share the same configuration file.
In Struts 1.1, you have two options: you can list multiple struts-config files as a comma-
delimited list, or you can subdivide a larger application into modules.
With the advent of modules, a given module has its own configuration file. This means each
team (each module would presumably be developed by a single team) has their own
configuration file, and there should be a lot less contention when trying to modify it.
Informing the Controller
In struts 1.0, you listed your configuration file as an initialization parameter to the action
servlet in web.xml. This is still done in 1.1, but it's augmented a little. In order to tell the Struts
machinery about your different modules, you specify multiple config initialization parameters,
with a slight twist. You'll still use "config" to tell the action servlet about your "default" module,
however, for each additional module, you will list an initialization parameter named
"config/module", where module is the name of your module (this gets used when determining
which URIs fall under a given module, so choose something meaningful!). For example:
...
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/conf/struts-default.xml</param-value>
</init-param>
You have Downloaded this file from kamma-Sangam Yahoo Group 88
<init-param>
<param-name>config/module1</param-name>
<param-value>/WEB-INF/conf/struts-module1.xml</param-value>
</init-param>
...
This says I have two modules. One happens to be the "default" module, which has no
"/module" in it's name, and one named "module1" (config/module1). I've told the controller it
can find their respective configurations under /WEB-INF/conf (which is where I put all my
configuration files). Pretty simple!
(My struts-default.xml would be equivalent to what most folks call struts-config.xml. I just like
the symmetry of having all my Struts module files being named struts-<module>.xml)
If you'd like to vary where the pages for each module is stored, see the forwardPattern setting for
the Controller.
Switching Modules
There are two basic methods to switching from one module to another. You can either use a
forward (global or local) and specify the contextRelative attribute with a value of true, or you
can use the built-in org.apache.struts.actions.SwitchAction.
Here's an example of a global forward:
...
<struts-config>
...
<global-forwards>
<forward name="toModuleB"
contextRelative="true"
path="/moduleB/index.do"
redirect="true"/>
...
</global-forwards>
...
</struts-config>
You could do the same thing with a local forward declared in an ActionMapping:
...
<struts-config>
...
<action-mappings>
...
<action ... >
<forward name="success"
contextRelative="true"
path="/moduleB/index.do"
redirect="true"/>
</action>
...
</action-mappings>
...
</struts-config>
Finally, you could use org.apache.struts.actions.SwitchAction, like so:
...
<action-mappings>
<action path="/toModule"
type="org.apache.struts.actions.SwitchAction"/>
You have Downloaded this file from kamma-Sangam Yahoo Group 89
...
</action-mappings>
...
Now, to change to ModuleB, we would use a URI like this:
http://localhost:8080/toModule.do?prefix=/moduleB&page=/index.do
If you are using the "default" module as well as "named" modules (like "/moduleB"), you can
switch back to the "default" module with a URI like this:
http://localhost:8080/toModule.do?prefix=&page=/index.do
That's all there is to it! Happy module-switching!
The Web Application Deployment Descriptor
The final step in setting up the application is to configure the application deployment
descriptor (stored in file WEB-INF/web.xml) to include all the Struts components that are
required. Using the deployment descriptor for the example application as a guide, we see that the
following entries need to be created or modified.
Configure the Action Servlet Instance
Add an entry defining the action servlet itself, along with the appropriate initialization
parameters. Such an entry might look like this:
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>
/WEB-INF/struts-config.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
The initialization parameters supported by the controller servlet are described below. (You
can also find these details in the Javadocs for the ActionServlet class.) Square brackets describe
the default values that are assumed if you do not provide a value for that initialization parameter.
config - Context-relative path to the XML resource containing the configuration information for
the default module. This may also be a comma-delimited list of configuration files. Each file is
loaded in turn, and its objects are appended to the internal
data structure. [/WEB-INF/struts-config.xml].
WARNING - If you define an object of the same name in more than one configuration file, the last
one loaded quietly wins.
config/${module} - Context-relative path to the XML resource containing the configuration
information for the application module that will use the specified prefix (/${module}). This can
be repeated as many times as required for multiple application modules. (Since Struts 1.1)
convertNull - Force simulation of the Struts 1.0 behavior when populating forms. If set to true,
the numeric Java wrapper class types (like java.lang.Integer) will default to null (rather than 0).
(Since Struts 1.1) [false]
rulesets - Comma-delimited list of fully qualified classnames of additional
org.apache.commons.digester.RuleSet instances that should be added to the Digester that will
be processing struts-config.xml files. By default, only the RuleSet for the standard
configuration elements is loaded. (Since Struts 1.1)
validating - Should we use a validating XML parser to process the configuration file (strongly
recommended)? [true]
Note that you must use the full uri defined in the various struts tlds so that the container
knows where to find the tag's class files. You don't have to alter your web.xml file or copy tlds
into any application directories.
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 DispatchAction
The DispatchAction class is used to group related actions into one class. DispatchAction is
an abstract class, so you must override it to use it. It extends the Action class.
It should be noted that you dont have to use the DispatchAction to group multiple actions into
one Action class.
You could just use a hidden field that you inspect to delegate to member() methods inside of
your action.
How you will save the data across different pages for a particular client request using
Struts
Several ways. The similar to the ways session tracking is enabled. Using cookies, URL-
rewriting, SSLSession, and possibilty threw in the database.
What is Struts?
Struts is a web page development framework and an open source software that helps
developers build web applications quickly and easily. Struts combines Java Servlets, Java Server
Pages, custom tags, and message resources into a unified framework. It is a cooperative,
synergistic platform, suitable for development teams, independent developers, and everyone
between.
You have Downloaded this file from kamma-Sangam Yahoo Group 95
How is the MVC design pattern used in Struts framework?
In the MVC design pattern, application flow is mediated by a central Controller. The
Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and
each handler acts as an adapter between the request and the Model. The Model represents, or
encapsulates, an application's business logic or state. Control is usually then forwarded back
through the Controller to the appropriate View. The forwarding can be determined by consulting
a set of mappings, usually loaded from a database or configuration file. This provides a loose
coupling between the View and Model, which can make an application significantly easier to
create and maintain.
Controller--Servlet controller which supplied by Struts itself; View --- what you can see on the
screen, a JSP page and presentation components; Model --- System state and a business logic
JavaBeans.
What helpers in the form of JSP pages are provided in Struts framework?
--struts-html.tld
--struts-bean.tld
--struts-logic.tld
What is Jakarta Struts Framework? - Jakarta Struts is open source implementation of MVC
(Model-View-Controller) pattern for the development of web based applications. Jakarta Struts
is robust architecture and can be used for the development of application of any size. Struts
framework makes it much easier to design scalable, reliable Web applications with Java.
What is ActionServlet?
The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the
Jakarta Struts Framework this class plays the role of controller. All the requests to the server
goes through the controller. Controller is responsible for handling all the requests.
How you will make available any Message Resources Definitions file to the Struts
Framework Environment?
Message Resources Definitions file are simple .properties files and these files contains the
messages that can be used in the struts project. Message Resources Definitions files can be
added to the struts-config.xml file through <message-resources /> tag.
Example:
<message-resources parameter=‖MessageResources‖ />
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;
You have Downloaded this file from kamma-Sangam Yahoo Group 97
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
automatically populated on the server side with data entered from a form on the client side.
How you will display validation fail errors on jsp page? The following tag displays all the
errors:
<html:errors/>
How you will enable front-end validation based on the xml in validation.xml? The
<html:javascript> tag to allow front-end validation based on the xml in validation.xml. For
example the code: <html:javascript formName=”logonForm”
dynamicJavascript=”true” staticJavascript=”true” /> generates the client side java script
for the form ―logonForm‖ as defined in the validation.xml file. The <html:javascript>
when added in the jsp file generates the client site validation script.
Agenda
•What is an EJB
•Bean Basics
•Component Contract
•Bean Varieties
–Session Beans
–Entity Beans
–Message Driven Beans
What is an EJB ?
Bean is a component
•A server-side component
•Contains business logic that operates on some temporary data or permanent database
•Is customizable to the target environment
•Is re-usable
•Is truly platform-independent
You have Downloaded this file from kamma-Sangam Yahoo Group 99
So, what is an EJB?
•Ready-to-use Java component
–Being Java implies portability, inter-operability
•Can be assembled into a distributed multi-tier application
•Handles threading, transactions
•Manages state and resources
•Simplifies the development of complex enterprise applications
Benefits …
•Pure Java implies portability
–exchange components without giving away the source.
•Provides interoperability
–assemble components from anywhere, can all work together.
EJB Component
server
You have Downloaded this file from kamma-Sangam Yahoo Group 101
Name Server
Bean places reference to
Home Object under JNDI
Client locates Home Object Naming service
Component Server
Client
Home
Object
Client calls create()
Bean Instance created Bean
You have Downloaded this file from kamma-Sangam Yahoo Group 102
Component Contract :
•Client-view contract
•Component contract Bean Instance
•EJB-jar file
Component
Contract
Client Container
Client View
Contract
Component Server
Client-view contract :
•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 provider’s
responsibilities
Bean provider’s
responsibilities
You have Downloaded this file from kamma-Sangam Yahoo Group 103
•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
•Avoid programming practices that interfere with container‘s runtime management of bean
instances
Ejb-jar file
•Standard format used by EJB tools for packaging (assembling) beans along with declarative
information
•Contract between bean provider and application assembler, and between application assembler
and application deployer
•The file includes:
–Java class files of the beans alo
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 ConsumersAsynchronous.
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.
You have Downloaded this file from kamma-Sangam Yahoo Group 104
•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
IntialContext Class :
Lookup( ) -> Searches and locate the distributed Objects.
EJBObject or EJBLocalObject
•Client never directly accesses instances of a Session Bean‘s class
•Client uses Session Bean‘s Remote Interface or Remote Home Interface to access its instance
•The class that implements the Session Bean‘s Remote Interface or Remote Home Interface is
provided by the container.
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 :
•Session bean container may temporarily transfer state of an idle stateful session bean instance
to some form of secondary storage.
•Transfer from working set to secondary storage is called instance passivation.
You have Downloaded this file from kamma-Sangam Yahoo Group 106
•Transfer back from the secondary storage to the instance variables is called instance
activation.
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 Bean‘s 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 object‘s 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 bean‘s 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
Create Methods :
•Entity Bean‘s Remote Home Interface can define multiple create() methods, each defining a
way of creating an entity object
•Arguments of create() initialize the state of the entity object
•Return type of a create() method is Entity Bean‘s Remote Interface
•The throws clause of every create() method includes the java.rmi.RemoteException and
javax.ejb.CreateException
finder Methods
•Entity Bean‘s Home Interface defines many finder methods
•Name of each finder method starts with the prefix ―find‖
•Arguments of a finder method are used by the Entity Bean implementation to locate requested
entity objects
•Return type of a finder method must be the Entity Bean‘s Remote Interface, or a collection of
Remote Interfaces
•The throws clause of every finder method includes the java.rmi.RemoteException and
javax.ejb.FinderException
Persistence Management
•Data access protocol for transferring state of the entity between the Entity Bean instances and
the database is referred to as object persistence
•There are two ways to manage this persistence during an application‘s lifetime
–Bean-managed
–Container-managed
<abstract-schema-name>CustomerBeanSchema</abstract-schema-name>
<cmp-field>
<description>id of the customer</description>
You have Downloaded this file from kamma-Sangam Yahoo Group 110
<field-name>iD</field-name>
</cmp-field>
<cmp-field>
<description>First name of the customer</description>
<field-name>firstName</field-name>
</cmp-field>
<cmp-field>
<description>Last name of the customer</description>
<field-name>lastName</field-name>
</cmp-field>
<primkey-field>iD</primkey-field>
You have Downloaded this file from kamma-Sangam Yahoo Group 112
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 EJB ?
Enterprise Java Bean is a specification for server-side scalable,transactional and multi-user
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:
Stateful Session Beans:They maintain conversational state between subsequest calls by a client
b) Stateful Session Beans : These beans have internal states. They can be stored (getHandle())
and restored (getEJBObject()) across client sessions.Since they can be persistence, they are also
called as Persistence Session Beans.
Stateless Session Bean:Consider this as a servlet equivalent in EJB. It is just used to service
clients regardless of state and does not maintain any state.
a) Stateless Session Beans : These beans do not have internal States. They need not be
passivated. They can be pooled into service multiple clients.
What is the difference between Stateful session bean and Stateless session bean
Stateful:
Stateful s.Beans have the passivated and Active state which the Stateless bean does not have.
Stateful beans are also Persistent session beans. They are designed to service business processes
that span multiple method requests or transactions.
Stateful session beans remembers the previous requests and reponses.
Stateful session beans does not have pooling concept.
Stateful Session Beans can retain their state on behave of an individual client.
Stateful Session Beans can be passivated and reuses them for many clients.
Stateful Session Bean has higher performance over stateless sessiob bean as they are pooled by
the application server.
Stateless:
You have Downloaded this file from kamma-Sangam Yahoo Group 113
Stateless Session Beans are designed to service business process that last only for a single
method call or request.
Stateless session beans do not remember the previous request and responses.
Stattless session bean instances are pooled.
Stateless Session Beans donot maintain states.
Stateless Session Beans, client specific data has to be pushed to the bean for each method
invocation which result in increase of network traffic.
When you will chose Stateful session bean and Stateless session bean
Stateful session bean is used when we need to maintain the client state . Example of statefull
session is Shoping cart site where we need to maintain the client state .
stateless session bean will not have a client state it will be in pool.
You have Downloaded this file from kamma-Sangam Yahoo Group 114
To maintain the state of the bean we prefer stateful session bean and example is to get mini
statement in
ATM we need sessions to be maintained.
What is Entity Bean. What are the various types of Entity Bean
Entity bean represents the real data which is stored in the persistent storage like Database or file
system. For example, There is a table in Database called Credit_card. This table contains
credit_card_no,first_name, last_name, ssn as colums and there are 100 rows in the table. Here
each row is represented by one instance of the entity bean and it is found by an unique key
(primary key) credit_card_no.
There are two types of entity beans.
1) Container Managed Persistence(CMP)
2) Bean Managed Presistence(BMP)
What is the difference between CMP and BMP
CMP means Container Managed Persistence. When we write CMP bean , we dont need to
write any JDBC code to connect to Database. The container will take care of connection our
enitty beans fields with database. The Container manages the persistence of the bean. Absolutely
no database access code is written inside the bean class.
BMP means Bean Managed Persistence. When we write BMP bean, it is programmer
responsiblity to write JDBC code to connect to Database.
CMP
- Container managed persistence
- Developer maps the bean fields with the database fields in the deployment descriptors.
- Developer need not provide persistence logic (JDBC) within the bean class.
- Containiner manages the bean field to DB field synchronization.
The point is only ENTITY beans can have theier pesristence mechanism as CMP or
BMP. Session beans, which usually contains workflow or business logic should never have
persistence code.Incase you choose to write persistence within your session bean, its usefull to
note that the persistence is managed by the container BMP.Session beans cannot be CMP and its
not possibel to provide field mapping for session bean.
BMPs are much harder to develop and maintain than CMPs.All other things are being
equal,choose CMPs over BMPs for pure maintainability.
There are limitations in the types of the data sources that may be supported for CMPs by
a container provide.Support for non JDBC type data sources,such as CICS,are not supported by
the current CMP mapping and invocation schema.Therefore accessing these would require a
BMP.
Complex queries might not be possible with the basic EJBQL for CMPs.So prefer BMPs
for complex queries.
If relations between entity beans are established then CMPs may be necessary.CMR has
ability to define manage relationships between entity beans.
Container will tyr to optimize the SQL code for the CMPs,so they may be scalable entity
beans than the BMPs.
BMPs may be inappropriate for larger and more performance sesitive applications.
You have Downloaded this file from kamma-Sangam Yahoo Group 117
eliminates time/system expenses for copying data variables, which provides a performance
advantage.
If you create an entity bean, you need to remember that it is usually used with a local client
view. If your entity bean needs to provide access to a client outside of the existing JVM (i.e., a
remote client), you typically use a session bean with a remote client view. This is the so-called
Session Facade pattern, the goal of which is that the session bean provides the remote client
access to the entity bean.
If you want to use container-managed relationship (CMR) in your enterprise bean, you
must expose local interfaces, and thus use local client view. This is mentioned in the EJB
specification.
Enterprise beans that are tightly coupled logically are good candidates for using local client
view. In other words, if one enterprise bean is always associated with another, it is perfectly
appropriate to co-locate them (i.e., deploy them both in one JVM) and organize them through a
local interface.
What is ACID
ACID is releated to transactions. It is an acronyam of Atomic, Consistent, Isolation and
Durable. Transaction must following the above four properties to be a better one
Atomic: It means a transaction must execute all or nothing at all.
Consistent: Consistency is a transactional characteristic that must be enforced by both the
transactional system and the application developer
Isolation: Transaation must be allowed to run itselft without the interference of the other
process or transactions.
Durable: Durablity means that all the data changes that made by the transaction must be written
in some type of physical storage before the transaction is successfully completed. This ensures
that transacitons are not lost even if the system crashes.
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.
Dirrty 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
You have Downloaded this file from kamma-Sangam Yahoo Group 118
2. RequiresNew – T1---T2
0---T1
3. Mandatory - T1---T1
0---Error
4. Supports - T1---T1
0---0
5. NotSupported - T1---0
0---0
6. Never - T1---Error
0---0
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.
You have Downloaded this file from kamma-Sangam Yahoo Group 119
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 is the difference between JNDI context, Initial context, session context and ejb
context
You have Downloaded this file from kamma-Sangam Yahoo Group 120
classes are located and what type of transaction etc. In a simple word, without deployment
descritor the Container ( EJB/Servlet/JSP container) will not know what to do with that module.
Deployment Descriptor is a file located in the WEB-INF directory that controls the behaviour of
Servlets and JSP.
The file is called Web.xml and contains
xmlHeader
Web.xml DOCTYPE Sevlet name
Web-appelements ------ Servlet Class
Init-parm
Servlet Configuration :
<web-app>
<Servlet>
<Servlet-name>Admin</Servlet-name>
<Servlet-Class>com.ds.AdminServlet</Servlet-class>
</Servlet>
<init-param>
<param-value> </param-value>
<param-name> admin.com</param-name>
</init-param>
<Servlet-mapping>
<Servlet-name>Admin</Servlet-name>
<url-pattern>/Admin</url-pattern>
</Servlet-mapping>
</web-app>
<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>
<assembly-descriptor>
<ejb-jar>
weblogic-ejb-jar.xml
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name> Statefulfinacialcalcu </ejb-name>
<jndi-name> statefulfinacalc </jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
What is CMR
CMR - Container Managed Relationships allows the developer to declare various types of
relationships between the entity beans
What is the difference between CMP 1.1 and CMP 2.0
CMR and sub classing of the CMP bean by the container
What are simple rules that a Primary key class has to follow
Implement the equals and hashcode methods.
How can i retrieve from inside my Bean(Stateless session and Entity CMP) the user name
which i am serving (the user name of user just logged in my web application)
Inside an EJB you may retrieve the "Caller" name, that is the login id by invoking:
sessionContext.getCallerIdentity().getName() where sessionContext is the instance of
"SessionContext" (setSessionContext) passed to the Session Bean, or the instance of
"EntityContext" (setEntityContext) passed to the Entity Bean.
You have Downloaded this file from kamma-Sangam Yahoo Group 124
your entity beans are handled under same transaction. If you're not running in a transaction, a
separate transaction will be set up for each call to your entity beans.
If your session bean is using bean-managed transactions, you can ensure that the calls are
handled in the same transaction by :
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?
Two Entity Beans are said to be Identical,if they have the same home inteface and their
primary keys are the same.To test for this ,you must use the component inteface's isIdentical()
method.
How the abstract classes in CMP are converted into concrete classes?
You have Downloaded this file from kamma-Sangam Yahoo Group 125
EJB2.0 allows developer to create only abstract classes and at the time of deployement the
container creates concrete classes of the abstract. It is easy for container to read abstract classes
and appropriately generate concrete classes.
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
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
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
d Runtime error
e Compile-time error for the bean implementation 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).
You have Downloaded this file from kamma-Sangam Yahoo Group 127
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
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
You have Downloaded this file from kamma-Sangam Yahoo Group 128
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 above, which Transaction Attributes will most likely meet the requirements
stated?
a A-RequiresNew, B-Mandatory
b A-Mandatory, B-RequiresNew
c A-RequiresNew, B-Supports
d A-NotSupported, B-RequiresNew
e A-RequiresNew, B-RequiresNew
-------------------------
--------------------------
You have Downloaded this file from kamma-Sangam Yahoo Group 130