Complete Java&J2 EE
Complete Java&J2 EE
JAVA
Abstraction: Showing the essential and hiding the non-Essential is known as Abstraction.
Encapsulation: The Wrapping up of data and functions into a single unit is known as
Encapsulation.
Encapsulation is the term given to the process of hiding the
implementation details of the object. Once an object is encapsulated,
its implementation details are not immediately accessible any more.
Instead they are packaged and are only indirectly accessed via the
interface of the object.
Inheritance: is the Process by which the Obj of one class acquires the properties of
Objs another Class.
A reference variable of a Super Class can be assign to any Sub
class derived from the Super class.
Inheritance is the method of creating the new class based on
already existing class , the new class derived is called Sub class
which has all the features of existing class and its own, i.e sub class.
Adv: Reusability of code , accessibility of variables and methods of
the Base class by the Derived class.
Polymorphism: The ability to take more that one form, it supports Method Overloading & Method
Overriding.
Method overloading: When a method in a class having the same method name with
different arguments (diff Parameters or Signatures) is said to be Method Overloading. This is
Compile time Polymorphism.
o
Using one identifier to refer to multiple items in the same scope.
Method Overriding: When a method in a Class having same method name with same
arguments is said to be Method overriding. This is Run time Polymorphism.
o Providing a different implementation of a method in a subclass of the class that
originally defined the method.
1. In Over loading there is a relationship between the methods
available in the same class ,where as in Over riding there is relationship
between the Super class method and Sub class method.
2. Overloading does not block the Inheritance from the Super class
, Where as in Overriding blocks Inheritance from the Super Class.
3. In Overloading separate methods share the same name, where
as in Overriding Sub class method replaces the Super Class.
4. Overloading must have different method Signatures , Where as
Overriding methods must have same Signatures.
Dynamic dispatch: is a mechanism by which a call to Overridden
function is resolved at runtime rather than at Compile time , and
this is how Java implements Run time Polymorphism.
Dynamic Binding: Means the code associated with the given procedure call is
not known until the time of call the call at run time. (it is associated with
Inheritance & Polymorphism).
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.
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-bypiece on demand basis.
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
o
o
Interface: Interfaces can be used to implement the Inheritance relationship between the non-related
classes that do not belongs to the same hierarchy, i.e. any Class and any where in hierarchy.
Using
Interface, you can specify what a class must do but not how it does.
A class can implement more than one Interface.
An Interface can extend one or more interfaces, by using the keyword extends.
All the data members in the interface are public, static and Final by default.
An Interface method can have only Public, default and Abstract modifiers.
An Interface is loaded in memory only when it is needed for the first time.
A Class, which implements an Interface, needs to provide the implementation of all the
methods in that Interface.
If the Implementation for all the methods declared in the Interface are not provided ,
the class itself has to declare abstract, other wise the Class will not compile.
If a class Implements two interface and both the Intfs have identical method
declaration, it is totally valid.
If a class implements tow interfaces both have identical method name and argument
list, but different return types, the code will not compile.
An Interface cant be instantiated. Intf Are designed to support dynamic method
resolution at run time.
An interface can not be native, static, synchronize, final, protected or private.
The Interface fields cant be Private or Protected.
A Transient variables and Volatile variables can not be members of Interface.
The extends keyword should not used after the Implements keyword, the Extends must
always come before the Implements keyword.
A top level Interface can not be declared as static or final.
If an Interface species an exception list for a method, then the class implementing the
interface need not declare the method with the exception list.
If an Interface cant specify an exception list for a method, the class cant throw an
exception.
If an Interface does not specify the exception list for a method, he class can not throw
any exception list.
The general form of Interface is
Access interface name {
return-type method-name1(parameter-list);
type final-varname1=value;
}
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
o
o
o
o
Access modifiers
Public
Abstract
Final
Static
Volatile
Constant
Synchronized
Transient
Native
Public : The Variables and methods can be access any where and any package.
Protected : The Variables and methods can be access same Class, same
Package & sub class.
Private : The variable and methods can be access in same class only.
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Same class
Private
Same-package & subclass
Same Package & non-sub classes
Different package & Sub classes
Different package & non- sub classes
Static : access modifier. Signa: Variable-Static int b; Method- static void meth(int x)
When a member is declared as Static, it can be accessed before any objects of its class are created and
without reference to any object. Eg : main(),it must call before any object exit.
Static can be applied to Inner classes, Variables and Methods.
Local variables cant be declared as static.
A static method can access only static Variables. and they cant refer to this or super in any way.
Static methods cant be abstract.
A static method may be called without creating any instance of the class.
Only one instance of static variable will exit any amount of class instances.
Classification : INTERNAL
Package : A Package is a collection of Classes Interfaces that provides a highlevel layer of access protection and name space management.
Finalize( ) method:
All the objects have Finalize() method, this method is inherited from the
Object class.
Finalize() is used to release the system resources other than memory(such
as file handles& network connecs.
Finalize( ) is used just before an object is destroyed and can be called prior
to garbage collection.
Finalize() is called only once for an Object. If any exception is thrown in the
finalize() the object is still eligible for garbage collection.
Finalize() can be called explicitly. And can be overloaded, but only original
method will be called by Ga-collect.
Finalize( ) may only be invoked once by the Garbage Collector when the
Object is unreachable.
The signature finalize( )
:
protected void finalize() throws
Throwable { }
Constructor( ) :
A constructor method is special kind of method that determines how an object is
initialized when created.
Constructor has the same name as class name.
Constructor does not have return type.
Constructor cannot be over ridden and can be over loaded.
Default constructor is automatically generated by compiler if class does not have
once.
If explicit constructor is there in the class the default constructor is not
generated.
If a sub class has a default constructor and super class has explicit constructor
the code will not compile.
Object : Object is a Super class for all the classes. The methods in Object class as follows.
Object clone( )
final void notify( )
Int
hashCode( )
Boolean equals( )
final void notify( )
Void finalize( )
String toString( )
Final Class getClass( )
final void wait( )
Class : The Class class is used to represent the classes and interfaces that are loaded by the JAVA Program.
Classification : INTERNAL
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.
Classification : INTERNAL
Float class : The Float and Double provides the methods isInfinite( )
and isNaN( ).
isInfinite( ) : returns true if the value being tested is infinetly large
or small.
isNaN( ) : returns true if the value being tested is not a number.
Character class : defines forDigit( ) digit( )
ForDigit( ) : returns the digit character associated with the value of
num.
digit( ) : returns the integer value associated with the specified
character (which is presumably) according to the specified radix.
String Tokenizer : provide parsing process in which it identifies the delimiters provided by the
user, by default delimiters are spaces, tab, new line etc., and separates them from the tokens.
Tokens are those which are separated by delimiters.
Observable Class: Objects that subclass the Observable class maintain a list of observers. When
an Observable object is updated it invokes the update( ) method of each of its observers to notify
the observers that it has changed state.
Observer interface : is implemented by objects that observe Observable objects.
Instanceof( ) :is used to check to see if an object can be cast into a specified type with out
throwing a cast class exception.
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.
What is heap in Java
JAVA is fully Object oriented language. It has two phases first
one is Compilation phase and second one is interpratation phase. The
Compilation phase convert the java file to class file (byte code is only
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Exception
Exception handling
Exception can be generated by Java-runtime system or they can be manually
generated by code.
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Exception class : is used for the exceptional conditions that are trapped by the program.
An exception is an abnormal condition or error that occur during the
execution of the program.
Error : the error class defines the conditions that do not occur under normal conditions.
Eg: Run out of memory, Stack overflow error.
Java.lang.Object
+.Java.Lang.Throwable
Throwable
+. Java.lang.Error
|
+. A whole bunch of errors
|
Exception
Error
+.Java.Lang.Exception
(Unchecked, Checked)
+.Java.Lang.RuntimeException
|
+. Various Unchecked Exception
|
+. Various checked Exceptions.
Two types of exceptions:
1. Checked Exceptions : must be declare in the method declaration or
caught in a catch block.
Checked exception must be handled at Compile Time. Environmental error
that cannot necessarly be detected by Testing, Eg: disk full, brocken Socket,
Database unavailable etc.
2. Un-checked Exceptions: Run-time Exceptions and Error, doest have to
be declare.(but can be caught).
Run-time Exceptions : programming errors that should be detectd in Testing ,
Arithmetic, Null pointer, ArrayIndexOutofBounds, ArrayStore, FilenotFound,
NumberFormate, IO, OutofMemory.
Errors: Virtual mechine error class not found , out of memory, no such
method , illegal access to private field , etc.
Classification : INTERNAL
{
}
Finally : when an exception is raised, the statement in the try block is
ignored, some times it is necessary
to process certain statements
irrespective of wheather an exception is raised or not, the finally block is
used for this purpose.
Throw : The throw class is used to call exception explicitly. You may want
to throw an exception when the user enters a wrong login ID and pass
word, you can use throw statement to do so.
The throw statement takes an single argument, which is an Object of
exception class.
Throw<throwable Instance>
If the Object does not belong to a valid exception class the compiler gives
error.
Throws :The throws statement 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>]
Eg: public void accept password( ) throws illegalException
{
System.out.println(Intruder);
Throw new illegalAccesException;
}
Multi Programming
A multithreaded program contains two or more parts that can run
concurrently, Each part a program is called thread and each part that
defines a separate path of excution.
Thus multithreading is a specified from of multitasking.
Classification : INTERNAL
The multiple threads in the process run at the same time, perform
different task and interact with each other.
Daemon Thread : Is a low priority thread which runs immedeatly on the
back ground doing the Garbage Collection operation for the Java Run time
System.
SetDaemon( ) is used to create DaemonThread.
Creating a Thread :
1. By implementing the Runnable Interface.
2. By extending the thread Class.
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 .
Getname() obtain a thread name.
Getname() obtain thread priority.
Start( )
- start a thread by calling a Run( ).
Run( )
- Entry point for the thread.
Sleep( )
- suspend a thread for a period of time.
IsAlive( ) - Determine if a thread is still running.
Join( )
- wait for a thread to terminate.
o
o
o
o
o
o
o
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.
Syntax:
public void <Class-name> extends <SuperClass-name>
implements Runnable
Eg: public Class myapplet extends Japplet implements Runnable
{
// Implement the Class
}
* Runnable interface is the most advantageous method to create
threads because we need not extend thread Class here.
New Thread
--
Runnable
Dead
Classification : INTERNAL
Classification : INTERNAL
Java.io.*;
new
BufferReader(new
2. CharacterStream : File
FileInputStream - Store the contents to the File.
FileOutStream - Get the contents from File.
PrintWrite pw = new printwriter(System.out.true);
Pw.println(
);
Eg :Class myadd
{
public static void main(String args[ ])
{
BufferReader
br
=
new
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
BufferReader(new
Map
class
Hash set
Sorted set
Tree set
List
Array List
Vector List
Linked List
Classification : INTERNAL
Sorted
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.
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.
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 List
Abstract Map
Abstract Set
Abstract
Array List
Map
Tree Map
Sequential
List
Hash Set
Tree Set
Hash
Linked List
List
|
Abstract List
|
Vector
|
Stack
HashSet : Implements Set Interface.
HashSet( );
The elements are not stored in sorted order.
Map
|
Dictonary
|
HashTable
|
Properities
HashSet hs=new
hs.add(m);
Classification : INTERNAL
TreeSet ts=new
TreeSet( );
The
elements
are
stored
in
sorted
ascending
order.
ts.add(H);
Access and retrieval times are quit fast, when storing a large amount
of data.
LinkedList l1=new
LinkedList( );
L1.add(R);
Classification : INTERNAL
automatically- we never see the Hash Code. Also the code cant
directly index into h c.
Enumerator
Enumerator vEnum =
))
while(vEnum.hasMoreElements
Object
element
System.out.println(vEnum.nextElement( ) + );
itr.next(
);
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
|
Abstract List
|
Vector
|
Stack
Map
|
Dictonary
|
HashTable
|
Properities
Classification : INTERNAL
VECTOR :
Vector implements dynamic array.
Vector v = new vector( );
Vector is a growable object.
V1.addElement(new
Integer(1));
Vector is Synchronized, it cant allow special characters and null values.
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.
Constructors : Vector() : Default constructor with initial size 10.
Vector(int size) : Vector whose initial capacity is specified by size.
Vector(int size,int incr)
:Vector whose initialize capacity is
specified by size and whose increment is specified by incr.
Methods :
final void addElement(Object element) : The object specified by
element is added to the vector.
final Object elementAt(int index) : Returns the element at the
location specified by index.
final boolean removeElement(Object element) : Removes
element from the vector
final boolean isEmpty() : Returns true if the vector is empty, false
otherwise.
final int size() : Returns the number of elements currently in the
vector.
final boolean contains(Object element) : Returns true if element
is contained by the vector and false if it is not.
STACK :
Stack is a subclass of Vector that implements a standard last-in,
first-out stack
Constructor : Stack() Creates an empty stack.
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.
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Hashtable()
Hashtable(int size)
Methods :
Object put(Object key,Object value) : Inserts a key and a value
into the hashtable.
Object get(Object key) : Returns the object that contains the
value associated with key.
boolean contains(Object value) : Returns true if the given value
is available in the hashtable. If not, returns false.
boolean containsKey(Object key) : Returns true if the given key
is available in the hashtable. If not, returns false.
Enumeration elements() : Returns an enumeration of the values
contained in the hashtable.
int size() : Returns the number of entries in the hashtable.
Properties
Properties is a subclass of Hashtable
Used to maintain lists of values in which the key is a String and the
value is also a String
Constructors
Properties()
Properties(Properties propDefault) : Creates an object that uses
propDefault for its default value.
Methods :
String getProperty(String key) : Returns the value associated
with key.
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.
Map
Iterator
Classification : INTERNAL
Set
List
|
SortedSet
SortedMap
ListIterator
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:
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 doesnt 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
Classification : INTERNAL
Abstract Set
Hash Set
Tree Set
Hash
Linked List
ArrayList
Similar to Vector: it encapsulates a dynamically reallocated
Object[] array
Why use an ArrayList instead of a Vector?
All methods of the Vector class are synchronized, It is safe to
access a Vector object from two threads.
ArrayList methods are not synchronized, use ArrayList in case of no
synchronization
Use get and set methods instead of elementAt and setElementAt
methods of vector
HashSet
Implements a set based on a hashtable
The default constructor constructs a hashtable with 101 buckets
and a load factor of 0.75
HashSet(int initialCapacity)
HashSet(int initialCapacity,float loadFactor)
loadFactor is a measure of how full the hashtable is allowed to get
before its capacity is automatically increased
Use Hashset if you dont care about the ordering of the elements in
the collection
TreeSet
Similar to hash set, with one added improvement
A tree set is a sorted collection
Insert elements into the collection in any order, when it is iterated,
the values are automatically presented in sorted order
Maps : Two implementations for maps:
HashMap
Classification : INTERNAL
TreeMap
uses a total ordering on the keys to organize them in a search tree
The hash or comparison function is applied only to the keys
The values associated with the keys are not hashed or compared.
How are memory leaks possible in Java
If any object variable is still pointing to some object which is of no
use, then JVM will not garbage collect that object and object will
remain in memory creating memory leak
What are the differences between EJB and Java beans
the main difference is Ejb componenets are distributed which means
develop once and run anywhere. java beans are not distributed.
which means the beans cannot be shared .
What would happen if you say this = null
this will give a compilation error as follows
cannot assign value to final variable this
Will there be a performance penalty if you make a method
synchronized? If so, can you make any design changes to
improve the performance
yes.the performance will be down if we use synchronization.
one can minimise the penalty by including garbage collection
algorithm, which reduces the cost of collecting large numbers of
short- lived objects. and also by using Improved thread
synchronization for invoking the synchronized methods.the invoking
will be faster.
How would you implement a thread pool
public class ThreadPool extends java.lang.Object implements
ThreadPoolInt
This class is an generic implementation of a thread pool, which takes
the following input
a) Size of the pool to be constructed
b) Name of the class which implements Runnable (which has a
visible default constructor)
and constructs a thread pool with active threads that are waiting for
activation. once the threads have finished processing they come back
and wait once again in the pool.
This thread pool engine can be locked i.e. if some internal operation
is performed on the pool then it is preferable that the thread engine
be locked. Locking ensures that no new threads are issued by the
engine. However, the currently executing threads are allowed to
continue till they come back to the passivePool
How does serialization work
Its like FIFO method (first in first out)
How does garbage collection work
There are several basic strategies for garbage collection:
reference counting, mark-sweep, mark-compact, and copying. In
addition, some algorithms can do their job incrementally (the entire
heap need not be collected at once, resulting in shorter collection
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
pauses), and some can run while the user program runs (concurrent
collectors). Others must perform an entire collection at once while
the user program is suspended (so-called stop-the-world collectors).
Finally, there are hybrid collectors, such as the generational collector
employed by the 1.2 and later JDKs, which use different collection
algorithms on different areas of the heap
How would you pass a java integer by reference to another
function
Passing by reference is impossible in JAVA but Java support the
object reference so.
Object is the only way to pass the integer by refrence.
What is the sweep and paint algorithm
The painting algorithm takes as input a source image and a list of
brush sizes. sweep algo is that it computes the arrangement of n
lines in the plane ... a correct algorithm,
Can a method be static and synchronized
no a static mettod can't be synchronised
Do multiple inheritance in Java
Its not possible directly. That means this feature is not provided by
Java, but it can be achieved with the help of Interface. By
implementing more than one interface.
What is data encapsulation? What does it buy you
The most common example I can think of is a javabean.
Encapsulation may be used by creating 'get' and 'set' methods in a
class which are used to access the fields of the object. Typically the
fields are made private while the get and set methods are public.
dEncapsulation can be used to validate the data that is to be
stored, to do calculations on data that is stored in a field or fields, or
for use in introspection (often the case when using javabeans in
Struts, for instance).
What is reflection API? How are they implemented
Reflection package is used mainlyfor the purpose of getting the
class name. by using the getName method we can get name of the
class for particular application .
Reflection is a feature of the Java programming language. It
allows an executing Java program to examine or "introspect" upon
itself, and manipulate internal properties of the program.
What are the primitive types in Java
According to Java in a Nutshell, 5th ed
boolean, byte, char, short, long float, double, int
Is there a separate stack for each thread in Java
No
What is heap in Java
JAVA is fully Object oriented language. It has two phases first
one is Compilation phase and second one is interpratation phase. The
Compilation phase convert the java file to class file (byte code is only
readable format of JVM) than Intepratation phase interorate the class
file line by line and give the proper result.
In Java, how are objects / values passed around
In Java Object are passed by reference and Primitive data is always
pass by value
Do primitive types have a class representation
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
to native code upon first execution, then executes the native code.
Thereafter, whenever the method is called, the native code is
executed. The adaptive optimization technique used by Hotspot is a
hybrid approach, one that combines bytecode interpretation and runtime compilation to native code.
Hotspot, unlike a regular JIT compiling VM, doesn't do "premature
optimization"
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.
What are the disadvantages of reference counting in garbage
collection?
An advantage of this scheme is that it can run in small chunks of
time closely interwoven with the execution of the program. This
characteristic
makes
it particularly
suitable
for
real-time
environments where the program can't be interrupted for very long.
A disadvantage of reference counting is that it does not detect
cycles. A cycle is two or more objects that refer to one another, for
example, a parent object that has a reference to its child object,
which has a reference back to its parent. These objects will never
have a reference count of zero even though they may be
unreachable by the roots of the executing program. Another
disadvantage is the overhead of incrementing and decrementing the
reference count each time. Because of these disadvantages,
reference counting currently is out of favor.
Is it advisable to depend on finalize for all cleanups
The purpose of finalization is to give an opportunity to an
unreachable object to perform any clean up before the object is
garbage collected, and it is advisable.
can we declare multiple main() methods in multiple classes.
ie can we have each main method in its class in our program?
YES
JDBC
How to Interact with DB?
Generally every DB vendor provides a User Interface through
which we can easily execute SQL querys and get the result (For
example
Oracle
Query
Manager
for
Oracle,
and
TOAD
(www.quest.com) tool common to all the databases). And these tools
will help DB developers to create database. But as a programmer we
want to interact with the DB dynamically to execute some SQL
queries from our application (Any application like C, C++, JAVA etc),
and for this requirement DB vendors provide some Native Libraries
(Vendor Specific) using this we can interact with the DB i.e. If you
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
ODBC API
C function calls
Oracle DSN
Sybase ODBC
SP API
SP API
SP API
Oracle
SQL server
Sybase
Oracle ODBC
My DSN
SQL Server DSN
Sybase DSN
SQL S
Sy
Sybase ODBC
Our DSN
Advantages
Single API (Protocol) is used to interact with any DB
Switching from one DB to another is easy
Doesnt require any modifications in the Application when
you want to shift from one DB to other.
What for JDBC?
As we have studied about ODBC and is advantages and came
to know that it provides a common API to interact with any DB which
has an ODBC Service Providers Implementation written in Native API
that can be used in your applications.
If an application wants to interact with the DB then the options
which have been explained up to now in this book are:
1. Using Native Libraries given by the DB vendor
2. Using ODBC API
And we have listed there Advantages and Disadvantages.
But if the application is a JAVA application then the above given
options are not recommended to be used due to the following
reasons
1. Native Libraries given by DB vendor
a. Application becomes vendor dependent and
Classification : INTERNAL
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
JDBC Application
1. JDBC Core API
S
2. JDBC Extension or Optional API
PA
PI JDBC
JDBC Core API (java.sql package)
This part of API deals with the following futures API
1. Establish a connection to a DB
2. Getting DB Details
JDBC Driver
3. Getting Driver Details
4. maintaining Local Transaction
SPAPI
5. executing querys
6. getting results (ResultSet)
7. preparing pre-compiled SQL querys and executing
8. executing procedures & functions
MS SQL Server DB
Oracle
DB API (javax.sql package)
JDBC Ext OR
Optional
This part of API deals with the following futures
1. Resource
Objects
with
Distributed
Transaction
Management support
SP I
2. Connection Pooling.
AP
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 components given under J2SE and J2EE.
JDBC Architecture:
Classification : INTERNAL
JAVA
Application
JDBC
ODBC
Driver
Native
ODBC
Client
driver
Libraries
DBMS
DBMS
Interface
client
libraries
DBMS
Interface
Server
Libraries
Classification : INTERNAL
Disadvantages
More number of layers between the application and DB.
And more number of API conversions leads to the downfall
of the performance.
Slower than type-2 driver
Where to use?
This type of drivers are generaly used at the development time to
test your applications.
Because of the disadvantages listed above it is not used at
production time. But if we are not available with any other type of
driver implementations for a DB then we are forced to use this type
of driver (for example Microsoft Access).
Examples of this type of drivers
JdbcOdbcDriver from sun
Suns JdbcOdbcDriver is one of type-1 drivers and comes along with
sun j2sdk (JDK).
Setting environment to use this driver
11 Software
ODBC libraries has to be installed.
11 classpath
No additional classpath settings are required apart from the
runtime jar (c:\j2sdk1.4\jre\lib\rt.jar) which is defaultly
configured.
11 Path
No additional path configuration is required.
How to use this driver
Driver class name sun.jdbc.odbc.JdbcOdbcDriver
Driver URL dbc:odbc:<DSN>
here <DSN> (Data Source Name) is an ODBC datasource
name which is used by ODBC driver to locate one of the ODBC
Service Provider implementation API which can in-turn
connect to DB.
Steps to create <DSN>
1. run Data Sources (ODBC) from Control
Panal\Administrative Tools\
(for Windows 2000 server/2000 professional/XP)
run ODBC Data Sources from Control Panel\
2. click on Add button available on the above displayed screen. this
opens a new window titled Create New Data Source which
displays all the available DBs lable DBs ODBC drivers currently
installed on your system.
3. Select the suitable driver and click on Finish
4. Give the required info to the driver (like username, service id etc)
Type-2 : Native API Partly JAVA Driver (Thick Driver) :
JDBC Database calls are translated into
Vendor-specific API calls. The database will process the request and
send the results back through API to JDBC Driver this will translate
the results to the JDBC standard and return them to the Java
application.
The Vendor specific language API must be installed on every
client
that runs the
JAVA application.
JDBC
JDBC Type II
JDBC
DBMS Client
SP API
Architecture
API
Application
libraries (native)
Driver
SP
N/W
You have Downloaded this file from kamma-Sangam Yahoo Group
Libra
2
Classification : INTERNAL
ries
OCI
DBMS Server
DBMS
Libraries
libraries (native)
This driver converts the JDBC call given by the Java application to a
DB specific native call (i.e. to C or C++) using JNI (Java Native
Interface).
Advantages :Faster than the other types of drivers due to native
library participation in socket programing.
Disadvantage : DB spcifiic native client library has to be installed in
the client machine.
Preferablly work in local network environment because
network service name must be configured in client system
Where to use?
This type of drivers are suitable to be used in server side
applications.
Not recommended to use with the applications using two tire model
(i.e. client and database layers) because in this type of model client
used to interact with DB using the driver and in such a situation the
client system sould have the DB native library.
Examples of this type of drivers
1. OCI 8 (Oracle Call Interface) for Oracle implemented by Oracle
Corporation.
Setting environment to use this driver
Software: Oracle client software has to be installed in
client machine
classpath
%ORACLE_HOME
%\ora81\jdbc\lib\classes111.zip
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 dlls 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
How to use this driver
Driver class name
weblogic.jdbc.oci.Driver
Classification : INTERNAL
Driver URL
jdbc:weblogic:oracle:HostName
JDBC
Application
JDBC
API
Net protocol
DBMS Interface
DBMS
DBMS API
Server
Listener
OCI Libraries
Middleware
Listener
DBMS Interface
Client
C:\IDSServer\classes\jdk14drv.jar
path
Classification : INTERNAL
Driver URL
dsn='IDSExamples'
jdbc:ids://localhost:12/conn?
JDBC API
Native Protocol
DBMS Interface
Server Listener
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.
Examples of this type of drivers
1) Thin driver for Oracle implemented by Oracle Corporation
Setting environment to use this driver
classpath
%ORACLE_HOME
%\ora81\jdbc\lib\classes111.zip
How to use this driver
Driver class name
oracle.jdbc.driver.OracleDriver
Driver URL
jdbc:oracle:thin:@HostName:<port
no>:<SID>
<port no> 1521
<SID> -> ORCL
2) MySQL Jconnector for MySQL database
Setting environment to use this driver
classpath
C:\mysql\mysql-connector-java3.0.8-stable\mysql-connector-java-3.0.8-stable-bin.jar
How to use this driver
Driver class name
Driver URL
com.mysql.jdbc.Driver
jdbc:mysql:///test
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
try {
// Load driver class into default ClassLoader
Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
// Obtain a connection with the loaded driver
con
=DriverManager.getConnection
("jdbc:odbc:digitalbook","scott","tiger");
URL
String
("<protocol>:<subprotocol>:<subname>", " ", " " ); }
// create a statement
st=con.createStatement();
//execute SQL query
rs =st.executeQuery ("select ename,sal from emp");
System.out.println ("Name
Salary");
System.out.println ("--------------------------------");
while(rs.next())
{
System.out.println
(rs.getString(1)+"
"+rs.getString(2));
}
rs.close ();
stmt.close ();
con.close ();
}
catch(Exception e)
{
e.printStackTrace ();
}
}
public static void main (String args[])
{
TypeIDriverTest demo=new TypeIDriverTest ();
}
}
// 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())
{
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
System.out.println
(rs.getString(1)+"
"+rs.getString(2));
}
rs.close ();
stmt.close ();
con.close ();
}
catch(Exception e)
{
e.printStackTrace ();
}
}
public static void main (String args[])
{
TypeIIDriverTest demo=new TypeIIDriverTest ();
}
}
Chapter 9 :
[javax.sql package]
This package supplements the java.sql package and is included as a
part of JDK 1.4 version. This package mainly provides following
features:
1. DataSource interface was introduced in substitution to
DriverManager class for getting connection objects.
2. Connection Pooling
3. Distributed TX management
4. RowSets
Applications can directly use DataSource and RowSet API but
connection pooling and Distributed TX management APIs are used
internally by the middle-tier infrastructure.
DataSource
DataSource is an interface. Driver vendor will provide
implementation for this interface (That means in case JDBC Driver
Type II driver Oracle vendor for Oracle DB, Intersolv in case of
IDSServer). This object is used to obtain connections into any type of
JDBC program. Though DriverManager class is ideal for getting DB
connection object, this class provides some extra features over
DriverManager class:
Applications will obtain DB connection objects through via this factory class
DataSource object will be registered into JNDI, hence any application
connected in the network can obtain this object by requesting JNDI API,
DataSource class is having one method called getConnection() geives one
Connection object
Application do not need to hard code a driver class
Changes can be made to a data source properties, which means that it is
not necessary to make changes in application code when something about
the data source or driver changes
Connection pooling and Distributed transactions are available through only
the connection obtained from this object. Connection obtained through
DriverManager class do not have this capability
DataSource interface is implemented by driver vendor. There are 3
types of implementations available:
11 Basic Implementation- Produces a standard connection
object.
11 Connection Pooling Implementation- Produces a
connection
object
that
automatically
participates
in
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
connection pooling. This implementation works with a middletier connection pooling manager.
11 Distributed transaction implementation- Produces a
connection object that may be used for distributed
transactions and almost always participates in connection
pooling. This implementation works with a middle-tier
transaction manager and almost always with a connection
pool manager.
A driver that is accessed via a DataSource object does not register
itself with the DriverManager. Rather, a DataSource object is
retrieved though a lookup operation and then used to create a
Connection object. With a basic implementation, the connection
obtained through a DataSource object is identical to a connection
obtained through the DriverManager facility.
Method Index
Connection getConnection()
This function
returns
Connection object on demand of this method.
Connection getConnection(String user, String pass) This
function returns Connection object on demand of this method
by passing username and password.
Sub classes of this interface are
Type III Driver IDSServer Intersolv ids.jdbc.IDSDataSource
Type III Driver WebLogic BEA weblogic.jdbc.jta.DataSource
XA Support
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
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
o
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.
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.
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.
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
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
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Type
III
Driver
WebLogic
weblogic.jdbc.connector.internal.ConnectionPool
Type II & IV driver Oracle DB - Oracle
BEA
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
Loading the Driver:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Conn=DriverManager.getConnection(jdbc:odbc:dsn, username,
password);
( ORACLE Driver )
Class.forName(Oracle.jdbc.driver.OracleDriver);
Conn=DriverManager.getConnection(jdbc:oracle:thin:@192.168.1.105
:1521:dbn, username, password);
Data base connection:
Public static void main(String args[]);
Connection con;
Statement st;
Resultset rs;
try {
// Getting all rows from Table
Clas.forName(sun.jdbc.odbc.jdbcodbc);
Conn=DriverManager.getConnction(jdbc.odbc.dsn, username ,
password);
st = con.createstatement( );
rs = st.executestatement(SELECT * FROM mytable);
while(rs.next());
{
String s= rs.getString(1); or rs.setString(COL_A);
int i = rs. getInt(2);
Float f = rs.getfloat(3);
Process(s,i,f);
}
catch(SQLException e)
{}
//Getting particular rows from Table
st = con.createstatement( );
rs = st.executequery(SELECT * FROM mytable WHERE COL A =
Prasad);
while(rs.next( ));
{
String s = rs.getString(1);
Int i = rs.getint(2);
Float f = rs.getfloat(3);
Process(s,i,f);
}
Catch(SQLException e); { }
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
The RowSet is different than other JDBC interfaces in that you can
write a RowSet to be vendor neutral. A third party could write a
RowSet implementation that could be used with any JDBC-compliant
database. The standard implementation supplied by Sun uses a
ResultSet to read the rows from a database and then stores those
rows as Row objects in a Vector inside the RowSet. In fact, a RowSet
implementation could be written to get its data from any source. The
only requirement is that the RowSet acts as if it was a ResultSet. Of
course, there is no reason that a vendor couldn't write a RowSet
implementation that is vendor specific.
The standard implementations have been designed to
provide a fairly good range of functionality. The implementations
provided are:
CachedRowSetImpl - This is the implementation of the RowSet
that is closest to the definition of RowSet functionality that we
discussed earlier. There are two ways to load this RowSet. The
execute ( ) method will load the RowSet using a Connection object.
The populate( ) method will load the RowSet from a previously
loaded ResultSet.
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.
JdbcRowSetImpl - This is a different style of implementation that is
probably less useful in normal circumstances. The purpose of this
RowSet is to make a ResultSet look like a JavaBean. It is not
serializable and it must maintain a connection to the database.
The remaining two implementations are used with the first three
implementations:
FilteredRowSetImpl - This is used to filter data from an existing
RowSet. The filter will skip records that don't match the criteria
specified in the filter when a next() is used on the RowSet.
JoinRowSetImpl - This is used to simulate a SQL join command
between two or more RowSet objects.
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.
DataSource.getConnection method will return Connection
object to the database
What is Connection Pooling ?
Connection pooling is a cache of data base connections that is
maintained in memory , so that the connections may be reuse.
Connection pooling is a place where a set of connections are
kept and are used by the different programers with out creating
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
SERVLETS
Web Components
Servlets
Java Server Pages (JSP)
Tags and Tag Libraries
Whats a Servlet?
Javas answer to CGI programming
Program runs on Web server and builds pages on the fly
When would you use servlets?
Data changes frequently e.g. weather-reports
Page uses information from databases e.g. on-line stores
Page is based on user-submitted data e.g search engines
Data changes frequently e.g. weather-reports
Page uses information from databases e.g. on-line stores
Page is based on user-submitted data e.g search engines
Servlet Class Hierarchy
javax.servlet.Servlet
Defines methods that all servlets must implement
init()
service()
destroy()
javax.servlet.GenericServlet
Defines a generic, protocol-independent servlet
javax.servlet.http.HttpServlet
To write an HTTP servlet for use on the Web
doGet()
doPost()
javax.servlet.ServletConfig
A servlet configuration object
Passes information to a servlet during initialization
Servlet.getServletConfig()
javax.servlet.ServletContext
To communicate with the servlet container
Contained within the ServletConfig object
ServletConfig.getServletContext()
javax.servlet.ServletRequest
Provides client request information to a servlet
javax.servlet.ServletResponse
Sending a response to the client
Basic Servlet Structure
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Hello World extends HttpServlet {
// Handle get request
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classes
Genericservlet
Classification : INTERNAL
ServletRequest
ServletResponce
ServletConfig
ServletContext
SingleThreadModel
ServletInputStream
ServletOutputStream
ServletException
UnavailableException
-
Javax.Servlet.Http
HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionContext
HttpSessionBindingListener
Classes
Cookie
HttpServlet
HttpSessionBindingEvent
HttpUtils
-
Exceptions
ServletException
UnavailableException
SERVLETS
What is the servlet?
Servlets are modules that extend request/response-oriented
servers, such as Java-enabled web servers. For example, a servlet
may be responsible for taking data in an HTML order-entry form and
applying the business logic used to update a company's order
database.
-Servlets are used to enhance and extend the functionality of
Webserver.
-Servlets handles Java and HTML separately.
What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can
synchronize requests. This allows servlets to support systems such
as on-line conferencing. Servlets can forward requests to other
servers and servlets. Thus servlets can be used to balance load
among several servers that mirror the same content, and to partition
a single logical service over several servers, according to task.
What are th characters of Servlet?
As Servlet are written in java, they can make use of extensive
power
of
the
JAVA API,such
as
networking
and
URL
access,multithreading,databaseconnectivity,RMI object serialization.
Efficient : The initilazation code for a servlet is executed only once,
when the servlet is executed for the first time.
Robest :
provide all the powerfull features of JAVA, such as
Exception handling and garbage collection.
Portable: This enables easy portability across Web Servers.
Persistance : Increase the performance of the system by executing
features data access.
What is the difference between JSP and SERVLETS
Servlets : servlet tieup files to independitently handle the static
presentation logic and dynamic business logic , due to this a changes
made to any file requires recompilation of the servlet.
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
-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( )
If services() are both for get and post methods.
-So if u want to use post method in html page,we use doPost() or
services() in servlet class.
-if want to use get methods in html page,we can use doGet() or services()
in servlet calss.
-Finally destory() is used to free the object.
What is the difference between ServletContext and ServletConfig?
Both are interfaces.
Servlet Config():The servlet engine implements the ServletConfig
interface in order to pass configuration information to a servlet. The
server passes an object that implements the ServletConfig interface
to the servlet's init() method.
A ServletConfig object passes configuration information from the
server to a servlet. ServletConfig also includes ServletContext object.
getParameter( ) , getServletContext( ) , getServletConfig( ),
GetServletName( )
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( )
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.
If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following
translation error:
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
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.
What information that the ServletRequest interface allows the servlet access to?
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
the
Classification : INTERNAL
-After executing the SendRedirect( ) the control will not return back
to same method.
-The Client receives the Http response code 302 indicating that
temporarly the client is being redirected to the specified location , if
the specified location is relative , this method converts it into an
absolute URL before redirecting.
-The SendRedirect( ) will come to the Client and go back,.. ie URL
appending will happen.
Response. SendRedirect( absolute path);
Absolutepath other than application ,
relative path - same
application.
When you invoke a forward request, the request is sent to
another resource on the server, without the client being informed
that a different resource is going to process the request. This process
occurs completely with in the web container. When a sendRedirtect
method is invoked, it causes the web container to return to the
browser indicating that a new URL should be requested. Because the
browser issues a completely new request any object that are stored
as request attributes before the redirect occurs will be lost. This
extra round trip a redirect is slower than forward.
do we have a constructor in servlet ? can we explictly provide a constructor in servlet programme
as in java program ?
We can have a constructor in servlet .
Session : A session is a group of activities that are performed by a
user while accesing a particular website.
Session Tracking :The process of keeping track of settings across
session is called session tracking.
Hidden Form Fields : Used to keep track of users by placing hidden
fields in the form.
-The values that have been entered in these fields are sent to the
server when the user submits the Form.
URL-rewriting : this is a technique by which the URL is modified to
include the session ID of a particular user and is sent back to the
Client.
-The session Id is used by the client for subsequent transactions
with the server.
Cookies : Cookies are small text files that are used by a webserver
to keep track the Users.
A cookie is created by the server and send back to the client , the
value is in the form of Key-value pairs. Aclient can accept 20 cookies
per host and the size of each cookie can be maximum of 4 bytes
each.
HttpSession : Every user who logs on to the website is
autometacally associated with an HttpSession Object.
-The Servlet can use this Object to store information about the users
Session.
-HttpSession Object enables the user to maintain two types of Data.
ie State and Application.
How to communicate between two servlets?
Two ways:
a. Forward or redirect from one Servlet to another.
b. Load the Servlet from ServletContext and access methods.
How to get one Servlet's Context Information in another Servlet?
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Access or load the Servlet from the Servlet Context and access the
Context Information
The following code snippet demonstrates the invocation of a JSP error page from within a
controller servlet:
protected void sendErrorRedirect(HttpServletRequest request,
HttpServletResponse response, String errorPageURL, Throwable e) throws
ServletException, IOException {
request.setAttribute ("javax.servlet.jsp.jspException", e);
getServletConfig().getServletContext().
getRequestDispatcher(errorPageURL).forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse
response)
{
try {
// do something
} catch (Exception ex) {
try {
sendErrorRedirect(request,response,"/jsp/MyErrorPage.jsp",ex);
} catch (Exception e) {
e.printStackTrace();
}
} }
Classification : INTERNAL
Classification : INTERNAL
jsp:include
jsp:forward
jsp:param
jsp:plugin
Scriptlets
Of form <% /* code goes here*/ %>
Gets copied into _ jspService method of generated servlet
Any valid Java code can go here
CODE:
<% int j; %>
<% for (j = 0; j < 3; j++) {%>
<value>
<% out. write(""+ j); %>
</ value><% } %>
OUTPUT
<value> 0</ value>
<value> 1</ value>
<value> 2</ value>
int j = 0;
void _jspService() {}
}
Declarations (<%! %>)
Used to declare class scope variables or methods
<%! int j = 0; %>
Gets declared at class- level scope in the generated servlet
int j = 0;
void _jspService() {}
}
Classification : INTERNAL
<table
width="500"
cellspacing="0"
cellpadding="3"
border="0">
<caption>Enter your name</caption>
<tr><td><b>Name</b></td><td><INPUT
size="20"
maxlength="20" TYPE="text" NAME="name"></td></tr>
</table>
<INPUT TYPE='SUBMIT' NAME='Submit' VALUE='Submit'>
<INPUT TYPE='hidden' NAME='catch' VALUE='yes'>
</FORM></BODY></HTML>
Generated Servlet
public void _jspService(HttpServletRequest request ,
HttpServletResponse response)
throws ServletException ,IOException {
out.write("<HTML><HEAD><TITLE>Hello.jsp</TITLE></HEAD><B
ODY>" );
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..
}
}
Tags & Tag Libraries
What Is a Tag Library?
JSP technology has a set of pre- defined tags
<jsp: useBean />
These are HTML like but
have limited functionality
Can define new tags
Look like HTML
Can be used by page authors
Java code is executed when tag is encountered
Allow us to keep Java code off the page
Better separation of content and logic
May Have Tags To
Process an SQL command
Parse XML and output HTML
Automatically call into an EJB component (EJB technologybased component)
Get called on every request to initialize script variables
Iterate over a ResultSet and display the output in an HTML table
Classification : INTERNAL
implements
BodyTag
Interface
BodyTagSupport
class
Simple Tag Example :
<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
-----------attr2=value2
----------->
-----------This tags's body
</ prefix:tagName>-----------Implementation of JSP page will use
action on page.
setAttr1(value1)
setAttr2(value2)
doStartTag()
doEndTag()
the tag handler for each
Summary
Classification : INTERNAL
Classification : INTERNAL
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/webjsptaglibrary_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
/WEBINF/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
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 getInitParametermethod 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
2. response:The response object represents the servers response to
request.
javax.servlet
3. pageContext : The page context specifies the single entry point
to many of the page attributes and is the convient place to put
shared data.
javax.servlet.jsp.pagecontext
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
But if its real time u can use DAO design patterns which is
widely used. for ex u write all ur connection object and and sql quires
in a defiened method later use transfer object [TO ]which is all ur
fields have get/set methods and call it in business object[BO] so DAO
is accessd with precaution as it is the crucial. Finally u define java
bean which is a class holding get/set method implementing
serialization thus the bean is called in the jsp. So never connect to
jdbc directly from client side since it can be hacked by any one to get
ur password or credit card info.
How do you call stored procedures from JSP
By using callable statement we can call stored procedures and
functions from the database.
How do you restrict page errors display in the JSP page
set isErrorPage=false
How do you pass control from one JSP page to another
we can forward control to aother jsp using jsp action tags forward
or incllude
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 does a servlet communicate with a JSP page?
The following code snippet shows how a servlet instantiates a
bean and initializes it with FORM data posted by a browser. The bean
is then placed into the request, and the call is then forwarded to the
JSP page, Bean1.jsp, by means of a request dispatcher for
downstream processing.
public void doPost (HttpServletRequest request, HttpServletResponse
response)
{
try {
govi.FormBean f = new govi.FormBean();
String id = request.getParameter("id");
f.setName(request.getParameter("name"));
f.setAddr(request.getParameter("addr"));
f.setAge(request.getParameter("age"));
//use the id to compute
//additional bean properties like info
//maybe perform a db query, etc.
// . . .
f.setPersonalizationInfo(info);
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
request.setAttribute("fBean",f);
getServletConfig().getServletContext().getRequestDispatcher
("/jsp/Bean1.jsp").forward(request, response);
} catch (Exception ex) {
...
}}
The JSP page Bean1.jsp can then process fBean, after first extracting
it from the default request scope via the useBean action.
jsp:useBean id="fBean" class="govi.FormBean" scope="request"/
jsp:getProperty name="fBean" property="name" /
jsp:getProperty name="fBean" property="addr" /
jsp:getProperty name="fBean" property="age" /
jsp:getProperty name="fBean" property="personalizationInfo" /
Is there a way I can set the inactivity lease period on a persession basis?
Typically, a default inactivity lease period for all sessions is set
within your JSPengine admin screen or associated properties file.
However, if your JSP engine supports the Servlet 2.1 API, you can
manage the inactivity lease period on a per-session basis. This is
done by invoking the HttpSession.setMaxInactiveInterval() method,
right after the session has been created.
For example:
<% session.setMaxInactiveInterval(300); %>
would reset the inactivity period for this session to 5 minutes. The
inactivity interval is set in seconds.
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 declare methods within my JSP page?
You can declare methods for use within your JSP page as
declarations. The methods can then be invoked within any other
methods you declare, or within JSP scriptlets and expressions.
Do note that you do not have direct access to any of the JSP implicit
objects like request, response, session and so forth from within JSP
methods. However, you should be able to pass any of the implicit JSP
variables as parameters to the methods you declare.
For example:
<%!
public String whereFrom(HttpServletRequest req) {
HttpSession ses = req.getSession();
...
return req.getRemoteHost();
}
%>
<%
out.print("Hi there, I see that you are coming in from ");
%>
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
<%
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.
<jsp:useBean id="foo" class="com.Bar.Foo" >
<jsp:setProperty name="foo" property="today"
value="<%=java.text.DateFormat.getDateInstance().format(new
java.util.Date())
%>"/ >
<%-- scriptlets calling bean setter methods go here --%>
</jsp:useBean >
How does JSP handle run-time exceptions?
You can use the errorPage attribute of the page directive to have
uncaught runtime exceptions automatically forwarded to an error
processing page.
For example:
<%@ page errorPage="error.jsp" %>
redirects the browser to the JSP page error.jsp if an uncaught
exception is encountered during request processing. Within error.jsp,
if you indicate that it is an error-processing page, via the directive:
<%@ page isErrorPage="true" %>
the Throwable object describing the exception may be accessed
within the error page via the exception implicit object.
Note: You must always use a relative URL as the value for the
errorPage attribute.
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
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the
proxy server
%>
How do I use comments within a JSP page
You can use "JSP-style" comments to selectively block out code
while debugging or simply to comment your scriptlets. JSP comments
are not visible at the client.
For example:
<%-- the scriptlet is now commented out
<%
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
out.println("Hello World");
%>
--%>
You can also use HTML-style comments anywhere within your JSP
page. These comments are visible at the client. For example:
<!-- (c) 2004 javagalaxy.com -->
Of course, you can also use comments supported by your JSP
scripting language within your scriptlets. For example, assuming Java
is the scripting language, you can have:
<%
//some comment
/**
yet another comment **/ %>
Can I stop JSP execution while in the midst of processing a
request?
Yes. Preemptive termination of request processing on an error
condition is a good way to maximize the throughput of a highvolume JSP engine. The trick (asuming Java is your scripting
language) is to use the return statement when you want to terminate
further processing. For example, consider:
<% if (request.getParameter("foo") != null) {
// generate some html or update bean property
} else {
/* output some error message or provide redirection back to the
input form after creating a memento bean updated with the 'valid'
form elements that were input. This bean can now be used by the
previous form to initialize the input elements that were valid then,
return from the body of the _jspService() method to terminate
further processing */
return;
}
%>
Is there a way to reference the "this" variable within a JSP
page?
Yes, there is. Under JSP 1.0, the page implicit object is equivalent
to "this", and returns a reference to the servlet generated by the JSP
page.
How do I perform browser redirection from a JSP page?
You can use the response implicit object to redirect the browser to a
different resource, as:
response.sendRedirect("http://www.exforsys.com/path/erro
r.html");
You can also physically alter the Location HTTP header attribute, as
shown below:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMA
NENTLY);
String newLocn = "/newpath/index.html";
response.setHeader("Location",newLocn);
%>
You can also use the: <jsp:forward page="/newpage.jsp" /> Also
note that you can only use this before any output has been sent to
the client. I beleve this is the case with the response.sendRedirect()
method as well. If you want to pass any paramateres then you can
pass using
<jsp:forward
page="/servlet/login">
<jsp:param
name="username" value="HARI" /> </jsp:forward>
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
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
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
e.
f.
g.
h.
Action objects
Action Form objects
Action mappings
Configuring web.xml file and struts-config.xml file
3. Struts
a.
b.
c.
d.
e.
f.
g.
View components
Composite View
Building page from templates
Jsp:include Vs struts template mechanism
Bean tags
Html tags
Logic tags
Template tags
4. Struts
a.
b.
c.
Controller components
Action classes
ActionServlet
Struts data source
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
The Model maintains the state and data that the application
represents .
The View allows the display of information about the model
to the user.
Classification : INTERNAL
Secur
i
t
y
UI Components
UI Process Components
Opera
t
Commun
i
i
ona
ca
l management
t
i
on
Service Interfaces
Business
Workflows
Business
Components
Business
Entities
Service Agents
Services
Data Sources
Controller Servlet
If()
If()
User
Reg JSP
You have Downloaded this file from kamma-Sangam Yahoo Group
Confirm.jsp
Error.jsp
Classification : INTERNAL
11
11
11
11
11
11
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.
JSP Model 1 Architecture
Classification : INTERNAL
Servlet
Servlet
Controller
User
Pass
Validator
3
Login
Browser
Servlet
Model
JSP
View
Beans
11
11
11
11
Classification : INTERNAL
11
11
11
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
Action
Servlet
Strutsconfig.xml
Classification : INTERNAL
J2EE
Component
(EJB)
7
Success
Response
Error
Response
ActionForm
DB
Action
Legac
y code
Front Controller
Context
The presentation-tier request handling mechanism must control
and coordinate processing of each user across multiple requests.
Such control mechanisms may be managed in either a centralized or
decentralized manner.
Problem
The system requires a centralized access point for presentationtier 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 viewsbecause that approach may lead to a more error-prone, reuse-bycopy- and-paste environment.
Typically, a controller coordinates with a dispatcher component.
Dispatchers are responsible for view management and navigation.
Thus, a dispatcher chooses the next view for the user and vectors
control to the resource. Dispatchers may be encapsulated within the
controller directly or can be extracted into a separate component.
While the Front Controller pattern suggests centralizing the
handling of all requests, it does not limit the number of handlers in
the system, as does a Singleton. An application may use multiple
controllers in a system, each mapping to a set of distinct services.
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Structure
Below figure represents the Front Controller class diagram pattern.
Classification : INTERNAL
Classification : INTERNAL
processConte
nt
processNoCac
he
processPrepro
cess
processMappi
ng
processRoles
processAction
Form
processPopula
te
processValida
te
processForwa
rd
processInclud
e
processAction
Create
processAction
Perform
processForwa
rdConfig
Action class
The Action class defines two methods that could be executed
depending on your servlet environment:
public ActionForward execute(ActionMapping mapping,
ActionForm form,
ServletRequest request,
ServletResponse response)
throws Exception;
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
Don't throw it, catch it! - Ever used a commercial website only to have a stack trace or
exception thrown in your face after you've already typed in your credit card number and
clicked the purchase button? Let's just say it doesn't inspire confidence. Now is your chance
to deal with these application errors - in the Action class. If your application specific code
throws expections you should catch these exceptions in your Action class, log them in your
application's log (servlet.log("Error message", exception)) and return the appropriate
ActionForward.
It is wise to avoid creating lengthy and complex Action classes. If
you start to embed too much logic in the Action class itself, you will
begin to find the Action class hard to understand, maintain, and
impossible to reuse. Rather than creating overly complex Action
classes, it is generally a good practice to move most of the
persistence, and "business logic" to a separate application layer.
When an Action class becomes lengthy and procedural, it may be a
good time to refactor your application architecture and move some of
this logic to another conceptual layer; otherwise, you may be left
with an inflexible application which can only be accessed in a webapplication 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
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
ways Struts can be used, the MailReader application does not always
follow best practices.
Action mapping implementation
In order to operate successfully, the Struts controller servlet needs to
know several things about how each request URI should be mapped
to an appropriate Action class. The required knowledge has been
encapsulated in a Java class named ActionMapping, the most
important properties are as follows:
o
o
o
o
o
o
type - Fully qualified Java class name of the Action implementation class used by this
mapping.
name - The name of the form bean defined in the config file that this action will use.
path - The request URI path that is matched to select this mapping. See below for examples
of how matching works and how to use wildcards to match multiple request URIs.
unknown - Set to true if this action should be configured as the default for this application, to
handle all requests not handled by another action. Only one action can be defined as a
default within a single application.
validate - Set to true if the validate method of the action associated with this mapping should
be called.
forward - The request URI path to which control is passed when this mapping is invoked. This
is an alternative to declaring a type property.
Classification : INTERNAL
<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.
Action Mapping Example
Here's a mapping entry based on the MailReader example
application. The MailReader application now uses DynaActionForms.
But in this example, we'll show a conventinal ActionForm instead, to
illustrate the usual workflow. Note that the entries for all the other
actions are left out:
<struts-config>
<form-beans>
<form-bean
name="logonForm"
type="org.apache.struts.webapp.example.LogonForm" />
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
</form-beans>
<global-forwards
type="org.apache.struts.action.ActionForward">
<forward
name="logon"
path="/logon.jsp"
redirect="false" />
</global-forwards>
<action-mappings>
<action
path ="/logon"
type ="org.apache.struts.webapp.example.LogonAction"
name ="logonForm"
scope ="request"
input ="/logon.jsp"
unknown="false"
validate="true" />
</action-mappings>
</struts-config>
First the form bean is defined. A basic bean of class
"org.apache.struts.webapp.example.LogonForm" is mapped to the
logical name "logonForm". This name is used as a request attribute
name for the form bean.
The "global-forwards" section is used to create logical name
mappings for commonly used presentation pages. Each of these
forwards is available through a call to your action mapping instance,
i.e. mapping.findForward("logicalName").
As you can see, this mapping matches the path /logon (actually,
because the MailReader example application uses extension
mapping, the request URI you specify in a JSP page would end in
/logon.do). When a request that matches this path is received, an
instance of the LogonAction class will be created (the first time only)
and used. The controller servlet will look for a bean in request scope
under key logonForm, creating and saving a bean of the specified
class if needed.
Optional but very useful are the local "forward" elements. In
the MailReader example application, many actions include a local
"success" and/or "failure" forward as part of an action mapping.
<!-- Edit mail subscription -->
<action
path="/editSubscription"
type="org.apache.struts.webapp.example.EditSubscriptionAction"
name="subscriptionForm"
scope="request"
validate="false">
<forward
name="failure"
path="/mainMenu.jsp"/>
<forward
name="success"
path="/subscription.jsp"/>
</action>
Using just these two extra properties, the Action classes are
almost totally independent of the actual names of the presentation
pages. The pages can be renamed (for example) during a redesign,
with negligible impact on the Action classes themselves. If the names
of the "next" pages were hard coded into the Action classes, all of
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
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"/>
...
</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.
Classification : INTERNAL
Classification : INTERNAL
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/do/*</url-pattern>
</servlet-mapping>
which means that a request URI to match the /logon path described
earlier might look like this:
http://www.mycompany.com/myapplication/do/logon
where /myapplication is the context path under which your
application is deployed.
Extension mapping, on the other hand, matches request URIs to the
action servlet based on the fact that the URI ends with a period
followed by a defined set of characters. For example, the JSP
processing servlet is mapped to the *.jsp pattern so that it is called
to process every JSP page that is requested. To use the *.do
extension (which implies "do something"), the mapping entry would
look like this:
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
and a request URI to match the /logon path described earlier
might look like this:
http://www.mycompany.com/myapplication/logon.do
WARNING - Struts will not operate correctly if you define more than
one <servlet-mapping> element for the controller servlet.
WARNING - If you are using the new module support in Struts 1.1,
you should be aware that only extension mapping is supported.
Configure the Struts Tag Libraries
Next, you must add an entry defining the Struts tag library.
The struts-bean taglib contains tags useful in accessing beans and
their properties, as well as defining new beans (based on these
accesses) that are accessible to the remainder of the page via
scripting variables and page scope attributes. Convenient
mechanisms to create new beans based on the value of request
cookies, headers, and parameters are also provided.
The struts-html taglib contains tags used to create struts input
forms, as well as other tags generally useful in the creation of HTMLbased user interfaces.
The struts-logic taglib contains tags that are useful in managing
conditional generation of output text, looping over object collections
for repetitive generation of output text, and application flow
management.
The struts-tiles taglib contains tags used for combining various view
components, called "tiles", into a final composite view.
The struts-nested taglib is an extension of other struts taglibs that
allows the use of nested beans.
Below is how you would define all taglibs for use within your
application. In practice, you would only specify the taglibs that your
application uses:
<taglib>
<taglib-uri>/tags/struts-bean
</taglib-uri>
<taglib-location>/WEB-INF/struts-bean.tld
</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-html
</taglib-uri>
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
<taglib-location>/WEB-INF/struts-html.tld
</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-logic
</taglib-uri>
<taglib-location>/WEB-INF/struts-logic.tld
</taglib-location>
</taglib>
<taglib>
<taglib-uri>/tags/struts-tiles
</taglib-uri>
<taglib-location>/WEB-INF/struts-tiles.tld
</taglib-location>
</taglib>
This tells the JSP system where to find the tag library descriptor
for this library (in your application's WEB-INF directory, instead of
out on the Internet somewhere).
Configure the Struts Tag Libraries (Servlet 2.3)
Servlet 2.3 Users only: The Servlet 2.3 specification simplifies the
deployment and configuration of tag libraries. The instructions above
will work on older containers as well as 2.3 containers (Struts only
requires a servlet 2.2 container); however, if you're using a 2.3
container such as Tomcat 4.x, you can take advantage of a simplified
deployment.
All that's required to install the struts tag libraries is to copy
struts.jar into your /WEB-INF/lib directory and reference the tags in
your code like this:
<%@
taglib
prefix="html" %>
uri=http://struts.apache.org/tags-html
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.
Add Struts Components To Your Application
To use Struts, you must copy the .tld files that you require into
your WEB-INF directory, and copy struts.jar (and all of the
commons-*.jar files) into your WEB-INF/lib directory.
Struts Bean Tags
This tag library contains tags useful in accessing beans and their
properties, as well as defining new beans (based on these accesses)
that are accessible to the remainder of the page via scripting
variables and page scope attributes. Convenient mechanisms to
create new beans based on the value of request cookies, headers,
and parameters are also provided.
Many of the tags in this tag library will throw a JspException at
runtime when they are utilized incorrectly (such as when you specify
an invalid combination of tag attributes). JSP allows you to declare
an "error page" in the <%@ page %> directive. If you wish to process
the actual exception that caused the problem, it is passed to the
error
page
as
a
request
attribute
under
key
org.apache.struts.action.EXCEPTION.
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
If you are viewing this page from within the Struts Documentation
Application (or online at http://struts.apache.org/), you can
learn more about using these tags in the Bean Tags Developer's
Guide.
Tag Name
Description
cookie
Define a scripting variable based on the value(s) of the
specified request cookie.
define
Define a scripting variable based on the value(s) of the
specified bean property.
header Load the response from a dynamic application request and
make it available as a bean
include
Render an internationalized message string to the
response.
message
Expose a specified item from the page context as a
bean.
page Define a scripting variable based on the value(s) of the
specified request parameter.
parameter Load a web application resource and make it available
as a bean.
resource
Define a bean containing the number of elements in a
Collection or Map.
size
Expose a named Struts internal configuration object as
a bean.
struts
Render the value of the specified bean property to the
current JspWriter.
Struts
The core of the Struts framework is a flexible control layer based
on
standard
technologies
like
Java
Servlets,
JavaBeans,
ResourceBundles, and XML, as well as various Jakarta Commons
packages. Struts encourages application architectures based on the
Model 2 approach, a variation of the classic Model-View-Controller
(MVC) design paradigm.
Struts provides its own Controller component and integrates
with other technologies to provide the Model and the View. For the
Model, Struts can interact with standard data access technologies,
like JDBC and EJB, as well as most any third-party packages, like
Hibernate, iBATIS, or Object Relational Bridge. For the View, Struts
works well with JavaServer Pages, including JSTL and JSF, as well as
Velocity Templates, XSLT, and other presentation systems.
The Struts framework provides the invisible underpinnings
every professional web application needs to survive. Struts helps you
create an extensible development environment for your application,
based on published standards and proven design patterns.
What is the difference between Struts 1.0 and Struts 1.1
The new features added to Struts 1.1 are 1. RequestProcessor
class 2. Method perform() replaced by execute() in Struts base
Action Class 3. Changes to web.xml and struts-config.xml
4.Declarative exception handling 5.Dynamic ActionForms 6.Plug-ins
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
What
is
the
difference
between
ActionErrors
and
ActionMessages
The difference between the classes is zero -- all behavior in
ActionErrors was pushed up into ActionMessages and all behavior in
ActionError was pushed up into ActionMessage. This was done in the
attempt to clearly signal that these classes can be used to pass any
kind of messages from the controller to the view -- errors being only
one kind of message
How you will handle errors and exceptions using Struts
There are various ways to handle exception:
1) To handle errors server side validation can be used using
ActionErrors classes can be used.
2) The exceptions can be wrapped across different layers to show a
user showable exception.
3)using validators
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 we will define in Struts-config.xml file. And explain
their purpose
The main control file in the Struts framework is the strutsconfig.xml XML file, where action mappings are specified. This file's
structure is described by the struts-config DTD file, which is defined
at http://jakarta.apache.org/struts/. A copy of the DTD can be found
on the /docs/dtds subdirectory of the framework's installation root
directory. The top-level element is struts-config. Basically, it consists
of the following elements:
data-sourcesA
set
of
data-source
elements,
describing
parameters needed to instantiate JDBC 2.0 Standard Extension
DataSource objects
form-beansA set of form-bean elements that describe the form
beans that this application uses
global-forwardsA set of forward elements describing general
available forward URIs
action-mappingsA set of action elements describing a request-toaction mapping
What
is
the
purpose
of
tiles-def.xml
file,
resourcebundle.properties file, validation.xml file
The Tiles Framework is an advanced version of that comes
bundled with the Struts Webapp framework. Its purpose is reduce
the duplication between jsp pages as well as make layouts flexible
and easy to maintain. It integrates with Struts using the concept of
named views or definitions.
What is Action Class. What are the methods in Action class
Action class is request handler in Struts. we will extend the Action
class and over ride the execute() method in which we will specify the
business logic to be performed.
Explain about token feature in Struts
Tokens are used to check for invalid path for by the uer:
1) if the user presses back button and submits the same page
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
2)or if the user refreshes the page which will result to the resubmit
of the previous action and might lead to unstabality..
to solve the abv probs we use tokens
1) in previous action type saveTokens(HttpServletreuest)
2) in current action check for duplication bu
if(!isValidToken())
What part of MVC does Struts represent
Bad question. Struts is a framework which supports the MVC pattern.
What are the core classes of struts?
The core classes of struts are ActionForm, Action, ActionMapping,
ActionForward etc.
What are the Important Components of Struts?
1. Action Servlet
2. Action Classes
3. Action Form
4. Validator Framework
5. Message Resources
6. Struts Configuration XML Files
7. View components like JSP
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.
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.
Who makes the Struts?
Struts is hosted by the Apache Software Foundation(ASF) as part
of its Jakarta project, like Tomcat, Ant and Velocity.
Why it called Struts?
Because the designers want to remind us of the invisible
underpinnings that hold up our houses, buildings, bridges, and
ourselves when we are on stilts. This excellent description of Struts
reflect the role the Struts plays in developing web applications.
Do we need to pay the Struts if being used in commercial
purpose?
No. Struts is available for commercial use at no charge under the
Apache Software License. You can also integrate the Struts
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
parameter=MessageResources
/>
Classification : INTERNAL
Classification : INTERNAL
At startup, in the init() method, the ActionServlet reads the Struts Config file and load
into memory.
Second Task by ActionServlet :
If the user types http://localhost:8080/app/submitForm.do in the browser URL bar, the
URL will be intercepted and processed by the ActionServlet since the URL has a
pattern *.do, with a suffix of "do". Because servlet-mapping is
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Third Task by ActionServlet : Then ActionServlet delegates the request handling to
another class called RequestProcessor by invoking its process() method.
<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>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Step 2. ActionServlet calls process() method of RequestProcessor.
The RequestProcessor does the following in its process() method:
a) The RequestProcessor looks up the configuration file for the URL pattern
/submitForm (if the URL is http://localhost:8080/app/submitForm.do). and and finds the
XML block (ActionMapping).
ActionMapping from struts-config.xml
<action path="/submitForm"
type="com.techfaq.emp.EmpAction"
name="EmpForm"
scope="request"
validate="true"
input="EmpForm.jsp">
<forward name="success"
path="success.jsp"/>
<forward name="failure" path="failure.jsp" />
</action>
b) The RequestProcessor instantiates the EmpForm and puts it in appropriate scope
either session or request.
The RequestProcessor determines the appropriate scope by looking at the scope
attribute in the same ActionMapping.
c) RequestProcessor iterates through the HTTP request parameters and populates the
EmpForm.
d) the RequestProcessor checks for the validateattribute in the ActionMapping.
If the validate is set to true, the RequestProcessor invokes the validate() method on the
EmpForm instance.
This is the method where you can put all the html form data validations.
If Validate fail the RequestProcessor looks for the input attribute and return to JSP
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
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
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.
Operational Benefits from EJB
Transaction management service
Distributed Transaction support
Portability
Scalability
Integration with CORBA possible
Support from multiple vendors
What Does EJB Really Define?
Component architecture
Specification to write components using Java
Specification to component server developers
Contract between developer roles in a
application project
components-based
Classification : INTERNAL
Business logic
JSP
Servlets
HTML
client
http
Bea
ns
rmi
J2EE Server
Client
Java
EJB Component
server
The Architecture Scenario
Application Responsibilities
-Create individual business and web components.
-Assemble these components into an application.
-Deploy application on an application server.
-Run application on target environment.
EJB Architecture Roles : Appointed for Responsibilities
Six roles in application development and deployment life cycle
Bean Provider
Application Assembler
Server Provider
Container Provider
Deployer
System Administrator
Each role performed by a different party.
Product of one role compatible with another.
Creating the Bean Instance
Look up for the Home Object through JNDI
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Component Server
Bean
Classification : INTERNAL
Component Contract :
Client-view contract
Bean Instance
Component contract
EJB-jar file
Component
Contract
Container
Client
Client View
Contract
Component Server
EJB-jar
Deployment
Deployment descriptor
descriptor
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 providers
responsibilities
Bean providers
responsibilities
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
Bean Varieties
Three Types of Beans:
Session Beans - Short lived and last during a session.
Entity Beans
- Long lived and persist throughout.
Message Driven Beans Asynchronous Message Consumers
Asynchronous.
Session Beans
A session object is a non-persistent object that implements some
business logic running on the server.
Executes on behalf of a single client.
Can be transaction aware.
Does not represent directly shared data in the database, although it
may access and update such data.
Is relatively short-lived.
Is removed when the EJB container crashes. The client has to reestablish a new session object to continue computation
Types of Session Beans
There are two types of session beans:
Stateless
Stateful
Message Consumers
Clients view of a Session Bean :
A client accesses a session object through the session beans
Remote Interface or Local Interface.
Each session object has an identity which, in general, does not
survive a crash
Locating a session beans home interface
Remote Home interface
Context initialContext = new InitialContext();
CartHome cartHome = (CartHome)
javax.rmi.PortableRemoteObject.narrow(initialContext.lookup(java:c
omp/env/ejb/cart), CartHome.class);
Local Home Interface
Context initialContext = new InitialContext();
CartHome
cartHome
=
(CartHome)
initialContext.lookup(java:comp/env/ejb/cart);
JNDI : used to locate Remote Objects created by bean.
portableRemoteObject Class : It uses an Object return by
Lookup( ).
narrow( ) -> Call the create( ) of HomeInterface.
IntialContext Class :
Lookup( ) -> Searches and locate the distributed Objects.
Session Beans Local Home Interface :
object that implements is called a session EJBLocalHome object.
Create a new session object.
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
All session objects of the same stateless session bean, within the
same home have the same object identity assigned by the container.
isIdentical(EJBObject otherEJBObject) method always returns true.
Container Responsibilities :
Manages the lifecycle of session bean instances.
Notifies instances when bean action may be necessary .
Provides necessary services to ensure session bean implementation
is scalable and can support several clients.
Activation and Passivation :
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.
Transfer back from the secondary storage to the instance variables
is called instance activation.
Entity Beans
Long Live Entity Beans!
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
EJB QL
Need for standardizing queries
Why not SQL?
EJB QL: EJB Query Language
Specification language
Based on the CMP Data Model (Abstract Persistence Schema)
Compiled to a target language: SQL
EJB QL Example
SELECT OBJECT(l) From OrderBean o, in(o.lineItems) l
SELECT
o.ORDER_ID
FROM
CREDITCARDEJBTABLE
a_1,
ORDEREJBTABLE
o
WHERE
((a_1.EXPIRES='03/05'
AND
o.CREDITCARD_ID = a_1.CREDITCARD_ID ))
EJB QL Example
SELECT c.address
FROM CustomerBeanSchema c
WHERE c.iD=?1 AND c.firstName=?2
SELECT ADDRESS.ID
FROM ADDRESS, CUSTOMER
WHERE CUSTOMER.CUSTOMERID=?
AND CUSTOMER.FIRSTNAME=?
AND CUSTOMER.CUSTOMERID = ADDRESS.CUSTOMERID
EJB QL: Deployment Descriptor
<query>
<description>Method finds large orders</description>
<query-method>
<method-name>findAllCustomers</method-name>
<method-params/>
</query-method>
<ejb-ql>SELECT OBJECT(c) FROM CustomerBeanSchema
c</ejb-ql>
</query>
Home Business Methods
Methods in the Home Interface
Implementation provided by Bean Provider
ejbHome<method> in the Bean
Exposed to the Client View
Not specific to any Bean instance
Select Methods
Defined as abstract method in the Bean class
ejbSelect<method>
Special type of a query method
Specified using a EJB QL statement
Not exposed to the Client View
Usually called from a business method
with
matching
Classification : INTERNAL
Classification : INTERNAL
Many to Many
Example Entity Bean: Order
public abstract OrderBean extends Entity Bean {
// Virtual Fileds <cmp-fields>
public abstract Long getOrderID();
public abstract void setOrderID(Long orderID);
// Virtual Fields <cmr-fields>
public abstract Address getShipingAddress();
public abstract void setShipingAddress (Address address);
public abstract Collection getLineItems();
public abstract void setLineItems (Collection lineItems);
}
Example Entity Bean: Product
public abstract OrderBean extends Entity Bean {
// Virtual Fields <cmp-field>
public abstract Long getProductID();
public abstract void setProductID(Long orderID);
// Virtual Fields <cmp-field>
public abstract String getProductCategory();
public abstract void setProductCategory (String category);
// NO Relationship Fields
}
Relationships: Deployment Descriptor
<ejb-relation>
<description>ONE-TO-ONE: Customer and
Address</description>
<ejb-relation-name>Customer-Address</ejb-relationname>
<ejb-relationship-role>
<ejb-relationship-role-name> customer has one addresss
</ejb-relationship-role-name>
<multiplicity>one</multiplicity>
<relationship-role-source>
<ejb-name>CustomerBean</ejb-name>
</relationship-role-source>
<cmr-field>
<cmr-field-name>address</cmr-field-name>
</cmr-field>
</ejb-relationship-role>
<ejb-relationship-role>
<ejb-relationship-role-name>Address belong to the
Customer </ejb-relationship-role-name>
<multiplicity>one</multiplicity>
<cascade-delete/>
<relationship-role-source>
<ejb-name>AddressBean</ejb-name>
</relationship-role-source>
</ejb-relationship-role>
</ejb-relation>
Classification : INTERNAL
EJB
What is the difference between normal Java object and EJB
Java Object:it's a reusable componet
EJB:is reusable and deployable component which can be deployed in
any container
EJB : is a distributed component used to develop business
applications. Container provides runtime environment for EJBs.
EJB is an Java object implemented according EJB specification.
Deployability is a feature.
What is the difference between JavaBean and EJB
Java Beans : is intra-process component,
JavaBeans is particularly well-suited for asynchronous, intraapplication communications among software
EJB : is an Inter-Process component
What is EJB ?
Enterprise Java Bean is a specification
scalable,transactional
and
multi-user
secure
applications. It provides a consistant component
creating distributed n-tier middleware.
Enterprise JavaBeans (EJB) is a technology that
platform.
EJBs are server-side components. EJB are used
distributed, transactional and secure applications
technology.
for server-side
enterprise-level
architecture for
based on J2EE
to develop the
based on Java
Classification : INTERNAL
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.
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
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.
What are advantages and disadvantages of CMP and BMP
CMP: Container managed persistence
Advantages:
1)Easy to develop and maintain.
2)Relationships can be maintained between different entities.
3)Optimization of SQL code will be done.
4)Larger and more performance applications can be done.
Disadvantages:
1)Will not support for some nonJDBC data sources,i.e,CICS.
2)Complex queries cannot be developed with EJBQL.
BMP:: Bean managed persistence
Advantages:
1)Support for nonJDBC data sources.
2)Complex queries can be build.
Disadvantages:
1)Hard to develop and maintain.
2)We cannot maintain the relationships between different entities.
3)Optimization of SQL code cannot be done by the container,because
bean it self contains the code.
4)Not appropriate for larger and complex applications.
What is difference between EJB 1.1 and EJB 2.0
EJB 2.0 adds the local beans, which are accessible only from within
the JVM where beans are running in.
In EJB 1.1, we had to implement remote client views for all these
beans, even if we had no remote clients.
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
4. Supports
- T1---T1
0---0
5. NotSupported - T1---0
0---0
6. Never - T1---Error
0---0
What is the difference between activation and passivation
Activation and Passivation is appilicable for only Stateful session
bean and Entity bean.
When Bean instance is not used for a while by client then EJB
Container removes it from memory and puts it in secondary storage
(often disk) so that the memory can be reused. This is called
Passivation.
When Client calls the bean instance again then Container takes
the passivated bean from secondary storage and puts it in memory
to serve the client request. This is called Activation.
What is Instance pooling
pooling of instances.
in stateless session beans and Entity Beans server maintains a pool
of instances.whenever server got a request from client, it takes one
instance from the pool and serves the client request.
What is the difference between HTTPSession and Stateful
Session Bean
From a logical point of view, a Servlet/JSP session is similar to an
EJB session. Using a session, in fact, a client can connect to a server
and maintain his state.
But, is important to understand, that the session is maintained in
different ways and, in theory, for different scopes.
A session in a Servlet, is maintained by the Servlet Container
through the HttpSession object, that is acquired through the request
object. You cannot really instantiate a new HttpSession object, and it
does not contains any business logic, but is more of a place where to
store objects.
A session in EJB is maintained using the SessionBeans. You
design beans that can contain business logic, and that can be used
by the clients. You have two different session beans: Stateful and
Stateless. The first one is somehow connected with a single client. It
maintains the state for that client, can be used only by that client
and when the client "dies" then the session bean is "lost".
A Stateless Session Bean does not maintain any state and
there is no guarantee that the same client will use the same
stateless bean, even for two calls one after the other. The lifecycle of
a Stateless Session EJB is slightly different from the one of a Stateful
Session EJB. Is EJB Containers responsability to take care of knowing
exactly how to track each session and redirect the request from a
client to the correct instance of a Session Bean. The way this is done
is vendor dependant, and is part of the contract.
What is the difference between find and select methods in
EJB
select method is not there in EJBs
A select method is similar to a finder method for Entity Beans, they
both use EJB-QL to define the semantics of the method.
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
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>
Classification : INTERNAL
Classification : INTERNAL
Country
Country
Country
Country
Package
Parameter
Sorting logic
Implementation
Sorting method
Comparable
Comparator
Sorting logic is in separate
Sorting logic must be in
class. Hence we can write
same class whose objects
different sorting based on
are being sorted. Hence
different attributes of objects
this is called natural
be sorted. E.g. Sorting using
ordering of objects
id,name etc.
Class whose objects to be
sorted do not need to
Class whose objects to be implement this interface. Som
sorted must implement this other class can implement this
interface. e.g Country
interface. E.g.class needs to implement CountrySortByIdComparato
comparable to collection of class can implement
Comparator interface to sort
country object by id
collection of country object b
id
int compareTo(Object
o1)
int compare(Object
o1,Object o2)
Classification : INTERNAL
Parameter
Comparable
than o1
2. zero this object
equals to o1
3. negative this
object is less than
o1
Collections.sort(List)
Calling method
Comparator
meaning.
1. positive o1 is greate
than o2
2. zero o1 equals to o2
3. negative o1 is less
than o1
Collections.sort(List,
Comparator)
Java.lang.Comparable Java.util.Comparator
Java code
For Comparable
We will create class country having attribute id and name. This
class will implement Comparable interface and implement
CompareTo method to sort collection of country object by id.
1. Country.java
Classification : INTERNAL
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
2.ComparatorMain.java
package org.arpit.javapostsforlearning;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ComparableMain {
/**
* @author Arpit Mandliya
*/
public static void main(String[] args) {
Country indiaCountry=new Country(1, "India");
Country chinaCountry=new Country(4, "China");
Country nepalCountry=new Country(3, "Nepal");
Country bhutanCountry=new Country(2, "Bhutan");
List<Country> listOfCountries = new
ArrayList<Country>();
listOfCountries.add(indiaCountry);
listOfCountries.add(chinaCountry);
listOfCountries.add(nepalCountry);
listOfCountries.add(bhutanCountry);
System.out.println("Before Sort : ");
for (int i = 0; i < listOfCountries.size(); i++) {
Country country=(Country) listOfCountries.get(i);
System.out.println("Country Id: "+country.getCountryId()
+"||"+"Country name: "+country.getCountryName());
}
Collections.sort(listOfCountries);
System.out.println("After Sort : ");
for (int i = 0; i < listOfCountries.size(); i++) {
Country country=(Country) listOfCountries.get(i);
System.out.println("Country Id: "+country.getCountryId()+"||
"+"Country name: "+country.getCountryName());
}
}
}
Output
Classification : INTERNAL
Country Id:
After Sort
Country Id:
Country Id:
Country Id:
Country Id:
package org.arpit.javapostsforlearning;
public class Country{
int countryId;
String countryName;
public Country(int countryId, String countryName) {
super();
this.countryId = countryId;
this.countryName = countryName;
}
public int getCountryId() {
return countryId;
}
public void setCountryId(int countryId) {
this.countryId = countryId;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
}
2.CountrySortbyIdComparator.java
package org.arpit.javapostsforlearning;
import java.util.Comparator;
//If country1.getCountryId()<country2.getCountryId():then
compare method will return -1
//If country1.getCountryId()>country2.getCountryId():then
compare method will return 1
//If country1.getCountryId()==country2.getCountryId():then
compare method will return 0
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
java.util.ArrayList;
java.util.Collections;
java.util.Comparator;
java.util.List;
Classification : INTERNAL
}
});
System.out.println("After Sort by name: ");
for (int i = 0; i < listOfCountries.size(); i++) {
Country country=(Country) listOfCountries.get(i);
System.out.println("Country Id: "+country.getCountryId()+"||
"+"Country name: "+country.getCountryName());
}
}
}
Output:
Classification : INTERNAL
</servlet-mapping>
Third Task by ActionServlet : Then ActionServlet delegates the request handling to
another class called RequestProcessor by invoking its process() method.
<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>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
Step 2. ActionServlet calls process() method of RequestProcessor.
The RequestProcessor does the following in its process() method:
a) The RequestProcessor looks up the configuration file for the URL pattern
/submitForm (if the URL is http://localhost:8080/app/submitForm.do). and and finds the
XML block (ActionMapping).
ActionMapping from struts-config.xml
<action path="/submitForm"
type="com.techfaq.emp.EmpAction"
name="EmpForm"
scope="request"
validate="true"
input="EmpForm.jsp">
<forward name="success"
path="success.jsp"/>
<forward name="failure" path="failure.jsp" />
</action>
b) The RequestProcessor instantiates the EmpForm and puts it in appropriate scope
either session or request.
The RequestProcessor determines the appropriate scope by looking at the scope
attribute in the same ActionMapping.
c) RequestProcessor iterates through the HTTP request parameters and populates the
EmpForm.
d) the RequestProcessor checks for the validateattribute in the ActionMapping.
If the validate is set to true, the RequestProcessor invokes the validate() method on the
EmpForm instance.
This is the method where you can put all the html form data validations.
If Validate fail the RequestProcessor looks for the input attribute and return to JSP
page mentioned in input tag.
If Validate pass goto next step.
e) The RequestProcessor instantiates the Action class specified in the ActionMapping
(EmpAction) and invokes the execute() method on the EmpAction instance.
signature of the execute method is
public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
return mapping.findForward("success");
}
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
f) In return mapping.findForward("success")
RequestProcessor looks for the success attribute and forward to JSP page mentioned
in success tag. i.e success.jsp.
In return mapping.findForward("failure")
RequestProcessor looks for the failure attribute and forward to JSP page mentioned in
failure tag. i.e. failure.jsp
Classification : INTERNAL
Iterating over a collection is uglier than it needs to be. Consider the following
method, which takes a collection of timer tasks and cancels them:
void cancelAll(Collection; c) {
for (Iterator; i = c.iterator(); i.hasNext(); )
i.next().cancel();
}
The iterator is just clutter. Furthermore, it is an opportunity for error. The
iterator variable occurs three times in each loop: that is two chances to get it
wrong. The for-each construct gets rid of the clutter and the opportunity for
error. Here is how the example looks with the for-each construct:
void cancelAll(Collection ; c) {
for (TimerTask t : c)
t.cancel();
}
When you see the colon (:) read it as in. The loop above reads as for each
TimerTask t in c. As you can see, the for-each construct combines beautifully
with generics. It preserves all of the type safety, while removing the remaining
clutter. Because you don't have to declare the iterator, you don't have to provide
a generic declaration for it. (The compiler does this for you behind your back,
but you need not concern yourself with it.
Autoboxing/Unboxing
This facility eliminates the drudgery of manual conversion between primitive
types (such as int) and wrapper types (such as Integer). Refer to JSR 201 .
As any Java programmer knows, you cant put an int (or other primitive
value) into a collection. Collections can only hold object references, so you
have to box primitive values into the appropriate wrapper class (which is
Integer in the case of int). When you take the object out of the collection, you
get the Integer that you put in; if you need an int, you must unbox the Integer
using the intValue method. All of this boxing and unboxing is a pain, and
clutters up your code. The autoboxing and unboxing feature automates the
process, eliminating the pain and the clutter.
The following example illustrates autoboxing and unboxing, along with
generics and the for-each loop. In a mere ten lines of code, it computes and
prints an alphabetized frequency table of the words appearing on the command
line.
import java.util.*;
// Prints a frequency table of the words on the command line
public class Frequency {
public static void main(String[] args) {
Map m = new TreeMap();
for (String word : args) {
Integer freq = m.get(word);
m.put(word, (freq == null ? 1 : freq + 1));
}
System.out.println(m);
}
}
java Frequency if it is to be it is up to me to do the watusi
{be=1, do=1, if=1, is=2, it=2, me=1, the=1, to=3, up=1, watusi=1}
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Typesafe Enums
This flexible object-oriented enumerated type facility allows you to create
enumerated types with arbitrary methods and fields. It provides all the benefits
of the Typesafe Enum pattern ("Effective Java," Item 21) without the verbosity
and the error-proneness. Refer to JSR 201.
In prior releases, the standard way to represent an enumerated type was the int
Enum pattern:
// int Enum Pattern - has severe problems!
public static final int SEASON_WINTER = 0;
public static final int SEASON_SPRING = 1;
public static final int SEASON_SUMMER = 2;
public static final int SEASON_FALL = 3;
This pattern has many problems, such as:
Not typesafe - Since a season is just an int you can pass in any other int
value where a season is required, or add two seasons together (which
makes no sense).
Printed values are uninformative - Because they are just ints, if you
print one out all
you get is a number, which tells you nothing about
what it represents, or even what type it is.
Classification : INTERNAL
method. For example, here is how one used the MessageFormat class to format
a message:
Object[] arguments = {
new Integer(7),
new Date(),
"a disturbance in the Force"
};
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet "
+ "{0,number,integer}.", arguments);
It is still true that multiple arguments must be passed in an array, but the
varargs feature automates and hides the process. Furthermore, it is upward
compatible with preexisting APIs. So, for example, the MessageFormat.format
method now has this declaration:
public static String format(String pattern, Object... arguments);
Static Import
This facility lets you avoid qualifying static members with class names
without the shortcomings of the "Constant Interface antipattern." Refer to JSR
201.
In order to access static members, it is necessary to qualify references with the
class they came from. For example, one must say:
double r = Math.cos(Math.PI * theta);
In order to get around this, people sometimes put static members into an
interface and inherit from that interface. This is a bad idea. In fact, it's such a
bad idea that there's a name for it: the Constant Interface Antipattern (see
Effective Java Item 17). The problem is that a class's use of the static members
of another class is a mere implementation detail. When a class implements an
interface, it becomes part of the class's public API. Implementation details
should not leak into public APIs.
The static import construct allows unqualified access to static members
without inheriting from the type containing the static members. Instead, the
program imports the members, either individually:
import static java.lang.Math.PI;
or en masse:
import static java.lang.Math.*;
Once the static members have been imported, they may be used without
qualification:
double r = cos(PI * theta);
Metadata (Annotations)
Annotations provide data about a program that is not part of the program itself.
They have no direct effect on the operation of the code they annotate.
Annotations have a number of uses, among them:
Information for the compiler Annotations can be used by the
compiler to detect errors or suppress warnings.
Compiler-time and deployment-time processing Software tools
can process annotation information to generate code, XML files, and so
forth.
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Collections Framework
Deployment (Java Web Start and Java Plug-in)
Drag and Drop
Instrumentation
Internationalization Support
I/O Support
Classification : INTERNAL
Or
Collections Framework
The primary theme of the API changes was better bidirectional collection access.
These new collection interfaces are provided:
Classification : INTERNAL
- simple immutable
Set<Object> identityHashSet=
Collections.newSetFromMap(
new IdentityHashMap<Object, Boolean>());
asLifoQueue(Deque) - returns a view of a Deque as a Last-in-firstout (Lifo) Queue.
The Arrays utility class now has methods copyOf and copyOfRange that
can efficiently resize, truncate, or copy subarrays for arrays of all types.
Before:
int[] newArray = new int[newLength];
System.arraycopy(oldArray, 0, newArray, 0, oldArray.length);
After:
int[] newArray = Arrays.copyOf(a, newLength);
Classification : INTERNAL
2.java.io Enhancements:
New class Console is added and it contains methods to access
a character-based console device. The readPassword()methods
disable echoing thus they are suitable for retrieval of sensitive
data such as passwords. The method System.console ()returns
the unique console associated with the Java Virtual Machine.
Increased Developer Productivity
3. GUI
- JFC and Swing integration with desktop by using Windows
API.
-Java 2D integration with desktop such as using desktop antialiasing font settings
- Splash screen direct support and can be shown before JVM
started
- System tray support with ability to add icons, tool tips, and
pop-up menus to the Windows or any other system tray (such
as Gnome).
Classification : INTERNAL
Classification : INTERNAL
to a Apache Derby database, the METAINF/services/java.sql.Driver file would contain the following
entry:
org.apache.derby.jdbc.EmbeddedDriver
We can simply call:
Connection conn =
DriverManager.getConnection(jdbcUrl, jdbcUser,
jdbcPassword);In JDBC 4.0, we dont need the Class.forName()
line.
2.Connection management enhancements:
Prior to JDBC 4.0, we relied on the JDBC URL to define a data
source connection. Now with JDBC 4.0, we can get a
connection to any data source by simply supplying a set of
parameters (such as host name and port number) to a
standard connection factory mechanism. New methods were
added to Connection and Statement interfaces to permit
improved connection state tracking and greater flexibility when
managing Statement objects in pool environments. The
metadata facility (JSR-175) is used to manage the active
connections. We can also get metadata information, such as
the state of active connections, and can specify a connection as
standard (Connection, in the case of stand-alone applications),
pooled (PooledConnection), or even as a distributed connection
(XAConnection) for XA transactions. Note that we dont use the
XAConnection interface directly. Its used by the transaction
manager inside a Java EE application server such as WebLogic,
WebSphere, or JBoss.
Classification : INTERNAL
Classification : INTERNAL
Ex1:
We can use getNextException() method in
SQLException to iterate through the exception chain. Heres
some sample code to process SQLException causal
relationships:
catch(SQLException ex) {
while(ex != null) {
LOG.error(SQL State: + ex.getSQLState());
LOG.error(Error Code: + ex.getErrorCode());
LOG.error(Message: + ex.getMessage());
Throwable t = ex.getCause();
while(t != null) {
LOG.error(Cause: + t);
t = t.getCause();
}
ex = ex.getNextException();
}
}
Ex2:
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
try
{
//
}
catch(SQLException exp1)
{
throw exp1;
}
catch(IOException exp2)
{
throw exp2;
}
catch(ArrayIndexOutofBoundsException exp3)
{
throw exp3;
}
Classification : INTERNAL
Ejb-jar.xml
Weblogic-ejb-jar.xml
<ejb-jar>
<enterprise-bean>
</Session>
<ejb-name>Statefulfinacialcalcu</ejb-name>
<home>fincal.stateful.fincalc</home>
<remote> fincal.stateful.fincalc </remote>
You have Downloaded this file from kamma-Sangam Yahoo Group
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
Questions
Classification : INTERNAL
Classification : INTERNAL
Classification : INTERNAL
d A-NotSupported, B-RequiresNew
e A-RequiresNew, B-RequiresNew
20.) If an RMI parameter implements java.rmi.Remote, how is it passed
"on-the-wire?"
Choice 1 : It can never be passed.
Choice 2 : It is passed by value.
Choice 3 : It cannot be passed because it implements java.rmi.Remote.
Choice 4 : (Correct) It cannot be passed unless it ALSO implements
java.io.Serializable.
Choice 5 : It is passed by reference.
21.) public synchronized void txTest(int i) {
System.out.println("Integer is: " + i); }
What is the outcome of attempting to compile and execute the method
above, assuming it is implemented in a stateful session bean?
Choice 1 : Run-time error when bean is created
Choice 2 : The method will run, violating the EJB specification.
Choice 3 : (Correct) Compile-time error for bean implementation class
Choice 4 : Compile-time error for remote interface
Choice 5 : Run-time error when the method is executed
22.) What is the CORBA naming service equivalent of JNDI?
Choice 1 : Interface Definition Language
Choice 2 : (Correct) COS Naming
Choice 3 : Lightweight Directory Access Protocol
Choice 4 : Interoperable Inter-Orb Protocol
Choice 5 : Computer Naming Service
Classification : INTERNAL
Choice 4 (Correct, Since only Statefull session bean and Entity Bean
can be passivated, and Entitybean can not call as th.create() normally, I
take it as statefull session bean)
Bean D
Choice 5
Bean E
------------------------Which one of the following phenomena is NOT addressedby readconsistency?
a Phantom read (Correct)
b Cached read
c Dirty read
d Non-repeatable read
e Fuzzy read
-------------------------Which one of the following methods is generally called
in both
ejbLoad() and ejbStore()?
a getEJBObject()
b getHandle()
c remove()
d getEJBHome()
e getPrimaryKey() (Correct)
Classification : INTERNAL