1 Java BASIC Concepts OOPS: Data Encapsulation : bind code together code with wrapper to the object Achieved through Private constructors in Java. Data Abstraction : designed with Implementation gaps for Sub classes to fill in.Achieve through Abstract Classes & Abstract Methods. Avoid Complexity. Abstract Class: Designed with implementation gaps for subclasses to fill in. Abstract Method : Defines all aspects of itself except what code it executes. Polymorphism: Object Taking more than 1 Form. Achieved in java through Method through Overloading and Method Overriding. Types of Polymorphism Compile time Polymorphism - Method Overloading – In a class two or more methods share the same name differed by its arguments Handled as below. class abc { public abc1(int a) { } public abc1(int a,int b){ } //AdditonalCode…. } Runtime Polymorphism - Method Overriding – Instead of inheriting a method from its super class, a subclass method writes it own definition for it. Handled as below. class abc1 { Public abc001(int a,int b) throws Exception { } // Some code } class abc2 extends abc1 { public abc001( int a ,int b) throws ClassNotFoundException { } // please note any exception thrown in class abc2for the above method // should be subclass of exception of method abc001 given in class abc1 // some code } Inheritance – A subclass uses method definitions, constructors and variables from a superclass just as they belong to subclass itself. Types Of Inheriatance. Single Inheritance Multi Level Inheritance Multiple Inheritance(Achieved through Interfaces). // For Inheritance method , The sub class method should have the same access specifier as its super class method. Alternative way to Inheritance , Use Dynamic Binding / Late Binding [ if the class to be imported is in same package its ok else import that package. Order to Follow while writing a Java class Package a; Import Java.io.*; Import java.lang.*; // not need 2 import Java.lang as its imported by default.No harm in importing again. Class class_Declaration { // Global Variable Declarations. // Inner Class [if required ] // Method Declarations. // Other Descriptions whatever required. }
2 VARIOUS TYPES TO CREATE INSTANCE OF A CLASS 1. Using new Operator : class_def c1 = new c1ass_def() // create instance for class class_def. class_def c1 = new class_defenition() // create instance for class class_defenition which is a different class, always note that wherever we go for declaration ,we should know that new is the operator that creates instance [ refers to memory allocation of class. 2. Using Class that returns a runtime value of a class 3. Create instance of a class invoke a constructor. Class A{ // implementation methods } Class B extends A { // Implementation code A a = new B(); } What will happen here. Ans : Though we give A a = new B() it will work , it will refer to class A not B. We can access Class A methods not class B. What will happen for B b = new A() Results in Class cast Exception. INTERFACES Interface – strip down of a class. Specifies set of methods that a instance must handle but omits inheritance relationships and method implementations. Public interface def { //variables declared are final & static by default [if declare int I,its value must be defined 10] //methods given without body //abstract methods by default. } Advantage : globally Accessible in any part of the project A interface extends another. A interface is used as replacement for of Multiple inheritance.A class implement an interface using implements keyword. Class a extends abc implements def // note abc is class, def a interface{ } interface ghi extends def, xyz{ } // def and xyz are interfaces. Marker interface – A interface defined with out any methods. Different types of compilers available in java 1.Javac Compiler 2.JIT compiler. Work of a compiler – Loading ,Linking , Initialization.
3 Abstract class Defines full set of methods Follows inheritance relationships. Class and methods are explicitly declared with K/W abstract to refer as abstract methods, refers can have non abstract methods too. Cannot have final or static variables. Abstract class can have constructors as nonabstract method but not Recommended,since no need to create instance.Instance will be created when its subclass object is invoked. Abstract class Scope is restricted to that particular package alone.
Interface Defines subset of methods that a instance must handle. Omits inheritance relationships but replaces multiple inheritance in java. No need to use keyword abstract as all methods are abstract by default Variables declared are final and static by default. Constructors not allowed.
Scope of a interface is global to the whole application.
ABSTRACT CLASS WITH CONSTRUCTOR : All the classes including the abstract classes can have constructors.Abstract class constructors will be called when its concrete subclass will be instantiated The purpose of abstract class is to provide common information for the subclasses.The abstract classes cannot be instantiated.You will get a compile error. An abstract class can have methods with full body apart and abstract method. This is especially useful when extending classes.Say,you have an super class Animal and sub-classes Dog,Cat,Cow etc.All the different type of animals have one thing comon.ie,sound.So the Animal class has methods to define these sub-classes and also a method called sound().Though this method does nothing.It is only used in subclasses and implemented.It is just declared in Animal class but not defined. JRE JRE is Java Runtime Environment. It is a place where java classes are run. Like in the case of an applet, a JRE needs to be installed on the web server where you are going to run the applet. JVM It is a program designed for different environment Java Virtual Machines operate on Java bytecode, which is normally (but not necessarily) generated from Java source code; a JVM can also be used to implement programming languages other than Java what is diff bet framework and design pattern? Design pattern is how to implement for a particular problem. Framework is designed on the design pattern. eg. Struts designed with different design patterns Java is strictly pass-by-value, no pass by reference. Class – A blue print for objects. Object - A software unit that combines structured set of data with set of operations for inspecting and manipulating that data. - Instance created to a class. Object Reference : a Object Pointer with strong restrictions for integrity and safety. Signature of Method : combination of Method Name and Method input types. Static :don‘tholdanyspecificstate No need to create instance Accessed directly by instance ref Value defined with static can be modified.
4 Staticmethodscannotbeoverriddensinceitdoesn‘tbelongtoanystate Static methods belong to the class, not specific objects of that class. Static variables are accessed by static methods. Native : other than java public native int meth() javah –jni nativeDemo Dis adv. --> Potential security risk. --> Loss of portability Volatile Permanent storage of memory. Use master-copy of the variable for accessing. Transient – value is not constant. instanceOf( ) – It is a 2 argument operator that checks at run time whether the 1st argument is compatiable with the 2nd. A a = new int A() a.instanceOf(A); Default Values String = null; int = 0; float = 0.0; double =0.0; long = 0; Boolean = false; short = 0; byte=0; Char=null; Data Types. Range Byte –28 to 28-1 byte b= (int) b+1 needstypecastingelsewon‘twork. Short -216 to 216 -1 int -232 to 232-1 long -264 to 264 -1 float 1.2e -302 to (1.2e302)-1 Array int a[] =new int[10] ; - allocates 10 spaces 0-9 int a1[][] = new int[10][10] - allocates 100 spaces 0-99 Arithemetic Operators +, - , * , / , % Ternary Operator Exp1 ? exp2 : exp3, Exp1 : true exp2, Exp1 : false exp3 Instance Variable Class Variable A separate data item for each instance of a A Single data item shared by a class & its class. instances. Eg. Class Eg. { int i1; } Class eg { static int i1; } Instance Method Can use this instance ref . Static Block static block can access multiple threads
Class Method No this instance reference available. Static Synchronized Block proceeds with single thread access at a time
Constructor: It is a method having same name as of the class, Need not be instantiated.Since instantiation is done automatically when create object for the class Can‘treturnavalue, adding void to constructor returns a error. can be overloaded, cannot be overridden, refer to particular class only , variables assigned is taken implicitly. A class can have more than one constructors through overloading concept Constructors without args will be called first ahead of other constructors.
5 Method Will have different name of the class. Need to be instantiated by a object of the class. Values defined inside a class is accessed through objects. Value may be returned. Can be overloaded and overridden
Constructor Same name of the class. Need not be instantiated. Values are taken implicitly. Cannot return value. Cannot be overridden can be overloaded.
Super – explicit access to constructors, Methods, variables of its super class. Must be the 1st valid statement in any method. This – refers to current object. Must be the 1st valid statement in any method. Key Words in Java – 47 + 2 Reserved words( const ,goto) .true, false are also reserved words. As on java version 1.4. operator overloading is not possible in java but we can overload + operator implicitly how? for eg. String s = "Abc"; s=s+"d" will give s="Abcd" Possibilities : Object o= String s; Possible, since you assign a string that is subclass to Object [Super class] Object to Integer ? no not possible, Since Integer is a Wrapper class & it holds the functionality to convert primitive Data types to Objects. To get all public methods in a class – getMethods() Different Types of Classes 1. Abstract Class Designed with implementation gaps for subclasses to fill in. 2. Adapter Class empty method implementation of a class.used to handle events avoid complexity. 3. Final Class [properties] – cannot be sub-classed. Final Method – cannot be overridden , can be overloaded. Final Variable – can‘tchangeitsvalueassigned. If Final Class is sub-classed, results in Compiler Error. 4. Anonymous class:Aclassdefinedinsideamethoddoesn‘thaveaname.Itdoesn‘thave constructors also. It is generally used to get the properties of the class. 5. Inner class A class defined inside another class. It is different from inheritance relationships. It can have all the properties of a class includes constructors, method definitions etc. it is used to reduce complexity. 6. Concrete Class It is a class defined by the programmers with full set of method implementations and variables. It can access an abstract class /interface or anything. 7. Singleton class : a class that create only one instance. Will have all methods declared static Constructors given are private constructors. For Singleton class to avoid cloning of class do the following 1. Make the singleton class implements java.lang.cloneable 2. Give method public void clone()
6 3. throw new cloneNotSupportedException 4. doing the above will not allow object to get duplicated. 8. Wrapper class – convert primitive(pre defined) data type into objects. Integer I = new Integer(); Primitive data types cannot be accessed directly. For that we use Wrapper class Different Wrapper classes 1. Integer, 2. Float, 3. Character 4. Boolean 5. Long 6. Short 7. Byte 8. Double JAVA.lang.* - Default import SYSTEM.OUT.PRINTLN() System – a class in java.lang Out – Static object reference of printwriter class Println() - a method in printwriter class. Advantages of JDK 1.5 1. has better handling of generic introduction 2. better in handling collection objects. ArrayList = new ArrayList 3. StringBuilder class used in placed of Asynchronous StringBuffer. Adding Annotations Annotations in Java is all about adding meta-data facility to the Java Elements. Like Classes, Interfaces or Enums, Annotations define a type in Java and they can be applied to several Java Elements. It can be seen in class declaration, method declaration, field declaration etc. The added Annotation to Java Elements have proven themselves to be considerably useful in many instances. public @interface TestAnnotation { // Property Definition here. } Types of Annotation 1. Target Annotation Annotation can only be applied to methods, then there is a Meta-Annotation (meta-data about meta-data) which tells for which element type this annotation is applicable. @Target(ElementType.METHOD) public @interface TestAnnotation { // Property Definitions here. } 2. Retention Annotation Retain the Annotation in the Source Code only Retain the Annotation in the Class file also. Retain the Annotation Definition during the Run-time so that JVM can make use of it. The Annotation that is used to achieve this is @Retention and it takes a possible values of SOURCE, CLASS and RUNTIME defined in RetentionPolicy Enumeration
7 Example : @Target(ElementType.METHOD) @Retention(RetentionPolicy.CLASS) public @interface TestAnnotation { // Property Definitions here. } Synchronized block and Synchronized Statements. A synchronized method uses the method receiver as a lock (i.e. this for non static methods, and the enclosing class for static methods). Synchronized blocks use the expression as a lock. synchronized void mymethod() { ... } void mymethod() { synchronized (this) { ... } } synchronized blocks, you can use any non-null object as a lock: synchronized (mymap) { mymap.put(..., ...); } For synchronized methods, the lock will be held throughout the method scope, while in the synchronized method, the lock is held only during the synchronized block (otherwise known as critical section). In practice, the JVM is permitted to optimize by removing some operations out of the synchronized block execution if it can prove that it can be done safely. Autoboxing & Autounboxing Java 5 also supports automatic unboxing, where wrapper types are automatically converted into their primitive equivalents if needed for assignments or method or constructor invocations.Java 5 (and hence AspectJ 1.5) supports automatic conversion of primitive types (int, float, double etc.) to their object equivalents (Integer, Float, Double,...) in assignments and method and constructor invocations. This conversion is know as autoboxing. Its not possible to put an int (or other primitive value) into a collection. Collections can only hold objectreferences,soit‘stheneedtoboxprimitivevaluesintotheappropriatewrapperclass(whichis Integer in the case of int). its possible to take the object out of the collection, as Integer and put in; if you need an int, you must unbox the Integer using the int Value method. For Example // Prints a employee table of the words on the command line import java.util.*; public class employeeTable { public static void main(String[] args) { Map m = new TreeMap(); for (String word : args) { Integer emp = m.get(word); m.put(word,emp ( == null ? 1 : map + 1)); } System.out.println(m); } } java employee 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} The program first declares a map from String to Integer, associating the number of times a word occurs on the command line with the word. Then it iterates over each word on the command line. For each word, it looks up the word in the map. Then it puts a revised entry for the word into the map. The line that does this (highlighted in green) contains both autoboxing and unboxing. To compute the new value to associate with the word, first it looks at the current value (freq). If it is null,
8 this is the first occurrence of the word, so it puts 1 into the map. Otherwise, it adds 1 to the number of prior occurrences and puts that value into the map. But of course you cannot put an int into a map, nor can you add one to an Integer. What is really happening is this: In order to add 1 to freq, it is automatically unboxed, resulting in an expression of type int. Since both of the alternative expressions in the conditional expression are of type int, so too is the conditional expression itself. In order to put this int value into the map, it is automatically boxed into an Integer. The result of all this magic is that you can largely ignore the distinction between int and Integer, with a few caveats. An Integer expression can have a null value. If your program tries to autounbox null, it will throw a NullPointerException. The == operator performs reference identity comparisons on Integer expressions and value equality comparisons on int expressions. Finally, there are performance costs associated with boxing and unboxing, even if it is done automatically. Generic Classes Generics allow you to abstract over types List myIntList = new LinkedList(); List ls = new ArrayList(); //1 Using Interfaces small excerpt from the definitions of the interfaces List and Iterator in package java.util: public interface List { void add(E x); Iterator iterator(); } public interface Iterator { E next(); boolean hasNext(); }
Reg Annonymous and Inner classes Additional properties to inner class 1. An inner class is a class defined inside another class 2. An inner class object is scoped not to the outer class, but to the instantiating object. 3. Even if the inner class object is removed from the outer class object that instantiated it, it retains the scoping to its creator. 4. If an object has a reference to another object's ("parent object"'s) inner class object, the inner class object is dealt with by that object as a separate, autonomous object, but in fact, it still has access to the private variables and methods of its parent object. 5. An inner class instantiation always remembers who it's parent object is and if anything changes in the parent object (e.g. one of its property's value changes), that change is reflected in all its inner class instantiations. 6. Inner classes are very useful in factory pattern situations. 7. Inner classes cannot have static members. only static final variables 8. Inner classes may inherit static members that are not compile-time constants even though they may not declare them. 9. If your class requires the use of a number of other classes that are related to each other (ie form a class hierarchy) and those classes are particular to the parent class (ie are ideal candidates for
9 implementation as inner classes) then it is probable that the super class of the inner class hierarchy will be abstract. normal class declaration] { [scoping] class [inner class's name] [extends ....] [ implements ...] { // properties and methods of the inner class } // rest of properties and methods of parent class } Additional Properties of Inner Class Anonymous inner classes are very similar to named inner classes: Anonymous inner classes can override methods of the superclass. Anonymous inner classes are scoped inside the private scoping of the outer class. They can access the internal (private) properties and methods of the outer class. References to an inner class can be passed to other objects. Note that it still retains its scoping. Anonymous inner classes must use the no parameter constructor of the superclass. Usages: Very useful for controlled access to the innards of another class. Very useful when you only want one instance of a special class. Anonymous Class Since an object made from the inner class has a "life" independent of its outer class object, there is a problem with accessing local variables, especially method input paramenters.
Inner Class Initialize a property that the inner class then uses -- properties have the cross-method-call persistence that local variables lack. Two ways to pass initializing parameters to an inner class: Make the local variable "final" -- compiler will automatically transfer the value to a more persistent portion of the computer memory. Disadvantage: the value cannot be changed. Java.Lang.* [a package that is imported by java by default ,if imported again no harm ] java.lang.Object Super class of All classes & objects. constructor : public Object() Methods: 1. public final Class getClass( ) --> Returns the Class of this Object 2. public int hashCode( ) return hashCode. Each Object in the Java system has a hashcode. The hashcode is a number that is usually different for different Objects. Stored in HashTable Hashcode will be available @ toString() method before overriding on overriding the value is modified. Each class will have its own hashcode().Every object created to the class will have same hashcode to the class.If used was to get hashcode . Hashcode is a 32 bit integer ASCII that is used to find the argument of the class. 3. public boolean equals(Object obj) --> Compares two Objects for equality. Returns a boolean that indicates whether this Object is equivalent to the specified Object. This method is used when an Object is stored in a hashtable. 4. protected void copy(Object src) throws ClassCastException --> Copies the contents of the specified Object into this Object. The contents of an Object are defined as the values of its instance variables. The parameter src must be of the same Class as this Object. If obj is not of the same type as this Object.
10
5. protected Object clone( ) throws OutOfMemoryError --> Creates a clone of this Object. A new instance is allocated and the copy() method is called to copy the contents of this Object into the clone. If there is not enough memory throw exception 6. public String toString( ) --> Returns a String that represents the value of this Object. It is recommended that all subclasses override this method. 7. public final void notify( ) throws InternalError --> Notifies a single waiting thread on a change in condition of another thread. The thread effecting the change notifies the waiting thread using notify(). Threads that want to wait for a condition to change before proceeding can call wait().can only be called from synchronized method. 8. public final void notifyAll( ) throws InternalError --> Notifies all of the threads waiting for a condition to change. Throws error If the current thread is not the owner of the Object's monitor. 9. public final void wait( long timeout) throws InterruptedException --> Causes a thread to wait until it is notified or the specified timeout expires. 10. public final void wait( ) throws InterruptedException --> Causes a thread to wait forever until it is notified. Interfaces in Java.Lang.*. 1. runnable --> The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called public void run() { } Cloneable --> empty method[marker] implemented interface. implemented to a class and override objects clone method. It is used to get the duplicate copy of an object. CloneNotSupportedException being thrown if class not implements cloneable interface. Comparable --> This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo() is referred to as its natural comparison method. Hashcode Hashcode is a unique 32 bit ascii value for a particular class. A class can have n number of objects with same Hashcode. Hashcode Is a method in Java.lang.Object unique code If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. public int hashCode() CharSequence --> A CharSequence is a readable sequence of characters. This interface provides uniform, read-only access to many different kinds of character sequences. To get the data in desired order to our constraint use comparable. StringS=newString―(abc‖); S=S+―d‖; NowS=―abcd‖,
11 String String is immutable.any value assigned cannot be altered. Simply stated, objects of type String are read only and immutable. Instantiation slower comparatively to a stringBuffer String class is used to manipulate character strings that cannot be changed.
StringBuffer StringBuffer grows.it is a growable array of string /characters. Instantiation is faster than a string.
String Buffer String Buffer is Synchronized
String Builder String Builder is not Synchronized, Performance is better than string buffer
The StringBuffer class is used to represent characters that can be modified.
Public static void main ( String a[ ] ) { } If used as Private static void main(in[] arg) { } --> 2 errors 1. runtime error as main is declared private 2. java by default takes arg as string args which is a class ,no datatype allowed. Public – access modifier Static – no need to create instance for the main method Void – no arguments Main( ) – 1st method invoked by JVM. String a[ ] – command-line arguments as string arguments. If command line arguments not given taken as empty not null To execute a set of code before creating object / main() put it as below static { //executable code need to get executed before creating object for the class } Condition statements– if. Iteration(Looping) – while, do-while, for. Jump statements – break, continue, return. System.out.println( ) System – a class in Java.Lang package. Out – Static object reference of printstream class of java.io package. Println( ) – a method in printstream class.
String Class methods CharAt() ; getChars() , toCharArray() , equals() ,equalsIgnoreCase() , equalsUpperCase() ,equalsLowerCase() , regionMatches() , compareTo(), indexOf(), lastIndexOf() , substring() , concat() , replace() ,trim() , getBytes() StringBuffer Class Methods Length() , Capacity() ,ensureCapacity() , setLength() , charAt(), setCharAt() ,getChars(), append(), insert(), reverse(), delete(), deleteCharAt(), replace(), subString() String s=new String() String(String s1) String(StringBuffer s2) // will be executed faster than the previous one. subString( ) - creates a copy of the string & a substring is generated from that copy.
12
Exception: A Condition that transfer a java program from a thrower to a catcher. Information is passed as Exception or error object. Throwable 1. Exceptions 2. errors. Compile time exception (Checked exception): --> exceptions part of java.Lang Package. --> Happens as the case of compile time --> handled by java directly. Example : classNotfoundException. FileNotFoundException. InterruptedException. Runtime Exception ( Unchecked exception)
--> handled by Programmer / User. --> exceptions occur at run time. --> Belong to system as a whole.may be case of wrong Input. Example : Runtime Exception. NumberFormatException StringIndexOutOfBoundsException ArrayIndexOutOfBoundsException. Occurence Of NullPointerException If a Method has 6 Parameters , If I pass 5 parameters at runtime ,it gives nullPointer Exception. Super class of Exception --> java.lang.Throwable Key Words in Exception : try , Catch , finally, throw, throws, Exception. Display exception to USER --> exception.printStackTrace(); Try – catch – finally try { // condition to check and the executable logic / code will be given here. } catch (Exception e) { The exception is caught here } finally { // Must execute things like closing a connection / statement will be given here. // A try must be followed with catch or finally blocks. } try {
System.exit(0); // deny finally to execute. // normal termination of execution // System.exit(non ZERO); Abnormal termination of condition.
} try{ // Executable code } catch(Exception e) { } catch(Exception e) { } // code will not be executed since Exception already caught. catch(Exception e) { } for throw
13 static int divide(int first,int second) throws MyException{ if(second==0) { throw new MyException("can't be divided by zero"); } return first/second; } execution from a thrower to a catcher. Throw Throws Declared with a reference name inside a declared along with a class / method. method. Statement below throw will not be executed. Exception is caught and is displayed to user. Only one exception can be given at a time Multiple exceptions can be declared. Try - catch compulsory Try – catch optional. Support both checked and unchecked Support only checked exception exceptions Error Exception Errors can be caught at the time of execution exception is a condition that transfer program of a program. Checked and unchecked exceptions are there. Syntax & logical errors are there. user-defined exception. Class user_defined_exception extends exception { // desired code in exception } Application Exception : Exceptions that are directly thrown to client. public class InvocationTargetException extends Exception public class UndeclaredThrowableException extends RuntimeException Difference between comparable() and comparator() Comparable shows that the class knows how to compare ITSELF against another class
Comparator interface allows a single class know how to compare two classes which (typically) are not the same type as the comparator.
THREADING THREAD A Set of sequential instructions that run independently of one another yet can directly share resources with other threads. Create instance of a thread or thread sub class – invoke start() on instance. 3 Phases of Thread – prebirth ,life , death. Ways to use Thread 1. Extend the Java.Lang.Thread Subclass Class myThread extends Thread { } 2. Implement the Runnable interface public interface Runnable { abstract public void run(); } Make use of it Animation happy = new Animation("Mr. Happy"); Thread myThread = new Thread( happy ); myThread.start(); Thread’s Execution time A Thread continues to execute until one of the following things happens:
14 It returns from its target run() method It's interrupted by an uncaught exception Its stop() method is called So what happens if the run() method for a thread never terminates, and the application that started the thread never calls its stop() method? The answer is that the thread lives on, even after the application that created it has finished. This means we have to be aware of how our threads eventually terminate, or an application can end up leaving orphaned threads that unnecessarily consume resources. Thread Processes takes same workspace for executing different takes separate workspace for executing operations with different data. different data. Error and Exception An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you cannot repair them at runtime.Though error can be caught in catch block but the execution of application will come to a halt and is not recoverable. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.) Thread synchronization -->different threads take proper turns while using shared resources. Monitor – set of code blocks marked, one thread at a time, a protected portion of code enforce one thread at a time policy. Static Synchronized --> thread obtain lock on the class object. Yield( ) --> provide maximum chances for other threads to run. Thread States in Yield – runnable, running, waiting , dead. Thread Class , Runnable Interface --> extends a thread using either thread class or implementing runnable interface. Public void run() { } // Create the object with the run() method Runnable runnable = new BasicThread2(); // Create the thread supplying it with the runnable object Thread thread = new Thread(runnable); // Start the thread thread.start(); Thread Properties --> thread can voluntarily relinquish control --> Preempted by higher priority thread. Priorities of thread: MIN_PRIORITY = 1 NORM_PRIORITY = 5 MAX_PRIORITY = 10 DAEMON THREAD : Daemon threads are service providers for other threads running in the same process as the daemon thread. call the setDaemon() method with the argument true check isDaemon() that returns true or false to check if the thread is a daemon thread or not. Example for Daemon thread : Garbage Collector. After all threads complete execution ,Daemon thread will execute.
15 Sleep() The time defined for a thread to stop temporarily from execution will be kept till the time completes and on any cause the thread will be allowed to get executed. For example say a thread given time 600ms to execute it takes only 400ms then that 200mscan‘tbeutilized.
wait( ) The time defined in milliseconds will not be kept till the end.If needed the thread is got back to execution b using notify() or notifyAll() methods. Here in this case the time taken [say 200ms in sleep] can be utilized by either using notify() or notifyall()
Notify() 'notify' wakes up a single thread waiting on the object and passes the control of the monitor to it.
NotifAll() notifyAll wakes up a larger candidate pool of threads - any of those threads that are notified are candidates to enter the 'running' state.
Methods in a thread class Final Boolean isAlive() Final void join() Final void setPriority(int level) { } Final void notify() Final void notifyAll() Final void suspend() Final void resume() Thread states --> Start() , ready() , sleep() , wait() , stop() Class abc { // int a; --> not a static variable, can‘tbeaccessedbymainmethod. Synchronization Synchronization among threads in Java is to serialize their access to some resource, namely an object. Synchronization makes sure only one thread at a time can perform certain activities that manipulate an object. In Java, every object has a lock associated with it. To be more specific, every class and every instance of a class has its own lock. The synchronized keyword marks places where a thread must acquire the lock before proceeding. Example class SpreadSheet { int cellA1, cellA2, cellA3; synchronized int sumRow() { return cellA1 + cellA2 + cellA3; } synchronized void setRow( int a1, int a2, int a3 ) { cellA1 = a1; cellA2 = a2; cellA3 = a3; } ... } ThreadGroup A ThreadGroup is used to represent a group of Threads. A tree structure can be formed from ThreadsGroups containing other ThreadGroups. Threads can only access the ThreadGroup to which they belong. This means that access to a ThreadGroups parent or other ThreadGroup is not permitted. Once a ThreadGroup is created various information can be obtained such as the ThreadGroups name, how many threads are active, the maximum priority that can be contained within the group and a host of other information.
16 The ThreadGroup class provides two constructors. ThreadGroup(String name) ThreadGroup(ThreadGroup parent, String name) public class ThreadGroupTest{ public static void main(String[] args){ ThreadGroup squares = new ThreadGroup("Squares"); Thread t1 = new Thread(squares, new T(), "t1"); Thread t2 = new Thread(squares, new T(), "t2"); t1.start(); t2.start(); System.out.println("ThreadGroup name is: " + squares.getName()); System.out.println("There are currently " + squares.activeCount() + " threads running"); System.out.println("The maximum priority of a Thread that can be contained within " + squares.getName() + " is " + squares.getMaxPriority()); System.out.println("There are currently " + squares.activeGroupCount() + " active groups"); System.out.println(squares.getName() + " parent is " + squares.getParent()); } } class T implements Runnable{ private int square; public void run(){ for(int i = 1; i < 5; i++){ square = i * i; System.out.println("Thread" + Thread.currentThread().getName()+" has a priority of " + Thread.currentThread().getPriority() + ": " + square); } } } what will happen if i set it as setPriority(100000000)? Exception in thread "main" java.lang.IllegalArgumentException at java.lang.Thread.setPriority(Unknown Source) at com.wellpoint.common.eis.edirouter.utils.XmlHelper.main(XmlHelper.java:1325) Cloning in Java Java supports two type of cloning: - Deep and shallow cloning. By default shallow copy is used in Java. Object class has a method clone() which does shallow cloning. In shallow copy the object is copied without its contained objects. Shallow clone only copies the top level structure of the object not the lower levels. It is an exact bit copy of all the attributes. Figure 1: Original java object obj
17 The shallow copy is done for obj and new object obj1 is created but contained objects of obj are not copied.
Figure 2: Shallow copy object obj1 It can be seen that no new objects are created for obj1 and it is referring to the same old contained objects. If either of the containedObj contain any other object no new reference is created Characteristic: If we do a = clone(b) 1) Then b.equals(a) 2) No method of a can modify the value of b. Deep Cloning Ans) In deep copy the object is copied along with the objects it refers to. Deep clone copies all the levels of the object
Figure 3 : Original Object obj When a deep copy of the object is done new references are created.
Figure 4: obj2 is deep copy of obj1 One solution is to simply implement your own custom method (e.g., deepCopy()) that returns a deep copy of an instance of one of your classes. This may be the best solution if you need a complex mixture of deep and shallow copies for different fields, but has a few significant drawbacks: You must be able to modify the class (i.e., have the source code) or implement a subclass. If you have a third-party class for which you do not have the source and which is marked final, you are out of luck.
18 Youmustbeabletoaccessallofthefieldsoftheclass‘ssuperclasses.Ifsignificantpartsoftheobject‘s state are contained in private fields of a superclass, you will not be able to access them. You must have a way to make copies of instances of all of the other kinds of objects that the object references. This is particularly problematic if the exact classes of referenced objects cannot be known until runtime. Custom deep copy methods are tedious to implement, easy to get wrong, and difficult to maintain. The method must be revisited any time a change is made to the class or to any of its superclasses. Other common solution to the deep copy problem is to use Java Object Serialization (JOS). The idea is simple:WritetheobjecttoanarrayusingJOS‘sObjectOutputStreamandthenuse ObjectInputStream to reconsistute a copy of the object. The result will be a completely distinct object, with completely distinct referenced objects. JOS takes care of all of the details: superclass fields, following object graphs, and handling repeated references to the same object within the graph. It will only work when the object being copied, as well as all of the other objects references directly or indirectly by the object, are serializable. (In other words, they must implement java.io.Serializable.) Fortunately it is often sufficient to simply declare that a given class implements java.io.Serializable and let Java‘sdefaultserialization mechanisms do their thing. Java Object Serialization is slow, and using it to make a deep copy requires both serializing and deserializing. There are ways to speed it up (e.g., by pre-computing serial version ids and defining custom readObject() and writeObject() methods), but this will usually be the primary bottleneck. The byte array stream implementations included in the java.io package are designed to be general enough to perform reasonable well for data of different sizes and to be safe to use in a multi-threaded environment. These characteristics, however, slow down ByteArrayOutputStream and (to a lesser extent) ByteArrayInputStream . Difference Between the two Ans) The differences are as follows: Consider the class: public class MyData{ String id; Map myData; } Theshallowcopyingofthisobjectwillhavenewidobjectandvaluesas‖―butwillpointtothemyDataof the original object. So a change in myData by either original or cloned object will be reflected in other also. But in deep copying there will be new id object and also new myData object and independent of original object but with same values. Shallow copying is default cloning in Java which can be achieved using clone() method of Object class. For deep copying some extra logic need to be provided. Disadvantages: Ans) Disadvantages of using Serialization to achieve deep cloning Serialization is more expensive than using object.clone(). Not all objects are serializable. Serialization is not simple to implement for deep cloned object.. constructor call on Deserialization During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream. By default, only one ResultSet object per Statement object can be open at the same time. Therefore, if the reading of one ResultSet object is interleaved with the reading of another, each must have been
19 generated by different Statement objects. All execution methods in the Statement interface implicitly close a statment's current ResultSet object if an open one exists. A stored procedure can process related data and return multiple result sets, this way may save fewer calls to database server. You need to include code to retrieve the result sets, Java JDBC Statement provide the getResultSet method to retrieve each result set. You can access the first result set by calling the getResultSet method on your Statement object. In a loop, position the cursor using the next method, and retrieve data from each column of the current row of the ResultSet object using getXXX methods. To determine if more result sets are available, you can call the getMoreResults method in Statement, which returns a boolean value of true if more result sets are available. If more result sets are available, you can call the getResultSet method again to access them, continuing the process until all result sets have been processed. If the getMoreResults method returns false, there are no more result sets to process. Calling getMoreResults() implicitly closes any previously returned ResultSet object(s) from method getResultSet. In the following example, an open connection to the Database SQL Server is passed in to the function, and the stored procedure is returns n result sets: public static void executeProcedure(Connection con) { try { CallableStatement stmt = con.prepareCall(...); ..... //Set call parameters, if you have IN,OUT, or IN/OUT parameters boolean results = stmt.execute(); int rsCount = 0; //Loop through the available result sets. while (results) { ResultSet rs = stmt.getResultSet(); //Retrieve data from the result set. while (rs.next()) { ....// using rs.getxxx() method to retieve data } rs.close(); //Check for next result set results = stmt.getMoreResults(); } stmt.close();
} catch (Exception e) { e.printStackTrace(); }
} When you make the call to the getMoreResults() method of the Statement class, the previously returned result set is implicitly closed. How to keep result sets open when you check the next availiable result set. You can call the one with a parameter getMoreResults(int current) method. The parameter current indicates what should happen to current ResultSet objects obtained using the method getResultSet. You can specify one of these constants: Statement.KEEP_CURRENT_RESULT : Checks for the next ResultSet, but does not close the current ResultSet. Statement.CLOSE_CURRENT_RESULT : Checks for the next ResultSet, and closes the current ResultSet. Statement.CLOSE_ALL_RESULTS : Closes all ResultSets that were previously kept open GARBGAGE COLLECTION
20 When a object or method or variable is no longer needed the memory space allocated will be garbage collected and is made available for reuse. Javadoesn‘tguaranteewhenGarbagecollectorwillbecalled. I t can be called in 4 ways as 1. Automatic call by compiler 2. System.gc(); 3. Protected void finalize() { } 4. use java.lang.ref.Reference.clear() to force Garbage collection to happen. can a for loop be garbage collected? The memory occupied by for loop is garbage collected. I mean for eg. you decl a variable i and increment the value. that i occupy some memory that memory is garbage collected. JVM is responsible for calling garbage collector garbage collector is a deamon thread. Java.lang.ref –A object is reclaimed or recreated is made available for reuse. use java.lang.ref.Reference.get() to reclaim the object that is enqued for gc [ for Detailed Description see below] Java.Lang.Ref HIERARCHY Classes public abstract class Reference extends Object class defines the operations common to all reference objects
Methods in Reference public void clear() --> Clears this reference object public boolean enqueue() --> Adds this reference object to the queue with which it is registered public Object get() --> Returns this reference object's referent. Public boolean isEnqueued() --> Tells whether or not this reference object has been enqueued, either by the program or by the garbage collector public class ReferenceQueue extends Object --> to which registered reference objects are appended by the garbage collector after the appropriate reachability changes are detected. Methods in ReferenceQueue public Reference poll( ) --> Polls this queue to see if a reference object is available, returning one immediately if so. public Reference remove( long timeout) --> Removes the next reference object in this queue, blocking until either one becomes available or the given timeout period expires. public Reference remove( ) --> Removes the next reference object in this queue, blocking until one becomes available. public class SoftReference extends Reference --> Soft reference objects, which are cleared at the discretion of the garbage collector in response to memory demand. Soft references are most often used to implement memory-sensitive caches. Constructors in SoftReference. SoftReference(Object referent)--> Creates a new soft reference that refers to the given object.
21 SoftReference(Object referent, ReferenceQueue q) --> Creates a new soft reference that refers to the given object and is registered with the given queue. PhantomReference extends Reference which are enqueued after the collector determines that their referents may otherwise be reclaimed. Methods in SoftReference Public Reference get() --> Returns this reference object's referent. public class WeakReference extends Reference --> Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings. Constructors --> SoftReference(Object referent), SoftReference(Object referent, ReferenceQueue q) Java.Lang.Reflect Classes public class AccessibleObject extends Object --> base class for Field, Method and Constructor objects. It provides the ability to flag a reflected object as suppressing default Java language access control checks when it is used. The access checks--for public, default (package) access, protected, and private members--are performed when Fields, Methods or Constructors are used to set or get fields, to invoke methods, or to create and initialize new instances of classes, respectively Constructor protected AccessibleObject() --> used by the Java Virtual Machine. Methods in AccessibleObject public static void setAccessible(AccessibleObject[] array,boolean flag) throws SecurityException --> Convenience method to set the accessible flag for an array of objects with a single security check (for efficiency). public void setAccessible(boolean flag)throws SecurityException --> Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks public boolean isAccessible() --> Get the value of the accessible flag for this object. public final class Array extends Object public static Object newI nstance(Class componentType,int length)throws NegativeArraySizeException --> Creates a new array with the specified component type and length. public static Object newInstance(Class componentType, int[] dimensions) throws IllegalArgumentException, NegativeArraySizeException --> Creates a new array with the specified component type and dimensions --> componentType - the Class object representing the component type of the new array --> dimensions - an array of int types representing the dimensions of the new array public static int getLength(Object array) --> Returns the length of the specified array object, as an int. public static Object get(Object array,int index) --> Returns the value of the indexed component in the specified array object. The value is automatically wrapped in an object if it has a primitive type. public static boolean getBoolean(Object array,int index) --> Returns the value of the indexed component in the specified array object, as boolean. Similarly getByte(), getChar()getShort(),getInt(),getLong(), getFloat(),getDouble(), public static void set(Object array, int index, Object value)
22 --> Sets the value of the indexed component of the specified array object to the specified new value. The new value is first automatically unwrapped if the array has a primitive component type. public static void setBoolean(Object array, int index, boolean z) --> Sets the value of the indexed component of the specified array object to the specified boolean value. Similarly setByte(),setChar(),setShort(),setInt(),setLong(),setFloat(), setDouble(). public final class Constructor extends AccessibleObject implements Member --> Constructor provides information about, and access to, a single constructor for a class. public Class getDeclaringClass() --> public String getName()--> Return Constructor name public int getModifiers()--> Java language modifiers for the constructor represented by this Constructor object, as an integer to decode modifiers public Class[] getParameterTypes()--> array of Class objects that represent the formal parameter types, in declaration order,length 0 refer no parameter. public Class[] getExceptionTypes()--> Returns an array of Class objects that represent the types of of exceptions declared to be thrown by the underlying constructor represented by this Constructor object. public boolean equals(Object obj)--> comapares this Constructor against the specified object. public int hashCode() --> returns hash code for constructor public String toString()--> Returns a string describing this Constructor. public Object newInstance(Object[] initargs) --> represented by this Constructor object to create and initialize a new instance of the constructor's declaring class, with the specified initialization parameters. public final class Method extends AccessibleObject implements Member method provides information about, and access to, a single method on a class or interface equals(Object obj) --> Compares this Method against the specified object getDeclaringClass()--> Returns the Class object representing the class or interface that declares the method represented by this Method object. getExceptionTypes()--> Returns an array of Class objects that represent the types of the exceptions declared to be thrown getModifiers() --> Java language modifiers for the method represented by this Method object, as an integer. getName()--> Returns the name of the method represented by this Method object, as a String. getParameterTypes()--> Returns an array of Class objects that represent the formal parameter types, in declaration order, of the method represented by this Method object. getReturnType()--> Returns a Class object that represents the formal return type of the method represented by this Method object. hashCode() --> Returns a hashcode for this Method. invoke(Object obj, Object[ ] args)--> Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.
23
toString()--> Returns a string describing this Method. public class Modifier extends Object --> provides static methods and constants to decode class and member access modifiers Fields Public static int ABSTRACT --> representing the abstract modifier. Public static int FINAL --> representing the final modifier. Public static int INTERFACE --> representing the interface modifier Public static int NATIVE --> representing the native modifier. Public static int PRIVATE --> representing the private modifier. Public static int PROTECTED --> representing the protected modifier Public static int STATIC--> representing the static modifier. Public static int STRICT --> representing the strictfp modifier. Public static int SYNCHRONIZED --> representing the synchronized modifier. Public static int TRANSIENT --> representing the transient modifier. Public static int VOLATILE --> representing the volatile modifier Methods returns true isAbstract(int mod) --> specifier integer includes the abstract modifier isFinal(int mod) --> specified integer includes the final modifier. isI nterface(int mod)--> specifier integer includes the interface modifier isNative(int mod) --> specifier integer includes the native modifier. isPrivate(int mod) --> specifier integer includes the private modifier isProtected(int mod)--> specifier integer includes the protected modifier. isPublic(int mod)--> specified integer includes the public modifier. isStatic(int mod)--> specifier integer includes the static modifier. isStrict(int mod)--> specifier integer includes the strictfp modifier. isTransient(int mod)--> specifier integer includes the transient modifier isVolatile(int mod)--> specified integer includes the volatile modifier. toString(int mod)--> Return a string, access modifier flags in the specified modifier public class Proxy extends Object implements Serializable --> Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods. getI nvocationHandler(Object proxy) --> Returns the invocation handler for the specified proxy instance getProxyClass(ClassLoader loader, Class[] interfaces)--> Returns the java.lang.Class object for a proxy class given a class loader and an array of interfaces. isProxyClass(Class cl)--> Returns true if and only if the specified class was dynamically generated to be a proxy class using the getProxyClass method or the newProxyInstance method. newProxyI nstance(ClassLoader loader,Class[] interfaces, InvocationHandler h) --> Returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler. public final class ReflectPermission extends BasicPermission Constructor --> public ReflectPermission(String name) Methods are inherited from java.security.BasicPermission --> equals, getActions, hashCode, implies, newPermissionCollection java.security.Permission --> checkGuard, getName, toString class java.lang.Object --> clone, finalize, getClass, notify, notifyAll, wait Interfaces in Java.Lang.Reflect public interface I nvocationHandler Methods public Object invoke(Object proxy,Method method, Object[] args)
24 throws Throwable --> Processes a method invocation on a proxy instance and returns the result. This method will be invoked on an invocation handler when a method is invoked on a proxy instance that it is associated with. public interface Member --> Member is an interface that reflects identifying information about a single member (a field or a method) or a constructor. Methods getDeclaringClass() --> Returns the Class object representing the class or interface that declares the member or constructor represented by this Member. getModifiers() --> Returns the Java language modifiers for the member or constructor represented by this Member, as an integer getName() --> Returns the simple name of the underlying member or constructor represented by this Member JAVA.IO PACKAGE Byte Streams handle I/O of raw binary data. FileInputStream FileOutputStream Example import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; public class CopyBytes { public static void main(String[] args) throws IOException { FileInputStream in = null; FileOutputStream out = null; try { in = new FileInputStream("xanadu.txt"); out = new FileOutputStream("outagain.txt"); int c; while ((c = in.read()) != -1) { out.write(c); } } finally { if (in != null) { in.close(); } if (out != null) { out.close(); } } } } Character Streams handle I/O of character data, automatically handling translation to and from the local character set. All character stream classes are descended from Reader and Writer. As with byte streams, there are character stream classes that specialize in file I/O: FileReader and FileWriter. The import java.io.FileReader;
25 import java.io.FileWriter; import java.io.IOException; public class CopyCharacters { public static void main(String[] args) throws IOException { FileReader inputStream = null; FileWriter outputStream = null; try { inputStream = new FileReader("xanadu.txt"); outputStream = new FileWriter("characteroutput.txt"); int c; while ((c = inputStream.read()) != -1) { outputStream.write(c); } } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } }
} } CopyCharacters is very similar to CopyBytes. The most important difference is that CopyCharacters uses FileReader and FileWriter for input and output in place of FileInputStream and FileOutputStream Buffered Streams optimize input and output by reducing the number of calls to the native API. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full. inputStream = new BufferedReader(new FileReader("xanadu.txt")); outputStream =new BufferedWriter(new fileWriter("characteroutput.txt")); It often makes sense to write out a buffer at critical points, without waiting for it to fill. This is known as flushing the buffer. Some buffered output classes support autoflush, specified by an optional constructor argument. When autoflush is enabled, certain key events cause the buffer to be flushed. For example, an autoflush PrintWriter object flushes the buffer on every invocation of println or format. See Formatting for more on these methods. To flush a stream manually, invoke its flush method. The flush method is valid on any output stream, but has no effect unless the stream is buffered. Data Streams handle binary I/O of primitive data type and String values. Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as well as String values. All data streams implement either the DataInput interface or the DataOutput interface. The program defines some constants containing the name of the data file and the data that will be written to it: static final String dataFile = "invoicedata"; static final double[] prices = { 19.99, 9.99, 15.99, 3.99, 4.99 }; static final int[] units = { 12, 8, 13, 29, 50 };
26 static final String[] descs = { "Java T-shirt", "Java Mug", "Duke Juggling Dolls", "Java Pin", "Java Key Chain" }; Then DataStreams opens an output stream. Since a DataOutputStream can only be created as a wrapper for an existing byte stream object, DataStreams provides a buffered file output byte stream. out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(dataFile))); DataStreams writes out the records and closes the output stream. for (int i = 0; i < prices.length; i ++) { out.writeDouble(prices[i]); out.writeInt(units[i]); out.writeUTF(descs[i]); } The writeUTF method writes out String values in a modified form of UTF-8. This is a variable-width character encoding that only needs a single byte for common Western characters. Now DataStreams reads the data back in again. First it must provide an input stream, and variables to hold the input data. Like DataOutputStream, DataInputStream must be constructed as a wrapper for a byte stream. in = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile))); double price; int unit; String desc; double total = 0.0; Now DataStreams can read each record in the stream, reporting on the data it encounters. try { while (true) { price = in.readDouble(); unit = in.readInt(); desc = in.readUTF(); System.out.format("You ordered %d units of %s at $%.2f%n", unit, desc, price); total += unit * price; } } catch (EOFException e) { } Notice that DataStreams detects an end-of-file condition by catching EOFException, instead of testing for an invalid return value Object Streams handle binary I/O of objects. The object stream classes are ObjectInputStream and ObjectOutputStream. These classes implement ObjectInput and ObjectOutput, which are subinterfaces of DataInput and DataOutput. If readObject() doesn't return the object type expected, attempting to cast it to the correct type may throw a ClassNotFoundException. Object ob = new Object(); out.writeObject(ob); out.writeObject(ob); Each writeObject has to be matched by a readObject, so the code that reads the stream back will look something like this: Object ob1 = in.readObject(); Object ob2 = in.readObject(); This results in two variables, ob1 and ob2, that are references to a single object.
27 Read a character from a keyboard / file. BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); fileInputStreamReader fin = new FileInputStreamReader(); br.load(fin); write a character into a file BufferedReader br = new BufferedReader(new OutputStreamReader(System.in)); fileOutputStreamReader fout = new FileOutputStreamReader(); br.store(fout); to read a character from Keyboard BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); br.readLine(); Return null when ends in EOF of File. TO UPLOAD & DOWNLOAD A FILE USING JAVA.IO.FILE. package com.resource.util; import import import import import import import import import
java.io.BufferedInputStream; java.io.BufferedOutputStream; java.io.File; java.io.FileInputStream; java.io.FileOutputStream; java.io.IOException; java.net.MalformedURLException; java.net.URL; java.net.URLConnection;
public class FileUpload { public void upload( String ftpServer, String user, String password, String fileName, File source ) throws MalformedURLException, IOException { if (ftpServer != null && fileName != null && source != null){ StringBuffer sb = new StringBuffer( "ftp://" ); // check for authentication else assume its anonymous access. if (user != null && password != null) { sb.append( user ); sb.append( ':' ); sb.append( password ); sb.append( '@' ); } sb.append( ftpServer ); sb.append( '/' ); sb.append( fileName ); sb.append( ";type=i" ); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { URL url = new URL( sb.toString() ); URLConnection urlc = url.openConnection(); bos = new BufferedOutputStream( urlc.getOutputStream());
28 bis = new BufferedInputStream( new FileInputStream( source )); int i; // read byte by byte until end of stream while ((i = bis.read()) != -1) { bos.write( i ); } } Finally { if (bis != null) try { bis.close(); } catch (IOException ioe) { ioe.printStackTrace(); } if (bos != null) try { bos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } Else { System.out.println( "Input not available." ); } } public void download( String ftpServer, String user, String password,String fileName, File destination ) throws MalformedURLException,IOException { if (ftpServer != null && fileName != null && destination != null) { StringBuffer sb = new StringBuffer( "ftp://" ); // check for authentication else assume its anonymous access. if (user != null && password != null) { sb.append( user ); sb.append( ':' ); sb.append( password ); sb.append( '@' ); } sb.append( ftpServer ); sb.append( '/' ); sb.append( fileName ); /* * type ==> a=ASCII mode, i=image (binary) mode, d= file * directory listing */ sb.append( ";type=i" ); BufferedInputStream bis = null; BufferedOutputStream bos = null; try { URL url = new URL( sb.toString()); URLConnection urlc = url.openConnection();
29 bis = new BufferedInputStream( urlc.getInputStream() ); bos = new BufferedOutputStream( new FileOutputStream( destination.getName())); int i; while ((i = bis.read()) != -1) { bos.write( i ); } } finally { if (bis != null) try { bis.close(); } catch (IOException ioe) { ioe.printStackTrace(); } if (bos != null) try { bos.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } } else { System.out.println( "Input not available" ); } } } Properties of a bean All variables are private. All methods are public. If a variable is declared public it can be globally accessed. Will have set() and get() methods Serializable - java.io.serializable It is an [empty method] Marker interface Writes the state of the object into byte stream. Allow automatic typecasting. Doesn‘tsupportTransientandstatic. Base fields alone are handled if the base class implements serializable. Used or always Refer to Dynamic Contents. serialization is the process of saving an object's state to a sequence of bytes, as well as the process of rebuilding those bytes into a live object at some future time. Object is persistent. Externizable --> provide additional control for object that write into a byte stream Public void readExternal(objectInput OI) throws IOEXception--> write primitive data Public void writeExternal(objectOutput OO) throws IOException JAVA.UTIL.PACKAGE PACKAGE HIERARCHY. AbstractCollection
30 --> AbstractSequentialList --> LinkedList --> AbstractList --> ArrayList --> Vector --> Stack --> AbstractSet --> HashSet --> LinkedHashSet --> TreeSet --> AbstractMap --> HashMap --> LinkedHashMap --> IdentityHashMap --> TreeMap --> weakHashMap --> Arrays --> BitSet --> Calender --> Georgian Calender --> Collections --> Concurrency --> Date --> Dictionary --> HashTable --> Propeties --> EventListenerProxy --> EventObject --> Locale --> Observable --> Permission --> BasicPermission --> PropertyPermission --> Random --> ResourceBundle --> ListResourceBundle --> PropertyResourceBundle --> StringTokenizier --> Timer --> TimerTask --> TimeZone --> SmpleTimeZone Interface Hierarchy --> Collection --> List --> Set --> SortedSet --> Comparator --> Enumeration --> Eventistener --> Iterator --> ListIterator --> Map
31 --> SortedMap --> Map.Entry --> Observer --> RandomAccess. BASIC DIFFERENCES Vector Initial Size = 10; Will double its size while growing [if Size=100 increase to 200 from 200 to 400 ] Synchronized Automatic type casting is allowed Contain Legacy(built-in) methods that are not part of collections f/w. Poor Performance HashMap Not synchronized Allow duplicates and null key/null values No order maintained. Best performance. Collections Class Not Synchronized Iterator can be used. Best Performance Iterator Uni Directional Hasnext() Next(); Remove() Used in ArrayList HashMap No order Maintained 1 null Key 2null values Allowed List having mechanism access should be the same List Allow Duplicates Index based Access Enumeration Enumeration contains 2 methods namely hasMoreElements() & nextElement(). Using remove() its possible to delete objects. Enumeration deals with objects Can modify collection Objects. Part of legacy classes
ArrayList Initial size need not be defined. Grow in 2/3rd of its size [ If size=100 increase to 150 then 225 etc] Not synchronized Doesn‘tallowautomatictypecasting Doesn‘thaveandlegacymethods. Best Performance HashTable synchronized doesn‘tallowduplicates,nullkey/nullvalues data is hashed and stored and maintained in order. Poor Performance. Legacy Class Synchronized Enumeration can be used. Poor Performance. ListIterator BiDirectional Hasnext(); Next() Remove() hasPrevoius() previous() Used in LinkedList. TreeMap Default sort No Null Key / null Value allowed Fast Access Map No duplicates allowed Key based access Iterator Iterator contains three methods namely hasNext(), next(),remove(). Not supported to delete objects with Iterator iteration deals with values only Not Possible. Part of Collections class. iterator is fail-safe. iterator to go through a collection you can be sure of no concurrent modifications in the underlying collection which may happen in multi-threaded environments.
32 Enumeration is not fail safe. HashSet The underlying data structure is Hashtable Heterogeneous objects are allowed Insertion order is not preserved and it is based on hashcode of the objects null insertion is possible
iterator is a design pattern and the purpose is to abstract looping. TreeSet The underlying data structure is balanced tree Heterogeneous objects are not allowed bydefalut Insertion order is not preserved and all the objects are inserted according to some sorting order. As the first element only null insertion is possible and in all other cases we will get NullPointerException
Some points about collection objects List –allow Duplicates Set –no duplicates MAP –key / Value Pair Set Interface --> extends Collection. -->Doesn‘tallowDuplicates. --> Order is not maintained. --> add() List
Map
--> allow Duplicates. --> Order is maintained. --> add(), addAll() --> Interface. --> Store key / value pairs --> Values may be duplicated. Accept null key / null values.
HashMap
--> a Class implement Map ,has no specific methods uses methods of map --> example for Adapter class
Dictionary
--> Store key/value pairs. -->Doesn‘tallowduplicates. --> Put(),get(),size(),isEmpty(),remove()
Property Methods Tree Map
--> load() & store()
--> store key /value pairs --> Stored in sorted order for rapid retrieval
SortedSet
--> asset that maintain its elements in Ascending order First() last() SortedMap --> A map that maintains its mappings in ascending key order. Immediate Super class of vector and ArrayList – AbstractList implements List interface. Example for Collection Objects Vector
33 import java.util.*; public class VectorDemo{ public static void main(String[] args){ Vector vector = new Vector(); int primitiveType = 10; Integer wrapperType = new Integer(20); String str = "tapan joshi"; vector.add(primitiveType); vector.add(wrapperType); vector.add(str); vector.add(2, new Integer(30)); System.out.println("the elements of vector: " + vector); System.out.println("The size of vector are: " + vector.size()); System.out.println("The elements at position 2 is: " + vector.elementAt(2)); System.out.println("The first element of vector is:"+ vector.firstElement()); System.out.println("The last element of vector is: " + vector.lastElement()); vector.removeElementAt(2); Enumeration e=vector.elements(); System.out.println("The elements of vector: " + vector); while(e.hasMoreElements()){ System.out.println("The elements are: " + e.nextElement()); } } } ArrayList import java.util.*; public class ArrayListDemo{ public static void main(String[] args) { ArrayList arl=new ArrayList(); Integer i1=new Integer(10); Integer i2=new Integer(20); Integer i3=new Integer(30); Integer i4=new Integer(40); String s1="tapan"; System.out.println("The content of arraylist is: " + arl); System.out.println("The size of an arraylist is: " + arl.size()); arl.add(i1); arl.add(i2); arl.add(s1); System.out.println("The content of arraylist is: " + arl); System.out.println("The size of an arraylist is: " + arl.size()); arl.add(i1); arl.add(i2); arl.add(i3); arl.add(i4); Integer i5=new Integer(50); arl.add(i5); System.out.println("The content of arraylist is: " + arl); System.out.println("The size of an arraylist is: " + arl.size()); arl.remove(3); Object a=arl.clone(); System.out.println("The clone is: " + a);
34 System.out.println("The content of arraylist is: " + arl); System.out.println("The size of an arraylist is: " + arl.size()); } } merge 2 Arraylist ArrayList x = new ArrayList(); ArrayList y= new ArrayList(); x.add(‗a‘); x.add(‗b‘); x.add(‗c‘); y.add(‗d‘); for(int i=0; i between servlets & web servers 2.Life Cycle Management --> life and death of servlets & JSP 3.Multithreading support --> create and save threads to each servlets. 4.Declarative security --> http://localhost:8080/index.html 5.JSPSupport --> JSP into Servlets. Servlet – It is a server side component used to Transfer information to a user which is embedded in a HTTP Servlets. Servlets are modules that extend request/response-oriented servers, such as javaenabled web servers.For example, a servlet might be responsible for taking data in an HTML order-entry formandapplyingthebusinesslogicusedtoupdateacompany‘sorderdatabase.
61
ServletContext Defines a set of methods that a servlet uses to communicate with its servlet container, refer to all / Common applications total web application. even to a jar file. public interface ServletContext for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.) In the case of a web application marked "distributed" in its deployment descriptor, there will be one context instance for each virtual machine, the context cannot be used as a location to share global information (because the information won't be truly global). Use an external resource like a database instead. servletContext.getParameter(―name‖,Value); servletConetxt.setParameter(―name‖,Value); ServletContext context = getServletContext(); InputStream is = context.getResourceAsStream("/yourfilename.cnf"); The ServletContext.getResourceAsStream() method the file can be located anywhere in your web application. It is recommended to keep it under the /WEB-INF directory if you don't want browers being able to access it. Your web application should use the ServletContext.getResourceAsStream() API when accessing web application resources. ServletContext Defines a set of methods that a servlet uses to communicate with its servlet container. The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized. You can specify param-value pairs for ServletContext object in tags in web.xml file. The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets. The ServletContext parameters are specified for an entire application outside of any particular servlet and are available to all the servlets within that application. public interface ServletConfig ServletConfig is a servlet configuration object used by a servlet container used to pass information to a servlet during initialization. All of its initialization parameters can ONLY be set in deployment descriptor. This interface is implemented by services in order to pass configuration information to a servlet when it is first loaded. A service writer implementing this interface must write methods for the servlet to use to get its initialization parameters and the context in which it is running. A servlet configuration object used by a servlet container to pass information to a servlet during initialization refer to particular (servlet) applications.to set() and get() value from a object. getInitParameter(String) Returns a string containing the value of the named initialization parameter of the servlet, or null if the parameter does not exist. getInitParameterNames() Returns the names of the servlet's initialization parameters as an enumeration of strings, or an empty enumeration if there are no initialization parameters. getServletContext()
Returns the context for the servlet.
servletConfig.getParameter(―name‖,Value); servletConfig.setParameter(―name‖,Value);
62 ServletConfig config = context.getServletConfig Config.getInitparameters (); Generic Servlet Support all kind of protocols like FTP,TCP,IP,UDP including HTTP. Application server support all kind of protocols. Weblogic,WebSphere,JBoss all can be used.
() HTTP-Servlet Support only HTTP Protocol. WebServer support only HTTP Protocol. Weblogic,WebSphere,JBoss all can be used also TomCat.
1.Generic( super class of all servlets) Methods 1. public void destroy() 2. public java.lang.String getInitParameter(java.lang.String name) 3. public java.util.Enumeration getInitParameterNames() 4. public ServletConfig getServletConfig() 5. public ServletContext getServletContext() 6. public java.lang.String getServletInfo() 7. public void init(ServletConfig config)throws ServletException 8. public abstract void service(ServletRequest req, ServletResponse res)throws ServletException,IOException 9. public java.lang.String getServletName() HttpServlet Servlet Life Cycle Init( ) & destroy( ) will be called only once. Service( ) will be called when first request is generated called any number of times . Init( ) --> Public void init(servletConfig sc) throws ServletException,IOException Service( ) Public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException Public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException --> get resource file Public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException --> doget() with extra info Public void doOptions(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException --> list of HTTP Methods Public void doTrace(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException --> client can see what is sent in other end. Public void doPut(httpServletRequest req, HttpServletResponse res) throws IOException, ServletException --> put into request URL Public void doDelete(httpServletRequest req, HttpServletResponse res) throws IOException, ServletException --> delete info from Requested URL Public void getServletInfo(httpServletRequest req, HttpServletResponse res) throws IOException, ServletException Destroy( ) Public void destroy() throws IOException, ServletException constructor constructors for dynamically loaded Java
Servlets init() typically used to perform servlet initialization
63 classes (such as servlets) couldn't accept arguments.
creating or loading objects that are used by the servlet in the handling of its requests . to provide a new servlet any information about itself and its environment, a server had to call a servlet's init() method and pass along an object that implements the ServletConfig interface ServletEngine / JSPEngine container calls web.xml COMMUNI CATION WITH HTML Data Transfer between Servlets 1. getParameter() 2.setParameter() 3. getInitPrameter() package jsp.tutorials.servletexample; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WelcomeServlet extends HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException { super.init(config); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * Get the value of form parameter */ String name = request.getParameter("name"); String welcomeMessage = "Welcome "+name; /* Set the content type(MIME Type) of the response. */ response.setContentType("text/html"); PrintWriter out = response.getWriter(); /* * Write the HTML to the response */ out.println(""); out.println(""); out.println(" A very simple servlet example"); out.println(""); out.println(""); out.println(""+welcomeMessage+""); out.println(""+"Click here to go back to input page "+""); out.println(""); out.println(""); out.close(); } public void destroy() { } }
64
Port Numbers Oracle – 1521 ,WebLogic – 7001 , RMI – 1099, Tomcat 8080. doGet( ) allow only 256 characters at a time. URL will be displayed.not secure. To avoid URL Display use encodeURL() togetthings.Can‘tmodifyanythingfromServer. Servlet Context ServletContext Defines a set of methods that a servlet uses to communicate with its servlet container. The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized. You can specify param-value pairs for ServletContext object in tags in web.xml file. The ServletContext parameters are specified for an entire application outside of any particular servlet and are available to all the servlets within that application
doPost( ) allow any number of characters at a time. url will not be displayed. to send data to be processed. Servlet Config. The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets
Deployment Descriptor – web.XML contents. . . . . < servlet-class> . . . . . . . . . . . . . 1 --> alternate way to create instance. 50 --> can invalidate of session if put 0. 404 Exception / filename.jsp --- -- HttpServletRequest , HttpServeltResponse --> Interfaces.
65
Javax.servlet contains: Interfaces Servlet ServletRequest ServletResponse ServletConfig ServletContext SingleThreadModel
Classes Generic Servlet ServletInputStream ServletOutputStream ServletException UnavailableException
Javax.servlet.http contains: Interfaces HttpServletRequest HttpServletResponse HttpSession HttpSessionContext HttpSessionBindingListener
Classes Cookie HttpServlet HttpSessionBindingEvent HttpUtils
A Sample File Upload Program using Servlets import java.io.IOException; import java.io.File; import java.io.PrintStream; import java.io.ByteArrayOutputStream; import java.util.Hashtable; import java.util.Enumeration; import javax.servlet.* ; import javax.servlet.http.* ; /* * * This is a basic file upload servlet. It will handle file uploads, * as performed by Netscape 3 and 4. Note: This program does not implement RFC 1867, merely a subset of it. */ public class FileUploadServlet extends HttpServlet { protected int maxSize = // ... public void init( ServletConfig sc ) { // ... } /* * * Since fileupload requires POST, we only override this method. * / protected void doPost( HttpServletRequest req, HttpServletResponse res ) throws ServletException, IOException { // ... } /* * * Obtain information on this servlet. * @return String describing this servlet. */ public String getServletInfo() { return "File upload servlet -- used to receive files"; } when i login to 1 application the path should forward to all the applications with out relogin SSO is one of them 2.store uid and pwd in session
66 3.store uid and pwd in DB Predefined Objects. 1. request 2.response 3.servletRequest 4.servletResponse 5.Session 6.Exception 7.Cookie. printWriter out = res.getWriter(); out.println() ;--> write data in Character Stream. ServeltOutputStream out1= res.getOutputStream() Out.write(oByteArray); --> Write in byte Stream. To restrict a servlet/ JSP to display in browser Res.setHeader(―pragma‖, ―no cache‖); bufferSize = 0 kb; // in JSP Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request.Inservletchaining,oneservlet‘soutputispipedtothenextservlet‘sinput.Thisprocess continues until the last servlet is reached. Its output is then sent back to the client. Servlet Tunneling : Used in applet to servlet communications, a layer over http is built so as to enable object serialization. Context GetAttribute() SetAttribute() RemoveAttribute() GetAttributeNames()
ServletRequest GetAttribute() SetAttribute() RemoveAttribute() GetAttributeNames()
HttpSession GetAttribute() SetAttribute() RemoveAttribute() GetAttributeNames()
For storing a variable temporarily for a particular request -->Req.setAttribute(―name‖,value); For storing a variable temporarily for a particular request -->session.SetAttribute(―name‖,value); GetServeltContext().setAttribute(―name‖,value); GetServeltContext().getAttribute(―name‖);--> will print its value. Lock Session & Context --> synchronized(getServletContext()); synchronized―(session‖); Session Tracking Methods. 1. Cookie( ) – it is a piece of information generated on the client side for identification of server. Cookie c1 = new Cookie(); c1.setValue(―name‖,value); c1.getCookie(); c1.setMaxAge(0) --> delete cookie 2.Hidden fields and Query strings – transfer data from page 1 to page 2 as hidden fields. 3.URL Rewriting.
67 Response.encodeURL(―/el.do‖) Response.encodeRedirectURL(―/el.do‖) add extra session id to this URL 4. Session( ) It is the time difference between a user login and logout. Store on the server side. HttpSession --> interface. HttpSession. S1=req.getSession(false); --> continue with existing session ID. HttpSession. S1=req.getSession(true); --> create new session. HttpSession.getSession(true); S1.setSession(―name‖,value); S1.getSession(); session.isNew() --> check if session is available. Major methods in Session getCreationTime(); getLastAccessedTime(); getMaxInactiveInterval(); setMaxInactiveInterval(); invalidate(); Close Session techniques 1. timeout. 2. close application 3. session.invalidate() 4. setMaxInactiveInterval(0) --> close session immediately. 5.Authentication --> Using HTTPS protocol. HTTPS Protocol define in Web.xml CONFIDENTIAL as on webService.xml
Inprotocol‖=HTTPS‖
Hidden field. The disadvantage is that every user action must result in the submission of a form or you lose the data. This limits the sort of HTML you can put on the page. Since hidden fields put all previous data on each form as you go through several forms the pages transmitted get bigger, and bigger, and bigger -- taking longer, and longer, and longer to load. Read XML DATA String XML=xml_data_as_a_string; File f = new File(C:\xmlData‖); FileWriter fw= new FileWriter(f); Fw.write(xml); singleThreadModel execute one servlet ( Thread) at a time.
68 class c1 extends httpServletRequest implements singleThreadModel . when a class get more than 1 request ,more than 1 instance will be created for a particular class. SSI – Server Side Include : Server-Side Includes allows embedding servlets within HTML pages using a special servlet tag. In many servlets that support servlets, a page can be processed by the server to include output from servlets at certain points inside the HTML page. This is accomplished using a special internal SSINCLUDE, which processes the servlet tags. SSINCLUDE servlet will be invoked whenever a file with an. shtml extension is requested. So HTML files that include server-side includes must be stored with an .shtml extension. servlet –servlet communication servletcontext.config.getServlet―(reqURL‖) TestServlet test= (TestServlet)getServletConfig().getServletContext().getServlet("OtherServlet"); Servlet – Servlet / JSP communication 1.servletcontext.config.requestDespacher(―reqURL‖) include(req,res); forward(req,res); RequestDispatcher request.setAttribute("selectedScreen", request.getServletPath()); 1. RequestDispatcher dispatcher = request.getRequestDispatcher ("/template.jsp"); if (dispatcher != null) { dispatcher.forward(request, response); } 2. servletcontext.config.sendRedirect(―reqURL‖) SendRedirect String destination ="/jsp/destination.jsp"; response.sendRedirect(response.encodeRedirectURL(destination)); response.sendRedirect(response.encodeRedirectURL("http://www.google.com")); Read a Data from XML ServletContext context = getServletContext(); String myValue = context.getInitParameter("emailid"); Forward( ) : javax.Servlet.RequestDispatcher interface. - RequestDispatcher.forward( ) works on the Server. - The forward( ) works inside the WebContainer. - The forward( ) restricts you to redirect only to a resource in the same web-Application. - After executing the forward( ), the control will return back to the same method from where the forward method was called. - The forward( ) will redirect in the application server itself, it does'n come back to the client. - The forward( ) is faster than Sendredirect( ) . To use the forward( ) of the requestDispatcher interface, the first thing to do is to obtain RequestDispatcher Object. The Servlet technology provides in three ways. 1. By using the getRequestDispatcher( ) of the javax.Servlet.ServletContext interface , passing a String containing the path of the other resources, path is relative to the root of the ServletContext. RequestDispatcher rd=request.getRequestDispatcher ("secondServlet"); Rd.forward(request, response);
69
2. getRequestDispatcher( ) of the javax.Servlet.Request interface , the path is relative to current HtpRequest. RequestDispatcher rd=getServletContext( ).getRequestDispatcher("servlet/secondServlet"); Rd.forward(request, response); 3. By using the getNameDispatcher( ) of the javax.Servlet.ServletContext interface. RequestDispatcher rd=getServletContext( ).getNameDispatcher("secondServlet"); Rd.forward(request, response); Sendredirect( ) : javax.Servlet.Http.HttpServletResponce interface - RequestDispatcher.SendRedirect( ) works on the browser. - The SendRedirect( ) allows you to redirect trip to the Client. - The SendRedirect( ) allows you to redirect to any URL. - 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. Include method this is used to tag in the contents of a resource as a part of the response flow as if it were part of the calling servlet. If you include a jsp or a servlet, it must not attempt to change the response status code or the http headers, as any such request will be ignored.
Forward this method is used to show a different resource in place of the servlet originally requested. This resource may be a jsp, a servlet etc. When a request is sent from the client to the web server through an url , the web container intercepts the request and sends it to another resource without the knowledge of the client browser. And a response is received from that resource after processing of the request is done.
RequestDespatcher control between servlets will be forwarded temporarily from one to another and is received back in servlet communications.
sendRedirect control is forward permanently from one servlet to another on servlet communications
Include Connection is temporarily forwarded and returned back SendRedirect 1. always sends a header back to the client/browser. this header then contains the resource(page/servlet) which u wanted to be
Forward Control is permanently forwarded to next servlet. Forward 1. resources from the server, where the fwd. call was made, can only be requested for.
70 redirected. 2. the browser uses this header to make another fresh request. 3. sendRedirect has a overhead as to the extra remort trip being incurred.
2.forward just routes the request to the new resources which u specify in ur forward call. 3.That means this route is made by the servlet engine at the server level only. no headers r sent to the browser which makes this very eficient. 4. the advantage is that u can point to any 4.also the request and response objects remain resource the same both from where the forward call was made and the resource which was called. res.sendRedirect () Jsp:Forward( ) With response.sendRedirect(), the browser is is more efficient. It forwards the asked to go get another page. All HTTP request to the specified JSP page on the server parameters of the original request are lost. The side, without asking the browser to generate a browser's location bar changes. new request. You can only forward to resources served by your application server! It also keeps the state. The browser's location bar doesn't change. Filters --> Afilterisanobjectthatcantransformarequestormodifyaresponse.Itwon‘t create response . They are preprocessors of requests before they reach a Servlet and postprocessors of responses after leaving a Servlet. Implement javax.servlet.filter I nterface Servlet filters can: Intercept a Servlet's invocation before the Servlet is called. Examine a request before the destination Servlet is invoked. Modify request headers and request data by subclassing the HttpServletRequest object and wrapping the original request. Modify the response headers and response data by subclassing the HttpServletResponse object and wrapping the original response. Intercept a Servlet's invocation after the servlet is called The designers of Servlet Filters identified the following examples for their use: 1. Authentication Filters. 2. Logging and Auditing Filters. 3. Image conversion Filters. 4. Data compression Filters. 5. Encryption Filters 6. Tokenizing Filters 1. Filters that trigger resource access events 2. XSL/T filters 3. Mime-type chain Filter Filer Life Cycle public interface Filter { public void init(FilterConfig filterConfig); public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain); public void destroy(); } init( ) : called when the filter is initialized and loaded into memory by the Servlet container; called when the filter is being put into service. doFilter( ) : called by the Servlet container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.
71 The FilterChain passed in to this method allows the Filter to pass on the request and response to the next entity in the chain. destroy( ) : called just prior to the filter being removed from memory; called when the filter is being taken out of service. The init and destroy methods manage an internal FilterConfig member variable The following two sections were added to web deployment descriptor that parallel the Servlet descriptors: filter: defines a unique filter name and the fully qualified class name that it references filter-mapping: maps URLs to filters In Web.xml Add the following TimerFilter com.informit.webtechnologies.TimerFilter TimerFilter /* Event Listeners Servlet context-level (application-level) event --> This involves resources or state held at the level of the application servlet context object. Session-level event --> This involves resources or state associated with the series of requests from a single user session; that is, associated with the HTTP session object. At each of these two levels, there are two event categories: 1. Lifecycle changes 2. Attribute changes Event Category Event Descriptions Interface Servlet context lifecycle changes Servlet context creation, at which point the first request can be serviced Imminent shutdown of the servlet context javax.servlet.ServletContextListener Servlet context attribute changes Addition of servlet context attributes javax.servlet. ServletContextAttributeListener Event Category Event Descriptions Interface Removal of servlet context attributes Replacement of servlet context attributes Session lifecycle changes Session creation Session invalidation Session timeout javax.servlet.http. HttpSessionListener Session attribute changes Addition of session attributes Removal of session attributes
72 Replacement of session attributes javax.servlet.http. HttpSessionAttributeListener Typical Event Listener Scenario The listener is notified of application startup. The application logs in to the database and stores the connection object in the servlet context. Servlets use the database connection to perform SQL operations. The listener is notified of imminent application shutdown (shutdown of the Web server or removal of the application from the Web server). Prior to application shutdown, the listener closes the database connection. Event Listener Declaration and Invocation In web.xml com.acme.MyConnectionManager com.acme.MyLoggingModule In a multithreaded application, attribute changes might occur simultaneously. There is no requirement for the servlet container to synchronize the resulting notifications; the listener classes themselves are responsible for maintaining data integrity in such a situation. Each listener class must have a public zero-argument constructor. Each listener class file must be packaged in the application WAR file, either under /WEBINF/ classes or in a JAR file in /WEB-INF/lib. ServletContextListener Methods, ServletContextEvent Class The ServletContextListener interface specifies the following methods: void contextInitialized(ServletContextEvent sce) --> The servlet container calls this method to notify the listener that the servlet context has been created and the application is ready to process requests. void contextDestroyed(ServletContextEvent sce) --> The servlet container calls this method to notify the listener that the application is about to be shut down. ServletContext getServletContext() --> The servlet container creates a javax.servlet.ServletContextEvent object that is input for calls to ServletContextListener methods. ServletContextAttributeListener Methods, ServletContextAttributeEvent Class The ServletContextAttributeListener interface specifies the following methods: void attributeAdded(ServletContextAttributeEvent scae) --> The servlet container calls this method to notify the listener that an attribute was added to the servlet context. void attributeRemoved(ServletContextAttributeEvent scae)--> The servlet container calls this method to notify the listener that an attribute was removed from the servlet context. void attributeReplaced(ServletContextAttributeEvent scae) --> The servlet container calls this method to notify the listener that an attribute was replaced in the servlet context. The container creates a javax.servlet.ServletContextAttributeEvent object that is input for calls to ServletContextAttributeListener methods. The ServletContextAttributeEvent class includes the following methods, which your listener can call: String getName() --> Use this to get the name of the attribute that was added, removed, or replaced.
73
Object getValue() --> Use this to get the value of the attribute that was added, removed, or replaced. In the case of an attribute that was replaced, this method returns the old value, not the new value. HttpSessionListener Methods, HttpSessionEvent Class The HttpSessionListener interface specifies the following methods: void sessionCreated(HttpSessionEvent hse) --> The servlet container calls this method to notify the listener that a session was created. void sessionDestroyed(HttpSessionEvent hse) --> The servlet container calls this method to notify the listener that a session was destroyed. The container creates a javax.servlet.http.HttpSessionEvent object that is input for calls to HttpSessionListener methods. The HttpSessionEvent class includes the following method, which your listener can call: HttpSession getSession() --> Use this to retrieve the session object that was created or destroyed, from which you can obtain information as desired. See HttpSessionAttributeListener Methods, HttpSessionBindingEvent Class The HttpSessionAttributeListener interface specifies the following methods: void attributeAdded(HttpSessionBindingEvent hsbe) --> The servlet container calls this method to notify the listener that an attribute was added to the session. void attributeRemoved(HttpSessionBindingEvent hsbe) --> The servlet container calls this method to notify the listener that an attribute was removed from the session. void attributeReplaced(HttpSessionBindingEvent hsbe) --> The servlet container calls this method to notify the listener that an attribute was replaced in the session. The container creates a javax.servlet.http.HttpSessionBindingEvent object that is input for calls to HttpSessionAttributeListener methods. The HttpSessionBindingEvent class includes the methods that follow, which your listener can call. String getName() --> Use this to get the name of the attribute that was added, removed, or replaced. Object getValue() --> Use this to get the value of the attribute that was added, removed, or replaced. In the case of an attribute that was replaced, this method returns the old value, not the new value. HttpSession getSession() --> Use this to retrieve the session object that had the attribute change. Event Listener Sample This section provides code for a sample that uses a servlet context lifecycle and session lifecycle event listener. This includes the following components: SessionLifeCycleEventExample: This is the event listener class, implementing the ServletContextListener and HttpSessionListener interfaces. SessionCreateServlet: This servlet creates an HTTP session. SessionDestroyServlet: This servlet destroys an HTTP session. index.jsp: This is the application welcome page (the user interface), from which you can invoke SessionCreateServlet or SessionDestroyServlet. web.xml: This is the deployment descriptor, where the servlets and listener class are
74 declared. Welcome Page: index.jsp Here is the welcome page, the user interface that enables you to invoke the session-creation servlet by clicking the Create New Session link, or to invoke the session-destruction servlet by clicking the Destroy Current Session link. OC4J HttpSession Event Listeners This example demonstrates the use of the HttpSession Event and Listener that is new with the Java Servlet 2.3 API. [Create New Session] [Destroy Current Session] Click the Create link above to start a new HttpSession. An HttpSession listener has been configured for this application. The servler container will send an event to this listener when a new session is created or destroyed. The output from the event listener will be visible in the console window from where OC4J was started. JSP Hello! The time is now --> @ the time of translation container convert JSP into a servlet
--> static add content from file @ translation time --> Page specific properties such as character encoding.
--> include Directory --> include etxt and code at translation time. Action Tags < jsp:useBean id=‖person‖type=‖classtype‖class=‖classname‖scope=‖―/ > id--> identifier for bean object type / class --> any one of the two is necessary.
75
< jsp:plugin type = bean/applet name=instance_name/ > < jsp:getProperty name =‖―property=‖ < >―/ jsp:setProperty> name --> identify actual bean object with useBean tag. Property --> property name in setter & getter in bean. < jsp:setProperty name =‖―property=‖―value=‖‖/> < jsp:include page= ‖x.jsp‖>--> happens At runtime --> powerful can reach outside web application. < jsp:forward page=‖x.jsp‖>--> buffer is cleared before forward. < jsp:param name=‖name‖value‖‖=/> JSP Life Cycle 1. Translation Phase 2. Request Processing Phase. 3. Instantiate and loading Phase 4. JspInit() _Jsp Service() // _JspService() JspService cannot be over ridden its final 5. JspDestroy() Include multiple pages using jsp:Include session.getattribute () append the value in the jsp url its works same was as jsp include can you give me its syntax but jsp include u can include only 1 jsp Implicit Objects in JSP 1. Request --> Javax.servlet.http.httpservletrequest 2. Response --> Javax.servlet.http. httpservletresponse 3. Session --> Javax.servlet.http.httpsession 4. Application --> Javax.servlet.http.ServletContext 5. Out --> Javax.servlet.jsp.JspWriter 6. Page --> used to call any methods defined by the servlet class. 7. PageContext --> Access to information associated with a request. Used in Parameter & cookies 8. Config --> Stores the Servlet configuration data 9. Exception --> Java.lang.throwable scope of variable --> page , request , session ,Application --> global. Default value of Scope --> Page Include Directive ( < % @/ > ) at the time of translation include a page. include the page at the time of compilation. Will not affect at request time Change will affect request time. Static Dynamic. Java Bean Taglib. Serializable Cant serializable 4 scope include request,res,page,app Only Page jsp / servlet. Support only JSP
76
Include Directive ( < % @ page /> ) Page directives --> check for Expr Language. Store data in a XML file. InitParam --> Only for a particular application. email-id
[email protected] ContextParam --> access for all or common applications. email-id
[email protected] JAAS --> Java Authorization and Authentication Service TYPE 1 : in WEB.XML UnhandledException UnhandledException.jsp TYPE 2 : errorpage , iserrorPage= ―true‖ errorPage = ― *.jsp‖ VALUES CHANGE FROM HTML TO JSP HTML CODE body, input { font-family:Tahoma; font-size:8pt; } Enter your first Number:
77 Enter your Second Number: 1. JSP CODE body, p { font-family:Tahoma; font-size:10pt; } Division is : Back. 2. ERROR PAGE Exceptional Even Occurred! body, p { font-family:Tahoma; font-size:10pt;padding-left:30; } pre { font-size:8pt; }