· 10 years ago · Oct 05, 2015, 10:54 PM
1 WEB PAGE WITH HOT SPOTS IN HTML
2Create a web page with the following using HTML
3i) To embed an image map in a web page
4ii) To fix the hot spots
5iii) Show all the related information when the hot spots are clicked.
6Aim:
7
8 To create webpage and embed map and fix the hot spots in that map and show related information
9
10Algorithm:
11
121. Start the program for embed map in web page
132. Create ImageMap.htm file
143. Set the coordination for the hot spot area.
154. Create separate html file for separate hot spots Like Tamilnadu,keral,karanadha
165. Finally terminate the program .
17
18Program:
19ImageMap.html :
20<HTML>
21<HEAD>
22<TITLE>Image Map</TITLE>
23</HEAD>
24<BODY>
25<MAP id = "picture">
26<AREA href = "TamilNadu.html" shape = "circle"
27coords = "170, 490, 30" alt = "Tamil Nadu" />
28<AREA href = "Karnataka.html" shape = "rect"
29coords = "115, 390, 150, 450" alt = "Karnataka" />
30<AREA href = "AndhraPradesh.html" shape = "poly"
31coords = "165, 355, 200, 355, 220, 380, 170, 425, 165,
32355" alt = "Andhra Pradesh" />
33<AREA href = "Kerala.html" shape = "poly"
34coords = "115, 455, 160, 470, 140, 485, 150, 505, 150,
35530, 135, 500, 115, 455" alt = "Kerala" />
36</MAP>
37<IMG src = "India.Jpg" alt = "India" usemap = "#picture" />
38</BODY>
39</HTML>
40
41
42TamilNadu.html:
43<HTML>
44<HEAD>
45<TITLE>About Tamil Nadu</TITLE>
46</HEAD>
47<BODY>
48<CENTER><H1>Tamil Nadu</H1></CENTER>
49<HR>
50<UL>
51<LI>Area : 1,30,058 Sq. Kms.</LI>
52<LI>Capital : Chennai</LI>
53<LI>Language : Tamil</LI>
54<LI>Population : 6,21,10,839</LI>
55</UL>
56</BODY>
57</HTML>
58
59AndhraPradesh.html:
60<HTML>
61<HEAD>
62<TITLE>About Andhra Pradesh</TITLE>
63</HEAD>
64<BODY>
65<CENTER><H1>Andhra Pradesh</H1></CENTER>
66<HR>
67<UL>
68<LI>Area : 2,75,068 Sq. Kms</LI>
69<LI>Capital : Hyderabad</LI>
70<LI>Language : Telugu</LI>
71<LI>Population : 7,57,27,541</LI>
72</UL>
73</BODY>
74</HTML>
75
76Kerala.html
77<HTML>
78<HEAD>
79<TITLE>About Kerala</TITLE>
80</HEAD>
81<BODY>
82<CENTER><H1>Kerala</H1></CENTER>
83<HR>
84<UL>
85<LI>Area : 38,863 Sq. Kms.</LI>
86<LI>Capital : Thiruvananthapuram</LI>
87<LI>Language : Malayalam</LI>
88<LI>Population : 3,18,38,619</LI>
89</UL>
90</BODY>
91</HTML>
92
93 Karnataka.html
94<HTML>
95<HEAD>
96<TITLE>About Karnataka</TITLE>
97</HEAD>
98<BODY>
99<CENTER><H1>Karnataka</H1></CENTER>
100<HR>
101<UL>
102<LI>Area : 1,91,791 Sq. Kms</LI>
103<LI>Capital : Bangalore</LI>
104<LI>Language : Kannada</LI>
105<LI>Population : 5,27,33,958</LI>
106</UL>
107</BODY>
108</HTML>
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138Tamil Nadu
139________________________________________
140Area : 1,30,058 Sq. Kms.
141Capital : Chennai
142Language : Tamil
143Population : 6,21,10,839
144Andhra Pradesh
145________________________________________
146Area : 2,75,068 Sq. Kms
147Capital : Hyderabad
148Language : Telugu
149Population : 7,57,27,541
150Kerala
151________________________________________
152Area : 38,863 Sq. Kms.
153Capital : Thiruvananthapuram
154Language : Malayalam
155Population : 3,18,38,619
156Karnataka
157________________________________________
158Area : 1,91,791 Sq. Kms
159Capital : Bangalore
160Language : Kannada
161Population : 5,27,33,958
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179RESULT :Thus a webpage was successfully created using HTML and image map was embedded where hotspots could be clicked and related information was displayed.
180
181
182EX 2
183WEB PAGE WITH CSS
184Create a web page with all types of Cascading style sheets.
185Aim:
186To create a webpage using Cascading Style Sheet.
187Algorithm:
188Step 1: Start the cascading program.
189Step 2: Give link from main page to other like cascading, Embedded.
190Step 3: Write the code for separate page. Finally terminate program Source code for html Programming for Home page and Cascading, Embedded, Inline style sheet.
191Step 4: find the style changes in your page.
192
193Program
194<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
195"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd">
196<html xmlns="http://www.w3.org/1999/xhtml">
197 <head>
198 <title>Embedded style sheet</title>
199 <style type="text/css">
200 h1
201 {
202 font-family:Arial;
203 color:green
204 }
205 h2
206 {
207 font-family:Arial;
208 color:red;
209 left:20px
210 }
211 h3
212 {
213 font-family:arial;
214 color:blue;
215 }
216 p
217 {
218 font-size:14pt;
219 font-family:verdana
220 }
221 </style>
222 </head>
223 <body>
224 <h1>
225 <center>
226 This page is created using Embedded Style Sheet
227 </center>
228 </h1>
229 <h2>
230 This line is aligned left and red colored.
231 </h2>
232 <p>
233 The embedded style sheet is the most commonly used style sheet.
234 This paragraph is written in Verdana font with font size of 14.
235 </p>
236 <h3>
237 This is a blue <a href=â€colorname.htmlâ€>colored</a> line.
238 </h3>
239</body>
240</html>
241
242
243
244External Style Sheet
245<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
246"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd">
247<html xmlns="http://www.w3.org/1999/xhtml">
248 <head>
249 <link rel="stylesheet" type="text/css" href="ex1.css" />
250 </head>
251 <body>
252 <h1 class="special"> <center> This page is created using External Style
253 Sheet</center> </h1>
254 <h2>
255 This line is aligned left and red colored.
256 </h2>
257 <p>
258 The External style sheet is the compact representation of Cascading
259 Style Sheets.
260 This paragraph is written in Monotype Corsiva font with font size of 14.
261 </p>
262 <h3>
263 This is a blue <a href=â€colorname.htmlâ€>colored</a> line.
264 </h3>
265 </body>
266</html>
267 The cascading style sheet ex1.css can be
268<!- - The file name ex1.css and can be opened in notepad.-->
269h1
270{
271 font-family:Arial
272}
273h2
274{
275 font-family:times new roman;
276 color:red;
277left:20px
278}
279h3
280{
281font-family:arial;
282color:blue;
283}
284p
285{
286 font-size:14pt;
287 font-family:Monotype Corsiva
288}
289
290
291RESULT: Thus a webpage was created using HTML and all types of cascading sheets were embedded successfully.
292EX-3
293XML DOM PARSER
294Create and save an XML document at the server, which contains 10 users Information. Write a Program, which takes user Id as an input and returns the User details by taking the user information from the XML document.
295
296Aim:
297To write a DOM parser in java for parsing XML which takes user Id as an input and returns the User details
298
299Algorithm:
3001. Import XML-related packages.
3012. Create a Document Builder
3023. Create a Document from a file or stream
3034. Extract the root element
3045. Examine attributes
3056. Get Userid from user as input.
3067. Print the relevant user details from the xml.
307
308Program
309
310Employee.xml
311<?xml version="1.0"?>
312<company>
313 <employee id="231">
314 <firstname>James</firstname>
315 <lastname>Harley</lastname>
316 <email>james@example.org</email>
317 <department>Human Resources</department>
318 <salary>1000</salary>
319 </employee>
320 <employee id="232">
321 <firstname>John</firstname>
322 <lastname>May</lastname>
323 <email>john@example.org</email>
324 <department>Logistics</department>
325 <salary>400</salary>
326 </employee>
327 <employee id="3">
328 <firstname>ghhh</firstname>
329 <lastname>Harley</lastname>
330 <email>james@example.org</email>
331 <department>Human Resources</department>
332 <salary>1000</salary>
333 </employee>
334 <employee id="4">
335 <firstname>fdf</firstname>
336 <lastname>Harley</lastname>
337 <email>james@example.org</email>
338 <department>Human Resources</department>
339 <salary>1000</salary>
340 </employee>
341</company>
342
343ReadXML.java
344 package mypackage;
345import javax.xml.parsers.DocumentBuilderFactory;
346import javax.xml.parsers.DocumentBuilder;
347import org.w3c.dom.Document;
348import org.w3c.dom.NodeList;
349import org.w3c.dom.Node;
350import org.w3c.dom.Element;
351import java.io.*;
352
353
354public class ReadXML {
355
356 public static final String xmlFilePath = "employee.xml";
357 public static void main(String argv[]) {
358 try {
359 File xmlFile = new File(xmlFilePath);
360 DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
361 DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
362 Document doc = documentBuilder.parse(xmlFile);
363 doc.getDocumentElement().normalize();
364 BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
365 String s = bufferRead.readLine();
366 System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
367 NodeList nodeList = doc.getElementsByTagName("employee");
368 System.out.println("===============================================================");
369 for (int itr = 0; itr < nodeList.getLength(); itr++) {
370
371 Node node = nodeList.item(itr);
372 if (node.getNodeType() == Node.ELEMENT_NODE) {
373 Element eElement = (Element) node;
374
375 String id= eElement.getAttribute("id");
376
377 if(id.equals(s))
378
379 {
380 System.out.println("First Name : "
381 + eElement.getElementsByTagName("firstname").item(0).getTextContent());
382 System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
383 System.out.println("Email : "+ eElement.getElementsByTagName("email").item(0).getTextContent());
384 System.out.println("Department : "+ eElement.getElementsByTagName("department").item(0).getTextContent());
385 System.out.println("Salary : "+ eElement.getElementsByTagName("salary").item(0).getTextContent());
386 break;
387
388 }
389 }
390 }
391 } catch (Exception e) {
392 e.printStackTrace();
393 }
394 }
395}
396
397OUTPUT
398run:
399232
400Root element :company
401===============================================================
402First Name : John
403Last Name : May
404Email : john@example.org
405Department : Logistics
406Salary : 400
407BUILD SUCCESSFUL (total time: 4 seconds)
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425RESULT:
426Thus an XML document which takes user Id as an input and returns the User details by taking the user information was successfully done and output was verified.
427
428EX-4
429SOCKET PROGRAMMING WITH JAVA
430Aim:
431To write programs in Java using sockets to implement the following:
432ï‚§ HTTP request
433
434ï‚§ FTP
435
436Program:
437i)Http Server
438/*
439 * To change this template, choose Tools | Templates
440 * and open the template in the editor.
441 */
442import java.net.*;
443import java.io.*;
444
445
446public class Grabber {
447
448 public static void main(String[] args) {
449
450 int port = 80;
451
452
453 try {
454 URL u = new URL("http://www.somehost.com/path/file.html");
455 if (u.getPort() != -1) port = u.getPort();
456 if (!(u.getProtocol().equalsIgnoreCase("http"))) {
457 System.err.println("Sorry. I only understand http.");
458
459 }
460 Socket s = new Socket(u.getHost(), port);
461 OutputStream theOutput = s.getOutputStream();
462 // no auto-flushing
463 PrintWriter pw = new PrintWriter(theOutput, false);
464 // native line endings are uncertain so add them manually
465 pw.print("GET " + u.getFile() + " HTTP/1.0\r\n");
466 pw.print("Accept: text/plain, text/html, text/*\r\n");
467 pw.print("\r\n");
468 pw.flush();
469 InputStream in = s.getInputStream();
470 InputStreamReader isr = new InputStreamReader(in);
471 BufferedReader br = new BufferedReader(isr);
472 int c;
473 while ((c = br.read()) != -1) {
474 System.out.print((char) c);
475 }
476 }
477 catch (MalformedURLException ex) {
478 System.err.println( " is not a valid URL");
479 }
480 catch (IOException ex) {
481 System.err.println(ex);
482 }
483
484 }
485
486 }
487
488
489OUTPUT
490run:
491HTTP/1.0 200 OK
492Cache-Control: no-cache
493Pragma: no-cache
494Content-Type: text/html; charset=utf-8
495Expires: -1
496Server: Microsoft-IIS/7.5
497X-AspNet-Version: 4.0.30319
498X-Powered-By: ASP.NET
499Date: Wed, 16 Sep 2015 06:22:02 GMT
500Content-Length: 26
501Age: 0
502
503<html><body></body></html>
504
505
506FTP SERVER
507package socketftp;
508import java.net.*;
509import java.io.*;
510import java.util.*;
511
512public class socketftps
513{
514 public static void main(String args[]) throws Exception
515 {
516 ServerSocket soc=new ServerSocket(5217);
517 System.out.println("FTP Server Started on Port Number 5217");
518 while(true)
519 {
520 System.out.println("Waiting for Connection ...");
521 transferfile t=new transferfile(soc.accept());
522
523 }
524 }
525}
526
527class transferfile extends Thread
528{
529 Socket ClientSoc;
530
531 DataInputStream din;
532 DataOutputStream dout;
533
534 transferfile(Socket soc)
535 {
536 try
537 {
538 ClientSoc=soc;
539 din=new DataInputStream(ClientSoc.getInputStream());
540 dout=new DataOutputStream(ClientSoc.getOutputStream());
541 System.out.println("FTP Client Connected ...");
542 start();
543
544 }
545 catch(Exception ex)
546 {
547 }
548 }
549 void SendFile() throws Exception
550 {
551 String filename=din.readUTF();
552 File f=new File(filename);
553 if(!f.exists())
554 {
555 dout.writeUTF("File Not Found");
556 return;
557 }
558 else
559 {
560 dout.writeUTF("READY");
561 FileInputStream fin=new FileInputStream(f);
562 int ch;
563 do
564 {
565 ch=fin.read();
566 dout.writeUTF(String.valueOf(ch));
567 }
568 while(ch!=-1);
569 fin.close();
570 dout.writeUTF("File Receive Successfully");
571 }
572 }
573
574 void ReceiveFile() throws Exception
575 {
576 String filename=din.readUTF();
577 if(filename.compareTo("File not found")==0)
578 {
579 return;
580 }
581 File f=new File(filename);
582 String option;
583
584 if(f.exists())
585 {
586 dout.writeUTF("File Already Exists");
587 option=din.readUTF();
588 }
589 else
590 {
591 dout.writeUTF("SendFile");
592 option="Y";
593 }
594
595 if(option.compareTo("Y")==0)
596 {
597 FileOutputStream fout=new FileOutputStream(f);
598 int ch;
599 String temp;
600 do
601 {
602 temp=din.readUTF();
603 ch=Integer.parseInt(temp);
604 if(ch!=-1)
605 {
606 fout.write(ch);
607 }
608 }while(ch!=-1);
609 fout.close();
610 dout.writeUTF("File Send Successfully");
611 }
612 else
613 {
614 return;
615 }
616
617 }
618
619
620 public void run()
621 {
622 while(true)
623 {
624 try
625 {
626 System.out.println("Waiting for Command ...");
627 String Command=din.readUTF();
628 if(Command.compareTo("GET")==0)
629 {
630 System.out.println("\tGET Command Received ...");
631 SendFile();
632 continue;
633 }
634 else if(Command.compareTo("SEND")==0)
635 {
636 System.out.println("\tSEND Command Receiced ...");
637 ReceiveFile();
638 continue;
639 }
640 else if(Command.compareTo("DISCONNECT")==0)
641 {
642 System.out.println("\tDisconnect Command Received ...");
643 System.exit(1);
644 }
645 }
646 catch(Exception ex)
647 {
648 }
649 }
650 }
651}
652FTP CLIENT
653package Socketftp;
654import java.net.*;
655import java.io.*;
656import java.util.*;
657
658
659class socketftp
660{
661 public static void main(String args[]) throws Exception
662 {
663 Socket soc=new Socket("127.0.0.1",5217);
664 transferfileClient t=new transferfileClient(soc);
665 t.displayMenu();
666
667 }
668}
669class transferfileClient
670{
671 Socket ClientSoc;
672
673 DataInputStream din;
674 DataOutputStream dout;
675 BufferedReader br;
676 transferfileClient(Socket soc)
677 {
678 try
679 {
680 ClientSoc=soc;
681 din=new DataInputStream(ClientSoc.getInputStream());
682 dout=new DataOutputStream(ClientSoc.getOutputStream());
683 br=new BufferedReader(new InputStreamReader(System.in));
684 }
685 catch(Exception ex)
686 {
687 }
688 }
689 void SendFile() throws Exception
690 {
691
692 String filename;
693 System.out.print("Enter File Name :");
694 filename=br.readLine();
695
696 File f=new File(filename);
697 if(!f.exists())
698 {
699 System.out.println("File not Exists...");
700 dout.writeUTF("File not found");
701 return;
702 }
703
704 dout.writeUTF(filename);
705
706 String msgFromServer=din.readUTF();
707 if(msgFromServer.compareTo("File Already Exists")==0)
708 {
709 String Option;
710 System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
711 Option=br.readLine();
712 if(Option=="Y")
713 {
714 dout.writeUTF("Y");
715 }
716 else
717 {
718 dout.writeUTF("N");
719 return;
720 }
721 }
722
723 System.out.println("Sending File ...");
724 FileInputStream fin=new FileInputStream(f);
725 int ch;
726 do
727 {
728 ch=fin.read();
729 dout.writeUTF(String.valueOf(ch));
730 }
731 while(ch!=-1);
732 fin.close();
733 System.out.println(din.readUTF());
734
735 }
736
737 void ReceiveFile() throws Exception
738 {
739 String fileName;
740 System.out.print("Enter File Name :");
741 fileName=br.readLine();
742 dout.writeUTF(fileName);
743 String msgFromServer=din.readUTF();
744
745 if(msgFromServer.compareTo("File Not Found")==0)
746 {
747 System.out.println("File not found on Server ...");
748 return;
749 }
750 else if(msgFromServer.compareTo("READY")==0)
751 {
752 System.out.println("Receiving File ...");
753 File f=new File(fileName);
754 if(f.exists())
755 {
756 String Option;
757 System.out.println("File Already Exists. Want to OverWrite (Y/N) ?");
758 Option=br.readLine();
759 if(Option=="N")
760 {
761 dout.flush();
762 return;
763 }
764 }
765 FileOutputStream fout=new FileOutputStream(f);
766 int ch;
767 String temp;
768 do
769 {
770 temp=din.readUTF();
771 ch=Integer.parseInt(temp);
772 if(ch!=-1)
773 {
774 fout.write(ch);
775 }
776 }while(ch!=-1);
777 fout.close();
778 System.out.println(din.readUTF());
779
780 }
781
782
783 }
784
785 public void displayMenu() throws Exception
786 {
787 while(true)
788 {
789 System.out.println("[ MENU ]");
790 System.out.println("1. Send File");
791 System.out.println("2. Receive File");
792 System.out.println("3. Exit");
793 System.out.print("\nEnter Choice :");
794 int choice;
795 choice=Integer.parseInt(br.readLine());
796 if(choice==1)
797 {
798 dout.writeUTF("SEND");
799 SendFile();
800 }
801 else if(choice==2)
802 {
803 dout.writeUTF("GET");
804 ReceiveFile();
805 }
806 else
807 {
808 dout.writeUTF("DISCONNECT");
809 System.exit(1);
810 }
811 }
812 }
813}
814
815
816OUTPUT
817run:
818FTP Server Started on Port Number 5217
819Waiting for Connection ...
820FTP Client Connected ...
821Waiting for Connection ...
822Waiting for Command ...
823 SEND Command Receiced ...
824Waiting for Command ...
825 SEND Command Receiced ...
826Waiting for Command ...
827 SEND Command Receiced ...
828Waiting for Command ...
829 SEND Command Receiced ...
830Waiting for Command ...
831 GET Command Received ...
832Waiting for Command ...
833
834Run:Client
835Enter Choice :1
836Enter File Name :new.txt
837File Already Exists. Want to OverWrite (Y/N) ?
838n
839[ MENU ]
8401. Send File
8412. Receive File
8423. Exit
843
844Enter Choice :2
845Enter File Name :new.txt
846Receiving File ...
847File Already Exists. Want to OverWrite (Y/N) ?
848
849
850RESULT:
851Thus the programs in Java using sockets to implement the following:
852ï‚§ HTTP request
853
854ï‚§ FTP
855was successfully done and correct was verified.
856
857
858
859
860
861
862
863
864
865EX-5
866SIMPLE CHAT APPLICATION WITH UDP
867Aim:
868To write a program in Java for creating simple chat application with datagram sockets and datagram packets.
869
870Program
871UDPserver.java
872
873import java.io.*;
874import java.net.*;
875
876class UDPServer
877{
878 public static void main(String args[]) throws Exception
879 {
880 DatagramSocket serverSocket = new DatagramSocket(9876);
881 byte[] receiveData = new byte[1024];
882 byte[] sendData = new byte[1024];
883 while(true)
884 {
885 DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
886 serverSocket.receive(receivePacket);
887 String sentence = new String( receivePacket.getData());
888 System.out.println("RECEIVED: " + sentence);
889 InetAddress IPAddress = receivePacket.getAddress();
890 int port = receivePacket.getPort();
891 String capitalizedSentence = sentence.toUpperCase();
892 sendData = capitalizedSentence.getBytes();
893 DatagramPacket sendPacket =
894 new DatagramPacket(sendData, sendData.length, IPAddress, port);
895 serverSocket.send(sendPacket);
896 }
897 }
898}
899OUTPUT
900CLIENT
901run:
902gfhj
903FROM SERVER:GFHJ
904SERVER
905run:
906gfhj
907nhgnghjgh
908RECEIVED: gfhj
909
910
911
912
913
914
915
916
917RESULT: Thus a program in Java for creating simple chat application with datagram sockets and datagram packet was successfully implemented and output was verified.
918
919
920
921EX-6
922SERVLETS FROM HTML
923Aim:
924To write a program to invoke servlets from HTML forms.
925Program:
926<html>
927<body>
928<form action="HelloForm" method="GET">
929First Name: <input type="text" name="first_name">
930<br />
931Last Name: <input type="text" name="last_name" />
932<input type="submit" value="Submit" />
933</form>
934</body>
935</html>
936HelloForm.java
937import java.io.*;
938import javax.servlet.*;
939import javax.servlet.http.*;
940
941// Extend HttpServlet class
942public class HelloForm extends HttpServlet {
943
944 // Method to handle GET method request.
945 public void doGet(HttpServletRequest request,
946 HttpServletResponse response)
947 throws ServletException, IOException
948 {
949 // Set response content type
950 response.setContentType("text/html");
951
952 PrintWriter out = response.getWriter();
953 String title = "Using GET Method to Read Form Data";
954 String docType =
955 "<!doctype html public \"-//w3c//dtd html 4.0 " +
956 "transitional//en\">\n";
957 out.println(docType +
958 "<html>\n" +
959 "<head><title>" + title + "</title></head>\n" +
960 "<body bgcolor=\"#f0f0f0\">\n" +
961 "<h1 align=\"center\">" + title + "</h1>\n" +
962 "<ul>\n" +
963 " <li><b>First Name</b>: "
964 + request.getParameter("first_name") + "\n" +
965 " <li><b>Last Name</b>: "
966 + request.getParameter("last_name") + "\n" +
967 "</ul>\n" +
968 "</body></html>");
969 }
970 // Method to handle POST method request.
971 public void doPost(HttpServletRequest request,
972 HttpServletResponse response)
973 throws ServletException, IOException {
974 doGet(request, response);
975 }
976}
977
978
979
980
981
982RESULT: Thus the program to invoke servlets from HTML forms was successfully implemented and output was verified.
983EX 7
984ON-LINE EXAMINATION WITH JDBC
985
986Aim: To write a program in Java to create three-tier applications using servlets for conducting on-line examination for displaying student mark list. Assume that student information is available in a database which has been stored in a database server.
987.
988Program:
989
990Main.jsp
991<%@page language="java" import="java.sql.*"%>
992<%@page import="java.io.*" %>
993<%@page import="java.util.*" %>
994<%
995String SeatNum,Name;
996String ans1,ans2,ans3,ans4,ans5;
997int a1,a2,a3,a4,a5;
998a1=a2=a3=a4=a5=0;
999Connection connect=null;
1000Statement stmt=null;
1001ResultSet rs=null;
1002Class.forName("oracle.jdbc.driver.OracleDriver");
1003connect = DriverManager.getConnection("jdbc:oracle:thin:@172.16.34.183:1521:csedb","exam130","exam130");
1004SeatNum = request.getParameter("Seat_no");
1005 Name = request.getParameter("Name");
1006 ans1 =request.getParameter("group1");
1007 if(ans1.equals("True"))
1008 a1=2;
1009 else
1010 a1=0;
1011 ans2 = request.getParameter("group2");
1012 if(ans2.equals("True"))
1013 a2=0;
1014 else
1015 a2=2;
1016 ans3 = request.getParameter("group3");
1017 if(ans3.equals("True"))
1018 a3=0;
1019 else
1020 a3=2;
1021 ans4 = request.getParameter("group4");
1022 if(ans4.equals("True"))
1023 a4=2;
1024 else
1025 a4=0;
1026 ans5 = request.getParameter("group5");
1027 if(ans5.equals("True"))
1028 a5=0;
1029 else
1030 a5=2;
1031 int Total=a1+a2+a3+a4+a5;
1032 stmt = connect.createStatement();
1033 String query = "INSERT INTO Studentable (" + "Seat_no,Name,Marks" + ") VALUES ('" +SeatNum + "', '" + Name + "', '"+Total+ "')";
1034 stmt.executeQuery(query);
1035 out.println("inserted");
1036 stmt.close();
1037 connect.close();
1038%>
1039
1040Main.html
1041<!DOCTYPE html>
1042<html>
1043 <head>
1044 <title>Online Examination</title>
1045 </head>
1046 <body bgcolor="pink">
1047 <center>
1048 <h1>ONLINE EXAMINATION</h1>
1049 </center>
1050 <hr/>
1051 <form action="main.jsp" method="post">
1052 <table>
1053 <tr>
1054 <td><h3>Seat Number:</h3></td>
1055 <td><input type="text" name="Seat_no"></td>
1056 </tr>
1057 <tr>
1058 <td><h3>Name:</h3></td>
1059 <td><input type="text" name="Name" size="50"></td>
1060 </tr>
1061 <tr>
1062 <td><b>Total Marks:10(Each question carries equal marks) </b></td>
1063 <td></td><td></td><td></td><td><b>Time: 15 Min.</b></td>
1064 </tr>
1065 </table>
1066 <hr/>
1067 <b><h2>1. Apache is an open source web server.</h2></b><br/>
1068 <input type="radio" name="group1" value="True"/>True
1069 <input type="radio" name="group1" value="False"/>False<br>
1070 <br/>
1071 <b><h2>2. In Modern PC there is no cache memory.</h2></b><br/>
1072 <input type="radio" name="group2" value="True">True
1073 <input type="radio" name="group2" value="False">False<br>
1074 <br/>
1075 <b><h2>3. Tim-Berner Lee is the originator of Java.</h2></b><br/>
1076 <input type="radio" name="group3" value="True"/>True
1077 <input type="radio" name="group3" value="False"/>False<br>
1078 <br/>
1079 <b><h2>4.JPG is not a video file extension.</h2></b><br/>
1080 <input type="radio" name="group4" value="True">True
1081 <input type="radio" name="group4" value="False">False<br>
1082 <br/>
1083 <b><h2>5. HTTP is a statefull protocol.</h2></b><br/>
1084 <input type="radio" name="group5" value="True">True
1085 <input type="radio" name="group5" value="False">False<br>
1086 <br/>
1087
1088 <center>
1089 <input type = "Submit" value="Submit"/>
1090 <input type = "reset" value="Clear"/><br><br>
1091 </center>
1092 </form>
1093 </body>
1094</html>
1095
1096
1097
1098Main.jsp
1099Inserted
1100
1101
1102RESULT: : Thus the program in Java to create three-tier applications using servlets for conducting on-line examination for displaying student mark list was successfully executed.
1103
1104EX-8
1105LOCK SERVLET TO A PARTICULAR SERVER IP
1106
1107Aim: To write a program to lock servlet itself to a particular server IP address and port number. It requires an init parameter key that is appropriate for its servlet IP address and port before it
1108unlocks itself and handles a request.
1109
1110Program
1111package serv;
1112import java.io.*;
1113import java.net.*;
1114import java.util.*;
1115import javax.servlet.*;
1116
1117public class lock extends GenericServlet {
1118
1119 // This servlet has no class or instance variables
1120 // associated with the locking, so as to simplify
1121 // synchronization issues.
1122
1123 @Override
1124 public void service(ServletRequest req, ServletResponse res)
1125 throws ServletException, IOException {
1126 res.setContentType("text/plain");
1127 PrintWriter out = res.getWriter();
1128
1129 // The piracy check shouldn't be done in init
1130 // because name/port are part of request.
1131
1132 String key = getServletContext().getInitParameter("rmiport");
1133 String host = req.getServerName();
1134 int port = req.getServerPort();
1135
1136 // Check if the init parameter "key" unlocks this server.
1137 if (! keyFitsServer(key, host, port)) {
1138 // Explain, condemn, threaten, etc.
1139 out.println("Pirated!");
1140 }
1141 else {
1142 // Give 'em the goods
1143 out.println("Valid");
1144 // etc...
1145 }
1146 }
1147
1148 // This method contains the algorithm used to match a key with
1149 // a server host and port. This example implementation is extremely
1150 // weak and should not be used by commercial sites.
1151 //
1152 private boolean keyFitsServer(String key, String host, int port) {
1153 System.out.println("key is "+key+ host+port);
1154 if (key == null) return false;
1155
1156 long numericKey = 0;
1157 try {
1158 numericKey = Long.parseLong(key);
1159 System.out.println("key is inside function"+numericKey);
1160
1161 }
1162 catch (NumberFormatException e) {
1163 return false;
1164 }
1165
1166 // The key must be a 64-bit number equal to the logical not (~)
1167 // of the 32-bit IP address concatenated with the 32-bit port number.
1168
1169 byte hostIP[];
1170 try {
1171 hostIP = InetAddress.getByName(host).getAddress();
1172 }
1173 catch (UnknownHostException e) {
1174 return false;
1175 }
1176
1177 // Get the 32-bit IP address
1178 long servercode = 0;
1179 for (int i = 0; i < 4; i++) {
1180 servercode <<= 8;
1181 servercode |= hostIP[i];
1182 }
1183
1184 // Concatentate the 32-bit port number
1185 servercode <<= 32;
1186 servercode |= port;
1187
1188 // Logical not
1189 long accesscode = ~numericKey;
1190
1191 // The moment of truth: Does the key match?
1192 return (servercode == accesscode);
1193 }
1194}
1195
1196
1197
1198UNLOCK A SERVLET
1199
1200
1201
1202
1203RESULT:
1204Thus the program to lock servlet itself to a particular server IP address and port number
1205Was successfully executed and output was verified.
1206EX-9
1207SESSION TRACKING WITH SERVLETS
1208
1209Aim: To write programs to implement session tracking using hidden form fields and for hit count using java.
1210a)Session tracking using hidden form fields
1211index.html
1212<form action="servlet1">
1213Name:<input type="text" name="userName"/><br/>
1214<input type="submit" value="go"/>
1215</form>
1216FirstServlet.java
1217import java.io.*;
1218import javax.servlet.*;
1219import javax.servlet.http.*;
1220
1221public class FirstServlet extends HttpServlet {
1222public void doGet(HttpServletRequest request, HttpServletResponse response){
1223 try{
1224
1225 response.setContentType("text/html");
1226 PrintWriter out = response.getWriter();
1227
1228 String n=request.getParameter("userName");
1229 out.print("Welcome "+n);
1230
1231 //creating form that have invisible textfield
1232 out.print("<form action='servlet2'>");
1233 out.print("<input type='hidden' name='uname' value='"+n+"'>");
1234 out.print("<input type='submit' value='go'>");
1235 out.print("</form>");
1236 out.close();
1237
1238 }catch(Exception e){System.out.println(e);}
1239 }
1240
1241}
1242
1243SecondServlet.java
1244
1245import java.io.*;
1246import javax.servlet.*;
1247import javax.servlet.http.*;
1248public class SecondServlet extends HttpServlet {
1249public void doGet(HttpServletRequest request, HttpServletResponse response)
1250 try{
1251 response.setContentType("text/html");
1252 PrintWriter out = response.getWriter();
1253
1254 //Getting the value from the hidden field
1255 String n=request.getParameter("uname");
1256 out.print("Hello "+n);
1257
1258 out.close();
1259 }catch(Exception e){System.out.println(e);}
1260 }
1261}
1262OUTPUT
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275b)Session Tracking for Hit Count
1276
1277HitCount.html
1278<body>
1279<h3>Hit Count Example with HttpSession</h3>
1280<form method="get" action="http://localhost:8080/w3schools.com"> Click for Hit Count <input type="submit" value="GET HITS">
1281 </form>
1282</body>
1283
1284HitCount Servlet
1285import java.io.*;
1286import javax.servlet.*;
1287 import javax.servlet.http.*;
1288import java.util.*;
1289 public class HitCount extends HttpServlet {
1290public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
1291 {
1292res.setContentType("text/html") ;
1293PrintWriter out = res.getWriter( );
1294 HttpSession session = req.getSession(); // this is how to get a session object
1295 Integer hitNumber = (Integer) session.getAttribute("rama"); // retrieving value from session object if(hitNumber == null) { hitNumber = new Integer(1);
1296} else
1297{
1298 hitNumber = new Integer(hitNumber.intValue()+1) ;
1299 } session.setAttribute("rama", hitNumber); // storing the value with session object
1300 out.println("Your Session ID: " + session.getId()); // never changes in the whole session out.println("<br>Session Creation Time: " + new Date(session.getCreationTime())); // never changes in the whole session
1301 out.println("<br>Time of Last Access: " + new Date(session.getLastAccessedTime())); // changes for every hit
1302out.println("<br>Latest Hit Count: " + hitNumber); // increments by 1 for every hit
1303 }
1304}
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319OUTPUT
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331RESULT: Thus the programs to implement session tracking using hidden form fields and for hit count using java was successfully executed and output was verified.
1332
1333EX-10
1334STATIC WEBPAGES INTO DYNAMIC WEB PAGES
1335
1336Aim: To Convert the static webpages of programs 1&2 into dynamic web pages using servlets (or JSP) and cookies. Hint: Users information (user id, password, credit card number) would be stored in web.xml. Each user should have a separate Shopping Cart.
1337
1338PROCEDURE:
13391) Create your own directory undertomcat/webapps(e.g.tr1)
13402) Copy the htmlfiles in tr1
13413) Copy the jsp files also into tr1
13424) Starttomcat give the following command
1343Catalina.batrun
1344Atinstallâ€dir/bin
13455)Give url as http://localhost:8081/tr1/Order.html
1346
1347Order.html:
1348<html>
1349 <head>
1350 <title>Shopping Cart</title>
1351 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
1352 </head>
1353 <body bgcolor="cyan"><br/><br/><br/>
1354 <div align="center">
1355 <form action="order.jsp" method="post">
1356 <table>
1357 <tr>
1358 <td>LOGIN ID:</td>
1359 <td><input type="text" name="id" value=""/></td>
1360 </tr>
1361 <tr>
1362 <td>PASSWORD:</td>
1363 <td><input type="password" name="pwd" value=""/></td>
1364 </tr>
1365 </table>
1366 <center>
1367 <input type="submit" value="Submit"/>
1368 <input type="reset" value="Clear"/><br/>
1369 </center>
1370 </form>
1371 </div>
1372 </body>
1373</html>
1374
1375Order.jsp:
1376<%@page import="java.sql.*"%>
1377<%@page import="java.io.*"%>
1378<!DOCTYPE html>
1379<%
1380 out.println("<html><body bgcolor=\"pink\">");
1381 String uid=request.getParameter("id");
1382 String pass=request.getParameter("pwd");
1383 Connection con=null;
1384 Statement st=null;
1385 ResultSet exe=null;
1386 Class.forName("oracle.jdbc.driver.OracleDriver");
1387 con=DriverManager.getConnection("jdbc:oracle:thin:@172.16.34.183:1521:csedb","system","manager");
1388 st=con.createStatement();
1389 String sql="select id,pwd from loginoo2 where id='"+uid+"' and pwd='"+pass+"'";
1390 ResultSet rs=st.executeQuery(sql);
1391
1392 if(rs.next()){
1393 out.println("SORRY INVALID CREDENTIALS!! TRY AGAIN<br><br>");
1394 out.println("Click <a href=\"ordersc.html\">HERE</a> to Retry");
1395 }
1396 else{
1397
1398 out.println("VALIDATION SUCCESSFUL!!<br><br>");
1399 out.println("Click <a href=\"ordersc2.html\">HERE</a> to proceed");
1400 }
1401 out.println("</body></html>");
1402%>
1403
1404Order2.html:
1405<html>
1406 <head>
1407 <title></title>
1408 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
1409 </head>
1410 <body bgcolor="cyan"><br/><br/><br/>
1411 <div>
1412 <form action="ordersc2.jsp" method="post">
1413 <table>
1414 <tr>
1415 <td>BOOK TITLE:</td>
1416 <td><input type="text" name="title" size="50" value=""/></td>
1417 </tr>
1418 <tr>
1419 <td>NO. OF BOOKS:</td>
1420 <td><input type="text" name="cnt" value=""/></td>
1421 </tr>
1422 <tr>
1423 <td>DATE:</td>
1424 <td><input type="text" name="date1" value=""/></td>
1425 </tr>
1426 <tr>
1427 <td>CREDIT CARD NO:</td>
1428 <td><input type="password" name="cno" value=""/></td>
1429 </tr>
1430 </table>
1431 <center>
1432 <input type="submit" value="OK"/>
1433 <input type="reset" value="Clear"/><br/>
1434 </center>
1435 </form>
1436 </div>
1437 </body>
1438</html>
1439
1440Order2.jsp:
1441<%@page import="java.sql.*"%>
1442<%@page import="java.io.*"%>
1443<!DOCTYPE html>
1444<%
1445 out.println("<html><body bgcolor=\"pink\">");
1446 String title1=request.getParameter("title");
1447 String ct=request.getParameter("cnt");
1448 String date2=request.getParameter("date1");
1449 String crno=request.getParameter("cno");
1450 int count=Integer.parseInt(ct);
1451 Class.forName("oracle.jdbc.driver.OracleDriver");
1452 Connection con=DriverManager.getConnection("jdbc:oracle:thin:@172.16.34.183:1521:csedb","exam130","exam130");
1453 int amt,x;
1454
1455 Statement st=con.createStatement();
1456 String s="select cost from bookoo1 where title='"+title1+"'";
1457 ResultSet rs1=st.executeQuery(s);
1458 int flag=0;
1459 while(rs1.next()){
1460 flag=1;
1461 x=Integer.parseInt(rs1.getString(1));
1462 amt=count*x;
1463 out.println("AMOUNT:"+amt+"<br><br><br><br>");
1464 Statement st1=con.createStatement();
1465 st1.executeUpdate("insert into detailsoo1('"+title1+"',"+amt+",'"+date2+"','"+crno+"')");
1466 out.println("YOUR ORDER HAS BEEN TAKEN<br>");
1467 }
1468 if(flag==0){
1469 out.println("SORRY BOOK NOT PRESENT!! TRY AGAIN<br><br>");
1470 out.println("Click <a href=\"ordersc2.html\">HERE</a> to Retry");
1471 }
1472 out.println("</body></html>");
1473%>
1474
1475OUTPUT
1476
1477
1478
1479
1480
1481
1482
1483RESULT : Thus the program to Convert the static webpages of programs 1&2 into dynamic web pages using servlets (or JSP) and cookies was successfully implemented and output was verified.
1484
1485EX-11
1486 JSP Struts Framework
1487
1488Aim:
1489To implement a simple program using following frameworks a. JSP Struts Framework
1490
1491Procedure:
1492Setting Up a Struts Application
1493In the IDE, a Struts application is nothing more than a normal web application accompanied by the Struts libraries and configuration files. You create a Struts application in the same way as you create any other web application in the IDE - using the New Web Application wizard, with the additional step of indicating that you want the Struts libraries and configuration files to be included in your application.
14941. Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu. Select Java Web in the list of Categories and then select Web Application in the list of Projects. Click Next.
14952. In the Name and Location panel, enter MyStrutsApp for Project Name and click Next.
14963. In the Server and Settings panel, select the server to which you want to deploy your application. Only servers that are registered with the IDE are listed. (To register a server, click Add next to the Server drop-down list.) Also, note that the Context Path to your deployed application becomes /MyStrutsApp. Click Next.
14974. Select Struts in the Frameworks panel.
1498
1499For purposes of this tutorial, do not change any of the configuration values in the lower region of this panel. The wizard displays the following configuration options.
1500• Action Servlet Name: The name of the Struts action servlet used in the application. The web.xml deployment descriptor contains an entry for the action servlet and specifies the appropriate Struts-specific parameters, such as the path to the servlet class within the Struts library and to the struts-config.xmlconfiguration file within the application.
1501• Action URL Pattern: Specifies the patterns of incoming requests which are mapped to the Struts action controller. This generates a mapping entry in the deployment descriptor. By default, only the *.do pattern is mapped.
1502• Application Resource: Lets you specify the resource bundle which will be used in the struts-config.xml file for localizing messages. By default, this iscom.myapp.struts.ApplicationResource.
1503• Add Struts TLDs: Lets you generate tag library descriptors for the Struts tag libraries. A tag library descriptor is an XML document which contains additional information about the entire tag library as well as each individual tag. In general this is not necessary, because you can refer to on-line URIs rather than local TLD files.
1504 Click Finish. The IDE creates the project folder in your file system. As with any web application in the IDE, the project folder contains all of your sources and the IDE's project metadata, such as the Ant build script. However, your web application in addition has all of the Struts libraries on its classpath. Not only are they on the application's classpath, but they are included in the project and will be packaged with it later when you build the project.
1505The project opens in the IDE. The Projects window is the main entry point to your project sources. It shows a logical view of important project contents. For example, if you expand several nodes within the new project, it may appear as follows:
1506
1507Note: Use the Files window (Window > Files) to see all of your project contents in a directory-based view.
1508The Struts-specific configuration files, as well as the application's deployment descriptor, are conveniently placed within the Configuration Files folder. Open the deployment descriptor (double-click the web.xml file node to have it display in the Source Editor). In order to handle Struts processing, a mapping is provided for the Struts controller servlet.
1509<servlet>
1510 <servlet-name>action</servlet-name>
1511 <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
1512 <init-param>
1513 <param-name>config</param-name>
1514 <param-value>/WEB-INF/struts-config.xml</param-value>
1515 </init-param>
1516 <init-param>
1517 <param-name>debug</param-name>
1518 <param-value>2</param-value>
1519 </init-param>
1520 <init-param>
1521 <param-name>detail</param-name>
1522 <param-value>2</param-value>
1523 </init-param>
1524 <load-on-startup>2</load-on-startup>
1525</servlet>
1526<servlet-mapping>
1527 <servlet-name>action</servlet-name>
1528 <url-pattern>*.do</url-pattern>
1529</servlet-mapping>
1530Above, the Struts controller servlet is named action and is defined in the Struts library (org.apache.struts.action.ActionServlet). It is set to handle all requests that satisfy the *.do mapping. In addition, initialization parameters for the servlet are specified by means of the struts-config.xml file, also contained in the WEB-INFfolder.
1531Creating JSP Pages
1532Begin by creating two JSP pages for the application. The first displays a form. The second is the view returned when login is successful.
1533• Creating a Login Page
1534• Creating a Success Page
1535Creating a Login Page
15361. Right-click the MyStrutsApp project node, choose New > JSP, and name the new file login. Click Finish. The login.jsp file opens in the Source Editor.
15372. In the Source Editor, change the content of both the <title> and <h1> tags (or <h2> tags, depending on the IDE version you are using) to Login Form.
15383. Add the following two taglib directives to the top of the file:
15394. <%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
1540<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
1541Many web applications use JSP pages for views in the MVC paradigm, so Struts provides custom tag libraries which facilitate interaction with HTML forms. These can be easily applied to a JSP file using the IDE's support for code completion. When you type in the Source Editor, the IDE provides you with code completion for Struts tags, as well as the Struts Javadoc. You can also invoke code completion manually by pressing Ctrl-Space:
1542
1543The bean taglib provides you with numerous tags that are helpful when associating a form bean (i.e., an ActionForm bean) with the data collected from the form. The html taglib offers an interface between the view and other components necessary to a web application. For example, below you replace common html form tags with Struts' <html:form> tags. One benefit this provides is that it causes the server to locate or create a bean object that corresponds to the value provided forhtml:form's action element.
15445. Below the <h1> (or <h2>) tags, add the following:
15456. <html:form action="/login">
15467.
15478. <html:submit value="Login" />
15489.
1549</html:form>
1550Whenever you finish typing in the Source Editor, you can tidy up the code by right-clicking and choosing Format (Alt-Shift-F).
155110. In the Palette (Window > Palette) in the right region of the IDE, drag a Table item from the HTML category to a point just above the <html:submit value="Login" /> line. The Insert Table dialog box displays. Set the rows to 3, columns to 2, and leave all other settings at 0. Later in the tutorial, you will attach a stylesheet to affect the table display.
1552
1553Click OK, then optionally reformat the code (Alt-Shift-F). The form in login.jsp now looks as follows:
1554<html:form action="/login">
1555 <table border="0">
1556 <thead>
1557 <tr>
1558 <th></th>
1559 <th></th>
1560 </tr>
1561 </thead>
1562 <tbody>
1563 <tr>
1564 <td></td>
1565 <td></td>
1566 </tr>
1567 <tr>
1568 <td></td>
1569 <td></td>
1570 </tr>
1571 <tr>
1572 <td></td>
1573 <td></td>
1574 </tr>
1575 </tbody>
1576 </table>
1577
1578 <html:submit value="Login" />
1579
1580</html:form>
1581Note: You can safely delete the <thead> table row, as it is not used in this tutorial.
1582In the first table row, enter the following (changes in bold):
1583<tr>
1584 <td>Enter your name:</td>
1585 <td><html:text property="name" /></td>
1586</tr>
1587In the second table row, enter the following (changes in bold):
1588<tr>
1589 <td>Enter your email:</td>
1590 <td><html:text property="email" /></td>
1591</tr>
1592The html:text element enables you to match the input fields from the form with properties in the form bean that will be created in the next step. So for example, the value of property must match a field declared in the form bean associated with this form.
1593Move the <html:submit value="Login" /> element into the second column of the third table row, so that the third table row appears as follows (changes in bold):
1594<tr>
1595 <td></td>
1596 <td><html:submit value="Login" /></td>
1597</tr>
1598At this stage, your login form should look as follows:
1599<html:form action="/login">
1600 <table border="0">
1601 <tbody>
1602 <tr>
1603 <td>Enter your name:</td>
1604 <td><html:text property="name" /></td>
1605 </tr>
1606 <tr>
1607 <td>Enter your email:</td>
1608 <td><html:text property="email" /></td>
1609 </tr>
1610 <tr>
1611 <td></td>
1612 <td><html:submit value="Login" /></td>
1613 </tr>
1614 </tbody>
1615 </table>
1616</html:form>
1617Creating a Success Page
16181. Right-click the MyStrutsApp project node, choose New > JSP, and name the new file success. In the Folder field, click the adjacent Browse button and selectWEB-INF from the dialog that displays. Click Select Folder to enter WEB-INF in the Folder field. Any files contained in the WEB-INF folder are not directly accessible to client requests. In order for success.jsp to be properly displayed, it must contain processed data. Click Finish.
16192. In the Source Editor, change the content of the newly created page to the following:
1620<head>
1621 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
1622 <title>Login Success</title>
1623</head>
1624<body>
1625 <h1>Congratulations!</h1>
1626
1627 <p>You have successfully logged in.</p>
1628
1629 <p>Your name is: .</p>
1630
1631 <p>Your email address is: .</p>
1632</body>
1633Add a bean taglib directive to the top of the file:
1634<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
1635Add the following <bean:write> tags (changes in bold):
1636<p>Your name is: <bean:write name="LoginForm" property="name" />.</p>
1637
1638<p>Your email address is: <bean:write name="LoginForm" property="email" />.</p>
1639By employing the <bean:write> tags, you make use of the bean taglib to locate the ActionForm bean you are about to create, and display the user data saved for name and email.
1640Creating an ActionForm Bean
1641A Struts ActionForm bean is used to persist data between requests. For example, if a user submits a form, the data is temporarily stored in the form bean so that it can either be redisplayed in the form page (if the data is in an invalid format or if login fails) or displayed in a login success page (if data passes validation).
16421. Right-click the MyStrutsApp project node and choose New > Other. Under Categories choose Struts, then under File Types choose Struts ActionForm Bean. Click Next.
16432. Type in LoginForm for the Class Name. Then select com.myapp.struts in the Package drop-down list and click Finish.
1644The IDE creates the LoginForm bean and opens it in the Source Editor. By default, the IDE provides it with a String called name and an int called number. Both fields have accessor methods defined for them. Also, the IDE adds a bean declaration to the struts-config.xml file. If you open the struts-config.xml file in the Source Editor, you can see the following declaration, which was added by the wizard:
1645<form-beans>
1646 <form-bean name="LoginForm" type="com.myapp.struts.LoginForm" />
1647</form-beans>
1648The IDE provides navigation support in the struts-config.xml file. Hold down the Ctrl key and hover your mouse over the LoginForm bean's fully qualified class name. The name becomes a link, enabling you to navigate directly to the class in the Source Editor:
1649
16503. In the LoginForm bean in the Source Editor, create fields and accompanying accessor methods that correspond to the name and email text input fields that you created in login.jsp. Because name has already been created in the LoginForm skeleton, you only need to implement email.
1651Add the following declaration beneath name (changes in bold):
1652private String name;
1653private String email;
1654To create accessor methods, place your cursor on email and press Alt-Insert.
1655
1656Select Getter and Setter, then in the dialog that displays, select email : String and click Generate. Accessor methods are generated for the email field.
1657Note: You can delete the declaration and accessor methods for number, as it is not used in this tutorial.
1658Creating an Action Class
1659The Action class contains the business logic in the application. When form data is received, it is the execute method of an Action object that processes the data and determines which view to forward the processed data to. Because the Action class is integral to the Struts framework, NetBeans IDE provides you with a wizard.
16601. In the Projects window, right-click the MyStrutsApp project node and choose New > Other. From the Struts category choose Struts Action and click Next.
16612. In the Name and Location panel, change the name to LoginAction.
16623. Select com.myapp.struts in the Package drop-down list.Type /login in Action Path. This value must match the value you set for the action attribute of the <html:form> tags in login.jsp. Make sure settings appear as n the screenshot below, then click Next.
1663
16644. In the third step of the wizard, you are given the opportunity to associate the Action class with a form bean. Notice that the LoginForm bean you previously created is listed as an option for ActionForm Bean Name. Make the following adjustments to the panel:
1665• Delete the forward slash for the Input Resource field
1666• Set Scope to Request (Session is the default scope setting in Struts.)
1667• Deselect the Validate ActionForm Bean option
1668Click Finish. The LoginAction class is generated, and the file opens in the Source Editor. Also note that the following action entry is added to the struts-config.xml file:
1669<action-mappings>
1670 <action name="LoginForm" path="/login" scope="request" type="com.myapp.struts.LoginAction" validate="false"/>
1671 <action path="/Welcome" forward="/welcomeStruts.jsp"/>
1672</action-mappings>
1673The name and scope attributes apply to the form bean that is associated with the action. Specifically, when an incoming request matches /login, the Struts framework automatically instantiates a LoginForm object and populates it with the form data sent in the request. The default value of validate is set to true. This tells the framework to call the validate method of the form bean. You deselected this option in the wizard however because you will hand-code simple validation in the next step, which does not require the validate method.
1674Implementing Validation
1675In the Source Editor, browse through the LoginAction class and look at the execute method:
1676public ActionForward execute(ActionMapping mapping, ActionForm form,
1677 HttpServletRequest request, HttpServletResponse response)
1678 throws Exception {
1679
1680 return mapping.findForward(SUCCESS);
1681}
1682Notice the definition of SUCCESS, listed beneath the LoginAction class declaration:
1683private final static String SUCCESS = "success";
1684Currently, the mapping.findForward method is set to unconditionally forward any request to an output view called success. This is not really desirable; you want to first perform some sort of validation on the incoming data to determine whether to send the success view, or any different view.
1685• Accessing Bean Data and Preparing a Forwarding Condition
1686• Setting Up an Error Message
1687Accessing Bean Data and Preparing a Forwarding Condition
1688Type in the following code within the body of the execute method:
1689// extract user data
1690LoginForm formBean = (LoginForm)form;
1691String name = formBean.getName();
1692String email = formBean.getEmail();
1693In order to use the incoming form data, you need to take execute's ActionForm argument and cast it as LoginForm, then apply the getter methods that you created earlier.
16941. Type in the following conditional clause to perform validation on the incoming data:
1695// perform validation
1696if ((name == null) || // name parameter does not exist
1697 email == null || // email parameter does not exist
1698 name.equals("") || // name parameter is empty
1699 email.indexOf("@") == -1) { // email lacks '@'
1700
1701 return mapping.findForward(FAILURE);
1702}
1703At this stage, the execute method should look as follows:
1704public ActionForward execute(ActionMapping mapping, ActionForm form,
1705 HttpServletRequest request, HttpServletResponse response)
1706 throws Exception {
1707
1708 // extract user data
1709 LoginForm formBean = (LoginForm) form;
1710 String name = formBean.getName();
1711 String email = formBean.getEmail();
1712
1713 // perform validation
1714 if ((name == null) || // name parameter does not exist
1715 email == null || // email parameter does not exist
1716 name.equals("") || // name parameter is empty
1717 email.indexOf("@") == -1) { // email lacks '@'
1718
1719 return mapping.findForward(FAILURE);
1720 }
1721
1722 return mapping.findForward(SUCCESS);
1723}
1724Add a declaration for FAILURE to the LoginAction class (changes in bold):
1725private final static String SUCCESS = "success";
1726private final static String FAILURE = "failure";
1727Using the above logic, the execute method forwards the request to the success view if the user provides an entry for both name and email fields, and the email entered contains an '@' sign. Otherwise, the failure view is forwarded. As will be demonstrated below in Adding forward Entries to struts-config.xml, you can set thefailure view to point back to the form page, so that the user has another chance to enter data in the correct format.
1728Setting Up an Error Message
1729If the login form is returned, it would be good to inform the user that validation failed. You can accomplish this by adding an error field in the form bean, and an appropriate<bean:write> tag to the form in login.jsp. Finally, in the Action object, set the error message to be displayed in the event that the failure view is chosen.
1730Open LoginForm and add an error field to the class:
1731// error message
1732private String error;
1733Add a getter method and a setter method for error, as demonstrated above.
1734Modify the setter method so that it appears as follows:
1735public void setError() {
1736 this.error =
1737 "<span style='color:red'>Please provide valid entries for both fields</span>";
1738}
1739Open login.jsp and make the following changes:
1740<html:form action="/login">
1741 <table border="0">
1742 <tbody>
1743 <tr>
1744 <td colspan="2">
1745 <bean:write name="LoginForm" property="error" filter="false"/>
1746 </td>
1747 </tr>
1748 <tr>
1749 <td>Enter your name:</td>
1750 <td><html:text property="name" /></td>
1751 </tr>
17521. In LoginAction, within the if conditional clause, add a statement to set the error message before forwarding the failure condition (changes in bold):
1753if ((name == null) || // name parameter does not exist
1754 email == null || // email parameter does not exist
1755 name.equals("") || // name parameter is empty
1756 email.indexOf("@") == -1) { // email lacks '@'
1757
1758 formBean.setError();
1759 return mapping.findForward(FAILURE);
1760}
1761Your completed LoginAction class should now appear as follows:
1762public class LoginAction extends org.apache.struts.action.Action {
1763
1764 private final static String SUCCESS = "success";
1765 private final static String FAILURE = "failure";
1766
1767 public ActionForward execute(ActionMapping mapping, ActionForm form,
1768 HttpServletRequest request, HttpServletResponse response)
1769 throws Exception {
1770
1771 // extract user data
1772 LoginForm formBean = (LoginForm)form;
1773 String name = formBean.getName();
1774 String email = formBean.getEmail();
1775
1776 // perform validation
1777 if ((name == null) || // name parameter does not exist
1778 email == null || // email parameter does not exist
1779 name.equals("") || // name parameter is empty
1780 email.indexOf("@") == -1) { // email lacks '@'
1781
1782 formBean.setError();
1783 return mapping.findForward(FAILURE);
1784 }
1785
1786 return mapping.findForward(SUCCESS);
1787
1788 }
1789}
1790Adding forward Entries to struts-config.xml
1791In order for the application to match JSP pages with forwarding conditions returned by LoginAction's execute method, you need to add forward entries to the struts-config.xml file.
17921. Open struts-config.xml in the Source Editor, right-click anywhere in the action entry for LoginForm, and choose Struts > Add Forward.
1793
17942. In the Add Forward dialog box, type success in Forward Name. Enter the path to success.jsp in the Resource File field (i.e., /WEB-INF/success.jsp). The dialog box should now look as follows:
1795
1796Click Add. Note that the following forward entry was added to struts-config.xml (changes in bold):
1797<action name="LoginForm" path="/login" scope="request" type="com.myapp.struts.LoginAction" validate="false">
1798 <forward name="success" path="/WEB-INF/success.jsp"/>
1799</action>
1800Perform the same action to add a forward entry for failure. Set the Resource File path to /login.jsp. The following forward entry is added to struts-config.xml (changes in bold):
1801<forward name="success" path="/WEB-INF/success.jsp"/>
1802<forward name="failure" path="/login.jsp"/>
1803Configuring and Running the Application
1804The IDE uses an Ant build script to build and run your web application. The IDE generated the build script when you created the project, basing it on the options you entered in the New Project wizard. Before you build and run the application, you need to set the application's default entry point to login.jsp. Optionally, you can also add a simple stylesheet to the project.
1805• Setting the Welcome Page
1806• Attaching a Stylesheet
1807• Running the Application
1808Setting the Welcome Page
18091. In the Projects window, double-click the web.xml deployment descriptor. The tabs listed along the top of the Source Editor provide you with an interface to theweb.xml file. Click on the Pages tab. In the Welcome Files field, enter login.jsp.
1810
1811Now click on the Source tab to view the file. Note that login.jsp is now listed in the welcome-file entry:
18122. <welcome-file>login.jsp</welcome-file>
1813Attaching a Stylesheet
18141. Add a simple stylesheet to the project. One easy way to do this is by saving this sample stylesheet to your computer. Copy the file (Ctrl-C), then in the IDE, select the Web Pages node in the Projects window and press Ctrl-V). The file is added to your project.
18152. Link the stylesheet to your JSP pages by adding a reference between the <head> tags of both login.jsp and success.jsp:
1816<link rel="stylesheet" type="text/css" href="stylesheet.css">
1817Running the Application
18181. In the Projects window, right-click the project node and choose Run. The IDE builds the web application and deploys it, using the server you specified when creating the project. The browser opens and displays the login.jsp page. Type in some data that should fail validation, i.e., either leave either field blank, or enter an email address with a missing '@' sign:
1819
1820
1821When you click Login, the login form page redisplays, containing an error message:
1822
1823
1824Try entering data that should pass validation. Upon clicking Login, you are presented with the success page:
1825
1826b)Hibernate
1827Procedure:
1828How Hibernate works (Short overview):
18291) First of all we define a configuration file that contains all the things like which database you will be using, what will be the user name and password and batch size of transaction.
18302) Configuration will help you give a session factory. You can think of it as an connection pool from JDBC but they are not all the same. Then you get session from the session factory that can be used to interact with the database.
18313) Session factory is single per application that again gives a lot of sessions to interact with the database.
1832Note: Session factory is thread safe and session is not thread safe.
1833Steps for making a hibernate application:
18341) You can start with defining all the POJO classes for all of your tables (that is what we call with an amazing word: mapping)
18351) Map each table to class
18362) Map each column of the table to the properties of the table
18372) Add the hibernate libraries and your Database connector depending on your type of database.
18383) Create the configuration file that will define everything about the database.
18394) Build the session factory object that you will get from the configuration object.
18405) Get the session from your session factory object.
18416) You will have to get session from session factory each time you want to perform data access logic.
1842Let’s build a sample application using NetBeans and MySQL:
18431) First we will add our tables to our default database TEST.
18442) Now open up MySQL Query browser: Use default database as TEST.
18453) Run the SQL as follow to create two tables as books and authors:
1846CREATE TABLES using the SQL:
1847DROP TABLE IF EXISTS `test`.`authors`;
1848CREATE TABLE `test`.`authors` (
1849`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
1850`name` varchar(45) DEFAULT NULL,
1851`age` int(10) unsigned DEFAULT NULL,
1852PRIMARY KEY (`id`)
1853) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1;
1854DROP TABLE IF EXISTS `test`.`books`;
1855CREATE TABLE `test`.`books` (
1856`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
1857`title` varchar(45) DEFAULT NULL,
1858`genre` varchar(45) DEFAULT NULL,
1859`author` int(10) unsigned NOT NULL,
1860PRIMARY KEY (`id`),
1861KEY `FK_New Table_1` (`author`),
1862CONSTRAINT `FK_New Table_1` FOREIGN KEY (`author`) REFERENCES `authors` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
1863) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
18644) After this, time has come to create the POJO classes:
1865Create a package as test package.
1866Define two classes in it as Book.java and Author.java
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943 Author.java :
1944package testPackage;
1945
1946public class Author{
1947 private int id;
1948 private String name;
1949 private int age;
1950
1951 public Author() {}
1952
1953 public Author(String name, int age) {
1954 this.name = name;
1955 this.age = age;
1956 }
1957
1958 public int getId() {
1959 return id;
1960 }
1961 public void setId( int id ) {
1962 this.id = id;
1963 }
1964
1965 public void setName(String name) {
1966 this.name = name;
1967 }
1968
1969 public int getAge() {
1970 return age;
1971 }
1972
1973 public String getName() {
1974 return name;
1975 }
1976
1977 public void setAge(int age) {
1978 this.age = age;
1979 }
1980}
1981
1982Book.java :
1983package testPackage;
1984
1985public class Book{
1986 private int id;
1987 private String title;
1988 private String genre;
1989 private Author author;
1990
1991 public Book() {}
1992 public Book(String title, String genre, Author author ) {
1993 this.title = title;
1994 this.genre = genre;
1995 this.author = author;
1996 }
1997 public int getId() {
1998 return id;
1999 }
2000 public void setId( int id ) {
2001 this.id = id;
2002 }
2003
2004 public Author getAuthor() {
2005 return author;
2006 }
2007
2008 public void setAuthor(Author author) {
2009 this.author = author;
2010 }
2011
2012 public String getGenre() {
2013 return genre;
2014 }
2015
2016 public void setGenre(String genre) {
2017 this.genre = genre;
2018 }
2019
2020 public String getTitle() {
2021 return title;
2022 }
2023
2024 public void setTitle(String title) {
2025 this.title = title;
2026 }
2027
2028}
2029So we created two tables and two classes here as Books and Authors and a reference from Books table to the Author table. That means we defined an Author for every Book we have.
2030You must keep the following in mind while using Hibernate:
2031• Each row from the author table (taking an example of Author) will be represented by hibernate as an object of the class Author.
2032• If you want more than one that will come as a List of class Author.
2033• A class is mapped to a table. It is like giving us a generalized idea about how does record from the Author table will look like.
20345) Now open Netbeans create a web application project, select Hibernate from the framework.
2035• You can also create a java application, but I like doing this way, if in future you want to integrate into a web application.
2036• Add the MySQL connector to the libraries. Right click on the Libraries project and add Jar.
2037• You will have a file named as hibernate.cfg.xml added to your project by default.Define your database name , its username and password.
2038Example :
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057 <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
2058 <property name="hibernate.connection.username">root</property>
2059 <property name="hibernate.connection.password">mindfire</property>
2060Hibernate.cfg.xml code :
2061<?xml version="1.0" encoding="UTF-8"?>
2062<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
2063<hibernate-configuration>
2064 <session-factory>
2065 <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
2066 <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
2067 <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
2068 <property name="hibernate.connection.username">root</property>
2069 <property name="hibernate.connection.password">mindfire</property>
2070 <property name="hibernate.show_sql">true</property>
2071 <property name="hibernate.current_session_context_class">thread</property>
2072 <property name="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</property >
2073
2074 <mapping resource="book.hbm.xml"/>
2075 </session-factory>
2076</hibernate-configuration>
2077Create a new hbm file in the same package as Hibernate.cfg.xml that will define the table definitions from the testPackage (Book.java and Auhor.java) as book.hbm.xml :
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102 book.hbm.xml code:
2103<?xml version="1.0" encoding="UTF-8"?>
2104<hibernate-mapping package="testPackage">
2105 <class name="Book" table="books">
2106 <meta attribute="class-description">
2107 This class contains the book detail.
2108 </meta>
2109 <id column="id" name="id" type="int">
2110 <generator class="native"/>
2111 </id>
2112 <property column="title" name="title" type="string"/>
2113 <property column="genre" name="genre" type="string"/>
2114 <many-to-one class="Author" column="author" name="author" not-null="true"/>
2115 </class>
2116 <class name="Author" table="Authors">
2117 <meta attribute="class-description">
2118 This class contains the author detail.
2119 </meta>
2120 <id column="id" name="id" type="int">
2121 <generator class="native"/>
2122 </id>
2123 <property column="name" name="name" type="string"/>
2124 <property column="age" name="age" type="int"/>
2125 </class>
2126</hibernate-mapping>
2127Explanations for hbm file above:
2128• We are mapping each table to class and each column to a property of class. The thing which need an explanation is :
2129• <id column=â€id†name=â€id†type=â€intâ€>
2130• <generator/>
2131</id>
2132• This <id> tag means we are telling hibernate to auto generate the id column , we don’t want to take the pain that we will assign the primary key each time we will create a new row. The primary key generation strategy that is the default for the database will be used.
2133• Also <many-to-one > tag, we are telling hibernate to apply a many to one mapping where each row from the Authors table will be matched to many rows in Books table
2134Test and run the application
2135Everything is set now you have done everything, time to test and run you hibernate. Create a new class as ManageBooks.java in your test package and there you go:
2136Explanation for ManageBooks :
21371)First of all we created an Author object and saved it in the table. We saved it in the addAuthor function only. That means you can see it in the Database after you come out of this function.
21382)Then we used that Author object to create the book object.
21393)After this we did a HQL query (in place of an SQL Query) to get all the books table records and iterated over them to print them on screen.
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233 ManageBooks.java :
2234package testPackage;
2235import java.util.*;
2236import org.hibernate.HibernateException;
2237import org.hibernate.Session;
2238import org.hibernate.Transaction;
2239import org.hibernate.SessionFactory;
2240import org.hibernate.cfg.Configuration;
2241
2242public class ManageBooks {
2243 private static SessionFactory factory;
2244 public static void main(String[] args) {
2245 try{
2246 factory = new Configuration().configure().buildSessionFactory();
2247 }catch (Throwable ex) {
2248 System.err.println("Failed to create sessionFactory object." + ex);
2249 throw new ExceptionInInitializerError(ex);
2250 }
2251 ManageBooks manageBook = new ManageBooks();
2252
2253 /* Let us have a author object */
2254 Author author = manageBook.addAuthor("Manoj",32);
2255 /* employee record in the database */
2256 Integer empID1 = manageBook.addBook("One in a million", "Motivation", author);
2257 /* List all the books */
2258 manageBook.listBooks();
2259 }
2260 /* Method to add an author record in the database */
2261 public Author addAuthor(String name, int age) {
2262 // get the session from session factory
2263 Session session = factory.openSession();
2264 Transaction tx = null;
2265 Integer authorID = null;
2266 Author author = null;
2267 try{
2268 // begin the transaction from the sessiom
2269 tx = session.beginTransaction(); // create a new object for author
2270 author = new Author(name, age);
2271 // save the author . It auto generates the Id .So need to give the id
2272 authorID = (Integer) session.save(author);
2273 //The changes to persistent object will be written to database.
2274 tx.commit(); }catch (HibernateException e) {
2275 if (tx!=null) tx.rollback();
2276 e.printStackTrace();
2277 }finally {
2278 // close the session
2279 session.close();
2280 }
2281 return author;
2282 }
2283 /* Method to add an book record in the database */
2284 public Integer addBook(String title, String genre,
2285 Author author){
2286 // Get the session from session factory
2287 Session session = factory.openSession();
2288 Transaction tx = null;
2289 Integer bookID = null;
2290 try{
2291 //begin the transaction
2292 tx = session.beginTransaction();
2293 //Create a new book object
2294 Book bookEntry = new Book(title, genre, author);
2295 // save the book object.The changes to persistent object will be written to database.
2296 bookID = (Integer) session.save(bookEntry);
2297 //The changes to persistent object will be written to database.
2298 tx.commit();
2299 }catch (HibernateException e) {
2300 if (tx!=null) tx.rollback();
2301 e.printStackTrace();
2302 }finally {
2303 //close the session.
2304 session.close();
2305 }
2306 return bookID;
2307 }
2308 /* Method to list all the books detail */
2309 public void listBooks( ){
2310 //Get the session from the session factory.
2311 Session session = factory.openSession();
2312 Transaction tx = null;
2313 try{
2314 tx = session.beginTransaction();
2315 //Make an HQL query to get the results from books table . You can also use SQL here.
2316 List books = session.createQuery("FROM Book").list();
2317 //Iterate over the result and print it.
2318 for (Iterator iterator =
2319 books.iterator(); iterator.hasNext();){
2320 Book book = (Book) iterator.next();
2321 System.out.print("Title : " + book.getTitle());
2322 System.out.print("\tGenre of the book: " + book.getGenre());
2323 // Get the author of the book here.
2324 Author author = book.getAuthor();
2325 System.out.println("Author of the book ");
2326 System.out.println("\tname : " + author.getName());
2327 System.out.println("\tage : " + author.getAge());
2328 }
2329 tx.commit();
2330 }catch (HibernateException e) {
2331 if (tx!=null) tx.rollback();
2332 e.printStackTrace();
2333 }finally {
2334 session.close();
2335 }
2336 }
2337}
2338
2339C)Spring
2340Procedure:
2341Setting up a New Project with Spring Web MVC Support
2342• Creating a Spring Web MVC Skeleton Project
2343• Running the Skeleton Project
2344Creating a Spring Web MVC Skeleton Project
2345Start by creating a new project for a web application using the Spring Framework.
23461. Choose New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the IDE's File menu. Select the Java Web category, then under Projects select Web Application. Click Next.
23472. In Project Name, type in HelloSpring. Click Next.
23483. In Step 3: Server and Settings, deselect the Enable Contexts and Dependency Injection option, as you are not working with the JSR-299 specification in this tutorial.
23494. Confirm that the GlassFish server is selected in the Server drop-down list. Click Next.
2350The Java EE version depends upon the version of the server that is selected. The default Java EE version is Java EE 7 Web when the selected server is GlassFish Server 4.0.
23515. In Step 4, the Frameworks panel, select Spring Web MVC.
23526. Select Spring Framework 3.x in the Spring Library drop-down list.
2353
2354Note that the IDE enables you to add the Spring 4.x library to your project, but for this tutorial you will use SimpleFormController that is not supported in Spring 4.x. Also, when you select Spring Web MVC, note that the JSTL (JavaServer Pages Standard Tag Library) library is added to the classpath during project creation by default. Deselect this option (as in the above screenshot), since you do not require JSTL for this tutorial.
23557. Click the Configuration tab and note that the wizard enables you to specify the name and mapping of the Spring Dispatcher servlet.
2356
23578. Click Finish. The IDE creates a project for the entire application, including all metadata, as well as the project's Ant build script which you can inspect from the Files window (Ctrl-2; ⌘-2 on Mac). You can view the template structure from the Projects window (Ctrl-1; ⌘-1 on Mac). Also note that four files open by default in the IDE's editor: dispatcher-servlet.xml, applicationContext.xml, redirect.jsp, and index.jsp.
23589. In the Projects window, expand the new project's Libraries node and note that the Spring JARs are included in the project's classpath.
2359
2360Running the Skeleton Project
2361Before making any changes to project files, try running the new project in the IDE:
23621. Click the Run Project ( ) in the IDE's main toolbar. The IDE automatically starts the GlassFish server if it is not already running, compiles the project, then deploys it to the server. Note any output displayed in the IDE's Output window (Ctrl-4; ⌘-4 on Mac). The generated output completes with a BUILD SUCCESSFUL message.
2363
2364The IDE's default browser starts up, and you see content from the welcome page view (/WEB-INF/jsp/index.jsp).
2365
2366When you run your project in the IDE, the project is compiled and deployed to the server, and then opens in your default browser. Furthermore, the IDE provides a Deploy on Save feature, which is activated by default for web projects. When you save files in the editor, your project is automatically recompiled and deployed to the server. To view changes, you can simply refresh pages in your browser.
2367In order to understand what just took place, start by examining the project's deployment descriptor (web.xml). To open this file in the Source Editor, right-click the WEB-INF> web.xml node in the Projects window and choose Edit. The default entry point for the application is redirect.jsp:
2368<welcome-file-list>
2369 <welcome-file>redirect.jsp</welcome-file>
2370</welcome-file-list>
2371Within redirect.jsp, there is a redirect statement that points all requests to index.htm:
2372<% response.sendRedirect("index.htm"); %>
2373In the deployment descriptor, note that all requests for URL patterns that match *.htm are mapped to Spring's DispatcherServlet.
2374<servlet>
2375 <servlet-name>dispatcher</servlet-name>
2376 <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
2377 <load-on-startup>2</load-on-startup>
2378</servlet>
2379
2380<servlet-mapping>
2381 <servlet-name>dispatcher</servlet-name>
2382 <url-pattern>*.htm</url-pattern>
2383</servlet-mapping>
2384The fully qualified name of the dispatcher servlet, as shown above, is org.springframework.web.servlet.DispatcherServlet. This class is contained in the Spring library, which was added to the project classpath when the project was created. You can verify this in the Projects window by drilling down from the Libraries node. Locate the spring-webmvc-3.1.1.RELEASE.jar, then expand it to find org.springframework.web.servlet >DispatcherServlet.
2385The DispatcherServlet handles incoming requests based on configuration settings found in dispatcher-servlet.xml. Open dispatcher-servlet.xmlby clicking on its tab in the editor. Note the following code.
2386<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
2387 <property name="mappings">
2388 <props>
2389 <prop key="/index.htm">indexController</prop>
2390 </props>
2391 </property>
2392</bean>
2393
2394<bean id="viewResolver"
2395 class="org.springframework.web.servlet.view.InternalResourceViewResolver"
2396 p:prefix="/WEB-INF/jsp/"
2397 p:suffix=".jsp" />
2398
2399<bean name="indexController"
2400 class="org.springframework.web.servlet.mvc.ParameterizableViewController"
2401 p:viewName="index" />
2402Three beans are defined in this file: indexController, viewResolver, and urlMapping. When the DispatcherServlet receives a request that matches*.htm such as index.htm, it looks for a controller within urlMapping that can accommodate the request. Above, you see that there is a mappings property that links/index.htm to indexController.
2403The runtime environment then searches for the definition of a bean named indexController, which is conveniently provided by the skeleton project. Note thatindexController extends ParameterizableViewController. This is another class provided by Spring, which simply returns a view. Above, note thatp:viewName="index" specifies the logical view name, which is resolved using the viewResolver by prepending /WEB-INF/jsp/ and appending .jsp to it. This allows the runtime to locate the file within the application directory, and respond with the welcome page view (/WEB-INF/jsp/index.jsp).
2404Overview of the Application
2405The application you create is comprised of two JSP pages (which can be referred to as views in MVC terminology). The first view contains an HTML form with an input field asking for the user's name. The second view is a page that simply displays a hello message containing the user's name.
2406The views are managed by a controller, which receives requests to the application and decides which views to return. It also passes to the views any information that they need to display (this is called a model). This application's controller is named HelloController.
2407In a complex web application, the business logic is not contained directly in the controller. Instead, another entity, named a service, is used by the controller whenever it needs to perform some business logic. In our application, the business logic is limited to the act of processing the hello message, and for this purpose you create a HelloService.
2408Implementing a Service
2409Now that you are sure your environment is set up properly, you can begin extending the skeleton project according to your needs. Start by creating the HelloService class.
24101. Click the New File ( ) button in the IDE's toolbar. (Alternatively, press Ctrl-N; ⌘-N on Mac.)
24112. Select the Java category, then select Java Class and click Next.
24123. In the New Java Class wizard that displays, type in HelloService for Class Name, and enter service for Package Name to create a new package for the class.
24134. Click Finish. The IDE creates the new class and opens it in the editor.
2414The HelloService class performs a very simple service. It takes a name as a parameter, and prepares and returns a String that includes the name. In the editor, create the following sayHello() method for the class (changes in bold).
2415public class HelloService {
2416
2417 public static String sayHello(String name) {
2418 return "Hello " + name + "!";
2419 }
2420}
2421Implementing the Controller and Model
2422You can use a SimpleFormController to handle user data and determine which view to return.
2423Note: SimpleFormController is deprecated in Spring 3.x. It is used in this tutorial for demonstration purposes. However, annotated controllers should be used instead of XML files.
24241. Open the New File wizard by pressing Ctrl-N (⌘-N on Mac). Under Categories select Spring Framework; under File Types select Simple Form Controller.
2425
2426NetBeans IDE provides templates for various Spring artifacts, including the Spring XML Configuration File, the AbstractController, and theSimpleFormController.
24272. Click Next.
24283. Name the class HelloController and create a new package for it by typing controller in the Package text field. Click Finish. The IDE creates the new class and opens it in the editor.
24294. Specify controller properties by uncommenting the setter methods that display by default in the class template. To uncomment the code snippet, highlight the code as in the image below, then press Ctrl-/ (⌘-/ on Mac).
2430
2431Pressing Ctrl-/ (⌘-/ on Mac) toggles comments in the editor.
24325. Make changes as follows (shown in bold).
2433public HelloController() {
2434 setCommandClass(Name.class);
2435 setCommandName("name");
2436 setSuccessView("helloView");
2437 setFormView("nameView");
2438}
2439Setting the FormView enables you to set the name of the view that is used to display the form. This is the page that contains the text field allowing users to enter their name. Setting the SuccessView likewise lets you set the name of the view that should display upon a successful submit. When you set the CommandName you define the name of the command in the model. In this case, the command is the form object with request parameters bound onto it. Setting the CommandClass allows you set the name of the command class. An instance of this class gets populated and validated upon each request.
2440Note that an error is flagged for Name in the setCommandClass() method:
2441
2442You now need to create the Name class as a simple bean to hold information for each request.
24436. In the Projects window, right-click on the project node and choose New > Java Class. The New Java Class wizard displays.
24447. Enter Name for the Class Name, and for Package select controller from the drop-down list.
24458. Click Finish. The Name class is created and opens in the editor.
24469. For the Name class, create a field named value, then create accessor methods (i.e., getter and setter methods) for this field. Start by declaring the value field:
2447public class Name {
2448
2449 private String value;
2450
2451}
2452To quickly type out 'private' you can type 'pr' then press Tab. The 'private' access modifier is automatically added to the line. This is an example of using the editor's code templates. For a full list of code templates, choose Help > Keyboard Shortcuts Card.
2453
2454The IDE can create accessor methods for you. In the editor, right-click on value and choose Insert Code (or press Alt-Insert; Ctrl-I on Mac). In the popup menu, choose Getter and Setter.
2455
245610. In the dialog that displays, select the value : String option, then click OK. The getValue() and setValue() methods are added to the Name class:
2457public String getValue() {
2458 return value;
2459}
2460
2461public void setValue(String value) {
2462 this.value = value;
2463}
246411. Press Ctrl-Tab and choose HelloController to switch back to the HelloController class. Note that the previous error badge has disappeared since the Nameclass now exists.
246512. Delete the doSubmitAction() method and uncomment the onSubmit() method. The onSubmit() method enables you to create your own ModelAndView, which is what is required here. Make the following changes:
2466@Override
2467protected ModelAndView onSubmit(
2468 HttpServletRequest request,
2469 HttpServletResponse response,
2470 Object command,
2471 BindException errors) throws Exception {
2472
2473 Name name = (Name) command;
2474 ModelAndView mv = new ModelAndView(getSuccessView());
2475 mv.addObject("helloMessage", helloService.sayHello(name.getValue()));
2476 return mv;
2477}
2478As indicated above, the command is recast as a Name object. An instance of ModelAndView is created, and the success view is obtained using a getter inSimpleFormController. Finally, the model is populated with data. The only item in our model is the hello message obtained from the HelloService created earlier. You use the addObject() method to add the hello message to the model under the name helloMessage.
247913. Fix import errors by right-clicking in the editor and choosing Fix Imports (Ctrl-Shift-I; ⌘-Shift-I on Mac).
2480
2481Note. Confirm that org.springframework.validation.BindException and org.springframework.web.servlet.ModelAndView are selected in the Fix All Imports dialog box.
248214. Click OK. The following import statement is added to the top of the file:
2483import org.springframework.web.servlet.ModelAndView;
2484As stated in the API documentation, this class "represents a model and view returned by a handler, to be resolved by a DispatcherServlet. The view can take the form of a String view name which will need to be resolved by a ViewResolver object; alternatively a View object can be specified directly. The model is a Map, allowing the use of multiple objects keyed by name."
2485
2486Note that at this stage, not all errors are fixed because the class still cannot identify the HelloService class, nor make use of its sayHello() method.
248715. Within HelloController, declare a private field named HelloService:
2488private HelloService helloService;
2489Then create a public setter method for the field:
2490public void setHelloService(HelloService helloService) {
2491 this.helloService = helloService;
2492}
2493Finally, right-click in the editor and choose Fix Imports (Ctrl-Shift-I; ⌘-Shift-I on Mac). The following statement is added to the top of the file:
2494import service.HelloService;
2495All errors should now be fixed.
249616. Register HelloService in applicationContext.xml. Open applicationContext.xml in the editor and enter the following bean declaration:
2497<bean name="helloService" class="service.HelloService" />
2498Spring support in the IDE includes code completion within XML configuration files for Java classes as well as bean references. To invoke code completion, press Ctrl-Space when working in the editor:
2499
250017. Register HelloController in dispatcher-servlet.xml. Open dispatcher-servlet.xml in the editor and enter the following bean declaration:
2501<bean class="controller.HelloController" p:helloService-ref="helloService"/>
2502Implementing the Views
2503To implement the view for this project, you need to create two JSP pages. The first, which you will call nameView.jsp, serves as the welcome page and allows users to input a name. The other page, helloView.jsp, displays a greeting message that includes the input name. Begin by creating helloView.jsp.
25041. In the Projects window, right-click the WEB-INF > jsp node and choose New > JSP. The New JSP File wizard opens. Name the file helloView.
25052. Click Finish. The new JSP page is created in the jsp folder and opens in the editor.
25063. In the editor, change the file's title to Hello, and change the output message to retrieve the helloMessage of the ModelandView object that is created inHelloController.
2507<head>
2508 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
2509 <title>Hello</title>
2510</head>
2511<body>
2512 <h1>${helloMessage}</h1>
2513</body>
2514Create another JSP page in the same manner as above, but name it nameView.
25154. In the editor, add the following Spring tag library declaration to nameView.jsp.
2516<%@taglib uri="http://www.springframework.org/tags" prefix="spring" %>
2517This imports the Spring tag library, which contains tags useful when implementing views as JSP pages.
25185. Change the contents of the <title> and <h1> tags to read: Enter Your Name.
25196. Enter the following code beneath the <h1> tags:
25207. <spring:nestedPath path="name">
2521 <form action="" method="post">
2522 Name:
2523 <spring:bind path="value">
2524 <input type="text" name="${status.expression}" value="${status.value}">
2525 </spring:bind>
2526 <input type="submit" value="OK">
2527 </form>
2528</spring:nestedPath>
2529spring:bind allows you to bind a bean property. The bind tag provides a bind status and value, which you use as the name and value of the input field. This way, when the form is submitted, Spring will know how to extract the submitted value. Here, our command class (controller.Name) has a value property, therefore you set thepath to value.
2530
2531spring:nestedPath enables you to prepend a specified path to a bean. So, when used with spring:bind as shown above, the path to the bean becomes:name.value. As you recall, the command name of HelloController is name. Therefore, this path refers to the value property of a bean named name in the page scope.
25328. Change the relative entry point for the application. Currently, the project entry point is still index.htm which, as described in Running the Skeleton Project above, redirects to WEB-INF/jsp/index.jsp. You can specify an entry point for the project when it is deployed and run. In the Projects window, right-click the project node and choose Properties. The Project Properties dialog displays. Under Categories select Run. In the Relative URL field, type in /hello.htm, then click OK.
2533
2534At this moment you may wonder where the mapping of hello.htm to HelloController is located. You have not added a mapping to the urlMapping bean, as is the case for index.htm, the skeleton project's welcome page. This is possible with a bit of Spring magic provided by the following bean definition in dispatcher-servlet.xml:
2535<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>
2536This bean is responsible for automatically creating an URL mapping for all controllers registered in the file. It takes the fully-qualified class name of the controller (in our case, controller.HelloController) and strips the package name and Controller suffix, then uses the result as a URL mapping. Therefore, forHelloController it creates a hello.htm mapping. This magic however does not work for controllers that are included in the Spring Framework, such asParameterizableViewController. They require an explicit mapping.
25379. In the Projects window right-click the project node and choose Run. This compiles, deploys and runs the project. Your default browser opens, displaying hello.htmas the project's nameView:
2538
2539Enter your name in the text field and click enter. The helloView displays with a greeting message:
2540
2541
2542
2543
2544EX-12
2545AJAX-PHP
2546AIM:Searching in real time with live searches, Getting the answer with auto complete, Chatting with friends ,Dragging and dropping with Ajax, Getting instant login feedback, Ajax-enabled popup menus, Modifying Web pages on the fly.
2547
2548a) Ajax-enabled drop down list
2549Main.php
2550<form name="testform" method='POST' action='dd-check.php'>
2551cat:<input type=text name=cat>
2552subcat:<input type=text name=subcat>
2553<input type=submit value=submit>
2554
2555dd-check.php
2556<!doctype html public "-//w3c//dtd html 3.2//en">
2557<html>
2558<head>
2559<title>Demo Multiple drop down list </title>
2560</head>
2561<body>
2562<?Php
2563$cat=$_POST['cat'];
2564$subcat=$_POST['subcat'];
2565echo "Value of \$cat = $cat <br>Value of \$subcat = $subcat ";
2566?>
2567<br><br>
2568<a href=dd.php>Reset and start again</a>
2569</body>
2570</html>
2571
2572dd.php
2573<?php
2574require 'config.php'; // Database connection
2575//////// End of connecting to database ////////
2576?>
2577<!doctype html public "-//w3c//dtd html 3.2//en">
2578<html>
2579<head>
2580<title>Multiple drop down list box from plus2net</title>
2581<SCRIPT language=JavaScript>
2582function reload(form)
2583{
2584var val=form.cat.options[form.cat.options.selectedIndex].value;
2585self.location='dd.php?cat=' + val ;
2586}
2587
2588</script>
2589</head>
2590<body>
2591<?Php
2592@$cat=$_GET['cat']; // Use this line or below line if register_global is off
2593if(strlen($cat) > 0 and !is_numeric($cat)){ // to check if $cat is numeric data or not.
2594echo "Data Error";
2595exit;
2596}
2597///////// Getting the data from Mysql table for first list box//////////
2598$quer2="SELECT DISTINCT category,cat_id FROM category order by category";
2599///////////// End of query for first list box////////////
2600/////// for second drop down list we will check if category is selected else we will display all the subcategory/////
2601if(isset($cat) and strlen($cat) > 0){
2602$quer="SELECT DISTINCT subcategory FROM subcategory where cat_id=$cat order by subcategory";
2603}else{$quer="SELECT DISTINCT subcategory FROM subcategory order by subcategory"; }
2604////////// end of query for second subcategory drop down list box ///////////////////////////
2605echo "<form method=post name=f1 action='dd-check.php'>";
2606/// Add your form processing page address to action in above line. Example action=dd-check.php////
2607////////// Starting of first drop downlist /////////
2608echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
2609foreach ($dbo->query($quer2) as $noticia2) {
2610if($noticia2['cat_id']==@$cat){echo "<option selected value='$noticia2[cat_id]'>$noticia2[category]</option>"."<BR>";}
2611else{echo "<option value='$noticia2[cat_id]'>$noticia2[category]</option>";}
2612}
2613echo "</select>";
2614////////////////// This will end the first drop down list ///////////
2615
2616////////// Starting of second drop downlist /////////
2617echo "<select name='subcat'><option value=''>Select one</option>";
2618foreach ($dbo->query($quer) as $noticia) {
2619echo "<option value='$noticia[subcategory]'>$noticia[subcategory]</option>";
2620}
2621echo "</select>";
2622////////////////// This will end the second drop down list ///////////
2623//// Add your other form fields as needed here/////
2624echo "<input type=submit value=Submit>";
2625echo "</form>";
2626?>
2627</body>
2628</html>
2629
2630
2631
2632OUTPUT
2633
2634
2635
2636
2637
2638b)Searching in real time with live searches
2639Live.html
2640<html>
2641<head>
2642<script>
2643function showResult(str) {
2644 if (str.length==0) {
2645 document.getElementById("livesearch").innerHTML="";
2646 document.getElementById("livesearch").style.border="0px";
2647 return;
2648 }
2649 if (window.XMLHttpRequest) {
2650 // code for IE7+, Firefox, Chrome, Opera, Safari
2651 xmlhttp=new XMLHttpRequest();
2652 } else { // code for IE6, IE5
2653 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
2654 }
2655 xmlhttp.onreadystatechange=function() {
2656 if (xmlhttp.readyState==4 && xmlhttp.status==200) {
2657 document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
2658 document.getElementById("livesearch").style.border="1px solid #A5ACB2";
2659 }
2660 }
2661 alert("str is"+str);
2662 xmlhttp.open("GET","livesearch.php?q="+str,true);
2663 xmlhttp.send();
2664}
2665</script>
2666</head>
2667<body>
2668
2669<form>
2670<input type="text" size="30" onkeyup="showResult(this.value)">
2671<div id="livesearch"></div>
2672</form>
2673</body>
2674</html>
2675
2676Livesearch.php
2677<?php
2678$xmlDoc=new DOMDocument();
2679$xmlDoc->load("links.xml");
2680$x=$xmlDoc->getElementsByTagName('link');
2681$q=$_GET["q"];
2682echo "rr".$q;
2683if (strlen($q)>0) {
2684 $hint="";
2685 for($i=0; $i<($x->length); $i++) {
2686 $y=$x->item($i)->getElementsByTagName('title');
2687 $z=$x->item($i)->getElementsByTagName('url');
2688 if ($y->item(0)->nodeType==1) {
2689 //find a link matching the search text
2690 if (stristr($y->item(0)->childNodes->item(0)->nodeValue,$q)) {
2691 if ($hint=="") {
2692 $hint="<a href='" .
2693 $z->item(0)->childNodes->item(0)->nodeValue .
2694 "' target='_blank'>" .
2695 $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
2696 } else {
2697 $hint=$hint . "<br /><a href='" .
2698 $z->item(0)->childNodes->item(0)->nodeValue .
2699 "' target='_blank'>" .
2700 $y->item(0)->childNodes->item(0)->nodeValue . "</a>";
2701 }
2702 }
2703 }
2704 }
2705}
2706if ($hint=="") {
2707 $response="no suggestion";
2708} else {
2709 $response=$hint;
2710}
2711echo $response;
2712?>
2713 Links.xml
2714<?xml version="1.0" encoding="utf-8"?>
2715<pages>
2716 <link>
2717 <title>HTML a tag</title>
2718 <url>http://www.w3schools.com/tags/tag_a.asp</url>
2719 </link>
2720 <link>
2721 <title>HTML br tag</title>
2722 <url>http://www.w3schools.com/tags/tag_br.asp</url>
2723 </link>
2724 <link>
2725 <title>CSS background Property</title>
2726 <url>http://www.w3schools.com/cssref/css3_pr_background.asp</url>
2727 </link>
2728 <link>
2729 <title>CSS border Property</title>
2730 <url>http://www.w3schools.com/cssref/pr_border.asp</url>
2731 </link>
2732 <link>
2733 <title>JavaScript Date Object</title>
2734 <url>http://www.w3schools.com/jsref/jsref_obj_date.asp</url>
2735 </link>
2736 <link>
2737 <title>JavaScript Array Object</title>
2738 <url>http://www.w3schools.com/jsref/jsref_obj_array.asp</url>
2739 </link>
2740</pages>
2741OUTPUT
2742
2743
2744c) PHP ,MYSQL and AJAX
2745<!DOCTYPE html>
2746<html>
2747<head>
2748<script>
2749function showUser(str) {
2750 if (str=="") {
2751 document.getElementById("txtHint").innerHTML="";
2752 return;
2753 }
2754 if (window.XMLHttpRequest) {
2755 // code for IE7+, Firefox, Chrome, Opera, Safari
2756 xmlhttp=new XMLHttpRequest();
2757 } else { // code for IE6, IE5
2758 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
2759 }
2760 xmlhttp.onreadystatechange=function() {
2761 if (xmlhttp.readyState==4 && xmlhttp.status==200) {
2762 document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
2763 }
2764 }
2765 xmlhttp.open("GET","getuser.php?q="+str,true);
2766 xmlhttp.send();
2767}
2768</script>
2769</head>
2770<body>
2771
2772<form>
2773<select name="users" onchange="showUser(this.value)">
2774<option value="">Select a person:</option>
2775<option value="1">Peter</option>
2776<option value="2">Lois Griffin</option>
2777<option value="3">Joseph Swanson</option>
2778<option value="4">Glenn Quagmire</option>
2779</select>
2780</form>
2781<br>
2782<div id="txtHint"><b>Person info will be listed here.</b></div>
2783
2784</body>
2785</html>
2786
2787
2788<!DOCTYPE html>
2789<html>
2790<head>
2791<style>
2792table {
2793 width: 100%;
2794 border-collapse: collapse;
2795}
2796
2797table, td, th {
2798 border: 1px solid black;
2799 padding: 5px;
2800}
2801
2802th {text-align: left;}
2803</style>
2804</head>
2805<body>
2806
2807<?php
2808$q = intval($_GET['q']);
2809
2810$con = mysql_connect('localhost','peter','abc123');
2811if (!$con) {
2812 die('Could not connect: ' . mysql_error($con));
2813}
2814
2815mysql_select_db("ajax_demo",$con);
2816$sql="SELECT * FROM user WHERE id = '".$q."'";
2817$result = mysql_query($con,$sql);
2818
2819echo "<table>
2820<tr>
2821<th>Firstname</th>
2822<th>Lastname</th>
2823<th>Age</th>
2824<th>Hometown</th>
2825<th>Job</th>
2826</tr>";
2827while($row = mysql_fetch_array($result)) {
2828 echo "<tr>";
2829 echo "<td>" . $row['FirstName'] . "</td>";
2830 echo "<td>" . $row['LastName'] . "</td>";
2831 echo "<td>" . $row['Age'] . "</td>";
2832 echo "<td>" . $row['Hometown'] . "</td>";
2833 echo "<td>" . $row['Job'] . "</td>";
2834 echo "</tr>";
2835}
2836echo "</table>";
2837mysql_close($con);
2838?>
2839</body>
2840</html>
2841
2842OUTPUT
2843
2844
2845Firstname Lastname Age Hometown Job
2846Peter Griffin 41 Quahog Brewery
2847
2848
2849
2850
2851RESULT: Thus Searching in real time with live searches, Getting the answer with auto complete, Chatting with friends ,Dragging and dropping with Ajax, Getting instant login feedback, Ajax-enabled popup menus, Modifying Web pages on the fly was successfully implemented and output was verified.
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885EX-13
2886AIRLINE RESERVATION-WEB SERVICE
2887
2888Aim:
2889To create a web service for implementing airline ticketing web service using oracle.
2890Algorithm
28911. Code the implementation class.
28922. Compile the implementation class.
28933. Use wsgen to generate the artifacts required to deploy the service.
28944. Package the files into a WAR file.
28955. Deploy the WAR file. The web service artifacts (which are used to communicate with clients) are generated by the Application Server during deployment.
28966. Code the client class.
28977. Use wsimport to generate and compile the web service artifacts needed to connect to the service.
28988. Compile the client class.
28999. Run the client.
2900DATABASE FOR AIRLINE RESERVATION
2901SQL> desc airways_table
2902 Name Null? Type
2903 ______________________________________________
2904 NUM NUMBER(10)
2905 NAME VARCHAR2(15)
2906 START_FROM VARCHAR2(15)
2907 DEST VARCHAR2(15)
2908
2909SQL> select * from airways_table;
2910
2911 NUM NAME START_FROM DEST
2912_____________________________________________________
2913 1001 british airways pune chennai
2914 2001 air india mumbai pune
2915 3001 indian airlines chennai pune
2916 2002 airindia chennai mumbai
2917 1002 british airways chennai pune
2918 1003 british airways mumbai pune
2919 3002 indian airlines pune mumbai
2920 2003 airindia pune mumbai
2921 3003 indian airlines pune mumbai
2922
29239 rows selected.
2924AIRLINE RESERVATION WEB SERVICE
2925package airinfo;
2926import javax.jws.WebMethod;
2927import javax.jws.WebParam;
2928import javax.jws.WebService;
2929import java.sql.*;
2930
2931
2932
2933@WebService( name="Test", serviceName = "TestDB" )
2934public class TestDB {
2935
2936 /**
2937 * Web service operation
2938 */
2939 @WebMethod(operationName = "getInfo")
2940 public String getInfo(@WebParam(name = "src")
2941 String src, @WebParam(name = "dest")
2942 String dest) {
2943 String str="";
2944 try
2945 {Class.forName("oracle.jdbc.driver.OracleDriver");
2946 System.out.println("inside testdb");
2947 Connection con=DriverManager.getConnection("jdbc:oracle:thin:@//192.168.9.185:1521/cse","system","manager");
2948
2949 Statement s=con.createStatement();
2950 if(src.equals("mumbai"))
2951 {
2952 if(dest.equals("pune"))
2953 s.executeQuery("SELECT * FROM airways_table WHERE Start_from='mumbai' AND Dest='pune'");
2954 else if(dest.equals("chennai"))
2955 s.executeQuery("SELECT * FROM airways_table WHERE Start_from='mumbai' AND Dest='chennai'");
2956 }
2957 else if(src.equals("pune"))
2958 {
2959 if(dest.equals("mumbai"))
2960 s.executeQuery("SELECT * FROM airways_table WHERE Start_from='pune' AND Dest='mumbai'");
2961 else if(dest.equals("chennai"))
2962 s.executeQuery("SELECT * FROM airways_table WHERE Start_from='pune' AND Dest='chennai'");
2963 }
2964 else if(src.equals("chennai"))
2965 {
2966 if(dest.equals("pune"))
2967 s.executeQuery("SELECT * FROM airways_table WHERE Start_from='chennai' AND Dest='pune'");
2968 else if(dest.equals("Mumbai"))
2969 s.executeQuery("SELECT * FROM airways_table WHERE Start_from='chennai' AND Dest='mumbai'");
2970 }
2971 ResultSet rs=s.getResultSet();
2972 str+="<table border=1>";
2973 while(rs.next())
2974 {
2975 str+="<tr><b>";
2976 str+="<td>";
2977 str+=rs.getString("name");
2978 str+="</td>";
2979 str+="</tr></b>";
2980 }
2981 str+="</table>";
2982
2983 }catch(ClassNotFoundException ex)
2984 {
2985 System.out.println(ex);
2986 }
2987 catch(SQLException ex)
2988 {
2989 System.out.println(ex);
2990 }
2991 return str;
2992 }
2993
2994}
2995
2996AIRLINE RESERVATION CLIENT
2997
2998index.jsp
2999
3000<html>
3001 <head>
3002 <title>AIRLINE RESERVATION SYSTEM</title>
3003 </head>
3004 <body bgcolor="khaki">
3005 <center>
3006 <h4>Travel Agent should fill up following information to get information about the Airline</h4>
3007 <form name="form1" method=GET action ="reserve.jsp">
3008 <table>
3009 <tr>
3010 <td><b>Source city: </b></td>
3011 <td><input type="text" name="Src_name" size="20" value=""></td>
3012 </tr>
3013 <tr>
3014 <td><b>Destination city: </b></td>
3015 <td><input type="text" name="Dest_name" size="20" value=""></td>
3016 </tr>
3017 <tr>
3018 <td><input type="submit" value="Submit"></td>
3019 </tr>
3020 </table>
3021 </form>
3022 </center>
3023 </body>
3024</html>
3025
3026
3027reserve.jsp
3028
3029<%@page contentType="text/html" pageEncoding="UTF-8"%>
3030
3031Airline Seat Confirmation
3032<%
3033String a1=request.getParameter("Src_name");
3034String a2=request.getParameter("Dest_name");
3035%>
3036<%-- start web service invocation --%>
3037
3038<%
3039try {
3040air.TestDB_Service service =new air.TestDB_Service();
3041air. TestDB port = service.get TestDB Port();
3042String result = port.get(a1, a2);
3043%>
3044<%
3045} catch (Exception ex) {
3046ex.printStackTrace();
3047}
3048%>
3049
3050<%-- end web service invocation --%>