Advertisement
Guest User

java

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