· 9 years ago · Dec 26, 2016, 04:08 PM
1Dr. AMBEDKAR INSTITUTE OF TECHNOLOGY
2(An Autonomous Institution, Affiliated to V.T.U, Belgaum)
3BANGALORE-560 056
4JAVA & J2EE
5LAB
6MANUAL
7Faraz Mohamed Rafi
8Department of Computer Science & Engineering
9TABLE OF CONTENTS
10Sl.
11No.
12Content Page
13No.
14JAVA 1-2
151a) Design and implement a JAVA Program to demonstrate Constructor Overloading
16and Method overloading.
173-4
181b) Write a JAVA program to implement Inner class and demonstrate its Access
19protections.
205
212a) Write a JAVA program to demonstrate reusability using Inheritance.
226
232b) Write a JAVA program to handle run-time errors using Exception Handling
24(Using Nested try catch and finally) mechanism.
257
263a) Write a JAVA program to create five threads with different priorities. Send two
27threads of the highest priority to sleep state. Check the aliveness of the threads and
28mark which is long lasting.
298-10
303b) Write a Java program using synchronized threads which demonstrate producerconsumer
31concepts.
3211-12
334a) Create an interface and implement it in a class in JAVA.
3413
354b) Write a program to make a package balance in which has account class with
36display_balance method in it. Import Balance package in another program to
37access display_Balance method of Account class.
3814-15
39JAVA APPLET 16-17
40EVENT HANDLING 18-19
415a) Write JAVA Applet program which handles Mouse Event.
4220-21
435b) Write JAVA Applet program to Pass parameters and display the same.
4422-23
45JAVA SWING 24-25
466. Write a Swing application which uses
47a) JTabbed Pane
48b) Each tab should Jpanel which include any one component given below in each
49JPanel
50c) ComboBox/List/Tree/RadioButton
5126-27
52SOCKET PROGRAMMING 28-29
537. Design and implement Client Server communication using socket programming
54(Client requests a file, Server responds to client with contents of that file which is
55then display on the screen by Client).
5630-32
57REMOTE METHOD INVOCATION (RMI) 33
588. Design and implement a simple Client Server Application using RMI. 34-35
59Servlet Programming Theory 36
60Running Servlet Programs in Eclipse EE 37-42
619. Implement a JAVA Servlet Program to implement a dynamic HTML using Servlet
62(user name and password should be accepted using HTML and displayed using a
63Servlet).
6443-44
6510. Design a JAVA Servlet Program to Download a file and display it on the screen
66(A link has to be provided in HTML, when the link is clicked corresponding file
67has to be displayed on Screen).
6845-47
6911a) Design a JAVA Servlet Program to implement RequestDispatcher object using
70include() and forward() methods.
7148-50
7211b) Implement a JAVA Servlet Program to implement sessions using HTTP Session
73Interface.
7451
75JavaServer Pages (JSP) 52-53
7612. Design a JAVA JSP Program to implement verification of a particular user login
77and display a welcome page.
7854-55
79JSP - JavaBeans 56
8013. Design and implement a JAVA JSP Program to get student information through a
81HTML and create a JAVA Bean Class, populate Bean and display the same
82information through another JSP.
8357-59
84Java & J2EE Lab
85Dept. of C.S.E, Dr.A.I.T Page 1
86JAVA
87Introduction
88Java programming language was originally developed by Sun Microsystems which was initiated by James
89Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]).
90Java is guaranteed to be Write Once, Run Anywhere.
91Java is:
92â€¢ï€ Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on
93the Object model.
94â€¢ï€ Platform independent: Unlike many other programming languages including C and C++, when Java
95is compiled, it is not compiled into platform specific machine, rather into platform independent
96byte code. This byte code is distributed over the web and interpreted by virtual Machine (JVM) on
97whichever platform it is being run.
98â€¢ï€ Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java would
99be easy to master.
100â€¢ï€ Secure: With Java's secure feature it enables to develop virus-free, tamper-free systems.
101Authentication techniques are based on public-key encryption.
102â€¢ï€ Architectural-neutral: Java compiler generates an architecture-neutral object file format which
103makes the compiled code to be executable on many processors, with the presence of Java runtime
104system.
105â€¢ï€ Portable: Being architectural-neutral and having no implementation dependent aspects of the
106specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability
107boundary which is a POSIX subset.
108â€¢ï€ Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile
109time error checking and runtime checking.
110â€¢ï€ Multithreaded: With Java's multithreaded feature it is possible to write programs that can do many
111tasks simultaneously. This design feature allows developers to construct smoothly running
112interactive applications.
113â€¢ï€ Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored
114anywhere. The development process is more rapid and analytical since the linking is an incremental
115and light weight process.
116â€¢ï€ High Performance: With the use of Just-In-Time compilers, Java enables high performance.
117â€¢ï€ Distributed: Java is designed for the distributed environment of the internet.
118â€¢ï€ Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an
119evolving environment. Java programs can carry extensive amount of run-time information that can
120be used to verify and resolve accesses to objects on run-time.
121Java & J2EE Lab
122Dept. of C.S.E, Dr.A.I.T Page 2
123Creating a simple Java Program
124Hello World example:
125class HelloWorld {
126public static void main (String args[]) {
127System.out.println("Hello World! ");
128}
129}
130This program has two main parts:
131â€¢ï€ All the program is enclosed in a class definition—here, a class called Hello World.
132â€¢ï€ The body of the program (here, just the one line) is contained in a method (function) called
133main(). In Java applications, as in a C or C++ program, main() is the first method (function)
134that is run when the program is executed.
135Compiling the above program :
136â€¢ï€ In Sun's JDK, the Java compiler is called javac.
137javac HelloWorld.java
138â€¢ï€ When the program compiles without errors, a file called HelloWorld.class is created, in the same
139directory as the source file. This is the Java bytecode file.
140â€¢ï€ Then run that bytecode file using the Java interpreter. In the JDK, the Java interpreter is called
141simply java.
142java HelloWorld
143If the program was typed and compiled correctly, the output will be:
144"Hello World!"
145Java & J2EE Lab
146Dept. of C.S.E, Dr.A.I.T Page 3
1471a) Design and implement a JAVA Program to demonstrate Constructor Overloading and Method
148overloading.
149import java.util.*;
150class arithmetic
151{
152int a,b;
153Scanner s1=new Scanner(System.in);
154arithmetic()
155{
156System.out.println("Enter any 2 Integers");
157a=s1.nextInt();
158b=s1.nextInt();
159}
160void display()
161{
162System.out.println("Addition = "+(a+b));
163System.out.println("Subtraction = "+(a-b));
164System.out.println("Multiplication = "+(a*b));
165System.out.println("Division = "+(a/b));
166}
167arithmetic(float a1, float b1)
168{
169System.out.println("Addition = "+(a1+b1));
170System.out.println("Subtraction = "+(a1-b1));
171System.out.println("Multiplication = "+(a1*b1));
172System.out.println("Division = "+(a1/b1));
173}
174void display(int x)
175{
176System.out.println("Square of "+x+" is "+(x*x));
177}
178}
179class Main
180{
181public static void main(String args[])
182{
183Scanner s1=new Scanner(System.in);
184System.out.println("ARITHMETIC OPERATIONS ON INTEGER");
185arithmetic a=new arithmetic();
186a.display();
187System.out.println("\nARITHMETIC OPERATIONS ON FLOAT");
188System.out.println("Enter any 2 Float Numbers");
189float a1=s1.nextFloat();
190float a2=s1.nextFloat();
191arithmetic arth1=new arithmetic(a1,a2);
192System.out.println("\nEnter Number to Find Square");
193int x=s1.nextInt();
194a.display(x);
195}
196}
197Java & J2EE Lab
198Dept. of C.S.E, Dr.A.I.T Page 4
199Output
200Java & J2EE Lab
201Dept. of C.S.E, Dr.A.I.T Page 5
2021b) Write a JAVA program to implement Inner class and demonstrate its Access protections.
203class outer
204{
205private int x=10;
206protected int z=30;
207class inner
208{
209private int x=20;
210protected int z=85;
211}
212public static void main(String args[])
213{
214outer obj1=new outer();
215inner obj2=new outer().new inner();
216System.out.println("Through Outer Class, x = "+obj1.x);
217System.out.println("Through Inner Class, x = "+obj2.x);
218}
219}
220class Main1b
221{
222public static void main(String args[])
223{
224outer ob1=new outer();
225outer.inner ob2=new outer().new inner();
226System.out.println("Through Different Class, Outer's protected z =
227"+ob1.z);
228System.out.println("Through Different Class, Inner's protected z =
229"+ob2.z);
230}
231}
232Output
233Java & J2EE Lab
234Dept. of C.S.E, Dr.A.I.T Page 6
2352a) Write a JAVA program to demonstrate reusability using Inheritance.
236class A
237{
238int x,y;
239void showxy()
240{
241System.out.println("x ="+ x + "\ny =" + y );
242}
243}
244class B extends A {
245int z;
246void showz() {
247System.out.println("z ="+z);
248System.out.println("x+y+z =" + (x + y + z));
249}
250}
251class inheridemo
252{
253public static void main(String a[])
254{
255A baseob=new A();
256B derob=new B();
257baseob.x=10;
258baseob.y=20;
259System.out.println("Contents of base class object :");
260baseob.showxy();
261derob.x=3;
262derob.y= 4;
263derob.z=5;
264System.out.println("Contents of derived class object :");
265derob.showxy();
266derob.showz();
267}
268}
269Output
270Java & J2EE Lab
271Dept. of C.S.E, Dr.A.I.T Page 7
2722b) Write a JAVA program to handle run-time errors using Exception Handling (Using Nested try catch
273and finally) mechanism.
274class FinallyDemo {
275//throw an exception out of the method
276static void procA() {
277try {
278System.out.println("inside procA");
279throw new RuntimeException("demo");
280} finally {
281System.out.println("Proc A's finally");
282}
283}
284// return from within a try block
285static void procB() {
286try {
287System.out.println("inside procB");
288return;
289} finally {
290System.out.println("procB's finally");
291}
292}
293//execute a try block normally
294static void procC() {
295try {
296System.out.println("Inside procC");
297} finally {
298System.out.println("procC's finally");
299}
300}
301public static void main(String args[]) {
302try {
303procA();
304} catch (Exception e) {
305System.out.println("Exception caught");
306}
307procB();
308procC();
309}
310}
311Output
312Java & J2EE Lab
313Dept. of C.S.E, Dr.A.I.T Page 8
3143a) Write a JAVA program to create five threads with different priorities. Send two threads of the
315highest priority to sleep state. Check the aliveness of the threads and mark which is long lasting.
316ThreadClass.java
317class ThreadClass implements Runnable
318{
319long click=0;
320Thread t;
321private volatile boolean running =true;
322public ThreadClass(int p)
323{
324t=new Thread(this);
325t.setPriority(p);
326}
327public void run()
328{
329while(running)
330{
331click++;
332}
333}
334public void stop()
335{
336running =false;
337}
338public void start()
339{
340t.start();
341}
342}
343Java & J2EE Lab
344Dept. of C.S.E, Dr.A.I.T Page 9
345Demo.java
346public class Demo {
347public static void main(String args[])
348{
349Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
350ThreadClass hi1=new ThreadClass(Thread.NORM_PRIORITY + 2);
351ThreadClass hi2=new ThreadClass(Thread.NORM_PRIORITY -2);
352ThreadClass hi3=new ThreadClass(Thread.NORM_PRIORITY + 3);
353ThreadClass hi4=new ThreadClass(Thread.NORM_PRIORITY - 3);
354ThreadClass hi5=new ThreadClass(Thread.NORM_PRIORITY +4);
355hi1.start();
356hi2.start();
357hi3.start();
358hi4.start();
359hi5.start();
360System.out.println("thread one is alive:" +hi1.t.isAlive());
361System.out.println("thread two is alive:" +hi2.t.isAlive());
362System.out.println("thread three is alive:" +hi3.t.isAlive());
363System.out.println("thread four is alive:" +hi4.t.isAlive());
364System.out.println("thread four is alive:" +hi5.t.isAlive());
365try
366{ hi5.t.sleep(1000);
367hi3.t.sleep(1000);
368}
369catch(InterruptedException e){
370System.out.println("main thread interrupted");
371}
372hi1.stop();
373hi2.stop();
374hi3.stop();
375hi4.stop();
376hi5.stop();
377try
378{
379System.out.println("waiting for threads to finish");
380hi1.t.join();
381hi2.t.join();
382hi3.t.join();
383hi4.t.join();
384hi5.t.join();
385}
386catch(InterruptedException e)
387{
388System.out.println("main thread interrupted");
389}
390System.out.println("priority of thread1:" +hi1.t.getPriority());
391System.out.println("priority of thread2:" +hi2.t.getPriority());
392System.out.println("priority of thread3:" +hi3.t.getPriority());
393System.out.println("priority of thread4:" +hi4.t.getPriority());
394System.out.println("priority of thread5:" +hi5.t.getPriority());
395System.out.println("thread one is alive:" +hi1.t.isAlive());
396System.out.println("thread two is alive:" +hi2.t.isAlive());
397System.out.println("thread three is alive:" +hi3.t.isAlive());
398System.out.println("thread four is alive:" +hi4.t.isAlive());
399System.out.println("thread five is alive:" +hi5.t.isAlive());
400System.out.println("main thread exiting");
401}
402}
403Java & J2EE Lab
404Dept. of C.S.E, Dr.A.I.T Page 10
405Output
406Java & J2EE Lab
407Dept. of C.S.E, Dr.A.I.T Page 11
4083b) Write a Java program using synchronized threads which demonstrate producer-consumer concepts.
409class Q {
410int n;
411boolean valueset = false;
412synchronized int get() {
413while (!valueset)
414try {
415wait();
416} catch (InterruptedException e) {
417System.out.println("Thread Interrupted");
418}
419System.out.println("Got :" + n);
420valueset = false;
421notify();
422return n;
423}
424synchronized void put(int n) {
425while (valueset)
426try {
427wait();
428} catch (InterruptedException e) {
429System.out.println("Thread interrupted");
430}
431this.n = n;
432valueset = true;
433System.out.println("put " + n);
434notify();
435}
436}
437class Producer implements Runnable {
438Q q;
439Producer(Q q) {
440this.q = q;
441new Thread(this, "Producer").start();
442}
443public void run() {
444int i = 0;
445while (true) {
446q.put(i++);
447}
448}
449}
450class Consumer implements Runnable {
451Q q;
452Consumer(Q q) {
453this.q = q;
454new Thread(this, "Consumer").start();
455}
456Java & J2EE Lab
457Dept. of C.S.E, Dr.A.I.T Page 12
458public void run() {
459int i = 0;
460while (true) {
461q.get();
462}
463}
464}
465class Demo {
466public static void main(String args[]) {
467Q q = new Q();
468new Producer(q);
469new Consumer(q);
470System.out.println("press ctrl+c to exit");
471}
472}
473Output
474Java & J2EE Lab
475Dept. of C.S.E, Dr.A.I.T Page 13
4764a) Create an interface and implement it in a class in JAVA.
477Callback.java
478package callback;
479public interface Callback {
480void Callback(int param);
481}
482Client.java
483package callback;
484public class Client implements Callback{
485public void Callback(int param) {
486System.out.println("Callback called with "+param);
487}
488}
489Testface.java
490package callback;
491public class Testface {
492public static void main(String[] args) {
493Callback c = new Client();
494c.Callback(42);
495}
496}
497Output
498Java & J2EE Lab
499Dept. of C.S.E, Dr.A.I.T Page 14
5004b) Write a program to make a package balance which has account class with display_balance method
501in it. Import balance package in another program to access display_balance method of account class.
502Account.java
503package Balance;
504import java.util.Scanner;
505public class Account {
506int curBalance, amt;
507public Account() {
508curBalance = 500;
509}
510void deposit() {
511Scanner s = new Scanner(System.in);
512System.out.println("Enter the amount :");
513amt = s.nextInt();
514curBalance += amt;
515System.out.println("Current balance is :" + curBalance);
516}
517void withdraw() {
518Scanner s = new Scanner(System.in);
519System.out.println("Enter the amount :");
520amt = s.nextInt();
521try {
522if ((curBalance - amt) < 500)
523throw new LessBalanceException(amt);
524curBalance -= amt;
525System.out.println("\nBalance left :" + curBalance);
526} catch (LessBalanceException e) {
527System.out.println(e);
528}
529}
530void display_balance() {
531System.out.println("Balance in your a/c :" + curBalance);
532}
533}
534class LessBalanceException extends Exception {
535int amt;
536LessBalanceException(int x) {
537System.out.println("Balance is less :" + amt);
538}
539}
540Java & J2EE Lab
541Dept. of C.S.E, Dr.A.I.T Page 15
542MainProgram.java
543package Balance;
544import java.util.Scanner;
545public class MainProgram {
546public static void main(String[] args) {
547int ch;
548Scanner s = new Scanner(System.in);
549Account a = new Account();
550while (true) {
551System.out.println("1:Deposit\t2:Withdraw\t3:Balance\t4:Exit\n");
552System.out.println("Enter your choice:");
553ch = s.nextInt();
554switch (ch) {
555case 1:
556a.deposit();
557break;
558case 2:
559a.withdraw();
560break;
561case 3:
562a.display_balance();
563break;
564case 4:
565return;
566default:
567System.out.println("Invalid choice\n");
568return;
569}
570}
571}
572}
573Output
574Java & J2EE Lab
575Dept. of C.S.E, Dr.A.I.T Page 16
576JAVA APPLET
577Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It
578runs inside the browser and works at client side.
579Features of Applets
580â€¢ï€ An applet is a Java class that extends the java.applet.Applet class.
581â€¢ï€ A main() method is not invoked on an applet, and an applet class will not define main().
582â€¢ï€ Applets are designed to be embedded within an HTML page.
583â€¢ï€ When a user views an HTML page that contains an applet, the code for the applet is downloaded
584to the user's machine.
585â€¢ï€ A JVM is required to view an applet.
586â€¢ï€ The JVM on the user's machine creates an instance of the applet class and invokes various methods
587during the applet's lifetime.
588The Applet (java.applet.Applet) class
589Every applet is an extension of the java.applet.Applet class. The base Applet class provides methods that
590a derived Applet class may call to obtain information and services from the browser context.
591The Applet class provides an interface by which the viewer or browser obtains information about the
592applet and controls the applet's execution. The viewer may:
593â€¢ï€ request information about the author, version and copyright of the applet
594â€¢ï€ request a description of the parameters the applet recognizes
595â€¢ï€ initialize the applet
596â€¢ï€ destroy the applet
597â€¢ï€ start the applet's execution
598â€¢ï€ stop the applet's execution
599The Applet class provides default implementations of each of these methods. Those implementations may
600be overridden as necessary.
601Life Cycle of an Applet
602For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
603applet.
604â€¢ï€ public void init(): This method is used to initialize the applet. It is invoked only once.
605â€¢ï€ public void start(): This method is automatically called after the browser calls the init() method. It
606is also called whenever the user returns to the page containing the applet after having gone off to
607other pages. It is used to start the applet.
608â€¢ï€ public void stop(): This method is used to stop the applet. It is automatically invoked when the
609applet is stopped or the browser is minimised.
610â€¢ï€ public void destroy(): This method is used to destroy the applet. It is invoked only once.
611Java & J2EE Lab
612Dept. of C.S.E, Dr.A.I.T Page 17
613The java.awt.Component class provides 1 life cycle method of applet.
614â€¢ï€ public void paint(Graphics g): Invoked immediately after the start() method, and also any time the
615applet needs to repaint itself in the browser. The paint() method is actually inherited from the
616java.awt class.
617A "Hello, World" Applet
618The following is a simple applet named HelloWorldApplet.java:
619import java.applet.*;
620import java.awt.*;
621public class HelloWorldApplet extends Applet
622{
623public void paint (Graphics g)
624{
625g.drawString ("Hello World", 25, 50);
626}
627}
628Getting Applet parameters
629The Applet.getParameter() method fetches a parameter from the applet tag given the parameter's name
630(the value of a parameter is always a string). If the value is numeric or other non-character data, the string
631must be parsed.
632Java & J2EE Lab
633Dept. of C.S.E, Dr.A.I.T Page 18
634EVENT HANDLING
635The Delegation Event Model
636The modern approach to handling events is based on the delegation event model, which defines standard
637and consistent mechanisms to generate and process events. Its concept is quite simple: a source generates
638an event and sends it to one or more listeners. In this scheme, the listener simply waits until it receives an
639event. Once an event is received, the listener processes the event and then returns. The advantage of this
640design is that the application logic that processes events is cleanly separated from the user interface logic
641that generates those events. A user interface element is able to “delegate†the processing of an event to
642a separate piece of code.
643In the delegation event model, listeners must register with a source in order to receive an event
644notification. This provides an important benefit: notifications are sent only to listeners that want to receive
645them.
646Events
647In the delegation model, an event is an object that describes a state change in a source. It can be generated
648as a consequence of a person interacting with the elements in a graphical user interface. Some of the
649activities that cause events to be generated are pressing a button, entering a character via the keyboard,
650selecting an item in a list, and clicking the mouse.
651Event Sources
652A source is an object that generates an event. This occurs when the internal state of that object changes
653in some way. Sources may generate more than one type of event. A source must register listeners in order
654for the listeners to receive notifications about a specific type of event. Each type of event has its own
655registration method.
656The general form is shown below:
657public void addTypeListener(TypeListener el)
658Here, Type is the name of the event, and el is a reference to the event listener. For example, the method
659that registers a keyboard event listener is called addKeyListener( ). The method that registers a mouse
660motion listener is called addMouseMotionListener( ). When an event occurs, all registered listeners are
661notified and receive a copy of the event object. This is known as multicasting the event. In all cases,
662notifications are sent only to listeners that register to receive them.
663Event Listener Interface
664The delegation event model has two parts: sources and listeners. Listeners are created by implementing
665one or more of the interfaces defined by the java.awt.event package. When an event occurs, the event
666source invokes the appropriate method defined by the listener and provides an event object as its
667argument.
668The KeyListener Interface
669This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are invoked when a
670key is pressed and released, respectively. The keyTyped( ) method is invoked when a character has been
671entered.
672The general forms of these methods are shown here:
673void keyPressed(KeyEvent ke)
674void keyReleased(KeyEvent ke)
675void keyTyped(KeyEvent ke)
676Java & J2EE Lab
677Dept. of C.S.E, Dr.A.I.T Page 19
678The MouseListener Interface
679This interface defines five methods. If the mouse is pressed and released at the same point,
680mouseClicked() is invoked. When the mouse enters a component, the mouseEntered( ) method is called.
681When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods are invoked
682when the mouse is pressed and released, respectively.
683The general forms of these methods are shown here:
684void mouseClicked(MouseEvent me)
685void mouseEntered(MouseEvent me)
686void mouseExited(MouseEvent me)
687void mousePressed(MouseEvent me)
688void mouseReleased(MouseEvent me)
689The MouseMotionListener Interface
690This interface defines two methods. The mouseDragged( ) method is called multiple times as the mouse
691is dragged. The mouseMoved( ) method is called multiple times as the mouse is moved.
692Their general forms are shown here:
693void mouseDragged(MouseEvent me)
694void mouseMoved(MouseEvent me)
695Java & J2EE Lab
696Dept. of C.S.E, Dr.A.I.T Page 20
6975a) Write JAVA Applet program which handles Mouse Event.
698/*
699<applet code = "MouseEvents" width = 300 height = 300>
700</applet>
701*/
702import java.awt.*;
703import java.awt.event.*;
704import java.applet.*;
705public class MouseEvents extends Applet implements MouseListener,
706MouseMotionListener {
707int mousex = 0, mousey = 0;
708String msg = "";
709public void init() {
710addMouseListener(this);
711addMouseMotionListener(this);
712}
713public void mouseClicked(MouseEvent e) {
714mousex = 0;
715mousey = 10;
716msg = "Mouse Clicked";
717repaint();
718}
719public void mousePressed(MouseEvent e) {
720mousex = e.getX();
721mousey = e.getY();
722msg = "Mouse Pressed";
723repaint();
724}
725public void mouseMoved(MouseEvent e) {
726showStatus("Mouse moved at :" + e.getX() + "," + e.getY());
727}
728public void mouseReleased(MouseEvent e) {
729mousex = e.getX();
730mousey = e.getY();
731msg = "Mouse Released";
732repaint();
733}
734public void mouseEntered(MouseEvent e) {
735mousex = 0;
736mousey = 10;
737msg = "Mouse Entered";
738repaint();
739}
740public void mouseDragged(MouseEvent e) {
741mousex = e.getX();
742mousey = e.getY();
743msg = "Mouse Dragged";
744repaint();
745Java & J2EE Lab
746Dept. of C.S.E, Dr.A.I.T Page 21
747}
748public void mouseExited(MouseEvent e) {
749mousex = 0;
750mousey = 10;
751msg = "Mouse Exited";
752repaint();
753}
754public void paint(Graphics g) {
755g.drawString(msg, mousex, mousey);
756}
757}
758Output
759Java & J2EE Lab
760Dept. of C.S.E, Dr.A.I.T Page 22
7615b) Write JAVA Applet program to Pass parameters and display the same.
762import java.awt.*;
763import java.applet.*;
764/*
765<applet code="ParamDemo" width=300 height=80>
766<param name=fontName value=Courier>
767<param name=fontSize value=14>
768<param name=leading value=2>
769<param name=accountEnabled value=true>
770</applet>
771*/
772public class ParamDemo extends Applet{
773String fontName;
774int fontSize;
775float leading;
776boolean active;
777// Initialize the string to be displayed.
778public void start() {
779String param;
780fontName = getParameter("fontName");
781if(fontName == null)
782fontName = "Not 222";
783param = getParameter("fontSize");
784try {
785if(param != null) // if not found
786fontSize = Integer.parseInt(param);
787else
788fontSize = 0;
789} catch(NumberFormatException e) {
790fontSize = -1;
791}
792param = getParameter("leading");
793try {
794if(param != null) // if not found
795leading = Float.valueOf(param).floatValue();
796else
797leading = 0;
798} catch(NumberFormatException e) {
799leading = -1;
800}
801param = getParameter("accountEnabled");
802if(param != null)
803active = Boolean.valueOf(param).booleanValue();
804}
805// Display parameters.
806public void paint(Graphics g) {
807g.drawString("Font name: " + fontName, 0, 10);
808g.drawString("Font size: " + fontSize, 0, 26);
809g.drawString("Leading: " + leading, 0, 42);
810g.drawString("Account Active: " + active, 0, 58);
811}
812}
813Java & J2EE Lab
814Dept. of C.S.E, Dr.A.I.T Page 23
815Output
816Java & J2EE Lab
817Dept. of C.S.E, Dr.A.I.T Page 24
818JAVA SWING
819Swing API is set of extensible GUI Components to ease developer's life to create JAVA based Front End/
820GUI Applications. It is built upon top of AWT API and acts as replacement of AWT API as it has almost every
821control corresponding to AWT controls. It is a part of Java Foundation Classes (JFC) that is used to create
822window-based applications
823MVC Architecture
824Swing API architecture follows loosely based MVC architecture in the following manner.
825â€¢ï€ A Model represents component's data.
826â€¢ï€ View represents visual representation of the component's data.
827â€¢ï€ Controller takes the input from the user on the view and reflects the changes in Component's data.
828â€¢ï€ Swing component have Model as a separate element and View and Controller part are clubbed in
829User Interface elements. Using this way, Swing has pluggable look-and-feel architecture.
830Swing features
831â€¢ï€ Light Weight - Swing component are independent of native Operating System's API as Swing API
832controls are rendered mostly using pure JAVA code instead of underlying operating system calls.
833â€¢ï€ Rich controls - Swing provides a rich set of advanced controls like Tree, TabbedPane, slider,
834colorpicker, table controls
835â€¢ï€ Highly Customizable - Swing controls can be customized in very easy way as visual appearance is
836independent of internal representation.
837â€¢ï€ Pluggable look-and-feel- SWING based GUI Application look and feel can be changed at run time
838based on available values.
839Every user interface considers the following three main aspects:
840â€¢ï€ UI elements: These are the core visual elements the user eventually sees and interacts with.
841Layouts: They define how UI elements should be organized on the screen and provide a final look
842and feel to the GUI (Graphical User Interface). This part will be covered in Layout chapter.
843â€¢ï€ Behaviour: These are events which occur when the user interacts with UI elements.
844Every SWING controls inherits properties from following Component class hierarchy.
845â€¢ï€ Component: A Container is the abstract base class for the non-menu user-interface controls of
846SWING. Component represents an object with graphical representation.
847â€¢ï€ Container: A Container is a component that can contain other SWING components.
848â€¢ï€ JComponent: A JComponent is a base class for all swing UI components. In order to use a swing
849component that inherits from JComponent, component must be in a containment hierarchy whose
850root is a top-level Swing container.
851Java & J2EE Lab
852Dept. of C.S.E, Dr.A.I.T Page 25
853SWING UI Elements:
854Following is the list of commonly used controls while designed GUI using SWING.
855SL.
856No.
857Control & Description
8581 JLabel: A JLabel object is a component for placing text in a container.
8592 JButton: This class creates a labelled button.
8604 JCheck Box: A JCheckBox is a graphical component that can be in either an on (true) or off (false)
861state.
8625 JRadioButton: The JRadioButton class is a graphical component that can be in either an on (true)
863or off (false) state. in a group.
8646 JList: A JList component presents the user with a scrolling list of text items.
8657 JComboBox: A JComboBox component presents the user with a show up menu of choices.
8668 JTextField: A JTextField object is a text component that allows for the editing of a single line of
867text.
8689 JPasswordField: A JPasswordField object is a text component specialized for password entry.
86910 JTextArea: A JTextArea object is a text component that allows for the editing of a multiple lines
870of text.
871Java & J2EE Lab
872Dept. of C.S.E, Dr.A.I.T Page 26
8736. Write a Swing application which uses
874a) JTabbed Pane
875b) Each tab should JPanel which include any one component given below in each JPanel
876c) ComboBox/List/Tree/RadioButton
877import javax.swing.*;
878/*
879<applet code="JTabbedPaneDemo" width=400 height=100>
880</applet>
881*/
882public class JTabbedPaneDemo extends JApplet {
883public void init() {
884try {
885SwingUtilities.invokeAndWait(
886new Runnable() {
887public void run() {
888makeGUI();
889}
890}
891);
892} catch (Exception exc) {
893System.out.println("Can't create because of " + exc);
894}
895}
896private void makeGUI() {
897JTabbedPane jtp = new JTabbedPane();
898jtp.addTab("Cities", new CitiesPanel());
899jtp.addTab("Colors", new ColorsPanel());
900jtp.addTab("Flavors", new FlavorsPanel());
901add(jtp);
902}
903}
904// Make the panels that will be added to the tabbed pane.
905class CitiesPanel extends JPanel {
906public CitiesPanel() {
907JButton b1 = new JButton("New York");
908add(b1);
909JButton b2 = new JButton("London");
910add(b2);
911JButton b3 = new JButton("Hong Kong");
912add(b3);
913JButton b4 = new JButton("Tokyo");
914add(b4);
915}
916}
917class ColorsPanel extends JPanel {
918public ColorsPanel() {
919JCheckBox cb1 = new JCheckBox("Red");
920add(cb1);
921JCheckBox cb2 = new JCheckBox("Green");
922add(cb2);
923JCheckBox cb3 = new JCheckBox("Blue");
924add(cb3);
925}
926}
927Java & J2EE Lab
928Dept. of C.S.E, Dr.A.I.T Page 27
929class FlavorsPanel extends JPanel {
930public FlavorsPanel() {
931JComboBox jcb = new JComboBox();
932jcb.addItem("Vanilla");
933jcb.addItem("Chocolate");
934jcb.addItem("Strawberry");
935add(jcb);
936}
937}
938Output
939Java & J2EE Lab
940Dept. of C.S.E, Dr.A.I.T Page 28
941SOCKET PROGRAMMING
942Sockets provide the communication mechanism between two computers using TCP. A client program
943creates a socket on its end of the communication and attempts to connect that socket to a server.
944When the connection is made, the server creates a socket object on its end of the communication. The
945client and server can now communicate by writing to and reading from the socket.
946The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism
947for the server program to listen for clients and establish connections with them.
948The following steps occur when establishing a TCP connection between two computers using sockets:
949â€¢ï€ The server instantiates a ServerSocket object, denoting which port number communication is to
950occur on.
951â€¢ï€ The server invokes the accept() method of the ServerSocket class. This method waits until a client
952connects to the server on the given port.
953â€¢ï€ After the server is waiting, a client instantiates a Socket object, specifying the server name and port
954number to connect to.
955â€¢ï€ The constructor of the Socket class attempts to connect the client to the specified server and port
956number. If communication is established, the client now has a Socket object capable of
957communicating with the server.
958â€¢ï€ On the server side, the accept() method returns a reference to a new socket on the server that is
959connected to the client's socket.
960After the connections are established, communication can occur using I/O streams. Each socket has both
961an OutputStream and an InputStream. The client's OutputStream is connected to the server's
962InputStream, and the client's InputStream is connected to the server's OutputStream.
963TCP is a two-way communication protocol, so data can be sent across both streams at the same time.
964There are following useful classes providing complete set of methods to implement sockets.
965ServerSocket Class Methods:
966The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests
967One of the four ServerSocket constructors are shown below:
968public ServerSocket(int port) throws IOException
969Attempts to create a server socket bound to the specified port. An exception occurs if the port is already
970bound by another application.
971If the ServerSocket constructor does not throw an exception, it means that your application has
972successfully bound to the specified port and is ready for client requests.
973Here are some of the common methods of the ServerSocket class:
974Java & J2EE Lab
975Dept. of C.S.E, Dr.A.I.T Page 29
976Sl.No Methods with Description
9771 public int getLocalPort()
978Returns the port that the server socket is listening on. This method is useful if you passed in 0 as the port
979number in a constructor and let the server find a port for you.
9802 public Socket accept() throws IOException
981Waits for an incoming client. This method blocks until either a client connects to the server on the
982specified port or the socket times out, assuming that the time-out value has been set using the
983setSoTimeout() method. Otherwise, this method blocks indefinitely
9843 public void setSoTimeout(int timeout)
985Sets the time-out value for how long the server socket waits for a client during the accept().
9864 public void bind(SocketAddress host, int backlog)
987Binds the socket to the specified server and port in the SocketAddress object. Use this method if you
988instantiated the ServerSocket using the no-argument constructor.
989When the ServerSocket invokes accept(), the method does not return until a client connects. After a client
990does connect, the ServerSocket creates a new Socket on an unspecified port and returns a reference to
991this new Socket. A TCP connection now exists between the client and server, and communication can
992begin.
993Socket Class Methods:
994The java.net.Socket class represents the socket that both the client and server use to communicate with
995each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket
996object from the return value of the accept() method.
997The Socket class has five constructors that a client uses to connect to a server. One of them is shown
998below:
999public Socket(String host, int port) throws UnknownHostException, IOException.
1000This method attempts to connect to the specified server at the specified port. If this constructor does not
1001throw an exception, the connection is successful and the client is connected to the server.
1002When the Socket constructor returns, it does not simply instantiate a Socket object but it actually attempts
1003to connect to the specified server and port.
1004Some methods of interest in the Socket class are listed here. Notice that both the client and server have a
1005Socket object, so these methods can be invoked by both the client and server.
1006Sl.No. Methods with Description
10071 public int getPort()
1008Returns the port the socket is bound to on the remote machine.
10092 public SocketAddress getRemoteSocketAddress()
1010Returns the address of the remote socket.
10113 public InputStream getInputStream() throws IOException
1012Returns the input stream of the socket. The input stream is connected to the output stream of the remote
1013socket.
10144 public OutputStream getOutputStream() throws IOException
1015Returns the output stream of the socket. The output stream is connected to the input stream of the
1016remote socket
10175 public void close() throws IOException
1018Closes the socket, which makes this Socket object no longer capable of connecting again to any server
1019Java & J2EE Lab
1020Dept. of C.S.E, Dr.A.I.T Page 30
10217. Design and implement Client Server communication using socket programming (Client requests a
1022file, Server responds to client with contents of that file which is then display on the screen by Client).
1023Client.java
1024import java.net.*;
1025import java.io.*;
1026public class Client {
1027public static void main(String[] args) {
1028Socket client = null;
1029BufferedReader br = null;
1030try {
1031System.out.println(args[0] + " " + args[1]);
1032client = new Socket(args[0],Integer.parseInt(args[1]));
1033} catch (Exception e){}
1034DataInputStream input = null;
1035PrintStream output = null;
1036try {
1037input = new DataInputStream(client.getInputStream());
1038output = new PrintStream(client.getOutputStream());
1039br = new BufferedReader(new InputStreamReader(System.in));
1040String str = input.readLine(); //get the prompt from the server
1041System.out.println(str);
1042String filename = br.readLine();
1043if (filename!=null){
1044output.println(filename);
1045}
1046String data;
1047while ((data=input.readLine())!=null) {
1048System.out.println(data);
1049}
1050client.close();
1051} catch (Exception e){
1052System.out.println(e);
1053}
1054}
1055}
1056Java & J2EE Lab
1057Dept. of C.S.E, Dr.A.I.T Page 31
1058Server.java
1059import java.net.*;
1060import java.io.*;
1061public class Server {
1062public static void main(String[] args) {
1063ServerSocket server = null;
1064try {
1065server = new ServerSocket(Integer.parseInt(args[0]));
1066} catch (Exception e) {
1067}
1068while (true) {
1069Socket client = null;
1070PrintStream output = null;
1071DataInputStream input = null;
1072try {
1073client = server.accept();
1074} catch (Exception e) {
1075System.out.println(e);
1076}
1077try {
1078output = new PrintStream(client.getOutputStream());
1079input = new DataInputStream(client.getInputStream());
1080} catch (Exception e) {
1081System.out.println(e);
1082}
1083//Send the command prompt to client
1084output.println("Enter the filename :>");
1085try {
1086//get the filename from client
1087String filename = input.readLine();
1088System.out.println("Client requested file :" + filename);
1089try {
1090File f = new File(filename);
1091BufferedReader br = new BufferedReader(new
1092FileReader(f));
1093String data;
1094while ((data = br.readLine()) != null) {
1095output.println(data);
1096}
1097} catch (FileNotFoundException e) {
1098output.println("File not found");
1099}
1100client.close();
1101} catch (Exception e) {
1102System.out.println(e);
1103}
1104}
1105}
1106}
1107Java & J2EE Lab
1108Dept. of C.S.E, Dr.A.I.T Page 32
1109Output
1110Create a file called testfile.txt in the folder where Client.java and Server.java is located. Add some content.
1111Open two terminals
1112Navigate to the src folder of your project
1113Java & J2EE Lab
1114Dept. of C.S.E, Dr.A.I.T Page 33
1115REMOTE METHOD INVOCATION (RMI)
1116The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed
1117application in java. The RMI allows an object to invoke methods on an object running in another JVM.
1118The RMI provides remote communication between the applications using two objects stub and skeleton.
1119Understanding stub and skeleton
1120RMI uses stub and skeleton object for communication with the remote object.
1121A remote object is an object whose method can be invoked from another JVM.
1122stub
1123The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through it.
1124It resides at the client side and represents the remote object. When the caller invokes method on the stub
1125object, it does the following tasks:
11261. It initiates a connection with remote Virtual Machine (JVM),
11272. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
11283. It waits for the result
11294. It reads the return value or exception, and
11305. It finally, returns the value to the caller.
1131skeleton
1132The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are routed
1133through it. When the skeleton receives the incoming request, it does the following tasks:
11341. It reads the parameter for the remote method
11352. It invokes the method on the actual remote object, and
11363. It writes and transmits (marshals) the result to the caller.
1137Steps to write the RMI program
11381. Create the remote interface
11392. Provide the implementation of the remote interface
11403. Compile the implementation class and create the stub and skeleton objects using the rmic tool
11414. Start the registry service by rmiregistry tool
11425. Create and start the remote application
11436. Create and start the client application
1144Java & J2EE Lab
1145Dept. of C.S.E, Dr.A.I.T Page 34
11468. Design and implement a simple Client Server Application using RMI.
1147AddServerIntf.java
1148import java.rmi.*;
1149public interface AddServerIntf extends Remote {
1150int add(int x, int y) throws RemoteException;
1151}
1152AddServerImpl.java
1153import java.rmi.*;
1154import java.rmi.server.*;
1155public class AddServerImpl extends UnicastRemoteObject implements
1156AddServerIntf{
1157public AddServerImpl() throws RemoteException {}
1158public int add(int x, int y) throws RemoteException {
1159return x+y;
1160}
1161}
1162AddServer.java
1163import java.rmi.*;
1164public class AddServer {
1165public static void main(String[] args) {
1166try{
1167AddServerImpl server = new AddServerImpl();
1168Naming.rebind("registerme",server);
1169System.out.println("Server is running...");
1170} catch (Exception e) {
1171System.out.println(e);
1172}
1173}
1174}
1175AddClient.java
1176import java.rmi.*;
1177public class AddClient {
1178public static void main(String[] args) {
1179try{
1180AddServerIntf client =
1181(AddServerIntf)Naming.lookup("registerme");
1182System.out.println("First number is :" + args[0]);
1183int x = Integer.parseInt(args[0]);
1184System.out.println("Second number is :" + args[1]);
1185int y = Integer.parseInt(args[1]);
1186System.out.println("Sum =" + client.add(x,y));
1187} catch (Exception e){
1188System.out.println(e);
1189}
1190}
1191}
1192Java & J2EE Lab
1193Dept. of C.S.E, Dr.A.I.T Page 35
1194Output:
1195Open a terminal
1196Navigate to the src folder of your project
1197In another terminal (while previous one is still running)
1198Navigate to the src folder of your project
1199In third terminal (while previous both are still open)
1200Navigate to the src folder of your project
1201Java & J2EE Lab
1202Dept. of C.S.E, Dr.A.I.T Page 36
1203SERVLET PROGRAMMING
1204Servlet technology is used to create web application (resides at server side and generates dynamic web
1205page).
1206They are modules of Java code that run in a server application.
1207The advantages of using Servlets over traditional CGI programs are:
12081. Better performance: because it creates a thread for each request not process.
12092. Portability: because it uses java language.
12103. Robust: Servlets are managed by JVM so no need to worry about momory leak, garbage collection
1211etc.
12124. Secure: because it uses java language.
1213Life cycle of a servlet
1214The life cycle of a servlet is controlled by the container in which the servlet has been deployed.
1215When a request is mapped to a servlet, the container performs the following steps:
12161. If an instance of the servlet does not exist, the web container:
1217a. Loads the servlet class
1218b. Creates an instance of the servlet class
1219c. Initializes the servlet instance by calling the init method. Initialization is covered in
1220Initializing a Servlet
12212. Invokes the service method, passing a request and response object.
12223. If the container needs to remove the servlet, it finalizes the servlet by calling the servlet’s destroy
1223method.
1224Servlet API
1225â€¢ï€ The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
1226â€¢ï€ The javax.servlet package contains many interfaces and classes that are used by the servlet or web
1227container. These are not specific to any protocol.
1228â€¢ï€ The javax.servlet.http package contains interfaces and classes that are responsible for http requests
1229only
1230javax.servlet package
1231â€¢ï€ The javax.servlet package contains a number of classes and interfaces that describe and define the
1232contracts between a servlet class and the runtime environment provided for an instance of such a
1233class by a conforming servlet container.
1234â€¢ï€ The Servlet interface is the central abstraction of the servlet API.
1235â€¢ï€ All servlets implement this interface either directly, or more commonly, by extending a class that
1236implements the interface.
1237â€¢ï€ The two classes in the servlet API that implement the Servlet interface are GeneriISErvlet and
1238HttpServlet .
1239â€¢ï€ For most purposes, developers will extend HttpServlet to implement their servlets while implementing
1240web applications employing the HTTP protocol.
1241â€¢ï€ The basic Servlet interface defines a service method for handling client requests. This method is called
1242for each request that the servlet container routes to an instance of a servlet.
1243Java & J2EE Lab
1244Dept. of C.S.E, Dr.A.I.T Page 37
1245Running Servlet Programs in Eclipse EE
1246To create a Servlet application in Eclipse IDE you will need to follow the following steps:
1247Step 1. Goto File -> New -> Dynamic Web Project
1248Step 2. Give a Name to your Project and click Next
1249Java & J2EE Lab
1250Dept. of C.S.E, Dr.A.I.T Page 38
1251Step 3. Check Generate web.xml Deployment Descriptor and click Finish
1252Java & J2EE Lab
1253Dept. of C.S.E, Dr.A.I.T Page 39
1254Step 4. Now, the complete directory structure of your Project will be automatically created by
1255Eclipse IDE.
1256Step 5. Click on First project, go to Java Resources -> src. Right click on src select New -> Servlet
1257Java & J2EE Lab
1258Dept. of C.S.E, Dr.A.I.T Page 40
1259Step 6. Give Servlet class name and click Next
1260Step 7. Give your Servlet class a Name of your choice.
1261Java & J2EE Lab
1262Dept. of C.S.E, Dr.A.I.T Page 41
1263Step 8. Leave everything else to default and click Finish
1264Step 9. Now your Servlet is created, write the code inside it.
1265Java & J2EE Lab
1266Dept. of C.S.E, Dr.A.I.T Page 42
1267Step 10. Now all you have to do is Start the server and run the application.
1268Step 11. Select the existing Tomcat server and click finish
1269Java & J2EE Lab
1270Dept. of C.S.E, Dr.A.I.T Page 43
12719. Implement a JAVA Servlet Program to implement a dynamic HTML using Servlet (user name and
1272password should be accepted using HTML and displayed using a Servlet).
1273Create a new servlet named Servlet9 in the project (as shown in the steps above from Page 37) and then type the
1274following code in it
1275Servlet9.java
1276import java.io.*;
1277import javax.servlet.*;
1278import javax.servlet.annotation.WebServlet;
1279import javax.servlet.http.*;
1280@WebServlet("/Servlet9")
1281public class Servlet9 extends HttpServlet {
1282protected void doPost(HttpServletRequest request, HttpServletResponse response)
1283throws ServletException, IOException {
1284response.setContentType("text/html");
1285PrintWriter out = response.getWriter();
1286String str = request.getParameter("uname");
1287String str1 = request.getParameter("pname");
1288out.println("<html>");
1289out.println("<body>");
1290out.println("Username is :" + str + "<br/>");
1291out.println("Password is :" + str1);
1292out.println("</body>");
1293out.println("</html>"); }
1294}
1295Under WebContent, create a new html file, Program9.html
1296<html>
1297<head>
1298<title>Program 9</title>
1299</head>
1300<body bgcolor=orange>
1301<form method="post" name="form1"
1302action="http://localhost:8080/ProjectName/ServletClassName">
1303<center>
1304<b><br/><br/>
1305Enter Username : <input type="text" name="uname" size="10"/>
1306<br/>
1307Enter Password : <input type="password" name="pname" size="10"/>
1308<br/><br/>
1309<input type="button" value="Submit" onclick="submit()"/>
1310</center>
1311<script type="text/javascript">
1312function validate(){
1313if(document.form1.uname.value =="" || document.from1.pname.value ==""){
1314alert("Fields cannot be blank");
1315return;
1316}
1317}
1318</script>
1319</form>
1320</body>
1321</html>
1322In the above html file, replace ProjectName and ServletClassName with your respective project and filename
1323Java & J2EE Lab
1324Dept. of C.S.E, Dr.A.I.T Page 44
1325Output
1326Java & J2EE Lab
1327Dept. of C.S.E, Dr.A.I.T Page 45
132810. Design a JAVA Servlet Program to Download a file and display it on the screen (A link has to be
1329provided in HTML, when the link is clicked corresponding file has to be displayed on Screen).
1330Create a new servlet named Servlet10 in the project (as shown in the steps in Page 37) and then type the following
1331code in it
1332Servlet10.java
1333import java.io.*;
1334import javax.servlet.*;
1335import javax.servlet.annotation.WebServlet;
1336import javax.servlet.http.*;
1337@WebServlet("/Servlet10")
1338public class Servlet10 extends HttpServlet {
1339protected void doGet(HttpServletRequest request, HttpServletResponse response)
1340throws ServletException, IOException {
1341response.setContentType("text/html");
1342PrintWriter out = response.getWriter();
1343String fname = request.getParameter("f1");
1344System.out.println(fname);
1345File f = new File(fname);
1346if (f.exists())
1347{
1348out.println(f.getName());
1349out.println("<hr size='2'style='color:green'>");
1350out.println("Contents of the file is:<br>");
1351out.println("<hr size='2' style='color:green'/><br>");
1352BufferedReader in = new BufferedReader(new FileReader(f));
1353String buf = "";
1354while ((buf = in.readLine()) != null)
1355{
1356out.write(buf);
1357out.flush();
1358out.println("<br>");
1359}
1360in.close();
1361out.println("<hr size='3'
1362style='color:red'></font></p></body>\n</html>");
1363}
1364else
1365{
1366out.println("Filename:" + fname);
1367out.println("<h1>File doesn't exist</h1>\n");
1368}
1369}
1370}
1371Under WebContent, create a new html file, Program10.html
1372Java & J2EE Lab
1373Dept. of C.S.E, Dr.A.I.T Page 46
1374<!DOCTYPE html>
1375<html>
1376<head>
1377<title>Program 10</title>
1378</head>
1379<script type="text/javascript">
1380function validate() {
1381if (document.form1.f1.value == "")
1382alert("First click on browse and select the file");
1383else
1384document.from1.submit();
1385}
1386</script>
1387<body bgcolor="lightblue">
1388<form name="form1" method="get"
1389action="http://localhost:8080/ProjectName/ServletClassName">
1390<p>
1391<center>
1392<br />
1393<h1>File Download Program</h1>
1394<br />
1395<h3>Click on browse and select the file</h3>
1396<br /> <input type="file" name="f1"> <br />
1397<br /> <input type="submit" value="Click to start downloading"
1398onclick="validate()">
1399</center>
1400</p>
1401</form>
1402</body>
1403</html>
1404In the above html file, replace ProjectName and ServletClassName with your respective project and filename
1405Output
1406Java & J2EE Lab
1407Dept. of C.S.E, Dr.A.I.T Page 47
1408Java & J2EE Lab
1409Dept. of C.S.E, Dr.A.I.T Page 48
141011 a) Design a JAVA Servlet Program to implement RequestDispatcher object using include() and
1411forward() methods.
1412Create a new servlet named Servlet11_a in the project (as shown in the steps in Page 37) and then type the
1413following code in it
1414Servlet11_a.java
1415import java.io.*;
1416import javax.servlet.*;
1417import javax.servlet.annotation.WebServlet;
1418import javax.servlet.http.*;
1419@WebServlet("/Servlet_a")
1420public class Servlet_a extends HttpServlet {
1421protected void doPost(HttpServletRequest request, HttpServletResponse response)
1422throws ServletException, IOException {
1423String decider = request.getParameter("decider");
1424PrintWriter out = response.getWriter();
1425RequestDispatcher rd = null;
1426if ("forward".equals(decider)) {
1427rd = request.getRequestDispatcher("Servlet_b");
1428rd.forward(request, response);
1429} else if ("include".equals(decider)) {
1430rd = request.getRequestDispatcher("Servlet_b");
1431rd.include(request, response);
1432}
1433out.println("<br/><center>Including second servlet in first
1434servlet</center>");
1435}
1436}
1437Similarly, create another servlet in the same project called Servlet11_b
1438Servlet11_b.java
1439import java.io.*;
1440import javax.servlet.*;
1441import javax.servlet.annotation.WebServlet;
1442import javax.servlet.http.*;
1443@WebServlet("/Servlet_b")
1444public class Servlet_b extends HttpServlet {
1445protected void doPost(HttpServletRequest request, HttpServletResponse response)
1446throws ServletException, IOException {
1447PrintWriter out = response.getWriter();
1448out.println("<html>");
1449out.println("<body bgcolor=skyblue>");
1450out.println("<center><h2>Second Servlet (forwarded from first
1451servlet)</center></h2>");
1452out.println("</body>");
1453out.println("</html>");
1454}
1455}
1456Java & J2EE Lab
1457Dept. of C.S.E, Dr.A.I.T Page 49
1458Under WebContent, create a new html file, Program11a.html
1459<!DOCTYPE html>
1460<html>
1461<head>
1462<title>Program 11a</title>
1463</head>
1464<body bgcolor="lightblue">
1465<form method="post" action="http://localhost:8080/ProjectName/Servlet_a">
1466<p>
1467<center>
1468<br /> <br />
1469<h1>Request Dispatcher Implementation</h1>
1470<br /> <br /> <input type="submit" name="decider" value="forward">
1471<br />
1472<br /> <input type="submit" name="decider" value="include">
1473</center>
1474</form>
1475</body>
1476</html>
1477In the above html file, replace ProjectName with your respective project and filename.
1478Output
1479Java & J2EE Lab
1480Dept. of C.S.E, Dr.A.I.T Page 50
1481On clicking forward button
1482On clicking include button
1483Java & J2EE Lab
1484Dept. of C.S.E, Dr.A.I.T Page 51
148511b) Implement a JAVA Servlet Program to implement sessions using HTTP Session Interface.
1486Create a new servlet named Servlet11b in the project (as shown in the steps in Page 37) and then type the
1487following code in it
1488Servlet11b.java
1489import java.io.*;
1490import javax.servlet.*;
1491import javax.servlet.annotation.WebServlet;
1492import javax.servlet.http.*;
1493@WebServlet("/Servlet11b")
1494public class Servlet11b extends HttpServlet {
1495protected void doGet(HttpServletRequest request, HttpServletResponse response)
1496throws ServletException, IOException {
1497response.setContentType("text/html");
1498PrintWriter out = response.getWriter();
1499HttpSession session = request.getSession(true);
1500String id = session.getId();
1501out.println("<html>");
1502out.println("<body>");
1503out.println("<br>");
1504out.println("Session ID = " + id);
1505out.println("<br>");
1506out.println("Session = " + session);
1507out.println("<br>");
1508Integer val = (Integer) session.getAttribute("sessiontest.counter");
1509if(val == null)
1510val = new Integer(1);
1511else
1512val = new Integer(val.intValue()+1);
1513session.setAttribute("sessiontest.counter", val);
1514out.println("You have visited this page " + val + " times.");
1515out.println("</body>");
1516out.println("</html>");
1517}
1518}
1519Output
1520Java & J2EE Lab
1521Dept. of C.S.E, Dr.A.I.T Page 52
1522JavaServer Pages (JSP)
1523JavaServer Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
1524platform-independent method for building Web-based applications by making use of special JSP tags, most
1525of which start with <% and end with %>.
1526A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a user interface
1527for a Java web application. Web developers write JSPs as text files that combine HTML or XHTML code,
1528XML elements, and embedded JSP actions and commands.
1529Using JSP, you can collect input from users through web page forms, present records from a database or
1530another source, and create web pages dynamically.
1531JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering
1532user preferences, accessing JavaBeans components, passing control between pages and sharing
1533information between requests, pages etc.
1534Advantages of using JSP
1535JavaServer Pages often serve the same purpose as programs implemented using the Common Gateway
1536Interface (CGI). But JSP offer several advantages in comparison with the CGI.
1537â€¢ï€ Performance is significantly better because JSP allows embedding Dynamic Elements in HTML
1538Pages itself instead of having a separate CGI files.
1539â€¢ï€ JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the
1540server to load an interpreter and the target script each time the page is requested.
1541â€¢ï€ JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all
1542the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
1543â€¢ï€ JSP pages can be used in combination with servlets that handle the business logic, the model
1544supported by Java servlet template engines.
1545Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications. This means
1546that JSP can play a part in the simplest applications to the most complex and demanding.
1547The general syntax and tags used for JSP development is shown below:
1548The Scriptlet:
1549A scriptlet can contain any number of JAVA language statements, variable or method declarations, or
1550expressions that are valid in the page scripting language.
1551Following is the syntax of Scriptlet:
1552<%
1553code fragment
1554%>
1555JSP Declarations:
1556A declaration declares one or more variables or methods that you can use in Java code later in the JSP file.
1557You must declare the variable or method before you use it in the JSP file.
1558Following is the syntax of JSP Declarations:
1559<%! declaration; [ declaration; ]+ ... %>
1560Java & J2EE Lab
1561Dept. of C.S.E, Dr.A.I.T Page 53
1562Following is the simple example for JSP Declarations:
1563<%! int i = 0; %>
1564<%! int a, b, c; %>
1565JSP Expression:
1566A JSP expression element contains a scripting language expression that is evaluated, converted to a String,
1567and inserted where the expression appears in the JSP file.
1568Because the value of an expression is converted to a String, you can use an expression within a line of text,
1569whether or not it is tagged with HTML, in a JSP file.
1570The expression element can contain any expression that is valid according to the Java Language
1571Specification but you cannot use a semicolon to end an expression.
1572Following is the syntax of JSP Expression:
1573<%= expression %>
1574Following is the simple example for JSP Expression:
1575<html>
1576<head><title>A Comment Test</title></head>
1577<body>
1578<p>
1579Today's date: <%= (new java.util.Date()).toLocaleString()%>
1580</p>
1581</body>
1582</html>
1583This would generate following result:
1584Today's date: 11-Sep-2010 21:24:25
1585JSP Comments:
1586JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when
1587you want to hide or "comment out" part of your JSP page.
1588Following is the syntax of JSP comments:
1589<%-- This is JSP comment --%>
1590Java & J2EE Lab
1591Dept. of C.S.E, Dr.A.I.T Page 54
159212. Design a JAVA JSP Program to implement verification of a particular user login and display a
1593welcome page.
1594Create a new Dynamic Web Project
1595Under WebContent, create a new html file, Program12.html
1596<!DOCTYPE html>
1597<html>
1598<head>
1599<title>Program 12</title>
1600</head>
1601<body bgcolor=lightblue>
1602<form method="post"
1603action="http://localhost:8080/ProjectName/Verification.jsp">
1604<p>
1605<center>
1606<br>
1607<br>
1608<h1>Verfication of a particular User Login</h1>
1609<br>
1610<br> Username:<input type=text name="uname" size=10><br>
1611Password:<input type=password name="pwd" size=10><br>
1612<br> <input type=submit value=submit>
1613</center>
1614</p>
1615</form>
1616</body>
1617</html>
1618In the above html file, replace ProjectName with your respective project and filename.
1619Under WebContent, create a new jsp file, Verification.jsp
1620Verification.jsp
1621<%!String username=null,password=null;%>
1622<%
1623username=request.getParameter("uname");
1624password=request.getParameter("pwd");
1625%>
1626<%
1627if(username.equals("john")&& password.equals("testpass"))
1628response.sendRedirect("Welcome.jsp");
1629else
1630out.println("<center><h4>Invalid username or password</h2></center>");
1631%>
1632Under WebContent, create another jsp file, Welcome.jsp
1633Welcome.jsp
1634<html>
1635<head>
1636<title>Welcome Page</title>
1637</head>
1638<body bgcolor=yellow>
1639<%
1640out.println("<center><h4>Welcome user<br>");
1641out.println("You are now logged in!</h4></center>");
1642%>
1643</body>
1644</html>
1645Java & J2EE Lab
1646Dept. of C.S.E, Dr.A.I.T Page 55
1647Output
1648Java & J2EE Lab
1649Dept. of C.S.E, Dr.A.I.T Page 56
1650JSP - JavaBeans
1651A JavaBean is a specially constructed Java class written in the Java and coded according to the JavaBeans
1652API specifications.
1653Following are the unique characteristics that distinguish a JavaBean from other Java classes:
1654â€¢ï€ It provides a default, no-argument constructor.
1655â€¢ï€ It should be serializable and implement the Serializable interface.
1656â€¢ï€ It may have a number of properties which can be read or written.
1657â€¢ï€ It may have a number of "getter" and "setter" methods for the properties.
1658JavaBeans Properties:
1659A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute can
1660be of any Java data type, including classes that you define.
1661A JavaBean property may be read, write, read only, or write only. JavaBean properties are accessed
1662through two methods in the JavaBean's implementation class:
1663Method Description
1664getPropertyName() For example, if property name is firstName, your method name would
1665be getFirstName() to read that property. This method is called accessor.
1666setPropertyName() For example, if property name is firstName, your method name would
1667be setFirstName() to write that property. This method is called mutator.
1668A read-only attribute will have only a getPropertyName() method, and a write-only attribute will have
1669only a setPropertyName() method.
1670Accessing JavaBeans:
1671The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a scripting
1672variable that can be accessed by both scripting elements and other custom tags used in the JSP. The full
1673syntax for the useBean tag is as follows:
1674<jsp:useBean id="bean's name" scope="bean's scope" typeSpec/>
1675Here values for the scope attribute could be page, request, session or application based on your
1676requirement. The value of the id attribute may be any value as a long as it is a unique name among other
1677useBean declarations in the same JSP.
1678Accessing JavaBeans Properties:
1679Along with <jsp:useBean...>, you can use <jsp:getProperty/> action to access get methods and
1680<jsp:setProperty/> action to access set methods. Here is the full syntax:
1681<jsp:useBean id="id" class="bean's class" scope="bean's scope">
1682<jsp:setProperty name="bean's id" property="property name"
1683value="value"/>
1684<jsp:getProperty name="bean's id" property="property name"/>
1685...........
1686</jsp:useBean>
1687The name attribute references the id of a JavaBean previously introduced to the JSP by the useBean action.
1688The property attribute is the name of the get or set methods that should be invoked.
1689Java & J2EE Lab
1690Dept. of C.S.E, Dr.A.I.T Page 57
169113. Design and implement a JAVA JSP Program to get student information through a HTML and create a JAVA
1692Bean Class, populate it and display the same information through another JSP.
1693Create a new Dynamic Web Project
1694Under WebContent, create a new html file, Program13.html
1695<!DOCTYPE html>
1696<html>
1697<head>
1698<title>Student Information</title>
1699</head>
1700<body bgcolor=orange>
1701<form action="http://localhost:8080/ProjectName/First.jsp" method="post">
1702<center>
1703<h1>student information</h1>
1704<h3>
1705USN :<input type="text" name="usn" size=20 /><br>
1706Student Name :<input type="text" name="sname" size=20/><br>
1707Total Marks :<input type="text" name="smarks" size=20/><br>
1708<br><input type="submit" value="DISPLAY" />
1709</h3>
1710</center>
1711</form>
1712</body>
1713</html>
1714In the above html file, replace ProjectName with your respective project and filename.
1715Under WebContent, create a new jsp file, Display.jsp
1716Display.jsp
1717<html>
1718<head>
1719<title>Student Information</title>
1720</head>
1721<body bgcolor=pink>
1722<jsp:useBean id="student" scope="request" class="beans.Student" />
1723<h2>Entered Student Information</h2>
1724<br>
1725<br>
1726<h3>
1727Student Name :<jsp:getProperty name="student" property="sname" /><br>
1728USN :<jsp:getProperty name="student" property="usn" /><br>
1729Total Marks :<jsp:getProperty name="student" property="smarks" />
1730</h3>
1731</body>
1732</html>
1733Under WebContent, create another jsp file, First.jsp
1734Java & J2EE Lab
1735Dept. of C.S.E, Dr.A.I.T Page 58
1736First.jsp
1737<html>
1738<head>
1739<title>Student Information</title>
1740</head>
1741<body>
1742<jsp:useBean id="student" scope="request" class="beans.Student" />
1743<jsp:setProperty name="student" property="*" />
1744<jsp:forward page="Display.jsp" />
1745</body>
1746</html>
1747Create a new java class inside a package (ex: package beans;)
1748Student.java
1749package beans;
1750public class Student implements java.io.Serializable {
1751public String sname;
1752public String usn;
1753public int smarks;
1754public Student() {
1755}
1756public void setsname(String e) {
1757sname = e;
1758}
1759public String getsname() {
1760return sname;
1761}
1762public void setusn(String en) {
1763usn = en;
1764}
1765public String getusn() {
1766return usn;
1767}
1768public void setsmarks(int m) {
1769smarks = m;
1770}
1771public int getsmarks() {
1772return smarks;
1773}
1774}
1775Java & J2EE Lab
1776Dept. of C.S.E, Dr.A.I.T Page 59
1777Output