Java 7th Sem Ashokkumar 44h64

  • ed by: Harshith Rai
  • 0
  • 0
  • December 2019
  • PDF

This document was ed by and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this report form. Report 2z6p3t


Overview 5o1f4z

& View Java 7th Sem Ashokkumar as PDF for free.

More details 6z3438

  • Words: 56,694
  • Pages: 239


Mr. Ashok Kumar K | 9742024066 | [email protected]

VTU 7th sem B.E (CSE/ISE)

JAVA/ J2EE Notes prepared by

Mr. Ashok Kumar K 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Unit 3:

Multithreaded Programming, Event Handling

Mr. Ashok Kumar K 9742024066 | [email protected]

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. 15 reasons to choose VTUPROJECTS.COM for your final year project work 1. Training from the scratch We train our students on all the languages and technologies required for developing the projects from the scratch. No prerequisites required. 2. Line by Line code explanation Students will be trained to such an extent where they can explain the entire project line by line code to their respective colleges. 3. Study Materials We provide the most efficient study material for each and every module during the project development 4. Trainers Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter expert in strengthening student's skillset for cracking any interviews. He will be having a thorough experience in working on both product and service driven industries. 5. Reports and PPTs Project report as per the university standards and the final presentation slides will be provided and each student will be trained on the same. 6. Video manuals Video manuals will be provided which will be useful in installing and configuring various softwares during project development 7. Strict SDLC Project development will be carried out as per the strict Software Development model 8. Technical Seminar topics We help students by providing current year's IEEE papers and topics of their wish for their final semester Technical seminars 9. Our Availability We will be available at our centers even after the class hours to help our students in case they have any doubts or concerns. 10. Weightage to your Resume Our students will be adding more weightage to their resumes since they will be well trained on various technologies which helps them crack any technical interviews 11. Skype/ Team viewer In case the student needs an emergency help when he/she is in their colleges, we will be helping out them through Skype/ Team viewer screen sharing 12. Practical Understanding Each and module in the project will be implemented and taught to the students giving practical real world applications and their use. 13. Mock demo and presentations Each student will have to prepare for mock demo and presentations every week so that he/she will be confident enough to demonstrate the project in their respective colleges 14. Communication & Soft skills Training We provide communication and soft skills training to each students to help improve their presentation and demonstration skills. 15. Weekly monitoring Each student will be monitored and evaluated on the status of the project work done which helps the students to obtain thorough understanding on how the entire project will be developed

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

MULTITHREADED PROGRAMMING 3.1 Multithreaded programming basics Definition of concurrency (multithreading) Concurrency is the ability to run multiple parts of the program in parallel. If a program can be divided into multiple independent parts, each performing a specific task, then executing these parts in parallel in an asynchronous way increases the throughput of the program. This type of programming is generally referred to as Concurrent Programming.

Process v/s Thread In Concurrent programming, there are two units of execution:  Processes  Threads Process

Thread

Definition: Process is an instance of an entire program in execution.

Definition: Thread is an execution path or the control flow of execution of a program.

A process has a separate execution environment. It has a complete, private set of basic run-time resources; each process has its own memory space

Threads exist within a process; every process has at least one thread. Threads share the process's resources, including memory and open files. Threads are called light-weight process

: Threads have their own call stack and can access shared data. These cause two problems  Visibility problem occurs if thread A reads shared data and thread B later changes this data and the thread A is unaware of this change.  Access problem can occur if several threads tries to access and share the same shared data at the same time.

3.2 Threads in Java A separate process will be created for each Java program within which one default thread (called the Main thread) starts executing the main function. This default thread or the main thread will be created by JVM. You can also create child threads using this. Main thread is something which you should mark as important, because:  

It is the thread using which other threads (child threads) can be created Ideally it must be the last thread to finish execution because it performs various shutdown operations.

Each thread in java is associated with an instance of the class java.lang.Thread.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Let's play with main thread for some time. , each thread will be having a name and priority (dealt later). A Thread can also sleep, meaning go to IDLE state for some specified amount of time. Below example does some exercise with the main thread. It first gets the access (reference) to main thread using currentThread() method in Thread class. It prints the name of the thread whose reference we have just got. It changes the name and priority of the thread using setName() and setPriority() methods respectively. It prints the numbers 0 through 4 with a delay of 1sec after each number. The thread is made to sleep for 1 sec after printing one number. A thread can be sent to sleep using Thread.sleep(long) method where the parameter is the amount of time in milliseconds. public class Example { public static void main(String arg[]) { Thread t = Thread.currentThread(); System.out.println("Hi Everyone .. I am a thread .. " + t); t.setName("NewMain"); t.setPriority(9); System.out.println("Hi Everyone .. I am the same thread .. " + t); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println(i); } } catch (InterruptedException e) { e.printStackTrace(); } } } Output

When you simply print a thread reference t, you know that it will invoke t.getString() method which printed something like this: Thread[main, 5, main]. Here is what actually they are:

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

3.3 Creating a Thread Threads in java can be created in two possible ways 1. 2.

By implementing Runnable interface By extending Thread class

Creating a thread by implementing Runnable interface Step 1: Simply define your own class and implement it by java.lang.Runnable interface. Define run() method and include the business logic of the thread within the run() method, because run() is the entry point for a thread and when it returns from this function, the thread dies. To put it differently, a thread will be active till it lies in the context of run() method. Instance of this class is called Runnable object since it implements Runnable interface. class MyThread implements Runnable { public void run() { System.out.println("Child thread started.. "); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Child .. " + i); } System.out.println("Child thread exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } }

Step 2: Creating a child thread is nothing but creating an instance of Thread class and ing the runnable object as a parameter for its constructor. , at this point of time you have only created a child thread, but you haven't started its execution yet. To do so, you should invoke start() method of the thread object you just created. It causes the child thread to start its execution. The JVM calls run() method of the child thread. The result is that two threads are running concurrently: the current thread (which returns from the call to the start method) and the other thread (which executes its run() method). It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution. public class Example { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread(); // Create a child thread Thread t1 = new Thread(m1); // Start (run) a child thread t1.start(); try { for (int i = 0; i < 5; i++) {

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Thread.sleep(1000); System.out.println("Main .. " + i); } System.out.println("Main thread exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } } Output:

The order of execution of two threads is not the same always. The output you are seeing above can't be predicted. Since the main thread and the child thread both are executing in parallel you can't expect the same ordering all the time. It just gets mixed up.

Observation: As a component developer you should focus on both the business logic and the required resources to create a thread. An application developer will simply makes use of this. What I meant to tell is you should allow full freedom to the of this thread. You should encapsulate the process of creating a thread within the custom Thread class itself, as shown below; Here is the optimized version of above program class MyThread implements Runnable { Thread t; MyThread() { t = new Thread(this); t.start(); } public void run() { System.out.println("Child thread started.. "); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Child .. " + i); } System.out.println("Child thread exiting .. "); } catch (InterruptedException e) {

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. e.printStackTrace(); } } } public class Test { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread(); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Main .. " + i); } System.out.println("Main thread exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } }

Creating a thread by extending Thread class Step 1: Simply extend your own class with java.lang.Thread. Define run() method and include the business logic of the thread within the run() method, because run() is the entry point for a thread and when it returns from this function, the thread dies. class MyThread extends Thread { public void run() { System.out.println("Child thread started.. "); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Child .. " + i); } System.out.println("Child thread exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } }

Step 2: Creating a thread is just creating an instance of the class defined in step 1. To begin the execution of the child thread, you should invoke the run() method of the object created. public class Test2 { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread(); // Start a thread m1.start(); try {

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Main .. " + i); } System.out.println("Main thread exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } }

Observation: As discusses previously, the logic of creating a thread should be encapsulated within the Thread class by the component developer. Here is the optimized version of the above program. class MyThread extends Thread { MyThread() { this.start(); } public void run() { System.out.println("Child thread started.. "); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Child .. " + i); } System.out.println("Child thread exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Test2 { public static void main(String arg[]) { // Runnable Object MyThread m1 = new MyThread();

try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Main .. " + i); } System.out.println("Main thread exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } }

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Now that you have two different ways of creating a thread, which one would you prefer? Creating a thread by implementing Runnable interface is preferred over extending the Thread class for two reasons.  

Inheritance should be done only if you are modifying or enhancing the base class behavior. Since our class doesn't modify or enhance the Thread class behavior, extending the Thread class is not recommended. If you extend the Thread class, you now don't have freedom of extending other classes (since multiple inheritances are not allowed). So we prefer implementing the Runnable interface and extending any other class.

Creating multiple threads You can create as many threads as you want. Below example creates four threads and starts them so that the four child threads along with the main thread prints the numbers 0 to 4 concurrently. One more thing you need to observe from below program is the method of asg a name to the child thread. Yes, you can set the name of a child thread by ing the name as a String argument to the Thread class constructor. class MyThread implements Runnable { Thread t; MyThread(String name) { t = new Thread(this, name); // 'name' is the child thread's name t.start(); } public void run() { System.out.println("New Thread started with the name .."+Thread.currentThread().getName()); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+" .. " + i); } System.out.println(Thread.currentThread().getName()+" exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Test { public static void // Runnable MyThread m1 MyThread m2 MyThread m3 MyThread m4

main(String arg[]) { Object = new MyThread("ChildOne"); = new MyThread("ChildTwo"); = new MyThread("ChildThree"); = new MyThread("ChildFour");

try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Main .. " + i); } System.out.println("Main thread exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } }

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Output

You can clearly see the order in which these threads execute can't be predicted. It depends on many things including the thread priority.

3.4 isAlive() and () Recall we had concluded that the main thread should be the last thread to terminate. But as we can see from the output of previous program, main thread is being terminated well before its child threads terminate. Right, the problem in discussion here is, what are the various ways to make the main thread to terminate at last?

There are three possible methods to make the main thread wait till all its child threads get terminated. Let’s analyze each one of them.

Method 1: Make the main thread to sleep for some specified amount of time just before its termination, so that all its child threads can

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. terminate by that time. class MyThread implements Runnable { Thread t; MyThread(String name) { t = new Thread(this, name); t.start(); }

public void run() { System.out.println("New Thread started with the name .. "+Thread.currentThread().getName()); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+" .. " + i); } System.out.println(Thread.currentThread().getName()+" exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Test { public static void // Runnable MyThread m1 MyThread m2 MyThread m3 MyThread m4

main(String arg[]) { Object = new MyThread("ChildOne"); = new MyThread("ChildTwo"); = new MyThread("ChildThree"); = new MyThread("ChildFour");

try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Main .. " + i); } } catch (InterruptedException e) { e.printStackTrace(); } // Main Thread will sleep for 10 seconds try { Thread.sleep(10000); } catch (Exception e) { e.printStackTrace(); } System.out.println("Main thread exiting .. "); } } Output:

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

You can observe the main thread is terminating at last. Drawback: How will you choose the amount of time that the main thread should sleep to ensure the termination of all its child threads?  

You would end up choosing some large amount of time therefore making the main thread sleep for some extra time even though all its child threads are already terminated. You would end up choosing lesser time giving no time for some of its child threads to terminate.

Method 2: Using isAlive() method. Main thread can invoke isAlive() method on each of its child threads to see if it is still running or already terminated. This way, the main thread will be in a continuous loop until all the child threads gets terminated. isAlive() is a method defined in Thread class and have the signature as follows: final boolean isAlive()

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. It returns true if the thread upon which it is called is still running. It returns false otherwise. Example class MyThread implements Runnable { Thread t; MyThread(String name) { t = new Thread(this, name); t.start(); } public void run() { System.out.println("New Thread started with the name .. "+Thread.currentThread().getName()); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+" .. " + i); } System.out.println(Thread.currentThread().getName()+" exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Test { public static void // Runnable MyThread m1 MyThread m2 MyThread m3 MyThread m4

main(String arg[]) { Object = new MyThread("ChildOne"); = new MyThread("ChildTwo"); = new MyThread("ChildThree"); = new MyThread("ChildFour");

try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Main .. " + i); } } catch (InterruptedException e) { e.printStackTrace(); }

// Main Thread will come out of this loop only after all the threads terminates while (true) { if (m1.t.isAlive() || m2.t.isAlive() || m3.t.isAlive() || m4.t.isAlive()) { // loop again } else break; // come out of the loop } System.out.println("Main thread exiting .. "); } } Output

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Drawback: This method has unspecified amount of continuous looping to check the status of the child threads thus wasting the runtime resources.

Method 3: Using () method. () is the method we mostly use to wait for a thread to finish its execution. () method is also defined in Thread class with the signature as follows: final void ( ) throws InterruptedException This method waits until the thread on which it is called terminates. Additional forms of ( ) allow you to specify a maximum amount of time that you want to wait for the specified thread to terminate. Example

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. class MyThread implements Runnable { Thread t; MyThread(String name) { t = new Thread(this, name); t.start(); }

public void run() { System.out.println("New Thread started with the name .. "+Thread.currentThread().getName()); try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println(Thread.currentThread().getName()+" .. " + i); } System.out.println(Thread.currentThread().getName()+" exiting .. "); } catch (InterruptedException e) { e.printStackTrace(); } } } public class Example { public static void // Runnable MyThread m1 MyThread m2 MyThread m3 MyThread m4

main(String arg[]) { Object = new MyThread("ChildOne"); = new MyThread("ChildTwo"); = new MyThread("ChildThree"); = new MyThread("ChildFour");

try { for (int i = 0; i < 5; i++) { Thread.sleep(1000); System.out.println("Main .. " + i); } } catch (InterruptedException e) { e.printStackTrace(); } try { m1.t.(); m2.t.(); m3.t.(); m4.t.(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Main thread exiting .. "); } } Output:

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

3.5 Thread priorities Each thread in Java will have an associated priority which is an integer value ranging from 1 (minimum) to 10 (maximum). Thread scheduler will use the thread priorities to determine the execution schedule of threads. Higher priority threads get the U much faster than the lower priority threads. If two threads have the same priority, the thread scheduler treats them equally and serves them based on First Come First Serve (FCFS) basis.

setPriority(int) and getPriority() Thread class defines two methods, one for setting the thread priority and the other for returning the current priority of a thread. Their signatures are as follows: void setPriority(int); sets the priority of a calling thread to the one ed as an argument. int getPriority(); returns the current priority of the calling thread

Priority range

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Thread priority is an integer value ranging from 1 to 10. Thread class defines three integer constants to represent this: Priority value 1 5 10

Integer Constant Thread.MIN_PRIORITY Thread.NORM_PRIORITY Thread.MAX_PRIORITY

Description Minimum priority of a thread Default priority of a thread Maximum priority of a thread

Example: class MyThread implements Runnable { Thread t; int count=0; MyThread(String name, int pri) { t = new Thread(this, name); t.setPriority(pri); t.start(); } public void run() { while (true) { count++; } } } public class Test { public static void // Runnable MyThread m1 MyThread m2

main(String arg[]) { Object = new MyThread("LowPriorityThread", Thread.MIN_PRIORITY); = new MyThread("HighPriorityThread", Thread.MAX_PRIORITY);

try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Low priority thread's execution count .. "+m1.count); System.out.println("High priority thread's execution count .. "+m2.count); } } Output:

As you can see, for the duration of 10 seconds the high priority thread has been given more U cycles compared to the low priority thread.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

3.6 Synchronization Definition Whenever two or more threads accesses the shared resources we need some mechanism to make sure that only one thread is given access to the shared resource at any point of time. The process by which this is achieved is called synchronization. This is to avoid the following problems:  

Visibility problem: It occurs if thread A reads shared data and thread B later changes this data and the thread A is unaware of this change. Access problem: It occurs if several threads tries to access and share the same shared data at the same time.

How synchronization works The block of code or in general any resources, which is shared among more than two threads and which needs to be synchronized, is called a monitor (also known as semaphore). Only one thread can access the monitor at any point of time. When a thread enters the monitor, we say that the thread has acquired the lock, and it prevents any other threads entering into the same monitor until it releases the lock by exiting the monitor.

Problem demonstration Below program has a class named Utility which defines a method called printMessage(String). It takes a string argument and prints it within the flower braces { and }. When two threads accesses this method at the same time each one ing a different string argument, the order in which these messages are printed are not jumbled (mixed up). class Utility { // this is the shared resource public void printMessage(String msg) { System.out.print("{"); System.out.print(msg); System.out.println("}"); } } class MyThread implements Runnable { Thread t; Utility util; String msg; MyThread(Utility util, String msg) { t = new Thread(this); this.util = util; this.msg = msg; t.start(); } public void run() { util.printMessage(msg); } } public class Example { public static void main(String arg[]) { Utility util = new Utility(); MyThread m1 = new MyThread(util, "Sachin"); MyThread m2 = new MyThread(util, "Kohli"); } }

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Output

Synchronization in Java can be achieved in two different ways: 1. 2.

Using synchronized methods Using synchronized blocks

Synchronized methods This solution is simple. Just prefix the keyword 'synchronized' to the shared resource which needs to be synchronized. The resource can be a method, variable or any other program elements. Here the shared resource is the printMessage() method. class Utility { // shared resource is synchronized synchronized public void printMessage(String msg) { System.out.print("{"); System.out.print(msg); System.out.println("}"); } } class MyThread implements Runnable { Thread t; Utility util; String msg; MyThread(Utility util, String msg) { t = new Thread(this); this.util = util; this.msg = msg; t.start(); } public void run() { util.printMessage(msg); } } public class Example { public static void main(String arg[]) { Utility util = new Utility(); MyThread m1 = new MyThread(util, "Sachin"); MyThread m2 = new MyThread(util, "Kohli"); } } Output

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Synchronized blocks The solution described above is simple and accepted as long as you have the access to Utility class so that you can modify it and add synchronized keyword. But, what if you are not the owner of Utility class? Meaning, you are not authorized to modify the class and you cannot add the synchronized keyword to its method. In these situations, you can go with synchronized blocks. Simply put calls to the methods defined by this class inside a synchronized block. This is the general form of the synchronized statement: synchronized(object) { // statements to be synchronized } Here, object is a reference to the object being synchronized. A synchronized block ensures that a call to a method that is a member of object occurs only after the current thread has successfully entered object’s monitor. class Utility { public void printMessage(String msg) { System.out.print("{"); System.out.print(msg); System.out.println("}"); } } class MyThread implements Runnable { Thread t; Utility util; String msg; MyThread(Utility util, String msg) { t = new Thread(this); this.util = util; this.msg = msg; t.start(); } public void run() { synchronized (util) { util.printMessage(msg); } } } public class Test { public static void main(String arg[]) { Utility util = new Utility(); MyThread m1 = new MyThread(util, "Sachin"); MyThread m2 = new MyThread(util, "Kohli"); } } Output

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

3.7 Inter thread communication There are three methods defined in Object class namely notify(), notifyAll(), and wait() that constitutes for inter thread communication.

wait(): This method tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and calls notify().

notify(): This method wakes up the first thread that called wait() on the same object.

notifyAll(): This method wakes up all the threads that called wait() on the same object. The highest priority thread will run first.

These methods can be called only within a synchronized context.

3.8 Producer Consumer Implementation Below example shows an implementation of solution for producer-consumer problem. It consists of four classes. 1. Class Q, the queue you are trying to synchronize. 2. Producer, threaded object that is producing queue entries. 3. Consumer, threaded object that is consuming queue entries. 4. PC, tiny class that creates single Q, Producer, and Consumer. class Q { int n; boolean valueSet = false; synchronized int get() { while (!valueSet) try { wait(); } catch (InterruptedException e) { System.out.println("InterruptedException caught"); }

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. System.out.println("Got: " + n); valueSet = false; notify(); return n; } synchronized void put(int n) { while (valueSet) try { wait(); } catch (InterruptedException e) { System.out.println("InterruptedException caught"); } this.n = n; valueSet = true; System.out.println("Put: " + n); notify(); } } class Producer implements Runnable { Q q; Producer(Q q) { this.q = q; new Thread(this, "Producer").start(); } public void run() { int i = 0; while (true) { q.put(i++); } } } class Consumer implements Runnable { Q q; Consumer(Q q) { this.q = q; new Thread(this, "Consumer").start(); } public void run() { while (true) { q.get(); } } } public class PCFixed { public static void main(String args[]) { Q q = new Q(); new Producer(q); new Consumer(q); System.out.println("Press Control-C to stop."); } } Output:

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

3.9 Different states of a Thread Below figure shows the various states of a thread and its life cycle starting from New state to Terminated state.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

EVENT HANDLING IN JAVA 3.10 Delegation Event Model Delegation Event Model constitutes of three entities: event, source, and listener.

Event Event is an object that describes the state change. These objects are encapsulated in a class hierarchy rooted at java.util.EventObject. An event is propagated from a "Source" object to a "Listener" object by invoking a method on the listener and ing in the instance of the event subclass which defines the event type generated.

Source An Event Source is an object which originates or "fires" events. (Example, an Applet). A source must listeners in order for the listeners to receive notifications about a specific type of event.

ing a listener: Each type of event has its own registration method. Here is the general form: public void addTypeListener(TypeListener el) Here, Type is the name of the event, and el is a reference to the event listener. For example, the method that s a keyboard event listener is called addKeyListener(). The method that s a mouse motion listener is called addMouseMotionListener().

Uning a listener: A source must also provide a method that allows a listener to un an interest in a specific type of event. The general form of such a method is this: public void removeTypeListener(TypeListener el) Here, Type is the name of the event, and el is a reference to the event listener. For example, to remove a keyboard listener, you would call removeKeyListener( ).

Listener A listener is an object which will be notified when an event occurs. A Listener is an object that implements a specific EventListener interface extended from the generic java.util.EventListener. It has two major requirements:  

First, it must have been ed with one or more sources to receive notifications about specific types of events. Second, it must implement methods to receive and process these notifications

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

3.11 Event Almost for every possible type of event that can occur (Ex, click a button, scroll the mouse, etc), Java defines a separate class for it. java.util.EventObject is the root of all the event classes. The class java.awt.AWTEvent, is a subclass of EventObject. It is the superclass (either directly or indirectly) of all AWT-based events used by the delegation event model. The package java.awt.event defines various event classes to describe the events generated by various interface elements. Here are the few: Event class ActionEvent

AdjustmentEvent ComponentEvent ContainerEvent FocusEvent InputEvent ItemEvent

KeyEvent MouseEvent

MouseWheelEvent TextEvent WindowEvent

Description Generated when a button is pressed, a list item is double-clicked, or a menu item is selected Generated when a scroll bar is manipulated. Generated when a component is hidden, moved, resized, or becomes visible Generated when a component is added to or removed from a container. Generated when a component gains or loses keyboard focus. Abstract superclass for all component input event classes. Generated when a check box or list item is clicked; also occurs when a choice selection is made or a checkable menu item is selected or deselected. Generated when input is received from the keyboard. Generated when the mouse is dragged, moved, clicked, pressed, or released; also generated when the mouse enters or exits a component. Generated when the mouse wheel is moved. Generated when the value of a text area or text field is changed. Generated when a window is activated, closed, deactivated, deiconified, iconified, opened, or quit.

Let's explore only KeyEvent and MouseEvent classes

KeyEvent A KeyEvent is generated when keyboard input occurs. There are three types of key events, which are identified by these integer constants:   

KEY_PRESSED KEY_RELEASED, and KEY_TYPED.

The first two events are generated when any key is pressed or released. The last event occurs only when a character is generated. , not all key presses result in characters. For example, pressing SHIFT does not generate a character. There are many other integer constants that are defined by KeyEvent.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. For example,  VK_0 through VK_9 and VK_A through VK_Z define the ASCII equivalents of the numbers and letters.  Here are some others: VK_ALT VK_DOWN VK_LEFT VK_RIGHT VK_CANCEL VK_ENTER VK_PAGE_DOWN VK_SHIFT VK_CONTROL VK_ESCAPE VK_PAGE_UP VK_UP The KeyEvent class defines several methods, but the most commonly used ones are getKeyChar( ), which returns the character that was entered, and getKeyCode( ), which returns the key code. Their general forms are shown here: char getKeyChar( ) int getKeyCode( )

MouseEvent There are eight types of mouse events. The MouseEvent class defines the following integer constants that can be used to identify them: MOUSE_CLICKED MOUSE_DRAGGED MOUSE_ENTERED MOUSE_EXITED MOUSE_MOVED MOUSE_PRESSED MOUSE_RELEASED MOUSE_WHEEL

The clicked the mouse. The dragged the mouse. The mouse entered a component. The mouse exited from a component. The mouse moved. The mouse was pressed. The mouse was released. The mouse wheel was moved.

Two commonly used methods in this class are getX( ) and getY( ). These returns the X and Y coordinate of the mouse within the component when the event occurred. Their forms are shown here: int getX() int getY()

3.12 Event Source Table below lists some of the interface components that can generate the events described in the previous section. Event Source Button Check box Choice List Menu Item Scroll bar Text components Window

Description Generates action events when the button is pressed. Generates item events when the check box is selected or deselected. Generates item events when the choice is changed. Generates action events when an item is double-clicked; generates item events when an item is selected or deselected. Generates action events when a menu item is selected; generates item events when a checkable menu item is selected or deselected. Generates adjustment events when the scroll bar is manipulated.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

3.13 Event Listener Listeners are created by implementing one or more of the interfaces defined by the java.awt.event package. When an event occurs, the event source invokes the appropriate method defined by the listener and provides an event object as its argument. Table below lists commonly used listener interfaces and provides a brief description of the methods that they define. Listener Interface ActionListener AdjustmentListener ComponentListener ContainerListener FocusListener ItemListener KeyListener MouseListener MouseMotionListener MouseWheelListener TextListener WindowFocusListener WindowListener

Description Defines one method to receive action events. Defines one method to receive adjustment events. Defines four methods to recognize when a component is hidden, moved, resized, or shown. Defines two methods to recognize when a component is added to or removed from a container. Defines two methods to recognize when a component gains or loses keyboard focus. Defines one method to recognize when the state of an item changes. Defines three methods to recognize when a key is pressed, released, or typed. Defines five methods to recognize when the mouse is clicked, enters a component, exits a component, is pressed, or is released.

KeyListener interface This interface defines following methods void keyPressed(KeyEvent ke) void keyReleased(KeyEvent ke) void keyTyped(KeyEvent ke)

MouseListener interface This interface defines following methods void mouseClicked(MouseEvent me) void mouseEntered(MouseEvent me) void mouseExited(MouseEvent me) void mousePressed(MouseEvent me) void moeleased(MouseEvent me)

MouseMotionListener interface This interface defines following methods void mouseDragged(MouseEvent me) void mouseMoved(MouseEvent me)

3.14 Example programs Handling Mouse Events To handle mouse events, you must implement the MouseListener and the MouseMotionListener interfaces. The following applet demonstrates the process. o It displays the current coordinates of the mouse in the applet’s status window.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. o o o o

Each time a button is pressed, the word “Down” is displayed at the location of the mouse pointer. Each time the button is released, the word “Up” is shown. If a button is clicked, the message “Mouse clicked” is displayed in the upper left corner of the applet display area. As the mouse enters or exits the applet window, a message is displayed in the upper-left corner of the applet display area. When dragging the mouse, a * is shown, which tracks with the mouse pointer as it is dragged.

import java.awt.*; import java.awt.event.*; import java.applet.*; public class MouseEventExample extends Applet implements MouseListener, MouseMotionListener { String msg = ""; int mouseX = 0, mouseY = 0; public void init() { addMouseListener(this); addMouseMotionListener(this); } // Handle mouse clicked. public void mouseClicked(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse clicked."; repaint(); } // Handle mouse entered. public void mouseEntered(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse entered."; repaint(); } // Handle mouse exited. public void mouseExited(MouseEvent me) { // save coordinates mouseX = 0; mouseY = 10; msg = "Mouse exited."; repaint(); } // Handle button pressed. public void mousePressed(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "Down"; repaint(); } // Handle button released. public void moeleased(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "Up"; repaint();

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. } // Handle mouse dragged. public void mouseDragged(MouseEvent me) { // save coordinates mouseX = me.getX(); mouseY = me.getY(); msg = "*"; showStatus("Dragging mouse at " + mouseX + ", " + mouseY); repaint(); } // Handle mouse moved. public void mouseMoved(MouseEvent me) { showStatus("Moving mouse at " + me.getX() + ", " + me.getY()); } // Display msg in applet window at current X,Y location. public void paint(Graphics g) { g.drawString(msg, mouseX, mouseY); } } Output:

Handling Keyboard Events To handle key board events, you will be implementing KeyListener interface. Before going to the program, Let's see how key events are generated. o When a key is pressed, a KEY_PRESSED event is generated. This results in a call to the keyPressed() event handler. o When the key is released, a KEY_RELEASED event is generated and the keyReleased( ) handler is executed. o If a character is generated by the keystroke, then a KEY_TYPED event is sent and the keyTyped( ) handler is invoked. Thus, each time the presses a key, at least two and often three events are generated. Here is the program to demonstrate the handling of key events. import java.awt.*; import java.awt.event.*;

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. import java.applet.*; public class KeyEventExample extends Applet implements KeyListener { String msg = ""; int X = 10, Y = 20; public void init() { addKeyListener(this); } public void keyPressed(KeyEvent ke) { showStatus("Key Down"); } public void keyReleased(KeyEvent ke) { showStatus("Key Up"); } public void keyTyped(KeyEvent ke) { msg += ke.getKeyChar(); repaint(); } public void paint(Graphics g) { g.drawString(msg, X, Y); } } Output

3.15 Adaptor Classes Java provides a special feature, called an adapter class, which can simplify the creation of event handlers.

Definition An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process ONLY some of the events that are handled by a particular event listener interface. You can define a new

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. class to act as an event listener by extending one of the adapter classes and implementing only those events in which you are interested. Table below shows Commonly Used Listener Interfaces Implemented by Adapter Classes. Adaptor class ComponentAdapter ContainerAdapter FocusAdapter MouseAdapter MouseMotionAdapter WindowAdapter

Listener Interface ComponentListener ContainerListener FocusListener KeyListener MouseListener MouseMotionListener

Example for Adaptor class import java.awt.*; import java.awt.event.*; import java.applet.*; public class AdapterDemo extends Applet { public void init() { addMouseListener(new MyMouseAdapter(this)); addMouseMotionListener(new MyMouseMotionAdapter(this)); } } class MyMouseAdapter extends MouseAdapter { AdapterDemo adapterDemo; public MyMouseAdapter(AdapterDemo adapterDemo) { this.adapterDemo = adapterDemo; } // Handle mouse clicked. public void mouseClicked(MouseEvent me) { adapterDemo.showStatus("Mouse clicked"); } } class MyMouseMotionAdapter extends MouseMotionAdapter { AdapterDemo adapterDemo; public MyMouseMotionAdapter(AdapterDemo adapterDemo) { this.adapterDemo = adapterDemo; } // Handle mouse dragged. public void mouseDragged(MouseEvent me) { adapterDemo.showStatus("Mouse dragged"); } }

3.16 Inner Classes, Anonymous Inner Classes We can handle events in an applet by using three different methods: By using “this” reference By using inner classes By using anonymous inner classes

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Till now we have seen how to handle events by using “this” reference.

Inner classes Below example shows how to handle the events by using an inner class. import java.applet.*; import java.awt.event.*; public class InnerClassDemo extends Applet { public void init() { addMouseListener(new MyMouseAdapter()); } class MyMouseAdapter extends MouseAdapter { public void mousePressed(MouseEvent me) { showStatus("Mouse Pressed"); } } } Advantage of handling the event by using inner class is that, the inner class can directly call the showStatus() method, and there is no need to store a reference to the applet.

Anonymous Inner classes An anonymous inner class is one that is not assigned a name. This example illustrates how to use anonymous inner class to handle events. import java.applet.*; import java.awt.event.*; public class AnonymousInnerClassDemo extends Applet { public void init() { addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent me) { showStatus("Mouse Pressed"); } }); } } The syntax new MouseAdapter( ) { ... } indicates to the compiler that the code between the braces defines an anonymous inner class. Furthermore, that class extends MouseAdapter. This new class is not named, but it is automatically instantiated when this expression is executed.

Mr. Ashok Kumar K | 9742024066 | [email protected]

VTU 7th sem B.E (CSE/ISE)

JAVA/ J2EE Notes prepared by

Mr. Ashok Kumar K 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Unit 4:

Swings

Mr. Ashok Kumar K 9742024066 | [email protected]

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

15 reasons to choose VTUPROJECTS.COM for your final year project work 1. Training from the scratch We train our students on all the languages and technologies required for developing the projects from the scratch. No prerequisites required. 2. Line by Line code explanation Students will be trained to such an extent where they can explain the entire project line by line code to their respective colleges. 3. Study Materials We provide the most efficient study material for each and every module during the project development 4. Trainers Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter expert in strengthening student's skillset for cracking any interviews. He will be having a thorough experience in working on both product and service driven industries. 5. Reports and PPTs Project report as per the university standards and the final presentation slides will be provided and each student will be trained on the same. 6. Video manuals Video manuals will be provided which will be useful in installing and configuring various softwares during project development 7. Strict SDLC Project development will be carried out as per the strict Software Development model 8. Technical Seminar topics We help students by providing current year's IEEE papers and topics of their wish for their final semester Technical seminars 9. Our Availability We will be available at our centers even after the class hours to help our students in case they have any doubts or concerns. 10. Weightage to your Resume Our students will be adding more weightage to their resumes since they will be well trained on various technologies which helps them crack any technical interviews 11. Skype/ Team viewer In case the student needs an emergency help when he/she is in their colleges, we will be helping out them through Skype/ Team viewer screen sharing 12. Practical Understanding Each and module in the project will be implemented and taught to the students giving practical real world applications and their use. 13. Mock demo and presentations Each student will have to prepare for mock demo and presentations every week so that he/she will be confident enough to demonstrate the project in their respective colleges 14. Communication & Soft skills Training We provide communication and soft skills training to each students to help improve their presentation and demonstration skills. 15. Weekly monitoring Each student will be monitored and evaluated on the status of the project work done which helps the students to obtain thorough understanding on how the entire project will be developed

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

4.1 Basics In unit 2, we had seen how to build interfaces using AWT.

Limitations of AWT API AWT translates its various visual components into their corresponding, platform-specific equivalents, or peers. Therefore, the look and feel will be decided by the platform and not by Java. Therefore, AWT is referred to as heavyweight. This led to following problems   

Component might act differently on different platforms Look and feel of each component was fixed and could not be easily changed by the program. It caused some restrictions on usage of the components.

Definition Swing API is set of extensible GUI Components to ease developer's life to create JAVA based Front End/ GUI Applications. It is built on top of AWT API and it overcomes most of its limitations. Swing has almost every control corresponding to AWT controls.

AWT versus Swing AWT AWT components are platform-dependent AWT is called the abstract window tool AWT components are heavyweight components AWT occupies more memory space AWT require javax.awt package AWT is not MVC based AWT works slower

Swing Swing are platform independent Swing is part of the java foundation classes Swing components are lightweight components because swing sits on the top of AWT Swing occupies less memory space Swing requires javax.swing package Swing are MVC based architecture Swing works faster

4.2 Swing features Here are the two key features of swing.

Lightweight Swing component are independent of native Operating System's API as Swing API controls are rendered mostly using pure JAVA code instead of underlying operating system calls.

Pluggable look and feel (PLAF) Swing based GUI Application’s look and feel logic can be separated from the component’s business logic.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Advantages of PLAF    

It is possible to define look and feel that is consistent across all platforms. Conversely, it is also possible to create a look and feel that acts like a specific platform. It is also possible to create a custom look and feel. Look and feel can be changed dynamically at runtime.

Other features of Swing

 Rich controls Swing provides a rich set of advanced controls like Tree, TabbedPane, slider, colorpicker, table controls

 Highly Customizable Swing controls can be customized in very easy way as visual appearance is independent of internal representation

4.3 Components and Containers Components   

A component is an independent visual control such as push button or a slider. In general, all the swing components are derived from JComponent class (apart from four top level containers). JComponent class inherits the AWT classes Container and Component

Containers  

A container holds a group of components. Thus, container is a special type of component that is designed to hold other components. There are two types of containers  Top level containers (JFrame, JApplet, JWindow, and JDialog): These containers do not inherit the JComponent. They do directly inherit the AWT classes Component and Container. Therefore, they are heavyweight. They cannot be contained within any other component.  Those who inherit JComponent are the second type of container: They are lightweight

Here are some of the Swing components: JApplet

JButton

JCheckBox

JCheckBoxMenuItem

JColorChooser

JComboBox

JComponent

JDesktopPane

JDialog

JEditorPane

JFileChooser

JFormattedTextField

JFrame

JInternalFrame

JLabel

JLayeredPane

JList

JMenu

JMenuBar

JMenuItem

JOptionPane

J

JField

JPopupMenu

JProgressBar

JRadioButton

JRadioButtonMenuItem

JRootPane

JScrollBar

JScrollPane

JSeparator

JSlider

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. JSpinner

JSplitPane

JTabbedPane

JTable

JTextArea

JTextField

JTextPane

JTogglebutton

JToolBar

JToolTip

JTree

JViewport

JWindow

4.4 The Swing packages Java SE6 defines following swing packages javax.swing javax.swing.border javax.swing.colorchooser javax.swing.event javax.swing.filechooser javax.swing.plaf javax.swing.plaf.basic javax.swing.plaf.metal javax.swing.plaf.multi javax.swing.plaf.synth javax.swing.table javax.swing.text javax.swing.text.html javax.swing.text.html.parser javax.swing.text.rtf javax.swing.tree javax.swing.undo

4.5 A Simple Swing Application import javax.swing.*; class Example { Example() { // Create a new JFrame container. JFrame frame = new JFrame("My first Swing Application"); // Give the frame an initial size. frame.setSize(400, 200); // Terminate the program when the closes the application. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Create a text-based label. JLabel label = new JLabel("WELCOME TO THE WORLD OF SWINGS. !!"); // Add the label to the content pane. frame.add(label); // Display the frame. frame.setVisible(true); }

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. public static void main(String args[]) { new Example(); } } Output

4.6 Event Handling Basics Change in the state of an object is known as event i.e. event describes the change in state of source. Events are generated as result of interaction with the graphical interface components. For example, clicking on a button, moving the mouse, entering a character through keyboard, selecting an item from list, scrolling the page are the activities that causes an event to happen. Foreground events: These events require the direct interaction of the . Example: Click on a button Background events: These don’t require the interaction of the . Example: OS interrupt. As we learnt in unit 3, delegation event model has the following key participants namely:   

Event: Event is an object that describes the state change. Event Source: An Event Source is an object which originates or "fires" events. Event Listener: A listener is an object which will be notified when an event occurs.

Event handling example: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Example { private private private private

JFrame JLabel JLabel J

mainFrame; headerLabel; statusLabel; ;

public Example()

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. { render(); } public static void main(String[] args) { Example swingControlDemo = new Example(); swingControlDemo.showEventDemo(); } private void render() { mainFrame = new JFrame("Java SWING Examples"); mainFrame.setSize(400, 400); mainFrame.setLayout(new GridLayout(3, 1)); headerLabel = new JLabel("", JLabel.CENTER); statusLabel = new JLabel("", JLabel.CENTER); statusLabel.setSize(350, 100); mainFrame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent windowEvent) { System.exit(0); } }); = new J(); .setLayout(new FlowLayout()); mainFrame.add(headerLabel); mainFrame.add(); mainFrame.add(statusLabel); mainFrame.setVisible(true); } private void showEventDemo() { headerLabel.setText("Control in action: Button"); JButton okButton = new JButton("OK"); JButton submitButton = new JButton("Submit"); JButton cancelButton = new JButton("Cancel"); okButton.setActionCommand("OK"); submitButton.setActionCommand("Submit"); cancelButton.setActionCommand("Cancel"); okButton.addActionListener(new ButtonClickListener()); submitButton.addActionListener(new ButtonClickListener()); cancelButton.addActionListener(new ButtonClickListener()); .add(okButton); .add(submitButton); .add(cancelButton); mainFrame.setVisible(true); } private class ButtonClickListener implements ActionListener { public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if (command.equals("OK"))

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. { statusLabel.setText("Ok Button clicked."); } else if (command.equals("Submit")) { statusLabel.setText("Submit Button clicked."); } else { statusLabel.setText("Cancel Button clicked."); } } } } Output

Steps involved in event handling 1. 2. 3. 4.

The clicks the button and the event is generated. Now the object of concerned event class is created automatically and information about the source and the event get populated with in same object. Event object is forwarded to the method of ed listener class. The method now gets executed and returns.

In order to design a listener class we have to develop some listener interfaces. These Listener interfaces forecast some public abstract callback methods which must be implemented by the listener class. If you do not implement the any if the predefined interfaces then your class can not act as a listener class for a source object.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

4.7 Create a Swing Applet Concept Swing-based applets are similar to AWT-based applets, but it extends JApplet rather than Applet. JApplet is derived from Applet. Thus, JApplet includes all of the functionality found in Applet and adds for Swing. Swing applets use the same four lifecycle methods as described in unit 2: init(), start(), stop(), and destroy() Painting is accomplished differently in Swing than it is in the AWT, and a Swing applet will not normally override the paint() method.

Example: import javax.swing.*; import java.awt.*; import java.awt.event.*; /* This HTML can be used to launch the applet: */ public class Example extends JApplet { JButton button1; JButton button2; JLabel label; // Initialize the applet. public void init() { render(); // initialize the GUI } // This applet does not need to override start(), stop(), // or destroy(). // Set up and initialize the GUI. private void render() { // Set the applet to use flow layout. setLayout(new FlowLayout()); // Make two buttons. button1 = new JButton("Button1"); button2 = new JButton("Button2"); // Add action listener for Alpha. button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent le) { label.setText("Button1 was pressed."); } }); // Add action listener for Beta. button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent le) { label.setText("Button2 was pressed."); } }); // Add the buttons to the content pane. add(button1); add(button2);

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. // Create a text-based label. label = new JLabel("Press a button."); // Add the label to the content pane. add(label); } } Output

Let’s discuss some of the lightweight components derived from JComponent class.

4.8 JLabel and ImageIcon Description A JLabel object provides text instructions or information on a GUI — display a single line of read-only text, an image or both text and image. JLabel defines three constructors JLabel(Icon icon) JLabel(String str) JLabel(String str, Icon icon, int align) Here, str and icon are the text and icon used for the label. The align argument specifies the horizontal alignment of the text and/or icon within the dimensions of the label. It must be one of the following values: LEFT, RIGHT, CENTER, LEADING, or TRAILING. these constants are defined in the SwingConstants interface, along with several others used by the Swing classes. The easiest way to obtain an icon is to use the ImageIcon class. ImageIcon implements Icon and encapsulates an image. Thus, an object of type ImageIcon can be ed as an argument to the Icon parameter of JLabel’s constructor

Example: import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet { public void init() { render();

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. } private void render() { // Create an icon. ImageIcon imgIcon = new ImageIcon("logo.png"); // Create a label. JLabel label = new JLabel("This is a sample message", imgIcon, JLabel.LEFT); // Add the label to the content pane. add(label); } } Output

4.9 JTextField Description JTextField is an input area where the can type in characters. If you want to let the enter multiple lines of text, you cannot use JTextField’s unless you create several of them. The solution is to use JTextArea, which enables the to enter multiple lines of text. When the types data into them and presses the Enter key, an action event occurs. If the program s an event listener, the listener processes the event and can use the data in the text field at the time of the event in the program JTextField defines three constructors JTextField(int cols) JTextField(String str, int cols) JTextField(String str) Here, str is the string to be initially presented, and

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. cols is the number of columns in the text field. If no string is specified, the text field is initially empty. If the number of columns is not specified, the text field is sized to fit the specified string.

Example import java.awt.*; import java.awt.event.*; import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet { JTextField textfield; public void init() { render(); } private void render() { // Change to flow layout. setLayout(new FlowLayout()); // Add text field to content pane. textfield = new JTextField(15); add(textfield); textfield.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { // Show text when presses ENTER. showStatus(textfield.getText()); } }); } } Output

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

4.10 The Swing buttons Swing defines four types of buttons: JButton, JToggleButton, JCheckBox, and JRadioButton. All are subclasses of the AbstractButton class, which extends JComponent The text associated with the button can be read and written via the following methods String getText() void setText(String str) A button generates an action event when it is pressed. Other events are also possible.

JButton The JButton class provides the functionality of a push button. JButton allows an icon, a string, or both to be associated with the push button. When the button is pressed, an ActionEvent is generated and it is handled by the actionPerformed() method of ed ActionListener It defines three constructors JButton(Icon icon) JButton(String str) JButton(String str, Icon icon) Here, str and icon are the string and icon used for the button Example: import java.awt.*; import java.awt.event.*;

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet implements ActionListener { JLabel label; public void init() { render(); } private void render() { // Change to flow layout. setLayout(new FlowLayout()); // Add buttons to content pane. ImageIcon aklcIcon = new ImageIcon("aklc.png"); JButton button1 = new JButton(aklcIcon); button1.setActionCommand("AKLC"); button1.addActionListener(this); add(button1); ImageIcon jmasterIcon = new ImageIcon("jmaster.png"); JButton button2 = new JButton(jmasterIcon); button2.setActionCommand("JMASTER"); button2.addActionListener(this); add(button2); // Create and add the label to content pane. label = new JLabel("Choose an institute"); add(label); } // Handle button events. public void actionPerformed(ActionEvent ae) { label.setText("You selected " + ae.getActionCommand()); } } Output

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

JToggleButton A toggle button looks just like a push button, but it acts differently because it has two states: pushed and released. That is, when you press a toggle button, it stays pressed rather than popping back up as a regular push button does. When you press the toggle button a second time, it releases (pops up). Therefore, each time a toggle button is pushed; it toggles between its two states. It generates an ItemEvent. Example: import java.awt.*; import java.awt.event.*; import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet { JToggleButton toggleButton; public void init() { render(); } private void render() { // Change to flow layout. setLayout(new FlowLayout()); // Make a toggle button. toggleButton = new JToggleButton("ON"); // Add an item listener for the toggle button. toggleButton.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { if (toggleButton.isSelected()) toggleButton.setText("OFF"); else

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. toggleButton.setText("ON"); } }); // Add the toggle button and label to the content pane. add(toggleButton); } } Output

JCheckBox The JCheckBox class provides the functionality of a check box. When the selects or deselects a check box, an ItemEvent is generated. Example import java.awt.*; import java.awt.event.*; import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet implements ItemListener { JLabel label; public void init() { render(); } private void render() { // Change to flow layout.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. setLayout(new FlowLayout()); // Add check boxes to the content pane. JCheckBox cb = new JCheckBox("C"); cb.addItemListener(this); add(cb); cb = new JCheckBox("C++"); cb.addItemListener(this); add(cb); cb = new JCheckBox("Java"); cb.addItemListener(this); add(cb); // Create the label and add it to the content pane. label = new JLabel("Select languages"); add(label); } // Handle item events for the check boxes. public void itemStateChanged(ItemEvent ie) { JCheckBox cb = (JCheckBox) ie.getItem(); if (cb.isSelected()) label.setText(cb.getText() + " is selected"); else label.setText(cb.getText() + " is cleared"); } } Output

JRadioButton Radio buttons are a group of mutually exclusive buttons, in which only one button can be selected at any one time. Example import java.awt.*;

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. import java.awt.event.*; import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet implements ActionListener { JLabel label; public void init() { render(); } private void render() { // Change to flow layout. setLayout(new FlowLayout()); // Create radio buttons and add them to content pane. JRadioButton b1 = new JRadioButton("Male"); b1.addActionListener(this); add(b1); JRadioButton b2 = new JRadioButton("Female"); b2.addActionListener(this); add(b2); // Define a button group. ButtonGroup bg = new ButtonGroup(); bg.add(b1); bg.add(b2); // Create a label and add it to the content pane. label = new JLabel("Select your Gender"); add(label); } // Handle button selection. public void actionPerformed(ActionEvent ae) { label.setText("You selected " + ae.getActionCommand()); } } Output

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

4.11 JTabbedPane Description A JTabbedPane contains a tab that can have a tool tip and a mnemonic, and it can display both text and an image. Procedure to use a tabbed pane  Create an instance of JTabbedPane.  Add each tab by calling addTab()  Add the tabbed pane to the content pane. Example: import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet { public void init() { render(); } private void render() { JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.addTab("Sem 1", new Sem1()); tabbedPane.addTab("Sem 2", new Sem2()); add(tabbedPane); } } // Make the s that will be added to the tabbed pane. @SuppressWarnings("serial") class Sem1 extends J { public Sem1()

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. { JButton b1 add(b1); JButton b2 add(b2); JButton b3 add(b3); JButton b4 add(b4);

= new JButton("Mathematics 1"); = new JButton("C"); = new JButton("Basic Electronics"); = new JButton("Chemistry");

} } @SuppressWarnings("serial") class Sem2 extends J { public Sem2() { JButton b1 = new add(b1); JButton b2 = new add(b2); JButton b3 = new add(b3); JButton b4 = new add(b4); } }

JButton("Mathematics 2"); JButton("Civil"); JButton("Basic Electricals"); JButton("Physics");

Output

4.12 JScrollPane Description JScrollPane is a lightweight container that automatically handles the scrolling of another component. The component being scrolled can either be an individual component, such as a table, or a group of components contained within another lightweight container, such as a J. In either case, if the object being scrolled is larger than the viewable area, horizontal and/or vertical scroll bars are automatically provided, and the component can be scrolled through the pane. Because JScrollPane automates scrolling, it usually eliminates the need to manage individual scroll bars

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Steps to use a scroll pane  Create the component to be scrolled.  Create an instance of JScrollPane, ing to it the object to be scrolled.  Add the scroll pane to the content pane

Example import java.awt.*; import javax.swing.*; @SuppressWarnings("serial") public class Example extends JApplet { public void init() { render(); } private void render() { // Add 400 buttons to a . J jp = new J(); jp.setLayout(new GridLayout(20, 20)); int b = 0; for (int i = 0; i < 20; i++) { for (int j = 0; j < 20; j++) { jp.add(new JButton("Button " + b)); ++b; } } // Create the scroll pane. JScrollPane jsp = new JScrollPane(jp); // Add the scroll pane to the content pane. // Because the default border layout is used, // the scroll pane will be added to the center. add(jsp, BorderLayout.CENTER); } } Output

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

4.13 JList Description JList s the selection of one or more items from a list.

Example import javax.swing.*; import javax.swing.event.*; import java.awt.*; @SuppressWarnings("serial") public class Example extends JApplet { JList list; JLabel label; JScrollPane scrollpane; // Create an array of cities. String Cities[] = { "Bangalore", "Mysore", "Mandya", "Hassan", "Kolar", "Shimoga", "Chikamagalur", "Dakshina Kannda", "Madikeri", "Gulbarga", "Dharwad", "Belgaum" }; public void init() { render(); } private void render() { // Change to flow layout. setLayout(new FlowLayout());// Create a JList. list = new JList(Cities); // Set the list selection mode to single selection. list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Add the list to a scroll pane. scrollpane = new JScrollPane(list);

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. // Set the preferred size of the scroll pane. scrollpane.setPreferredSize(new Dimension(120, 90)); // Make a label that displays the selection. label = new JLabel("Choose a City"); // Add selection listener for the list. list.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent le) { // Get the index of the changed item. int idx = list.getSelectedIndex(); // Display selection, if item was selected. if (idx != -1) label.setText("Current selection: " + Cities[idx]); else // Otherwise, reprompt. label.setText("Choose a City"); } }); // Add the list and label to the content pane. add(scrollpane); add(label); } } Output

4.14 JComboBox Description JComboBox is a combination of a text field and a drop-down list. A combo box normally displays one entry, but it will also display a dropdown list that allows a to select a different entry. Example import java.awt.*; import java.awt.event.*; import javax.swing.*;

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. @SuppressWarnings("serial") public class Example extends JApplet { JLabel label; JComboBox comboBox; String flags[] = { "aklc", "jmaster" }; public void init() { render(); } private void render() { // Change to flow layout. setLayout(new FlowLayout()); // Instantiate a combo box and add it to the content pane. comboBox = new JComboBox(flags); add(comboBox); // Handle selections. comboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String s = (String) comboBox.getSelectedItem(); label.setIcon(new ImageIcon(s + ".png")); } }); // Create a label and add it to the content pane. label = new JLabel(new ImageIcon("aklc.png")); add(label); } } Output

4.15 JTable Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Description JTable is a component that displays rows and columns of data. You can drag the cursor on column boundaries to resize columns. You can also drag a column to a new position. Depending on its configuration, it is also possible to select a row, column, or cell within the table, and to change the data within a cell. Steps to setup a simple JTable.  Create an instance of JTable.  Create a JScrollPane object, specifying the table as the object to scroll.  Add the table to the scroll pane  Add the scroll pane to the content pane. Example import javax.swing.*; /* */ @SuppressWarnings("serial") public class Example extends JApplet { public void init() { render(); } private void render() { // Initialize column headings. String[] colHeads = { "USN", "Name", "Gender" }; // Initialize data. Object[][] data = { { 7, "Vidya", "Female" }, { 9, "Ashok", "Male" }, { 12, "Manoj", "Male" }, { 44, "Rekha", "Female" } }; JTable table = new JTable(data, colHeads); // Add the table to a scroll pane. JScrollPane jsp = new JScrollPane(table); // Add the scroll pane to the content pane. add(jsp); } } Output

Mr. Ashok Kumar K | 9742024066 | [email protected]

a

VTU 7th sem B.E (CSE/ISE)

JAVA/ J2EE Notes prepared by

Mr. Ashok Kumar K 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

INTRODUCTION TO J2EE There are three kinds of applications we can think of 1.

Standalone applications Standalone applications are those which works based on “where you write the code is where you run the code”. i.e., if you want to run a standalone application in a client’s machine, you need to have the code residing in that machine; else the application is not runnable. Example: Games (which requires installations), GTalk, etc

2.

Web applications Here it is not required for the code to be present in every client’s machine. Instead, the application will be deployed in a centralized sever, whereas the clients makes a request to access this application through a web browser. Server processes multiple clients’ request and makes a response to each client request.

3.

Mobile applications These are the application developed for hand held devices like PDAs, mobile phones, IPODs, IPADs, etc.

J2SE (Java to Standard Edition) is a Java platform designed for standalone applications. J2EE (Java to Enterprise Edition) is a Java platform designed for Web applications or server side applications. J2ME (Java to Micro Edition) is a Java platform designed for Mobile applications.`

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

J2EE Multi-tier Architecture

J2EE is a multi-tier architecture (four layered architecture). The layers are named as follows:    

Client tier Web tier Business logic tier Database tier Client tier Any component that is capable of initiating a request to the server is said to sit in the client tier of the J2EE architecture. Example for client tier component would be a HTML page, browser, etc Web tier Web tier component receives the request from the client tier component and forwards the request to the appropriate business logic tier to process it. Due to security perspective and other issues, the business logic is delegated to the next tier. Example for Web tier component would be a servlet. Business logic tier The components in this tier are responsible for implementing the core business logic for the request from client tier. Example for business logic tier component would be a EJB (Enterprise Java Bean). It might make a connection to the fourth tier to perform various database operations. Database tier The components in this tier are responsible for storing the application’s data. They provide the application’s data to the upper tiers upon making a request. Example: MySQL, Oracle, DB2, and Sybase database.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Unit 5:

Java to Data Base Connection (JDBC)

Mr. Ashok Kumar K 9742024066 | [email protected]

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

15 reasons to choose VTUPROJECTS.COM for your final year project work 1. Training from the scratch We train our students on all the languages and technologies required for developing the projects from the scratch. No prerequisites required. 2. Line by Line code explanation Students will be trained to such an extent where they can explain the entire project line by line code to their respective colleges. 3. Study Materials We provide the most efficient study material for each and every module during the project development 4. Trainers Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter expert in strengthening student's skillset for cracking any interviews. He will be having a thorough experience in working on both product and service driven industries. 5. Reports and PPTs Project report as per the university standards and the final presentation slides will be provided and each student will be trained on the same. 6. Video manuals Video manuals will be provided which will be useful in installing and configuring various softwares during project development 7. Strict SDLC Project development will be carried out as per the strict Software Development model 8. Technical Seminar topics We help students by providing current year's IEEE papers and topics of their wish for their final semester Technical seminars 9. Our Availability We will be available at our centers even after the class hours to help our students in case they have any doubts or concerns. 10. Weightage to your Resume Our students will be adding more weightage to their resumes since they will be well trained on various technologies which helps them crack any technical interviews 11. Skype/ Team viewer In case the student needs an emergency help when he/she is in their colleges, we will be helping out them through Skype/ Team viewer screen sharing 12. Practical Understanding Each and module in the project will be implemented and taught to the students giving practical real world applications and their use. 13. Mock demo and presentations Each student will have to prepare for mock demo and presentations every week so that he/she will be confident enough to demonstrate the project in their respective colleges 14. Communication & Soft skills Training We provide communication and soft skills training to each students to help improve their presentation and demonstration skills. 15. Weekly monitoring Each student will be monitored and evaluated on the status of the project work done which helps the students to obtain thorough understanding on how the entire project will be developed

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

5.1 Basics Definition JDBC (Java Database Connectivity) is an API for the Java programming language that defines how a client may access the database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases. JDBC classes are present in java.sql package.

History JDBC was a part of JDK 1.1 (Feb 19, 1997) and was developed by a team named Javasoft of Sun Microsystems.

JDBC Components JDBC project by Javasoft comprises of two things: JDBC APIs and JDBC Driver

JDBC APIs JDBC APIs are the library functions that performs common tasks associated with database usage like: Opening/ Closing the connection with the database, Creating SQL statements, Executing that SQL queries in the database, and Viewing & Modifying the resulting records

JDBC Driver A JDBC driver is a software component enabling a Java application to interact with a database. It is the actual implementation of the defined interfaces in the JDBC API for interacting with your database server.

5.2 JDBC Drivers There are many possible implementations of JDBC drivers. These implementations are categorized as follows:

Type 1 JDBC Driver: These drivers implement the JDBC API as a mapping to another data access API, such as ODBC (Open Database Connectivity). Drivers of this type are generally dependent on a native library, which limits their portability. Example: The JDBC-ODBC Bridge.

Type 2 JDBC Driver: These drivers are written partly in the Java programming language and partly in native code. These drivers use a native client library specific to the data source to which they connect. Again, because of the native code, their portability is limited. Example: Oracle's OCI (Oracle Call Interface) client-side driver.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Type 3 JDBC Driver: These drivers use a pure Java client and communicate with a middleware server using a database-independent protocol. The middleware server then communicates the client's requests to the data source.

Type 4 JDBC Driver: These drivers are pure Java and implement the network protocol for a specific data source. The client connects directly to the data source.

5.3 JDBC Process Brief Overview of JDBC Process There are five steps in the JDBC process for a Java program to communicate with the database. Let's see them in brief and later elaborate each step.

Step 1: Load the Driver Here you should load and initialize the class representing the MySQL JDBC Driver. The code snippet to do this is given below: try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Couldn't load the Driver"); }

Step 2: Establish the Connection Next, you need to establish a connection with the data source you want to use. A data source can be a DBMS, a legacy file system, or some other source of data with a corresponding JDBC driver. We use the static getConnection() method in DriverManager class to get the connection. Its syntax is shown below: static Connection getConnection (url, name, ) throws SQLException url is the path to the database name and are the credentials to the database. It is optional. Sample code snippet is given below: Connection con = null; try { con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/College", "root", "lordshiva");

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. } catch (SQLException e) { System.out.println("Couldn't Obtain the connection"); }

Step 3: Create the SQL Statement and Execute the SQL Query 3a.) Creating the query You should obtain any of the Statement object in order to execute the query. Statement object can be either Statement, PreparedStatement, or CallableStatement which will be explained later. Here we use createStatement() method of Connection class to create the simple Statement. 3b.) Executing the query Once the statement is ready, you can execute the SQL query using executeQuery() method as demonstrated in the below code snippet. It returns a ResultSet object. Statement st = null; ResultSet rs = null; String qry = "select * from student"; try { st = con.createStatement(); rs = st.executeQuery(qry); } catch (SQLException e) { System.out.println("Error while processing SQL query"); }

Step 4: Process the result set The output of the SQL query will be encapsulated in ResultSet object. A ResultSet object contains zero or more records (or rows). We should iterate over each record (or row) in order to print it in the console as demonstrated below: try { String id, name; int age; double aggregate; while (rs.next()) { id = rs.getString("id"); name = rs.getString("name"); age = rs.getInt("age"); aggregate = rs.getDouble("aggr"); System.out.println(id + "\t" + name + "\t" + age + "\t" + aggregate); } } catch (SQLException e) { System.out.println("Error while processing SQL results"); }

Step 5: Close the connection At last, a very important step of all is to close the database connection. This releases the external resources like cursor, handlers etc. Typically, closing the connection should be done in the finally block. try { con.close(); } catch (Exception e) { System.out.println("Error while closing the connection"); }

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

5.4 Loading the JDBC Driver When you are using JDBC outside of an application server, the DriverManager class manages the establishment of Connections. You should specify to the DriverManager which JDBC drivers it should try to make Connections with. The easiest way to do this is to use Class.forName() on the class that implements the java.sql.Driver interface. With MySQL, the name of this class is com.mysql.jdbc.Driver. try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println("Couldn't load the Driver"); } Make sure that the driver class (com.mysql.jdbc.Driver) is available in the classpath so that it can be loaded and initialized by the JVM.

5.5 Establishing the Connection Concept Once the JDBC driver has been loaded and initialized, the Java component can now obtain a connection to the external database associated with the driver. To do this, you must invoke getConnection() method of DriverManager class ing three arguments as shown in the syntax below: static Connection getConnection (url, , ) throws SQLException Here,   

url: a database url of the form jdbc:subprotocol:subname : the database on whose behalf the connection is being made : the 's

It returns a Connection object. url is made of three components;  jdbc: It is the protocol being used.  subprotocol: It is the JDBC driver name.  subname: It is the name of the database.

Example: Connection con = null; try { con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/College", "root", "lordshiva"); } catch (SQLException e) { System.out.println("Couldn't Obtain the connection"); }

ing additional parameters for authentication Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Some databases would require additional details other than name and to grant the access to the database. The question here is how would you provide these additional propertied to DriverManager's getConnection() method. This additional information must be associated with a Properties object which is ed as an argument in getConnection() method. Example: Connection con = null; try { FileInputStream fis = new FileInputStream( new File("DBProps.txt") ); Properties props = new Properties(); props.load(fis); con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/college", props); } catch (SQLException e) { System.out.println("Couldn't Obtain the connection"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }

Setting Timeout Whenever a J2EE component requests connection with the external database, there are possibilities where the DBMS may not respond to it due to various reasons. In this case, the J2EE component will wait indefinitely till the DBMS responds to it. To avoid this indefinite delay, you can set a timeout period after which the DriverManager will stall (cancel) the attempt to connect to the DBMS. To set the timeout period, you can use setoginTimeout() method in DriverManager class whose syntax is given below: public static void setTimeout(int seconds) Likewise, you can use getTimeout() method to retrieve the current timeout period that has been set. Its syntax is shown below: public static int getTimeout()

5.6 Statements in JDBC A Statement is an interface that represents a SQL statement. You execute Statement objects, and they generate ResultSet objects, which is a table of data representing a database result set. You need a Connection object to create a Statement object. For example, stmt = con.createStatement(); There are three different kinds of statements:

Statement: Used to implement simple SQL statements with no parameters. PreparedStatement: (Extends Statement) Used for precompiling SQL statements that might contain input parameters. These input parameters will be given a value in the runtime. CallableStatement: (Extends PreparedStatement) Used to execute stored procedures that may contain both input and output parameters.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Statement The Statement object is used whenever a J2EE component needs to immediately execute a query without first having the query compiled. Before you can use a Statement object to execute a SQL statement, you need to create one using the Connection object's createStatement() method, as in the following example: Statement st = null; try { st = con.createStatement(); } catch (SQLException e) { e.printStackTrace(); } Once you've created a Statement object, you can then use it to execute a SQL statement with one of its three execute methods. 

boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL.



int executeUpdate(String SQL) : Returns the numbers of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement.



ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement.

Just as you close a Connection object to save database resources, for the same reason you should also close the Statement object. A simple call to the close() method will do the job.

Example: import java.sql.*; public class Example { public static void main(String arg[]) { Statement st = null; ResultSet rs = null; Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "lordshiva"); String qry = "select * from student"; st = con.createStatement(); rs = st.executeQuery(qry); String id, name; int age; double aggregate; System.out.println("Table Data are as follows .. \n"); while (rs.next()) { id = rs.getString("id"); name = rs.getString("name"); age = rs.getInt("age"); aggregate = rs.getDouble("aggr"); System.out.println(id + "\t" + name + "\t" + age + "\t" }

+ aggregate);

System.out.println("\n\nDeleting those students having lesser than 35%

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. aggregate ..\n"); String qry2 = "delete from student where aggr < 35"; int rows = st.executeUpdate(qry2); System.out.println(rows + " rows deleted .. "); } catch (Exception e) { e.printStackTrace(); } finally { try { st.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } } } Output:

PreparedStatement The PreparedStatement is used to compile the query first before executing it. The PreparedStatement interface extends the Statement interface which gives you added functionality. This statement gives you the flexibility of supplying input arguments dynamically. All parameters (arguments) are represented by the ? symbol, which is known as the place holder. You must supply values for every parameter before executing the SQL statement. The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter. Each parameter marker is referred to by its ordinal position. The first marker represents position 1, the next position 2, and so forth. If you forget to supply the values, you will receive an SQLException. All of the Statement object's methods for interacting with the database: execute(), executeQuery(), and executeUpdate() also work with the PreparedStatement object. However, the methods are modified to use SQL statements that can take input the parameters.. Example PreparedStatement ps = null; try { String qry = "update student set name=? where id=?"; ps = con.prepareStatement(qry); ps.setString(1, "Ashok Kumar"); ps.setString(2, "1VK06IS009"); ps.execute(); } catch (SQLException e) {

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. e.printStackTrace(); } finally { try { ps.close(); } catch (Exception e) { e.printStackTrace(); } } Just as you close a Statement object, for the same reason you should also close the PreparedStatement object. A simple call to the close() method will do the job.

CallableStatement CallableStatement object is used to execute a call to the stored procedure from within a J2EE object. The stored procedure can be written in PL/SQL, Transact-SQL, C, or another programming language. The stored procedure is a block of code and is identified by a unique name. Here is the simple MySQL stored procedure: CREATE OR REPLACE PROCEDURE getStudName (STUD_ID IN VARCHAR, STUDENT_NAME OUT VARCHAR) AS BEGIN SELECT name INTO STUDENT_NAME FROM Student WHERE ID = STUD_ID; END; Here three types of parameters exist:   

IN: A parameter whose value is unknown when the SQL statement is created. You bind values to IN parameters with the setXXX() methods. OUT: A parameter whose value is supplied by the SQL statement it returns. You should this parameter using OutParameter() method. You retrieve values from the OUT parameters with the getXXX() methods. INOUT: A parameter that provides both input and output values. You bind variables with the setXXX() methods and retrieve values with the getXXX() methods.

Example CallableStatement cs = null; try { String qry = "{CALL getStudName (?,?) }"; cs = con.prepareCall(qry); cs.setString(1, "1VK06IS009"); cs.OutParameter(2, Types.VARCHAR); cs.execute(); String name = cs.getString(2); System.out.println("Student name is .. "+name); } catch (Exception e) { e.printStackTrace(); } finally { try {

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. cs.close(); } catch (Exception e) { e.printStackTrace(); } } Just as you close other Statement object, for the same reason you should also close the CallableStatement object. A simple call to the close() method will do the job.

Difference between Statement, PreparedStatement, and CallableStatement in brief Statement The Statement object is used whenever a J2EE component needs to immediately execute a query without first having the query compiled No input/ output arguments can be supplied

PreparedStatement The PreparedStatement is used to compile the query first before executing it.

CallableStatement CallableStatement object is used to execute a call to the stored procedure from within a J2EE object

Input arguments can be supplied dynamically prepareStatement() method of Connection object is used to get the PreparedStatement object.

Both input and output arguments can be supplied dynamically prepareCall() method of Connection object is used to get the CallableStatement object.

Example:

Example:

Example:

String qry = "select * from student";

String qry = "update student set name=? where id=?";

String qry = "{CALL getStudName (?,?) }";

PreparedStatement ps = con.prepareStatement(qry);

CallableStatement cs = con.prepareCall(qry);

ps.setString(1, "Ashok Kumar");

cs.setString(1, "1VK06IS009");

createStatement() method of Connection object is used to get the Statement object.

Statement st = con.createStatement(); rs = st.executeQuery(qry);

ps.setString(2, "1VK06IS009");

cs.OutParameter(2, Types.VARCHAR);

ps.execute();

cs.execute();

5.7 ResultSet in JDBC As you know, the executeQuery() method is used to send the query to the DBMS and returns a ResultSet object that contains data that was requested by the query. A ResultSet object maintains a virtual cursor that points to a row in the result set. The term "result set" refers to the virtual table of row and column data contained in a ResultSet object. The virtual cursor is initially positioned above the first row of data when the ResultSet is returned by executeQuery() method. There are various methods in the ResultSet interface. These methods can be grouped into three categories as follows   

Get methods: used to view the data in the columns of the current row being pointed by the virtual cursor. Navigational methods: used to move the virtual cursor around the virtual table. Update methods: used to update the data in the columns of the current row.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Reading the ResultSet using Get methods There is a get method in ResultSet interface for each of the possible data types of the form getXXX() where XXX is the data type of the column, and each get method has two versions:  One that takes in a column name Example: String name = rs.getString("name");  One that takes in a column index. Example: String name = rs.getString(1);

Example: import java.sql.*; public class Example { public static void main(String arg[]) { try { Class.forName("com.mysql.jdbc.Driver"); Connection con = null; con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/college", "root", "lordshiva"); Statement st = null; ResultSet rs = null; String qry = "select * from student"; st = con.createStatement(); rs = st.executeQuery(qry); String id, name; int age; double aggregate; while (rs.next()) { id = rs.getString("id"); name = rs.getString(2); age = rs.getInt("age"); aggregate = rs.getDouble(4); System.out.println(id + "\t" + name + "\t" + age + "\t" + aggregate); } } catch (Exception e) { e.printStackTrace(); } } } Output:

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Scrollable ResultSet Types of ResultSet Type of ResultSet ResultSet.TYPE_FORWARD_ONLY ResultSet.TYPE_SCROLL_INSENSITIVE

ResultSet.TYPE_SCROLL_SENSITIVE

Meaning The cursor can only move forward in the result set. This is the default. The cursor can scroll forwards and backwards, and the result set is not sensitive to changes made by others to the database that occur after the result set was created. The cursor can scroll forwards and backwards, and the result set is sensitive to changes made by others to the database that occur after the result set was created.

You should specify one of the type of ResultSet while creating a Statement object. You should this as an argument to createStatement() or preparedStatement() method. If you don't specify anything, the default one will be TYPE_FORWARD_ONLY.

Concurrency of ResultSet Rows contained in ResultSet's virtual table can either be read only or be updatable. This selection can be made by ing either one of the below as an argument to createStatement() or preparedStatement() method. ResultSet concurrency ResultSet.CONCUR_READ_ONLY ResultSet.CONCUR_UPDATABLE

Meaning Creates a read-only result set. This is the default. Creates an updateable result set

Example 1: Statement st = null; st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE); Example 2: Statement st = null; st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);

Scrolling a ResultSet There are several methods in the ResultSet interface that involve moving the cursor. They are: public void beforeFirst() throws SQLException 1

Moves the cursor to the front of this ResultSet object, just before the first row. This method has no effect if the result set contains no rows. public void afterLast() throws SQLException

2

Moves the cursor to the end of this ResultSet object, just after the last row. This method has no effect if the result set contains no rows. public boolean first() throws SQLException

3

Moves the cursor to the first row in this ResultSet object public void last() throws SQLException

4

Moves the cursor to the last row in this ResultSet object.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. public boolean absolute(int row) throws SQLException

5

Moves the cursor to the given row number in this ResultSet object. If the row number is positive, the cursor moves to the given row number with respect to the beginning of the result set. The first row is row 1, the second is row 2, and so on. If the given row number is negative, the cursor moves to an absolute row position with respect to the end of the result set. For example, calling the method absolute(-1) positions the cursor on the last row; calling the method absolute(-2) moves the cursor to the next-to-last row, and so on. An attempt to position the cursor beyond the first/last row in the result set leaves the cursor before the first row or after the last row. public boolean relative(int row) throws SQLException

6

Moves the cursor a relative number of rows, either positive or negative. Attempting to move beyond the first/last row in the result set positions the cursor before/after the first/last row. Calling relative(0) is valid, but does not change the cursor position. public boolean previous() throws SQLException

7

Moves the cursor to the previous row in this ResultSet object. When a call to the previous method returns false, the cursor is positioned before the first row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown. If an input stream is open for the current row, a call to the method previous will implicitly close it. A ResultSet object's warning change is cleared when a new row is read. public boolean next() throws SQLException

8

Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on. When a call to the next method returns false, the cursor is positioned after the last row. Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.

public int getRow() throws SQLException 9

Retrieves the current row number. The first row is number 1, the second number 2, and so on. public void moveToInsertRow() throws SQLException

10

Moves the cursor to the insert row. The current cursor position is ed while the cursor is positioned on the insert row. The insert row is a special row associated with an updatable result set. It is essentially a buffer where a new row may be constructed by calling the updater methods prior to inserting the row into the result set public void moveToCurrentRow() throws SQLException

11

Moves the cursor to the ed cursor position, usually the current row. This method has no effect if the cursor is not on the insert row.

Note 1: Not all the Drivers are scrollable. Here is the code snippet to test whether a driver s a scrollable ResultSet try { Class.forName("com.mysql.jdbc.Driver"); Connection con = null; con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "lordshiva");

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. DatabaseMetaData dbmeta = con.getMetaData(); System.out.println("s TYPE_FORWARD_ONLY ? .. " +dbmeta.sResultSetType(ResultSet.TYPE_FORWARD_ONLY)); System.out.println("s TYPE_SCROLL_INSENSITIVE ? .. " +dbmeta.sResultSetType(ResultSet.TYPE_SCROLL_INSENSITIVE)); System.out.println("s TYPE_SCROLL_SENSITIVE ? .. " +dbmeta.sResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE));

} catch (Exception e) { e.printStackTrace(); }

Note 2: Setting the maximum number of rows returned in a ResultSet try { Class.forName("com.mysql.jdbc.Driver"); Connection con = null; con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "lordshiva"); Statement st = con.createStatement(); st.setFetchSize(200); ResultSet rs = st.executeQuery("select * from student"); } catch (Exception e) { e.printStackTrace(); }

Updating a ResultSet The ResultSet interface contains a collection of update methods for updating the data of a result set. As with the get methods, there are two updateXXX() methods for each data type, where XXX is the data type of the column:\ 



One that takes in a column name. Example, rs.updateString("Name", "Ashoka"); One that takes in a column index. Example, rs.updateString(2, "Ashoka");

Updating a row in the result set changes the columns of the current row in the ResultSet object (virtual table), but not in the underlying database. To update your changes to the row in the database, you need to invoke one of the following methods.

public void updateRow() Updates the underlying database with the new contents of the current row of this ResultSet object. This method cannot be called when the cursor is on the insert row.. public void deleteRow() Deletes the current row from this ResultSet object and from the underlying database. This method cannot be called when the cursor is on the insert row.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. public void refreshRow() Refreshes the current row with its most recent value in the database. This method cannot be called when the cursor is on the insert row. public void cancelRowUpdates() Cancels the updates made to the current row in this ResultSet object. This method may be called after calling an updater method(s) and before calling the method updateRow to roll back the updates made to a row. If no updates have been made or updateRow has already been called, this method has no effect. public void insertRow() Inserts the contents of the insert row into this ResultSet object and into the database. The cursor must be on the insert row when this method is called..

Examples: 1. Updating the ResultSet rs = st.executeQuery(qry); while (rs.next()) { if (rs.getString("name").equals("Ashok")) { rs.updateString("name", "Ashok Kumar"); rs.updateRow(); } } 2. Deleting a Row rs = st.executeQuery(qry); while (rs.next()) { if (rs.getString("name").equals("Prasad")) { rs.deleteRow(); } }

5.8 Database Transaction Concept and Definition A Database Transaction consists of a set of SQL statements, each of which must be successfully completed for the transaction to be completed. If one fails, SQL statements that executed successfully up to that point in the transaction must be rolled back. A database transaction, by definition, must be atomic, consistent, isolated and durable. Database practitioners often refer to these properties of database transactions using the acronym ACID. 



Atomicity: Atomicity requires that each transaction is "all or nothing": if one part of the transaction fails, the entire transaction fails, and the database state is left unchanged. An atomic system must guarantee atomicity in each and every situation, including power failures, errors, and crashes. To the outside world, a committed transaction appears (by its effects on the database) to be indivisible ("atomic"), and an aborted transaction does not happen. Consistency: The consistency property ensures that any transaction will bring the database from one valid state to another. Any data written to the database must be valid according to all defined rules, including but not limited to constraints, cascades, triggers, and any combination thereof.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. 



Isolation: The isolation property ensures that the concurrent execution of transactions results in a system state that would be obtained if transactions were executed serially, i.e. one after the other. Providing isolation is the main goal of concurrency control. Depending on concurrency control method, the effects of an incomplete transaction might not even be visible to another transaction Durability: Durability means that once a transaction has been committed, it will remain so, even in the event of power loss, crashes, or errors. In a relational database, for instance, once a group of SQL statements execute, the results need to be stored permanently (even if the database crashes immediately thereafter). To defend against power loss, transactions (or their effects) must be recorded in a non-volatile memory.

A Transactional database is a DBMS where write transactions on the database are able to be rolled back if they are not completed properly (e.g. due to power or connectivity loss). Most modern relational database management systems fall into the category of databases that transactions.

commit() and rollback() methods A database transaction isn't completed until the J2EE component calls the commit() method of the Connection object. All SQL statements executed prior to the call to the commit() method can be rolled back. However, once the commit() method is called, none of the SQL statements can be rolled back. The commit() method must be called regardless if the SQL statement is part of a transaction or not. Till now, we never issued a commit() on the database but still we were able to save the data in the database. This is because of the auto commit feature of the database connection. If a J2EE component is implementing a transaction, then the auto commit feature should be turned off. This can be done as follows: try { Class.forName("com.mysql.jdbc.Driver"); Connection con = null; con = DriverManager.getConnection("jdbc:mysql://localhost:3306/college", "root", "lordshiva"); con.setAutoCommit(false); } catch (Exception e) { e.printStackTrace(); } Let's see a simple transaction processing example. Below program executes two SQL queries, both of which update the student's aggregate and age. Each SQL statement will be executed separately and a commit() method is called upon success. However, if any of the statement fails (throws an exception), the transaction is rolled back by invoking rollback() method in the catch clause. import java.sql.*; public class Example { public static void main(String arg[]) { Connection con = null; Statement st1 = null; Statement st2 = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection

("jdbc:mysql://localhost:3306/college", "root",

"lordshiva"); con.setAutoCommit(false); String qry1 = "update student set aggr=86.17, age=25 where id='1VK06IS009' ";

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. String qry2 = "update student set aggr=71.13, age=27 where id='1VK04IS034' "; st1 = con.createStatement(); st2 = con.createStatement(); st1.execute(qry1); st2.execute(qry2); System.out.println("Transaction success .."); con.commit(); } catch (Exception e) { System.out.println("Transaction failed .."); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { try { st1.close(); st2.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } } }

Using savepoints A transaction may consist of many tasks, some of which don't need to be rolled back when the transaction fails. The J2EE component can control the number of tasks that are rolled back by using savepoints. A savepoint is a virtual marker that defines the task at which the rollback stops. When you set a savepoint you define a logical rollback point within a transaction. If an error occurs past a savepoint, you can use the rollback method to undo either all the changes or only the changes made after the savepoint. Example, Here we execute two SQL statements. After executing one SQL statement, a savepoint is set. The transaction is rolled back till this savepoint after executing both the statements. Thus only second SQL statement will be rolled back and the first SQL statement will be committed. import java.sql.*; public class Example { public static void main(String arg[]) { Connection con = null; Statement st1 = null; Statement st2 = null;

try { Class.forName("com.mysql.jdbc.Driver");

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. con = DriverManager.getConnection "jdbc:mysql://localhost:3306/college", "root", "lordshiva"); con.setAutoCommit(false);

String qry1 = "insert into student values ('1VK08IS026', 'Naveen', 23, 46.8)"; String qry2 = "update student set aggr=86.17, age=25 where id='1VK06IS009' "; st1 = con.createStatement(); st2 = con.createStatement(); st1.execute(qry1); Savepoint sp1 = con.setSavepoint(); st2.execute(qry2); con.rollback(sp1); con.releaseSavepoint(sp1); System.out.println("Transaction success .."); con.commit(); } catch (Exception e) { System.out.println("Transaction failed .."); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { try { st1.close(); st2.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } } }

Batching SQL statements Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance. The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together. The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement. A value of -1 indicates the failure of update statement.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove Example import java.sql.*; public class Example { public static void main(String arg[]) { Connection con = null; Statement st1 = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection

("jdbc:mysql://localhost:3306/college",

"root", "lordshiva"); con.setAutoCommit(false);

String qry1 = "update student set aggr=86.17, age=25 where id='1VK06IS009' "; String qry2 = "update student set aggr=71.17, age=27 where id='1JB04IS034' "; String qry3 = "update student set aggr=42.55, age=23 where id='1VK08IS026' "; st1 = con.createStatement(); st1.addBatch(qry1); st1.addBatch(qry2); st1.addBatch(qry3); st1.executeBatch(); st1.clearBatch(); System.out.println("Transaction success .."); con.commit(); } catch (Exception e) { System.out.println("Transaction failed .."); try { con.rollback(); } catch (SQLException e1) { e1.printStackTrace(); } e.printStackTrace(); } finally { try { st1.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } } }

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

5.9 Meta Data There are two types of metadata that can be retrieved from the DBMS.  DatabaseMetaData which is the data about the database  ResultSetMetaData which is the data about the Result Set

DatabaseMetaData Meta data is the data about the data. A J2EE component can access the metadata by using the DatabaseMetaData interface. It is used to retrieve information about databases, tables, column, indexes, etc. getMetaData() method of Connection object is used to retrieve the metadata about the database. Here are some of the methods available in DatabaseMetaData interface: getDatabaseProductName(): getName(): getURL(): getSchemas(): getPrimaryKeys(): getProcedures(): getTables():

Returns the product name of the DBMS Returns the name Returns the URL for the database. Returns all the schema names available in this database Returns primary keys Returns stored procedure names Returns names of tables in the database

Example import java.sql.*; public class Example { public static void main(String arg[]) { Connection con = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/college", "root", "lordshiva"); DatabaseMetaData dbmetadata = con.getMetaData(); System.out.println("Database product name: .. " +dbmetadata.getDatabaseProductName()); System.out.println("Database name: .. " +dbmetadata.getName()); System.out.println("Database URL: .. "+dbmetadata.getURL()); } catch (Exception e) { e.printStackTrace(); } finally { try { con.close(); } catch (Exception e) { e.printStackTrace(); } } } } Output:

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

ResultSetMetaData ResultSetMetaData interface describes the Result set (virtual database). getMetaData() method of the ResultSet object can be used to retrieve the Result set metadata. The most commonly used methods in ResultSetMetaData interface are: getColumnCount(): getColumnName(int number): getColumnType(int number):

Returns the number of columns obtained in the ResultSet. Returns the name of the column specified by the column number. Returns the data type of the column specified by the column number

Example import java.sql.*; public class Example { public static void main(String arg[]) { Connection con = null; Statement st = null; try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/college", "root", "lordshiva"); String qry = "select * from student"; st = con.createStatement(); ResultSet rs = st.executeQuery(qry); ResultSetMetaData rsmetadata = rs.getMetaData(); System.out.println("Column count: .. " +rsmetadata.getColumnCount()); System.out.println("First Column name : .. " +rsmetadata.getColumnName(1)); } catch (Exception e) { e.printStackTrace(); } finally { try { st.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } } } Output:

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

5.10 Exceptions There are three kinds of exceptions that are thrown by JDBC methods. 

SQLException: It commonly reflects a syntax error in the query and is thrown by many of the methods contained in java.sql package.



SQLWarning: It throws warnings received by the connection from the DBMS. The getWarning() method of the Connection object retrieves the warning and the getNextWarning() method retrieves the subsequent warnings.



DataTruncation: It is thrown whenever a data is lost due to the truncation of the data value.

Mr. Ashok Kumar K | 9742024066 | [email protected]

VTU 7th sem B.E (CSE/ISE)

JAVA/ J2EE Notes prepared by

Mr. Ashok Kumar K 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Unit 6:

Servlet

Mr. Ashok Kumar K 9742024066 | [email protected]

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. 15 reasons to choose VTUPROJECTS.COM for your final year project work 1. Training from the scratch We train our students on all the languages and technologies required for developing the projects from the scratch. No prerequisites required. 2. Line by Line code explanation Students will be trained to such an extent where they can explain the entire project line by line code to their respective colleges. 3. Study Materials We provide the most efficient study material for each and every module during the project development 4. Trainers Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter expert in strengthening student's skillset for cracking any interviews. He will be having a thorough experience in working on both product and service driven industries. 5. Reports and PPTs Project report as per the university standards and the final presentation slides will be provided and each student will be trained on the same. 6. Video manuals Video manuals will be provided which will be useful in installing and configuring various softwares during project development 7. Strict SDLC Project development will be carried out as per the strict Software Development model 8. Technical Seminar topics We help students by providing current year's IEEE papers and topics of their wish for their final semester Technical seminars 9. Our Availability We will be available at our centers even after the class hours to help our students in case they have any doubts or concerns. 10. Weightage to your Resume Our students will be adding more weightage to their resumes since they will be well trained on various technologies which helps them crack any technical interviews 11. Skype/ Team viewer In case the student needs an emergency help when he/she is in their colleges, we will be helping out them through Skype/ Team viewer screen sharing 12. Practical Understanding Each and module in the project will be implemented and taught to the students giving practical real world applications and their use. 13. Mock demo and presentations Each student will have to prepare for mock demo and presentations every week so that he/she will be confident enough to demonstrate the project in their respective colleges 14. Communication & Soft skills Training We provide communication and soft skills training to each students to help improve their presentation and demonstration skills. 15. Weekly monitoring Each student will be monitored and evaluated on the status of the project work done which helps the students to obtain thorough understanding on how the entire project will be developed

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

6.1 History Earlier in client- server computing, each application had its own client program and it worked as a interface and need to be installed on each 's personal computer. Later we had the era of Common Gateway Interface (CGI). The Common Gateway Interface was one of the practical techniques developed for creating dynamic content. By using the CGI, a web server es requests to an external program and after executing the program the content is sent to the client as the output. In CGI when a server receives a request it creates a new process to run the CGI program, so creating a process for each request requires significant server resources and time, which limits the number of requests that can be processed concurrently. CGI applications are platform dependent. There is no doubt that CGI played a major role in the explosion of the Internet but its performance, scalability issues make it less than optimal solutions. Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.

Advantages of Servlets over CGI Here is the brief comparison between Servlet and CGI. Servlet

CGI

Servlets is inexpensive in of memory usage

CGI is more expensive than Servlets in of memory usage

Servlet are platform independent

CGI is platform dependent

In Servlets, the Java Virtual Machine stays up, and each request

In

is handled by a lightweight Java thread.

heavyweight operating system process.

Java security manager on the server enforces a set of restrictions

There is no for Security Manager in CGI

CGI,

each

request

is

handled

by

a

to protect the resources on a server machine. So servlets are trusted. The full functionality of the Java class libraries is available to a

CGI has limited libraries

servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already. Servlets can link directly to the Web server

CGI cannot directly link to Web server.

Servlets can share data among each other

CGI does not provide sharing property

Servlets can perform session tracking and caching of previous

CGI cannot perform session tracking and caching

computations.

of previous computations.

Servlets can read and set HTTP headers, handle cookies,

CGI cannot read and set HTTP headers, handle

tracking sessions

cookies, tracking sessions.

Defining a Servlet Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and databases or applications on the HTTP server. Using Servlets, you can collect input from s through web page forms, present records from a database or another source, and create web pages dynamically.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed by means of a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.

6.2 Setting up Servlet Runtime Environment Prerequisite: JDK is installed and configured properly. Like any other Java program, you need to compile a servlet by using the Java compiler javac and after compiling the servlet application, it would be deployed in a configured environment to test and run. To run a Servlet, you need a web server that s Servlet. Apache Tomcat is one of them. Apache Tomcat is an open source software implementation of the Java Servlet and Java Server Pages (JSP) technologies and can act as a standalone server for testing servlets and can be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your machine: 1. 2.

latest version of Tomcat from http://tomcat.apache.org/. Once you ed the installation, unpack the binary distribution into a convenient location. For example in C:\apachetomcat-7.0.26 on windows, or /usr/local/ apache-tomcat-7.0.26 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations.

Tomcat can be started by executing the following commands. 

In Windows %CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-5.5.29\bin\startup.bat



In Linux/ Unix $CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-5.5.29/bin/startup.sh

After startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display following result:

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Tomcat can be stopped by executing the following commands 

In Windows %CATALINA_HOME%\bin\shutdown or C:\apache-tomcat-5.5.29\bin\shutdown



In Linux $CATALINA_HOME/bin/shutdown.sh or /usr/local/apache-tomcat-5.5.29/bin/shutdown.sh

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

6.3 Servlet Life Cycle A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet. 1.

Browser sends a HTTP request to the web server (through URL, submitting a form, etc)

2.

Web server receives the request and maps this request to a particular Servlet. The servlet is retrieved and dynamically loaded into the server address space

3.

init() method of the servlet is called by the web server only when the servlet is first loaded into the memory. You may initialization parameters to this method to configure the Servlet.

4.

Web server invokes service() method of the servlet. This method is called to process the HTTP request. It is possible to read the parameters from the request and is also possible to send a response back to the browser. The servlet remains in the server’s address space and is available to process any other HTTP requests received from clients. The service() method is called for each HTTP request.

5.

Finally, the server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server. The server calls the destroy() method to relinquish any resources such as file handles that are allocated for the servlet.

You can visualize the servlet architecture through the following figure.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Web server A web server uses HTTP protocol to transfer data. In a simple situation, a type in a URL (e.g. www.jmaster.in) in browser (a client), and get a web page to read. So what the server does is sending a web page to the client. The transformation is in HTTP protocol which specifies the format of request and response message. Examples for noncommercial web servers are Apache Tomcat, JBoss, GlassFish, Jetty, etc Servlet Container Servlet container is the component of a web server that interacts with Java servlets. A Servlet container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights. A web container implements the web component contract of the Java EE architecture, specifying a runtime environment for web components that includes security, concurrency, lifecycle management, transaction, deployment, and other services.

6.4 Generic Servlet versus HTTP servlet There are two different kinds of servlet classes that you will come across at later point of time when we start coding the servlet examples. In this section, we will understand these two kinds of servlets.  

GenericServlet is just that, a generic, protocol-independent servlet. HttpServlet is a servlet tied specifically to the HTTP protocol. GenericServlet

HTTPServlet

GenericServlet defines a generic, protocolindependent servlet.

HttpServlet defines a HTTP protocol specific servlet.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. GenericServlet gives a blueprint and makes writing servlet easier GenericServlet provides simple versions of the lifecycle methods init, service, and destroy and of the methods in the ServletConfig interface

HttpServlet gives a blueprint for Http servlet and makes writing them easier HttpServlet extends the GenericServlet and hence inherits the properties of GenericServlet.

6.5 Servlet Libraries Two packages contain the classes and interfaces that are required to build servlets. These are  javax.servlet, and  javax.servlet.http. They constitute the Servlet API. Keep in mind that these packages are not part of the Java core packages. Instead, they are standard extensions provided by the web servers.

javax.servlet package Below are some of the classes and interfaces defined in javax.servlet package

Interfaces Interface Servlet ServletConfig ServletContext ServletRequest ServletResponse

Description Declares life cycle methods for a servlet Allows servlets to get initialization parameters Enables servlets to log events and access information about their environment. Used to read data from a client request Used to write data to a client response

Classes Class GenericServlet ServletInputStream ServletOutputStream ServletException UnavailableException

Description Implements the Servlet and ServletConfig interfaces. Provides an input stream for reading requests from a client. Provides an output stream for writing responses to a client. Indicates a servlet error occurred. Indicates a servlet is unavailable.

javax.servlet.http package Below are some of the classes and interfaces defined in javax.servlet.http package

Interfaces Interface HttpServletRequest HttpServletResponse HttpSession HttpSessionBindingListener

Description Enables servlets to read data from an HTTP request. Enables servlets to write data to an HTTP response. Allows session data to be read and written. Informs an object that it is bound to or unbound from a session.

Classes

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Class Cookie HttpServlet HttpSessionEvent HttpSessionBindingEvent

Description Allows state information to be stored on a client machine. Provides methods to handle HTTP requests and responses. Encapsulates a session-changed event. Indicates when a listener is bound to or unbound from a session value, or that a session attribute changed.

6.6 Servlet Examples Example 1: My first Servlet You would require writing three files to run a simple servlet  HelloServlet.java : A servlet, which is a Java class file  hello.html : A web page to invoke the servlet by sending a request  web.xml : A deployment descriptor which will map the request from the web page to the servlet And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.

Step 1: Create HelloServlet.java package com.aklc.servlet; import java.io.*; import javax.servlet.*; public class HelloServlet extends GenericServlet {

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { // Set the response type (MIME Type) resp.setContentType("text/html"); // Get the writer object w.r.t the client. // So you can write to the browser (client) using this writer object PrintWriter pw = resp.getWriter(); // Enclose your response string inside println() method pw.println("

Hello World, Welcome to the world of Servlet 652l2n

"); // Close the writer object pw.close(); } }

Step 2: Create hello.html

Servlet Examples 47346u

Click here to run a simple servlet.

Step 3: Update web.xml Add the below entry to web.xml <servlet> <servlet-name>FirstServlet <servlet-class>com.aklc.servlet.HelloServlet <servlet-mapping> <servlet-name>FirstServlet /hello

Step 4: Run hello.html on the server Here is the output you would see

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Upon clicking on 'Click here' link, it takes you to the following screen.

You can directly run the project in any of the web browser by entering the below URL (provided that the application is deployed in tomcat server and it is up and running) http://localhost:8080/ / In the above the example, the URL looks like, http://localhost:8080/PractiseApp/hello.html

Example 2: Reading request parameters The ServletRequest interface includes methods that allow you to read the names and values of parameters that are included in a client request. We will develop a servlet that illustrates their use. You would require writing three files to run a simple servlet  ReadParamServlet.java : A servlet, which is a Java class file. It reads the parameters from the request.  Param.html : A web page to invoke the servlet by sending a request. It es the parameters to the servlet.  web.xml : A deployment descriptor which will map the request from the web page to the servlet And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Step 1: Create ReadParamServlet.java package com.aklc.servlet; import java.io.*; import javax.servlet.*; public class ReadParamServlet extends GenericServlet { public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter pw = resp.getWriter(); String name=req.getParameter("name"); pw.println("

Welcome, "+name+" 1f5g2h

"); pw.close(); } }

Step 2: Create Param.html ing parameters to a Servlet
Enter your name:



Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.


Step 3: Update web.xml Add the below entry to web.xml <servlet> <servlet-name>ParamServlet <servlet-class>com.aklc.servlet.ReadParamServlet <servlet-mapping> <servlet-name>ParamServlet /paramEx

Step 4: Run Param.html on the server. You can enter the direct URL in the browser. http://localhost:8080/PractiseApp/Param.html

Clicking on "Click me" button takes you to below screen

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

HTTPServlet Whenever the web browser fetches a file (a page, a picture, etc) from a web server, it does so using HTTP (Hypertext Transfer Protocol). HTTP is a request/response protocol, which means your computer sends a request for some file (ex, Get me the file 'home.html'), and the web server sends back a response ("Here's the file", followed by the file itself). HTTP 1.1 defines the following request methods:       

GET: Retrieves the resource identified by the request URL HEAD: Returns the headers identified by the request URL POST: Sends data of unlimited length to the Web server PUT: Stores a resource under the request URL DELETE: Removes the resource identified by the request URL OPTIONS: Returns the HTTP methods the server s TRACE: Returns the header fields sent with the TRACE request

The HttpServlet class provides specialized methods that handle the various types of HTTP requests. A servlet developer typically overrides one of these methods. These methods are doDelete(), doGet(), doHead(), doOptions(), doPost(), doPut(), and doTrace().

Http Get request and Http Post request Here we will develop a servlet that handles an HTTP GET request. The servlet is invoked when a form on a web page is submitted.

Example 3: HTTP Get request You would require writing three files   

GetRequestServlet.java: An HTTP servlet, which is a Java class that extends HttpServlet getRequest.html: A web page to invoke the servlet by sending a request. It sends a GET request web.xml : A deployment descriptor which will map the request from the web page to the servlet

And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Step 1: Create GetRequestServlet.java package com.aklc.servlet; import java.io.*; import javax.servlet.http.*; import javax.servlet.*; public class GetRequestServlet extends HttpServlet

{

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String un = req.getParameter("name"); String pwd = req.getParameter(""); resp.setContentType("text/html"); PrintWriter pw = resp.getWriter(); pw.println("

Welcome, "+un+" 2m5q6u

"); pw.println("

Your is .. "+pwd); pw.close(); } } Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Step 2: Create getRequest.html Handling HTTP Get Request 4o6r65

Enter your name:

Enter your :



Step 3: Create web.xml Add the below entry to web.xml <servlet> <servlet-name>GetReqServlet <servlet-class>com.aklc.servlet.GetRequestServlet <servlet-mapping> <servlet-name>GetReqServlet /getReq

Step 4: Run getRequest.html in the browser by entering the below URL http://localhost:8080/PractiseApp/getRequest.html

Upon clicking on "Click me" button, it takes you to the below screen.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Example 4: HTTP Post Request Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked when a form on a web page is submitted. You would require writing three files   

PostRequestServlet.java: An HTTP servlet, which is a Java class that extends HttpServlet postRequest.html: A web page to invoke the servlet by sending a request. It sends a POST request web.xml : A deployment descriptor which will map the request from the web page to the servlet

And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Step 1: Create PostRequestServlet.java package com.aklc.servlet; import java.io.*; import javax.servlet.http.*; import javax.servlet.*; public class PostRequestServlet extends HttpServlet

{

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String un = req.getParameter("name"); String pwd = req.getParameter(""); resp.setContentType("text/html"); PrintWriter pw = resp.getWriter(); pw.println("

Welcome, "+un+" 2m5q6u

"); pw.println("

Your is .. "+pwd); pw.close(); } } Step 2: Create postRequest.html Handling HTTP Post Request Mr. Ashok Kumar K | 9742024066 | [email protected] www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. 5p563

Enter your name:

Enter your :



Step 3: Create web.xml Add the below entry to web.xml <servlet> <servlet-name>PostReqServlet <servlet-class>com.aklc.servlet.PostRequestServlet <servlet-mapping> <servlet-name>PostReqServlet /postReq

Step 4: Run getRequest.html in the browser by entering the below URL http://localhost:8080/PractiseApp/postRequest.html

1 Upon clicking on "Click me" button, it takes you to the below screen.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Difference between HTTP Get and HTTP Post requests

HTTP Get Request

HTTP Post Request

Parameters for an HTTP GET request are included as part of the URL that is sent to the web server.

Parameters for an HTTP POST request are NOT included as part of the URL that is sent to the web server.

Example: http://localhost:8080/PractiseApp/getReq? name=Ashok&=lordshiva

Example: http://localhost:8080/PractiseApp/postReq

6.7 Cookies Concept Web applications are typically a series of HTTP requests and responses. As HTTP is a stateless protocol, information is not automatically saved between HTTP requests. Web applications use cookies to store state information on the client. Cookies can be used to store information about the , the 's shopping cart, and so on. Cookies are small bits of textual information that a Web server sends to a browser. By having the server read cookies it sent the client previously, the site can provide visitors with a number of conveniences like  Identifying a during e-commerce session  Avoiding name and entered again and again  Customizing a site based on 's browsing history  Focusing ment The Cookie class provides an easy way for servlet to read, create, and manipulate HTTP cookies on the web browser. A servlet uses the getCookies() method of HTTPServletRequest class to retrieve cookies as request. The addCookie() method of HTTPServletResponse class sends a new cookie to the browser. You can set the age of cookie by setMaxAge() method.

Example 1: Creating a Cookie Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Here we will develop a simple web application that creates a new Cookie variable by name 'RegID' in the browser. You would require writing these three files:  WriteCookie.java : An HTTP servlet, which is a Java class that extends HttpServlet  cookieWrite.html : A web page to invoke the servlet by sending a request.  web.xml : A deployment descriptor which will map the request from the web page to the servlet And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.

Step 1: Create WriteCookie.java package com.aklc.servlet; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class WriteCookieServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getParameter("id"); Cookie mycookie = new Cookie("RegID", id); resp.addCookie(mycookie); resp.setContentType("text/html"); PrintWriter pw = resp.getWriter();

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. pw.println("

Cookie has been successfully created .. 3a366

"); pw.close();

} }

Step 2: Create cookieWrite.html Creating a cookie ..

Enter your Reg ID:



Step 3: Update web.xml Add the below entry to web.xml <servlet> <servlet-name>WriteCookie <servlet-class>com.aklc.servlet.WriteCookieServlet <servlet-mapping> <servlet-name>WriteCookie /writeCookie

Step 4: Run getRequest.html in the browser by entering the below URL http://localhost:8080/PractiseApp/cookieWrite.html

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Example 2: Reading the previously created cookie Here we will develop a simple web application that creates a new Cookie variable by name 'RegID' in the browser. You would require writing these three files:  ReadCookieServlet.java : An HTTP servlet, which is a Java class that extends HttpServlet  cookieRead.html : A web page to invoke the servlet by sending a request.  web.xml : A deployment descriptor which will map the request from the web page to the servlet And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Step 1: Create ReadCookieServlet.java package com.aklc.servlet; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ReadCookieServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie[] cookies = req.getCookies(); String name=""; String value=""; for (int i=0;i
Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. resp.setContentType("text/html"); PrintWriter pw = resp.getWriter(); pw.println("

Welcome, Stored RegID is .. "+value+" 24t6o

"); pw.close();

} }

Step 2: Create cookieWrite.html Reading a cookie ..



Step 3: Update web.xml Add the below entry to web.xml <servlet> <servlet-name>readCookie <servlet-class>com.aklc.servlet.ReadCookieServlet <servlet-mapping> <servlet-name>readCookie /readCookie

Step 4: Run getRequest.html in the browser by entering the below URL http://localhost:8080/PractiseApp/cookieRead.html

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

6.8 Session Handling As mentioned earlier, HTTP is a "stateless" protocol which means each time when a client retrieves a web page, the client opens a separate connection to the web server and the server does not keep any record of previous client request. The question here is how can we maintain the session between the client and a server?

What happens if we don't maintain the session between the client and the server? To understand this, take an example of online shopping experience. When you are doing on-line shopping, if the session is not maintained then it makes our shopping application problematic. When you add an entry to your cart, how does the server know what's already in your cart? Even if servers did retain contextual information, you'd still have problems with e-commerce. When you move from the page where you specify what you want to buy (hosted on the regular web server) to the page that takes your credit card number and shipping address (hosted on the secure server that uses SSL), how does the server what you were buying?

There are some typical solutions to this problem. (Different ways of tracking activity in a web application) 

Cookies A web server can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie. Drawback: This may not be an effective way because many time browser does not a cookie.



Hidden fields A web server can send a hidden HTML form field along with a unique session ID as follows: This entry means that, when the form is submitted, the specified name and value are automatically included in the request. Each time when web browser sends request back, then session_id value can be used to keep the track of different web browsers. Drawback: Clicking on a regular (< a href='' > ) anchor link does not result in a form submission, so hidden form fields also cannot general session tracking.



URL Rewriting

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. For example, with http://jmaster.in/home.html;sessionid=12345, the session identifier is attached as sessionid=12345 which can be accessed at the web server to identify the client. Drawback: You would have generate every URL dynamically to assign a session ID though page is simple static HTML page



HttpSession Servlet provides HttpSession Interface which provides a way to identify a across more than one page request or visit to a Web site and to store information about that . The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the .

Example You would get HttpSession object by calling the public method getSession() of HttpServletRequest, as below: HttpSession session = request.getSession(); Here we will develop a simple web application that demonstrates the session handling. You would require writing these three files:  SessionTrackServlet.java : An HTTP servlet, which is a Java class that extends HttpServlet  sessionTrack.html.html : A web page to invoke the servlet by sending a request.  web.xml : A deployment descriptor which will map the request from the web page to the servlet And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Step 1: Create SessionTrackServlet.java package com.aklc.servlet; import import import import

java.io.*; javax.servlet.*; javax.servlet.http.*; java.util.*;

public class SessionTrackServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(true); Date createTime = new Date(session.getCreationTime()); Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "Welcome Back to my website"; int visitCount = 0; String ID="";

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. // Check if this is new comer on your web page. if (session.isNew()){ title = "Welcome to my website"; session.setAttribute("ID", "ABCD"); } else { visitCount = (Integer)session.getAttribute("visitCount"); visitCount = visitCount + 1; ID = (String)session.getAttribute("ID"); } session.setAttribute("visitCount", visitCount); resp.setContentType("text/html"); PrintWriter pw = resp.getWriter(); pw.println("

" + title + " 205r70

" + "

Session Infomation 2rs4w

" + " " + " " + " " + " " + " " + " " + " "+ " " + " " + " " + " "+ " " + " " + " " + " "+ " " + " " + " " + " "+ " " + " " + " " + " "+ " " + "
Session info value
id" + session.getId() + "
Creation Time" + createTime + "
Time of Last Access" + lastAccessTime + "
ID" + ID + "
Number of visits" + visitCount + "
" ); } }

Step 2: Create sessionTrack.html Session Handling DEMO

Visit my website

Step 3: Update web.xml Add the below entry to web.xml <servlet> <servlet-name>SessionTrack <servlet-class>com.aklc.servlet.SessionTrackServlet <servlet-mapping>

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. <servlet-name>SessionTrack /sessionTrack

Step 4: Run getRequest.html in the browser by entering the below URL http://localhost:8080/PractiseApp/sessionTrack.html

First time when you click on the link, you see the page shown below.

Refreshing it, meaning visiting it again, you see the below page

Mr. Ashok Kumar K | 9742024066 | [email protected]

VTU 7th sem B.E (CSE/ISE)

JAVA/ J2EE Notes prepared by

Mr. Ashok Kumar K 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Unit 7:

Java Server Pages, Remote Method Invocation

Mr. Ashok Kumar K 9742024066 | [email protected]

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

15 reasons to choose VTUPROJECTS.COM for your final year project work 1. Training from the scratch We train our students on all the languages and technologies required for developing the projects from the scratch. No prerequisites required. 2. Line by Line code explanation Students will be trained to such an extent where they can explain the entire project line by line code to their respective colleges. 3. Study Materials We provide the most efficient study material for each and every module during the project development 4. Trainers Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter expert in strengthening student's skillset for cracking any interviews. He will be having a thorough experience in working on both product and service driven industries. 5. Reports and PPTs Project report as per the university standards and the final presentation slides will be provided and each student will be trained on the same. 6. Video manuals Video manuals will be provided which will be useful in installing and configuring various softwares during project development 7. Strict SDLC Project development will be carried out as per the strict Software Development model 8. Technical Seminar topics We help students by providing current year's IEEE papers and topics of their wish for their final semester Technical seminars 9. Our Availability We will be available at our centers even after the class hours to help our students in case they have any doubts or concerns. 10. Weightage to your Resume Our students will be adding more weightage to their resumes since they will be well trained on various technologies which helps them crack any technical interviews 11. Skype/ Team viewer In case the student needs an emergency help when he/she is in their colleges, we will be helping out them through Skype/ Team viewer screen sharing 12. Practical Understanding Each and module in the project will be implemented and taught to the students giving practical real world applications and their use. 13. Mock demo and presentations Each student will have to prepare for mock demo and presentations every week so that he/she will be confident enough to demonstrate the project in their respective colleges 14. Communication & Soft skills Training We provide communication and soft skills training to each students to help improve their presentation and demonstration skills. 15. Weekly monitoring Each student will be monitored and evaluated on the status of the project work done which helps the students to obtain thorough understanding on how the entire project will be developed

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

JAVA SERVER PAGES 7.1 Basics Servlets are powerful and sometimes they are a bit cumbersome when it comes to generating complex HTML. Most servlets contain a little code that handles application logic and a lot more code that handles output formatting (presentation logic). This can make it difficult to separate and reuse portions of the code when a different output format is needed. For these reasons, web application developers turn towards JSP as their preferred servlet environment. Below is the snap shot of the servlet program that we have seen in previous chapter. Notice the application logic and presentation logic are coupled together which is not recommended. In later sections we see how JSP helps in separating the application logic from the presentation logic.

Defining a JSP A JSP page is a text based document containing static HTML and dynamic actions which describe how to process a response to the client in a more powerful and flexible manner. Most of a JSP file is a plain HTML but it also will be interspersed with special JSP tags. Java Server Pages (JSP) is a server side program that is similar in design and functionality to a java Servlet. A JSP is called by client to provide a web service, the nature of which depends on the J2EE Application.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Difference between JSP and Servlet Servlet is written using Java programming language and responses are encoded as an output string object that is ed to the println() method. The output string object is formatted in HTML, XML, or whatever format are required by the client

JSP is written in HTML, XML, or in the client’s format that is interspersed with the scripting elements, directives, and actions comprised of Java programming language and JSP syntax

Advantages of JSPs over Servlet      

Servlets use println statements for printing an HTML document which is usually very difficult to use. JSP has no such tedious task to maintain. JSP needs no compilation, CLASSPATH setting and packaging. In a JSP page visual content and logic are separated, which is not possible in a servlet. There is automatic deployment of a JSP; recompilation is done automatically when changes are made to JSP pages. Usually with JSP, Java Beans and custom tags web application is simplified Reduces Development time

7.2 JSP Architecture A JSP page is executed in a JSP container (or JSP engine), which is installed in a web server (or an application server). When a client requests for a JSP page the engine wraps up the request and delivers it to the JSP page along with a response object. The JSP page processes the request and modifies the response object to incorporate the communication with the client. The container or the engine, on getting the response, wraps up the responses from the JSP page and delivers it to the client. The underlying layer for a JSP is actually a servlet implementation. The abstraction of the request and response are the same as the ServletRequest and ServletResponse respectively. If the protocol used is HTTP, then the corresponding objects are HttpServletRequest and HttpServletResponse. The first time when the engine intercepts a request for a JSP, it compiles this translation unit (the JSP page and other dependent files) into a class file that implements the servlet protocol. If the dependent files are other JSPs they are compiled into their own classes. Since most JSP pages use HTTP, their implementation classes must actually implement the javax.servlet.jsp.HttpJspPage interface, which is a sub interface of javax.servlet.jsp.JspPage. The javax.servlet.jsp.JspPage interface contains two methods: public void jspInit() This method is invoked when the JSP is initialized and the page authors are free to provide initialization of the JSP by implementing this method in their JSPs. public void jspDestroy() This method is invoked when the JSP is about to be destroyed by the container. Similar to above, page authors can provide their own implementation.

The javax.servlet.jsp.HttpJspPage interface contains one method:

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. public void _jspService (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException This method generated by the JSP container, is invoked, every time a request comes to the JSP. The request is processed and the JSP generates appropriate response. This response is taken by the container and ed back to the client.

7.3 JSP Tags JSP tags define java code that is to be executed before the output of a JSP program is sent to the browser. There are five types of JSP tags: 1. Comment Tag 2.

Declaration statement Tag

3.

Directive Tag

4.

Expression Tag

5.

Scriptlet Tag

Comment Tag A comment tag opens with <%-- and closes with --%>, and is followed by a comment that usually describes the functionality of statements that follow the comment tag. Ex: <%-This is a JSP Comment --%>

Declaration Statement Tag A Declaration statement tag opens with <%! and is followed by a Java declaration statements that define variables, objects, and methods. Ex: <%! int a; String s; Employee e = new Employee(); %>

Directive Tag A Directive tag opens with <%@ and closes with %>. There are three commonly used directives.  Import Used to import java packages into JSP program Ex: <%@ page import = “java.sql.*” %> 

Include It inserts a specified file into the JSP program replacing the include tag Ex: <%@ include file = ”Keogh\book.html” %>

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. 

Taglib It specifies a file that contains a tag library Ex: <%@ taglib uri = “myTags.tld” %>

Expression Tag An expression tag opens with <%= and is used for an expression statement whose result replaces the expression tag. It closes with %> Ex: <%! int a = 5, b = 10; %> <%= a+b %>

Scriptlet Tag A scriptlet tag opens with <% and contains commonly used java control statements and loops. It closes with %>

7.4 Implicit Objects in JSP JSP Implicit Objects are the Java objects that the JSP Container makes available to developers in each page and developer can call them directly without being explicitly declared. JSP Implicit Objects are also called pre-defined variables. JSP s nine Implicit Objects which are listed below:

Object request

Description This is the HttpServletRequest object associated with the request. This is the HttpServletResponse object associated with the response to the client. This is the PrintWriter object used to send output to the client. This is the HttpSession object associated with the request. This is the ServletContext object associated with application context. This is the ServletConfig object associated with the page. This encapsulates use of server-specific features like higher performance JspWriters. This is simply a synonym for this, and is used to call the methods defined by the translated servlet class. The Exception object allows the exception data to be accessed by designated JSP.

response out session application config pageContext page Exception

7.5 Example JSP Programs 1. JSP to illustrate variables declarations and usage <%!

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. int a = 10; String s = "TEST"; %>

int value is <%= a %> String value is <%= s %>



2. JSP that defines a method and illustrates its usage. <%! int findSum(int a, int b) { return a+b; } %>

sum of 2 and 5 is <%=findSum(2,5) %>



3. JSP to illustrate control statements <%! int grade = 70; %> <% if (grade >= 70 ) {%> FCD <% } else if (grade<70 && grade>=60) { %> FC <% } else if (grade<60 && grade>=50) { %> SC <% } else if (grade<50 && grade>=35) { %> Just <% } else { %> FAIL <% } %>

4. JSP to illustrate looping statements <% for (int i=0;i<10;i++) { HELLO WORLD <% } %>

Mr. Ashok Kumar K | 9742024066 | [email protected]

%>

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

7.6 Request String The browser generates a request string whenever the submit button is selected. The request string consists of: 1. URL 2.

Query String

Example

Query String JSP program should parse the query string to extract the values of fields that are to be processed by a JSP. A JSP can parse the query string in two ways: a)

Using request.getParameter() getParameter() method requires an argument, which is the name of the field whose value you want to retrieve. Ex: <%! String uname = request.getParameter(“name”); String pword = request.getParameter(“”); %>

b)

Using request.getParameterValues() Multi valued fields (such as checkboxes and select menus) can be read using getParameterValues() method. It returns multiple values from the field specified as an argument to this method. Ex: <%! String[] games = request.getParameterValues(“favgames”); %>

Example Program Here we will develop a sample JSP to read the parameters from the client request. You would require writing these three files  param.html 

readParam.jsp

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. And, here is the structure of your dynamic web project created in Eclipse. Notice the placement of the above files in the project.

Step 1: Create param.html
Enter your name:

Select your favourite games :
<select name='games' multiple=multiple>



Step 2: Create readParam.jsp <% String name = request.getParameter("name"); String games[] = request.getParameterValues("games"); %> Welcome, <%= name %>

Your favourite games are :
<%

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. for (int i=0;i <%= games[i] %>
<% } %> Step 3: Run param.html by entering the direct URL in the browser.

URL A URL is divided into four parts: 

Protocol It defines the rules that are used to transfer the request string from the browser to JSP program. Three commonly used protocols are HTTP, HTTPS, and FTP



Host It is the internet protocol address (IP) or name of the server that contains the JSP program.



Port It is the port that the host monitors. If the port is not specified, it is defaulted to 80. Whenever HTTP is used, the host will be monitoring the port 80



Virtual path to JSP program The server maps this virtual path to the physical path

Example for URL:

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

7.7 Sessions in JSP As mentioned earlier, HTTP is a "stateless" protocol which means each time when a client retrieves a web page, the client opens a separate connection to the web server and the server does not keep any record of previous client request. The question here is how can we maintain the session between the client and a server? As explained in the previous chapter, there are four possible ways to maintain the session between client and a server  Cookies 

Hidden fields



URL Rewriting



HttpSession interface (session object)

7.7.1 Hidden Fields A hidden field is a field in HTML form whose value isn’t displayed on the HTML page. You can assign a value to the hidden field in a JSP program before the program sends the HTML page to the browser. Consider a screen which asks for name and . Here is how the session is tracked using hidden field: 

Upon submitting the form, the browser sends the name and to the JSP program.



The JSP program then validates the name and and generates another dynamic HTML page. This newly generated HTML page has a form that contains hidden field which is assigned a ID along with other fields as well.



When the submits the form in the new HTML page, the ID stored in the hidden field and other information on the form are sent to the JSP program.



This cycle continues where the JSP program processing the request string receives the ID as a parameter and then es the ID to the next dynamically built HTML page as a hidden field. In this way, each HTML page and subsequent JSP program has access to ID and therefore can track the session.

7.7.2 Cookies A cookie is a small piece of information created by a JSP program that is stored in the client’s hard disk by the browser. Cookies are used to store various kind of information such as name, , and preferences, etc. Sample JSP program to create a Cookie <%! String cName = "ID"; String cValue = "1VK06IS009"; Cookie myCookie = new Cookie (cName, cValue);

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. %> <% response.addCookie(myCookie); %> Sample JSP program to read the Cookie <%! String cName = "ID"; String name; String value; int found = 0; %> <%

<%

Cookie[] myCookies = request.getCookies(); for (int i=0;i<myCookies.length;i++) { name = myCookies[i].getName(); if (name.equals(cName)) { value = myCookies[i].getValue(); found = 1; } } if (found==1) { %>

Cookie Name: <%= cName %>

Cookie Value: <%= value %>

} else { %>

Cookie NOT FOUND



<%>} %>

7.7.3 session object A JSP database system is able to share information among JSP programs within a session by using a session object. Each time a session is created, a unique ID is assigned to the session and stored as a cookie. The unique ID enables JSP programs to track multiple sessions simultaneously while maintaining data integrity of each session. In addition to session ID, a session object is also used to store other types of information called attributes. Sample JSP program to create a session attribute <%! String attName = "ID"; String attValue = "1VK06IS009"; %> <% session.setAttribute(attName, attValue); %>

Sample JSP program to read session attribute

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. <%! Enumeration<String> e; %> <% e = session.getAttributeNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); String value = (String) session.getAttribute(name); %>

Attribute name : <%= name %>

Attribute value : <%= value %>

<% } %>

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

REMOTE METHOD INVOCATION 7.8 Basics Definition and concepts A Java object runs within a JVM. Likewise, a J2EE application runs within JVM; however, objects used by a J2EE application do not need to run on the same JVM as the J2EE application. This is because a J2EE application and its components can invoke objects located on different JVM by using Java RMI system. RMI is used for remote communication between Java applications and components, both of which must be written in Java Programming language. RMI is used to connect together a client and a server.  A client is an application or component that requires the services of an object to fulfill a request. 

A server creates an object and makes the object available to the clients

RMI handles transmission of requests and provides the facility to load the object’s bytecode, which is referred to as dynamic code loading Following fig visualizes the RMI process

When client references a remote object, the RMI es a remote stub for the remote object. The remote stub is the local proxy for the remote object. The client calls the method on the local stub whenever the client wants to invoke one of the remote object’s methods.

7.9 The RMI Process There are three steps necessary to make an object available to remote clients 1. Design an object

2. Compile the object Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. 3. Make the object accessible to remote clients over the network

Deg an object Besides defining the business logic of an object, the developer must define a remote interface for the object, which identifies methods that are available to remote clients. In addition to methods that can be invoked by remote clients, the developer must also define other methods that the processing of client invoked methods. There are referred as server methods, while methods invoked by a client are called client methods.

Compile the object Compilation of the object is a two-step process  Compile the object using the javac compiler This will create the byte codes for the objects. 

Compile the object using rmic compiler This will create a stub for the object

Make the object available to remote client It is done by loading the object into a server. Make sure the RMI remote object registry is running. If not, type the following at the command line: C:\> start rmiregistry

7.10 Server Side Server side of RMI consists of a remote interfaces and methods. Remote interfaces provide the API for clients to access the methods. Methods provide the business logic that fulfills a client’s request whenever the client remotely invokes them.

Example for Remote interface is shown below: HelloInterface.java import java.rmi.*; public interface HelloInterface extends Remote { public String say() throws RemoteException; }

Remote Object that implements the remote interface is shown below: Hello.java import java.rmi.*; import java.rmi.server.*; public class Hello extends UnicastRemoteObject implements HelloInterface { public String say() throws RemoteException { System.out.println(“Hello World”); } }

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Below program in the server side makes the Remote object available to the clients by binding it to the naming registry. HelloServer.java import java.rmi.Naming; public class HelloServer { public static void main (String[] argv) { if (System.getSecurityManager() == null) System.setSecurityManager(new RMISecurityManager()); try { Naming.rebind("MyObj", new Hello ()); System.out.println ("Server is connected"); } catch (Exception e) { System.out.println ("Server not connected: " + e); } } } Clients can access the remote object by looking up the naming registry for the appropriate entry.

7.11 Client Side Below example shows how a client can lookup the naming registry to get an instance of the remote object. It also illustrates how a client can use the remote object to call its methods. HelloClient.java import java.rmi.Naming; public class HelloClient { public static void main(String[] argv) { if (System.getSecurityManager() == null) System.setSecurityManager(new RMISecurityManager()); try { HelloInterface hello = (HelloInterface) Naming .lookup("//192.168.10.201/MyObj"); System.out.println(hello.say()); } catch (Exception e) { System.out.println("HelloClient exception: " + e); } } }

Mr. Ashok Kumar K | 9742024066 | [email protected]

VTU 7th sem B.E (CSE/ISE)

JAVA/ J2EE Notes prepared by

Mr. Ashok Kumar K 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

Unit 8:

Enterprise Java Beans (EJB)

Mr. Ashok Kumar K 9742024066 | [email protected]

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. 15 reasons to choose VTUPROJECTS.COM for your final year project work 1. Training from the scratch We train our students on all the languages and technologies required for developing the projects from the scratch. No prerequisites required. 2. Line by Line code explanation Students will be trained to such an extent where they can explain the entire project line by line code to their respective colleges. 3. Study Materials We provide the most efficient study material for each and every module during the project development 4. Trainers Each faculty in AKLC will be having 6+ years of corporate Industry experience and will be a subject matter expert in strengthening student's skillset for cracking any interviews. He will be having a thorough experience in working on both product and service driven industries. 5. Reports and PPTs Project report as per the university standards and the final presentation slides will be provided and each student will be trained on the same. 6. Video manuals Video manuals will be provided which will be useful in installing and configuring various softwares during project development 7. Strict SDLC Project development will be carried out as per the strict Software Development model 8. Technical Seminar topics We help students by providing current year's IEEE papers and topics of their wish for their final semester Technical seminars 9. Our Availability We will be available at our centers even after the class hours to help our students in case they have any doubts or concerns. 10. Weightage to your Resume Our students will be adding more weightage to their resumes since they will be well trained on various technologies which helps them crack any technical interviews 11. Skype/ Team viewer In case the student needs an emergency help when he/she is in their colleges, we will be helping out them through Skype/ Team viewer screen sharing 12. Practical Understanding Each and module in the project will be implemented and taught to the students giving practical real world applications and their use. 13. Mock demo and presentations Each student will have to prepare for mock demo and presentations every week so that he/she will be confident enough to demonstrate the project in their respective colleges 14. Communication & Soft skills Training We provide communication and soft skills training to each students to help improve their presentation and demonstration skills. 15. Weekly monitoring Each student will be monitored and evaluated on the status of the project work done which helps the students to obtain thorough understanding on how the entire project will be developed

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

8.1 Enterprise Java Beans Concept and Definition An Enterprise Java Bean (EJB) is a component of the J2EE architecture that primarily provides business logic to a J2EE application and interacts with other server side J2EE components. The nature of business logic and the interaction with the other server side J2EE components are dependent on the J2EE application. EJB provides an architecture to develop and deploy component based enterprise applications considering robustness, high scalability and high performance. An EJB application can be deployed on any of the application server compliant with J2EE 1.3 standard specification..

Advantages of EJB  



Simplifies the development of large scale enterprise level application. Application Server/ EJB container provides most of the system level services like transaction handling, logging, load balancing, persistence mechanism, exception handling and so on. Developer has to focus only on business logic of the application. EJB container manages life cycle of EJB instances thus developer needs not to worry about when to create/delete EJB objects.

Types of EJBs Session Bean Session bean contains business logic used to provide a service to a client and exists for the duration of the client server session. A session bean terminates once the session with their client server terminates. Entity Bean Entity beans represent persistent data storage. data can be saved to database via entity beans and later on can be retrieved from the database in the entity bean. Message Driven Bean Message driven bean is designed for clients to invoke server side business logic using asynchronous communication, which is a special case of a stateless session bean. It is used to receive message from a JMS resource (Queue or Topic)

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest.

EJB Architecture

EJB container is a vendor provided entity located on the EJB server that manages system level services for EJB. EJB container is one of the several containers, each of which handles a J2EE component such as JSP or servlets. A client’s request for web services is made to a web server, which forwards the client’s request to the appropriate server. Typically either the JSP or Servlet receives the client request and uses JNDI to look up the EJB resource. The EJB object is returned and is used to get the EJB’s home or local class. The home class is used to reference the bean class through the EJB’s remote class. The session and entity beans must have two interfaces  Home interface or local interface The local clients that are on the same JVM as the EJB interact with the EJB using the home interface.  Remote interface Remote interface is used by remote clients that are capable of accessing the EJB container from an application that is compliant with RMI and IIOP.

8.2 Deployment Descriptors Concept and Definition Deployment descriptor describes how EJBs are managed at runtime and enables the customization of EJB behavior without modification to the EJB code such as describing runtime attributes of transactional context. The behavior of an EJB can be modified within the deployment descriptor without having to modify the EJB class or the EJB interface. Format of the deployment descriptor A deployment descriptor is written in a file using XML syntax. Many times an IDE (Integrated Development Environment) like Eclipse will automatically generates the deployment descriptor. The deployment descriptor file is packaged in the Java

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Archive (JAR) file along with other files that are required to deploy EJB. An EJB container references the deployment descriptor file to understand how to deploy and manage EJBs contained in the package.

Deployment descriptor for EJB 1.1 <ejb-jar> <enterprise-beans> <entity> <ejb-name>myEJB com.aklc.ejb.MyEJBHome com.aklc.ejb.MyEJBRemote <ejb-class>com.aklc.ejb.MyEJB Container <prim-key-class>java.lang.String False

Deployment descriptor for EJB 2.0 <ejb-jar> <enterprise-beans> <entity> <ejb-name>myEJB com.aklc.ejb.MyEJBHome com.aklc.ejb.MyEJBRemote com.aklc.ejb.MyEJBHomeLocal com.aklc.ejb.MyEJBLocal <ejb-class>com.aklc.ejb.MyEJB Container <prim-key-class>java.lang.String False

Description of the elements used Element <enterprise-bean> <entity> <session> <message-driven>

Description Defines the URL for the DTD and the organization that defines the DTD Describes one or more EJB contained within a JAR file Describes the type of EJB as entity bean Describes the type of EJB as session bean Describes the type of EJB as message driven bean

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. <ejb-name> <ejb-class> <prim-key-class>

Describes the name of session or entity bean Describes the fully qualified class name of the session or entity bean remote home interface Describes the fully qualified class name of the session or entity bean remote interface Describe the fully qualified class name of the session or entity bean class Specifies either container managed persistence or bean managed persistence Describes the primary key class for entity beans Specifies that back (reentrant invocations) is allowed or not Describes the fully qualified class name of the session or entity bean local home interface Describes the fully qualified class name of the session or entity bean local interface

Customizing the EJB behavior by defining the environment variables The <env-entry> element is used in the deployment descriptor to define values that an EJB can use to customize the EJB’s behavior Defining the environment variable <env-entry> <env-entry-name>ingGrade <env-entry-type>java.lang.Integer <env-entry-value>35 Accessing the environment variable InitialContext jc = new InitialContext(); Integer grade = (Integer) jc.lookup("java:comp/env/ingGrade");

Security elements Defining the <security-role> element <security-role-ref> <description>myEJB security role Supervisor ing the role name from within EJB boolean supervisor = context.isCallerInRole("Supervisor"); if (!supervisor) { throw new AccessDeniedException(); }

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Transaction elements A transaction is a single unit of work items which follows the ACID properties. ACID stands for Atomic, Consistent, Isolated and Durable.  Atomic: If any of work items fails, the complete unit is considered failed. Success meant all items executes successfully.  Consistent: A transaction must keep the system in consistent state.  Isolated: Each transaction executes independent of any other transaction.  Durable: Transaction should survive system failure if it has been executed or committed. EJB Container/Servers are transaction servers and handles transactions context propagation and distributed transactions. Transactions can be managed by the container or by custom code handling in bean's code.  Container Managed Transactions: In this type, container manages the transaction states.  Bean Managed Transactions: In this type, developer manages the life cycle of transaction states.

EJB Transaction Attributes An EJB server will manage a transaction based on the EJB’s transaction attribute when the EJB is deployed. This is referred to as container managed. A transaction attribute can apply at the EJB level or at the method level. An EJB’s transaction attribute is defined in the deployment descriptor by asg one of the following values to the transaction attribute: 

    

REQUIRED Indicates that business method has to be executed within transaction otherwise a new transaction will be started for that method. REQUIRES_NEW Indicates that a new transaction is to be started for the business method. S: Indicates that business method will execute as part of transaction. NOT_ED: Indicates that business method should not be executed as part of transaction. MANDATORY: Indicates that business method will execute as part of transaction otherwise exception will be thrown. NEVER: Indicates if business method executes as part of transaction then an exception will be thrown.

8.3 Session Java Bean Concept and Definition A session bean contains business logic used to provide a service to a client and exists for the duration of the client server session. A session bean terminates once the session with the client server terminates. A session bean is not persistent. (That is, its data is not saved to a database)

Types of Session Beans Session beans are of three types: stateful and stateless. Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. 

Stateful Session Beans A stateful session bean retains the state (data) between the method calls with a client during a session. Because the client interacts (“talks”) with its bean, this state is often called the conversational state. As its name suggests, a session bean is similar to an interactive session. A session bean is not shared; it can have only one client, in the same way that an interactive session can have only one . When the client terminates, its session bean appears to terminate and is no longer associated with the client. The state is retained for the duration of the client/bean session. If the client removes the bean, the session ends and the state disappear. This transient nature of the state is not a problem, however, because when the conversation between the client and the bean ends, there is no need to retain the state.



Stateless Session Beans A stateless session bean does not retain the state between method calls and typically performs business logic that doesn’t require data to be maintained during the session. When a client invokes the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client but only for the duration of the invocation. When the method is finished, the client-specific state should not be retained. Clients may, however, change the state of instance variables in pooled stateless beans, and this state is held over to the next invocation of the pooled stateless bean. Except during method invocation, all instances of a stateless bean are equivalent, allowing the EJB container to assign an instance to any client. That is, the state of a stateless session bean should apply across all clients. Because they can multiple clients, stateless session beans can offer better scalability for applications that require large numbers of clients. Typically, an application requires fewer stateless session beans than stateful session beans to the same number of clients. A stateless session bean can implement a web service, but a stateful session bean cannot. Stateful session bean

Stateless session bean

Retains state between the method calls

Does not retain state between the method calls Can be shared between clients Its life time is controlled by the container

Cannot be shared between clients Its life time is controlled by clients

A code skeleton of a session bean import import import import

javax.ejb.SessionBean; javax.ejb.SessionContext; javax.ejb.EJBException; java.rmi.RemoteException;

public class CalculatorBean implements SessionBean {

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. public int add(int a, int b) throws RemoteException { return a + b; } public void setSessionContext(SessionContext sessionContext) throws EJBException, RemoteException { } public void ejbCreate() throws EJBException, RemoteException { } public void ejbRemove() throws EJBException, RemoteException { } public void ejbActivate() throws EJBException, RemoteException { } public void ejbivate() throws EJBException, RemoteException { } }

8.4 Entity Java Bean Concept and Definition Entity bean is used to manage a collection of data retrieved from a database and stored in memory. An entity bean inserts, updates, and removes data while maintaining the integrity of the data. Data collected and managed by an entity bean is referred to as persistent data and is managed in one of the two ways  Container managed persistence  Bean managed persistence

Container managed persistence (CMP) A container managed persistence (CMP) bean requires the container to manage the persistence. A CMP entity is heavily dependent on from the EJB container. The EJB container synchronizes the state of the entity bean with the database. However, EJB container varies by vendor. Most vendors automatic persistence between the entity bean and a relational database. Skeleton of an entity bean class myEJB implements EntityBean { int iD; private Product myProduct; public void ejbPostCreate() { } public Product getProduct() { return myProduct; } public void setProduct(Product prod) { myProduct = prod;

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. } public void setEntityContext(EntityContext cntx) { } public void unsetEntityContext() { } public void ejbLoad() { } public void ejbStore() { } public void ejbActivate() { } public void ejbivate() { } public void ejbRemove() { } } The product object definition import java.io.Serializable; class Product implements Serializable { public String prodName, prodDescription; public Product(String name, String desc) { prodName = name; prodDescription = desc; } } Home interface public interface myEJBHome extends EJBHome { public myEJB create(Integer prodID) throws RemoteException, CreateException; public myEJB findByPrimaryKey(Integer prodID) throws RemoteException, FinderException; } Remote Interface public interface myEJBRemote extends EJBObject { public getProduct() throws RemoteException; public setProduct(Product prod) throws RemoteException; }

Accessing the CMP bean

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. Calling the CMP using the home interface javax.naming.Context jndiContext = new InitialContext(); Object obj = jndiContext.lookup("java:comp/env/ejb/myEJBHome"); myEJB mybean = obj.create(4321); Calling the CMP using the remote interface javax.naming.Context jndiContext = new InitialContext(); Object obj = jndiContext.lookup("java:comp/env/ejb/myEJBHome"); Product prod = obj.getProduct();

Bean managed persistence (BMP) A bean managed persistence (CMP) bean requires a bean to manage the persistence. A BMP bean uses the JDBC API or another appropriate database API to interface with the database. However, these interactions take place under the direction of the EJB container. That is, the EJB container tells the BMP bean when to insert a new record, retrieve data, modify data, or delete data. A skeleton of a BMP bean class myBMPEJB implements EntityBean { public void ejbLoad() { // Read data from a database } public void ejbStore() { // Save data to a database } public void ejbCreate() { // Insert a record into the database } public void ejbRemote() { // Remove a record from a database } public Product findProduct() { // Find the specified product } }

8.5 Message Driven Bean Concept and Definition A message driven bean is designed for clients to invoke server side business logic using asynchronous communication, which is a special case of a stateless session bean.

Mr. Ashok Kumar K | 9742024066 | [email protected]

www.vtuprojects.com | Final year IEEE project development and training from scratch by Mr. Ashok Kumar K. Registration started. 9742013378 or 9742024066 and lock your project at the earliest. There isn’t any home interface or remote interface for a MDB. Instead, a MDB monitors Java Message Service (JMS) communications and reacts to messages sent by clients. Client don’t directly access a MDB. Instead, the MDB intercedes and processes requests anonymously. This is possible because a MDB is stateless.

Skeleton of a MDB class myMDB implements MessageListener, MessageDrivenBean { public void setMessageDrivenContext(MessageDrivenContext mdc) { } public void ejbCreate() { } public void ejbRemove() { } public void onMessage(Message clientMessage) { } } The onMessage() method is where the MDB processes messages received indirectly from a client.

8.6 The JAR file Concept EJB classes and related files are packaged together into a Java Archive (JAR) file for deployment. The JAR file is a compressed file format that was originally designed to reduce the size of software so it could be easily be transported. The JAR file used to package an EJB must contain the following; however it is customary to keep the dependent classes and interfaces in different JAR files.  EJB classes  Dependent classes  Remote interface  Home interface  Dependent interface  Primary key class  Deployment descriptor You can use the JAR utility by entering jar cf followed by name of the JAR file, and then followed by the path and names of files that will be archived.

Mr. Ashok Kumar K | 9742024066 | [email protected]

Related Documents c2h70

Java 7th Sem Ashokkumar 44h64
December 2019 36
Rgpv 7th Sem Scheme Cse. 4i6r
December 2019 41
3rd Sem Java Lab Programs 3i1p19
January 2022 0
63959584 7th Sem Power Electronics Lab Manual 4dg4b
November 2019 61
Java In A Nutshell, 7th Edition.pdf e5j5r
October 2022 0
Anna University Eee 3rd Sem,5th Sem,7th Sem Syllabus - Www.annaunivedu.info 8412h
October 2021 0

More Documents from "Harshith Rai" 164p3j

Java 7th Sem Ashokkumar 44h64
December 2019 36
Lathe Machine 6l5h5j
July 2022 0
Pedoman Red Code 3jt2y
August 2020 0
Isu Dan Tren Puskesmas Idaman 6g713e
October 2020 0
Ib Math Hl Ia Criteria 2c4m19
December 2021 0
Scholastic Average Sheet 4z5w46
December 2019 48