• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Web technology
 

Web technology

on

  • 18,712 views

 

Statistics

Views

Total Views
18,712
Views on SlideShare
18,712
Embed Views
0

Actions

Likes
0
Downloads
62
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Microsoft Word

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Web technology Web technology Document Transcript

    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH STUDY MATERIAL WEB TECHNOLOGY DEPARTMENT OF IT R S Vel Tech Vel Tech Multi Tech Dr.Rangarajan Dr.Sakunthala Engineering College Vel Tech High Tech Dr. Rangarajan Dr.Sakunthala Engineering College SEM - VIIIVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 1
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH INDEXUNITS PAGE NO.I. Introduction 06II. Dynamic HTML 106III. Multimedia 169IV. Database- ASP – XML 218V. Servlets and JSP 289 # 42 & 60, Avadi – Veltech Road, Avadi, Chennai – 62.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 2 R S
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Phone : 044 26840603 email : veltech@vsnl.com 26841601 website : www.vel-tech.org 26840766 www.veltechuniv.edu.in∗ Student Strength of Vel Tech increased from 413 to 10579, between 1997 and 2010.∗ Our heartfelt gratitude to AICTE for sanctioning highest number of seats and highest number of courses for the academic year 2009 – 2010 in Tamil Nadu, India.∗ Consistent success on academic performance by achieving 97% - 100% in University examination results during the past 4 academic years.∗ Tie-up with Oracle Corporation for conducting training programmes & qualifying our students for International Certifications.∗ Permission obtained to start Cisco Networking Academy Programmes in our College campus.∗ Satyam Ventures R&D Centre located in Vel Tech Engineering College premises.∗ Signed MOU with FL Smidth for placements, Project and Training.∗ Signed MOU with British Council for Promotion of High Proficiency in Business English, of the University of Cambridge, UK (BEC).∗ Signed MOU with NASSCOM.∗ Signed MOU with INVICTUS TECHNOLOGY for projects & Placements.∗ Signed MOU with SUTHERLAND GLOBAL SERVICES for Training & Placements.∗ Signed MOU with Tmi First for Training & Placements.VELTECH, VEL TECH MULTI TECH engineering colleges Accredited by TCSVEL TECH, VEL TECH MULTI TECH, VEL TECH HIGH TECH, engineering colleges & VEL SRI RANGA SANKU(ARTS & SCIENCE) Accredited by CTS.Companies Such as TCS, INFOSYS TECHNOLOGIES, IBM, WIPRO TECHNOLOGIES, KEANE SOFTWARE & TINFOTECH, ACCENTURE, HCL TECHNOLOGIES, TCE Consulting Engineers, SIEMENS, BIRLASOFT,MPHASIS(EDS), APOLLO HOSPITALS, CLAYTON, ASHOK LEYLAND, IDEA AE & E, SATYAM VENTURES,UNITED ENGINEERS, ETA-ASCON, CARBORANDUM UNIVERSAL, CIPLA, FUTURE GROUP, DELPHI-TVSDIESEL SYSTEMS, ICICI PRULIFE, ICICI LOMBARD, HWASHIN, HYUNDAI, TATA CHEMICAL LTD, RECKITTBENKIZER, MURUGAPPA GROUP, POLARIS, FOXCONN, LIONBRIDGE, USHA FIRE SAFETY, MALCO,YOUTELECOM, HONEYWELL, MANDOBRAKES, DEXTERITY, HEXAWARE, TEMENOS, RBS, NAVIA MARKETS,EUREKHA FORBES, RELIANCE INFOCOMM, NUMERIC POWER SYSTEMS, ORCHID CHEMICALS, JEEVANDIESEL, AMALGAMATION CLUTCH VALEO, SAINT GOBAIN, SONA GROUP, NOKIA, NICHOLAS PHARIMAL,SKH METALS, ASIA MOTOR WORKS, PEROT, BRITANNIA, YOKAGAWA FED BY, JEEVAN DIESEL visit ourcampus annually to recruit our final year Engineering, Diploma, Medical and Management Students. Preface to the First Edition This edition is a sincere and co-ordinated effort which we hope has made agreat difference in the quality of the material. “Giving the best to the students,VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 3
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHmaking optimum use of available technical facilities & intellectual strength” hasalways been the motto of our institutions. In this edition the best staff across thegroup of colleges has been chosen to develop specific units. Hence the material, as awhole is the merge of the intellectual capacities of our faculties across the group ofInstitutions. 45 to 60, two mark questions and 15 to 20, sixteen mark questions foreach unit are available in this material.Prepared By : Mr. P. Vijay Anand. Asst. Professor. Mr. Mahesh Asst. Professor.IT1451 WEB TECHNOLOGYUNIT I INTRODUCTION 8History of the Internet and World Wide Web – HTML 4 protocols – HTTP, SMTP, POP3, MIME, IMAP.Introduction to JAVA Scripts – Object Based Scripting for the web. Structures – Functions – Arrays –Objects.UNIT II DYNAMIC HTML 9Introduction – Object refers, Collectors all and Children. Dynamic style, Dynamic position, frames,navigator, Event Model – On check – On load – Onenor – Mouse rel – Form process – Event Bubblers –Filters – Transport with the Filter – Creating Images – Adding shadows – Creating Gradients – CreatingVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 4
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHMotion with Blur – Data Binding – Simple Data Binding – Moving with a record set – Sorting table data –Binding of an Image and table.UNIT III MULTIMEDIA 9Audio and video speech synthesis and recognition - Electronic Commerce – E-Business Model – E-Marketing – Online Payments and Security – Web Servers – HTTP request types – System Architecture –Client Side Scripting and Server side Scripting – Accessing Web servers – IIS – Apache web server.UNIT IV DATABASE- ASP – XML 10Database, Relational Database model – Overview, SQL – ASP – Working of ASP – Objects – File SystemObjects – Session tracking and cookies – ADO – Access a Database from ASP – Server side Active-XComponents – Web Resources – XML – Structure in Data – Name spaces – DTD – Vocabularies – DOMmethods.UNIT V SERVLETS AND JSP 9Introduction – Servlet Overview Architecture – Handling HTTP Request – Get and post request –redirecting request – multi-tier applications – JSP – Overview – Objects – scripting – Standard Actions –Directives.TEXT BOOK1. Deitel & Deitel, Goldberg, “Internet and world wide web – How to Program”, Pearson Education Asia,2001.REFERENCES1. Eric Ladd, Jim O’ Donnel, “Using HTML 4, XML and JAVA”, Prentice Hall of India – QUE, 1999.2. Aferganatel, “Web Programming: Desktop Management”, PHI, 2004.3. Rajkamal, “Web Technology”, Tata McGraw-Hill, 2001. UNIT – I HISTORY OF THE INTERNET PART – A1. What is ARPA what was key benefit of ARPANET? Advanced Research project agency of the Department of defense. The key benefit ofARPANET was that it enabled the researchers to communicate quickly and easily throughelectronic mail to facilitate a world wide comm.2. What is the primary goal of ARPANET. To allow multiple users to send and receive information simultaneously over thecommunication paths eg. Phone lines.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 5
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH3. What is packet switching? Packet switching is a Network operation technique in which digital data was sent in smallbundles called as packets along with the address information to be routed to their destinations.4. What is TCP. How it is used? TCP is the transmission control protocol used for communicating over the ARPANET. Itmainly insures the proper routing of messages from sender to receiver and their on time arrival.5. What is IP. The communication if different Networks was accomplished truly with the development ofIts Internet protocol used for creating networks of networks, the current architectures of theinternet.6. Application use of Internet Universities Research Institutions Military /Defence Area Business.7. Define WWW. Word Wide Web allows computer users to locate and view multimedia based documentslike documents with text, graphics, animations, audios (or) videos on do almost any subject. It wasdeveloped by Timberners – Lee of CERN in 1990.8. What is the use of Internet? The internet mixes computing and comm. Technologies and provides instant andconvenient worldwide accessible information’s.9. What is W3C. Word Wide Web consortium decided to developing nor proprietary, interoperabletechnologies for the world wide web. The primary goal is to make the web universally accessible –regardless of ability, language or culture. The WSC is also a standardization organization webtechnologies standardized by the WSC are called Recommendations which is a document thatspecifies a technology’s role, syntax rules.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 6
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH10. What is the use of Java script? i) Java script is an object –based scripting lang for with strong. (Proper software support for engineering techniques) ii) It introduces client side scripting which makes web pages more dynamic and interactive. iii) It provides the programming foundation for the more complex server side scripting.11. What is structured programming. A Disciplined approach to write programs that are clearer and easier to test, degdebug andmodify.12. Give examples for client based web Applications clients and server based web applications.Client based web applications clients i) XHTML ii) Java script iii) DHTML iv) Mash v) Dream vi) XMLServer based web applications 1. Web servers 2. Databases 3. Asp-NET 4. CGI 5. Perl 6. AHP 7. cold fusion13. What is web Browser? Web browsers are software programs that allow users to access the web’s rich multimediacontent to access the tremendous amount of information available on the web.e.g. Microsoft IE and Netscape14. Explain the following protocols.i) MIME (multipurpose internet Mail Extension)Basic idea is to continue to use the RFC 822 format, but to add structure to the message body anddefine encoding rules form non- ASCII messages.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 7
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHii) SMTP is a simple ASCII protocol Within the Internet, email is delivered by having the source machine wstablish a TCPconnection to port 25 of the destination machine. Listerining to this port is an email daemon thatspeaks SMTP which accepts incoming connections & copies messages from them into appropriatemailboxes. If a message cannot be delivered an error report containing the first part of theundelivered message is returned to the sender.iii) POP – Post Office Protocol is a simple protocol used for fetching email from a remote mailboxand to store it on the user’s local machine to be read later. The user to log in, log out, fetchmessages and delete messages. The protocol itself consists of ASCII text and has something of theflavor of SMTP.iv) IMAP (Interactive Mail Access Protocol) this is a more ophisticated delivery protocol whichwas designed to help the suer who uses multiple computers, perhaps a work station in the office, apc at home and a laptop on the road. The basic idea behind IMAP is for the email server tomaintain a central respository that can be accessed from any machine. MIME defines five new message headers. (i) MIME – version  Identifies the MIME version. (ii) Content – Description  Human – readable string telling what is in the message. (iii) Content – Id:  Unique – identifier (iv) Content – transfer – encoding  How the body is wrapped for transmission. (v) Content – Type  nature of message.15. What do you mean by XHTML elements? The spacing displayed by a browser in a web page is determined by the XHTML elementused to format the page.16. What is the use of <script> tag? The <script> tag indicates to the browser that the text that follows is part of a script.Attribute type specifies the scripting language used in the script – such as Java script.17. What is the use of browser’s Document object? The browser’s document object represents the XHTML document currently being displayedin the browser. The document object allows a script programmer to specify XHTML text to bedisplayed in the XHTML document. The browser contains a complete set of objects that allow script programmers to access andmanipulated every element of an XHTML document.18. What does the window object’s prompt method denote?VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 8
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH The window object’s prompt method displays a dialog into which the user can type avalue. The first argument is a message (called a prompt) that directs the user to take a specificaction. The optional second argument is the default string to display in the text field.19. Write Java script statements to accomplish each of the following tasks. a) var c, this IsAVariable, q76354, number b) value = window . prompt(“Enter an integer”, “0”); c) var age = parseInt(string value); d) if (number !=7) window . alert( “The variable number is not equal to 7”); e) document . write ln (“This is a Java Script program”); f) document. Write ln (“This is a<br />Java Script program”);20. Write a statement (or comment) to accomplish each of the following tasks. a) // Calculate the product of three integers b) var x,y,z, result; c) var xVal, yval, zval; d) xval=window. Prompt (“enter first integer:’, “0”); e) yVal =window. Prompt (“Enter second inter;”, “0”); f) zVal = window. Prompt (“Enter third integer;”, “0”); g) x= parseInt(xVal);21. What is definite repetition? Counter controlled repetition is often called as definite repetition, because the number ofrepetitions is known before the loop begins executing.22. Give the rules for forming structures programs. i. Begin with “Simplest flowchart” ii. Any rectangle (action) can be replaced by 2 rectangles (actions) in sequence. iii. Any rectangle (action) can be replaced by any control structure (sequence if, if…else, switch, while, do….while or for) iv. Rules 2&3 may be applied as often in any order.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 9
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH PART – B1. Explain in detail about the Equality and Relational operators in Java script with an exampleprogram. The section introduces a version of Java Script’s If statement that allows a program to makea decision based on the truth or falsity of a condition. if the condition is met (i.e., the condition istrue). The statement in the body of the if statement is executed. If the condition is not met (i.e., thecondition is false), the statement in the body of the if statement is not executed. We will see anexample shortly. Conditions in if statements can be formed by using the equality operators and relationaloperators summarized in fig. The relational operators all have the same level of precedence andassociate from left to right. The equality operators both have the same level of precedence, whichis lower than the precedence of the relational operators. The equality operators also associate fromleft to right. Java script Standard algebraic Sample Java equality or Meaning of Java script equality operator or Script relational condition relational operator condition operator Equality operators = == X==y X is equal to y ≠ != X!=y X is not equal to y Relational operators > > X>y X is greater than y < < X<y X is less than y ≥ >= x>=y X is greater than or equal to y ≤ <= X<=y X is less than or equal to y Figure: Equality and relational operatorsVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 10
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHCommon Programming Error: Reversing the operators !=, >=and <=, as in =!, =>and =<, respectively, is a syntax error.Common Programming Error: Confusing the equality operator, ==, with the assignment operator, =, is a logic error. Theequality operator should be read as “is equal to,” and the assignment operator should be read as“gets” or “gets the value of.” Some people prefer to read the equality operator as “double equals”or “equals equals”. The script in figure uses four if statements to display a time-sensitive greeting on awelcome page. The script obtains the local time from the user’s computer and converts it to a 12-hour clock format. Using this value, the script displays as appropriate greeting for the currenttime of day. The script and sample output are shown in figure. 1. <? xml version =”1.0”?> 2. <! DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 //EN” 3. http://www.w3.org/TR/xhtml 11/DTD/xhtml11.dtd> 4. 5. <!-- fig. welcome 6. html --> 6. <!-- Using Relational Operators --> 7. 8. <html xmlns = http://www.w3.org/1999/xhtml> 9. <head> 10. <title> Using Relations Operators </title> 11. 12. <script type = “text/javascropt”> 13. <!-- 14. var name, //string entered by the user 15. now = new Date (), //current date and time 16. hour = now.getHours(); //current hour (0-23) 17. 18. // read, the name from the prompt box as a string, 19. name=window. prompt( “please enter your name”, “GalAnt” ); 20. 21. // determine whether it is morning 22. if ( hour < 12 ) 23. document.write ( “<h1>Good Morning, “); 24. 25. // determine whether the time is PMVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 11
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 26. if ( hour >= 12 ) 27. { 28. // convert to a 12 hour clock 29. hour = hour – 12; 30. 31. // determine whether it is before 6 PM 32. if ( hour < 6 ) 33. document. write ( “<h1> Good Afternoon, “ ); 34. 35. // determine whether it is after 6 PM 36. if ( hour >= 6 ) 37. document. write ( “<h1> Good Evening, “ ) 38. } 39. 40. document. write ln( name + 41. “ , welcome to Javascript programming ! </h1>” ); 42. // -- > 43. </script> 44. 45. </head> 46. 47. <body> 48. <p> Click Refresh (or Reload) to run this script again. </p> 49. </body> 50. </html> Figure: Using equality and relational operators (part 2 of 2) Lines 14-16 declare the variables used in the script. Remember that variables may bedeclared in one declaration or in multiple declarations. If more than one variable is declared in asingle declaration (as in this example), the names are separated by commas (,). This list of namesVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 12
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHis referred to as a comma-separated list. Once again, note the comment at the end of each line,indicting the purpose of each variable in the program. Also not that some of the variables areassigned a value in the declaration. JavaScript allows you to assign a value to a variable when thevariable is declared. Line 15 sets the variable now to a new Date object, which contains information about thecurrent local time. In section 7.2, we introduced the document object, an object that encapsulatesdata pertaining to the current Web page. Programmers may choose to use other objects toperform specific tasks or obtain particular pieces of information. Here, we use JavaScript’s built-inDate object to acquire the current local time. We create a new instance of an object by using thenew operator followed by the type of the object, Date, and a pair of parentheses. Some objectsrequire that arguments be placed in the parentheses to specify details about the object to becreated. In this case, we leave the parentheses empty to create a default Date object containinginformation about the current date and time. After line 15 executes, the variable now refers to thenew Date object. [Note: We did not need to use the new operator when we used the documentand window objects because these objects always are created by the browser] line 16 sets thevariable hour to an integer equal to the current hour (in a 24-hour clock format) returned by theDate object’s getHours method. Please refer to Chapter 12 for a more detailed discussion of theDate object’s attributes and methods, and of objects in general. As in the preceding example, thescript uses window. prompt to allow the user to enter a name to display as part of the greeting(line 19). To display the correct time-sensitive greeting, the script must determine whether the user isvisiting the page during the morning, afternoon or evening. The first if statement (line 22-23)compares the value of variable hour with the integer value12. if hour is less than 12, then the useris visiting the page during the morning, and the statement at line 23 outputs the string “Goodmorning”. If this condition is not met, line 23 is not executed. Line 26 determines whether hour isgreater than or equal to 12. if hour is greater than or equal to 12, then the user is visiting the pagein either the afternoon or the evening. Lines 27-38 execute to further determine the appropriategreeting. If hour is less than 12, then the JavaScript interpreter does not execute these lines andcontinues to line40. The {in line 27 begins a block of statements (lines 27-38) that are all executed together ifhour is greater than or equal to 12. Line 29 subtracts 12 from hour, converting the current hourfrom a 24-hour clock format to a 12-hour clock format. The if statement (line 32) determineswhether hour is now less than 6. If it is, then the time is between noon and 6 PM, and line 33outputs the string “Good Afternoon”. If hour is greater than or equal to 6, the time is between 6PM and midnight, and the script outputs the greeting “Good Evening” (lines 36-37). The brace} inline 38 ends the block of statements associated with the if statement in line 26. Note that ifstatements can be nested, i.e., one if statement can be placed inside another if statement. The ifstatements that determine whether the user is visiting the page in the afternoon or the evening(lines 32-33 and lines 36-37) only execute if the script has already established that hour is greaterthan or equal to 12 (line 26). If the script has already determined the current time of day to bemorning, these additional comparisons are not performed. Finally, lines 40-41 display theVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 13
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHremaining part of the greeting, which does not depend on the time of day.Note the indentation of the if statements throughout the program. Such indentation enhancesprogram readability.Good Programming Practice: Indent the statement in the body of an if statement to make the body of the statement standout and to enhance program readability.Good Programming Practice: Place only one statement per line in a program. This format enhances program readability.Common programming Error: Forgetting the left and right parentheses for the condition in an if statement is a syntaxerror. The parentheses are required. Note that there is no semicolon (;) at the end of the first line of each if statement. Includingsuch a semicolon would result in a logic error at execution time. For example, If ( hour < 12 ) ; document. write ( “<h1> Good Morning, “);would actually be interpreted by JavaScript erroneously as if ( hour < 12 ) ; document. write ( “<h1> Good Morning, “ ); Where the semicolon on the line by itself – called the empty statement – is the statement toexecute it the condition in the if statement is true. When the empty statement executes, no task isperformed in the program. The program then continues with the next statement, which executesregardless of whether the condition is true of false.2. Explain in detail about the history of the Internet. In the late 1960s, one of the authors (HMD) was a graduate student at MIT. His research atMIT’s Project Mac (now the Laboratory for Computer Science – the home of the Word Wide WebConsortium) was funded by ARPA- the Advanced Research Projects Agency of the Department ofDefense. ARPA sponsored a conference at which several dozen ARPA – funded graduate studentwere brought together at the University of illionols at Urbana-Champaign to meet and shareideas. During the conference. ARPA rolled out the blue prints of networking the main computerssystems of about a dozen ARPA – funded universities and research institutions. They wee to beconnected with communications lines operating at a then – stunning 56Kbps (i.e., 56,000 bits persecond) – this at a time when most people (of the few who could) were connecting over telephoneVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 14
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHlines to computers at a rate of 110 bits per second. HMD vividly recalls the excitement at theconference. Researchers at Harvard talked about communicating with the Univac1180”supercomputer” at the University of Utah to handle calculations related to their computergraphics research. Many other intriguing possibilities were raised. Academic research was on theverge of taking a giant leap forward. Shortly after this conference, ARPA proceeded to implementthe ARPANET, the grandparent of today’s Internet. Things worked out differently from what as originally planned. Rather than the primarybenefit of researchers sharing one other’s computers, it rapidly became clear that enablingresearchers to communicate quickly and easily via what became known as electronic mail (e-mail,for short) was the key benefit of the ARPANET. This is true even to day on the Internet, as e-mailfacilities communication of all kinds among hundreds of millions of people world wide. One of the primary goals of ARPANET was to allow multiple users to send and receiveinformation simultaneously over the same communications paths (e.g., phone lines). The networkoperated with a technique called packet switching, in which digital data was sent in smallbundles called packets. The packets contained address, error control and sequencing information.The address information allowed packets contained address, error control and sequencinginformation. The address information allowed packets to be routed to their destinations. Thesequencing information helped reassemble the packets ( which, because of complex routingmechanisms, could actually arrive out of order) into their original order for presentation to therecipient. Packets form different senders were intermixed on the same lines. This packet –switching technique greatly reduced transmission costs, as compared with the cost of dedicatedcommunications lines. The network was designed to operate without centralized control if a portion of thenetwork failed, the remaining working portions would still route packets from senders to receiverover alternative paths. The protocols for communicating over the ARPANET became known as TCP –theTransmission Control Protocol. TCP ensured that messages were properly routed from sender toreceiver and that they arrived intact. As the Internet evolved, organizations worldwide were implementing their own networksfor both intraorganization (i.e., within the organization) and interorganzation (i.e., betweenorganizations) communications. A wide variety of networking hardware and software appeared .one challenge was to get these different networks to communicate. ARPANET accomplished thiswith the development of IP – the Internet Protocol, truly creating a “network of networks,” thecurrent architecture of the Internet. The combined set of protocols is now commonly calledTCP/IP. Initially, Internet use was limited to universities and research institutions; then the militarybegan using the Internet. Eventually, the government decided to allow access to the Internet forcommercial purposes. Initially, there was resentment in the research and military communities –VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 15
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHthese groups were concerned that response times would become poor as “ the Net” becamesaturated with users. In fact, the exact opposite has occurred. Businesses rapidly realized that they could tunetheir operations and offer new and better services to their clients. So they started spending vastamount of money to develop and enhance the Internet. This generated fierce competition amongcommunications carriers and hardware and software suppliers to meet this demand. The result isthat bandwidth (i.e., the information carrying capacity) on the Internet has increasedtremendously and costs have decreased significantly.3. Write a simple program to print a line of text in a web page and explain the tags. Java Script uses notations that may appear strange to nonprogrammers. We begin byconsidering a simple script (or program) that displays the text “Welcome to Java Scriptprogramming!” in the body of an XHTML document. The internet Explorer Web browser containsa Java Script interpreter, which processes the commands written in Java Script. The Java Scriptcode and its output are shown in Fig. 1. <7xml version = “1.0”7> 2. <IDOCTYPE html PUBLIC” =//w3c//DTD XHTML 1.0 Strict /EN” 3. http://www.w3.org/TR/xhtml 1/DTD/xhtml 1-strict .dtd > 4. 5. <!- - Fig. 7.1 : welcome. html - - > 6. <!- - Displaying the line of text - - > 7. 8. <html xmlns = http://www.w3 org/1999/xhtml> 9. <head> 10. <title> A First Program in Java Script / title> 11. 12. <script type = “text/java script “> 13. <! - - 14. document. Written ln ( 15. “<hl= Welcome to Java script programming !</hl>”); 16. // - - > 17. </script> 18. 19. </ head ><body></body> 20. </html>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 16
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure: First program in Java Script This program illustrates several important Java Script features. We consider each line of theXHTML document and script in detail. As in the preceding chapters, we have given each XHTMLdocument line numbers for the reader’s convenience; the line numbers are not part of the XHTMLdocument or of the Java Script programs. Lines 14-15 do the “real work” of the script, namely,displaying the phrase Welcome to Java Script programming! In the Web page. However, let usconsider each line in order. Line 9 indicates the beginning of the <head> section of the XHTML document. For themoment, the Java Script code we write will appear in the <head> section. The browser interpretsthe contents of the <head> section first, so the Java Script programs we write there will executebefore the <body> of the XHTML document displays. In later chapters on Java script and in thechapters on dynamic HTML, we illustrate inline scripting, in which Java Script code is written inthe <body> of an XHML document. Line 11 is simply in blank line to separate the <script> tag in line 12 from the other XHTMLelements. This effect helps the script sand out in the XHTML document and makes the documenteasier to read. Line 12 uses the <script> tag to indicate to the browser that the text which follows is par ofa script. The type attribute specifies the type of files as well as the scripting language used in thescript – in this case, a text file written in Java script. Both Microsoft internet Explorer and Netscapeuse Java Script as the default scripting language. [Note Even though Microsoft calls the languageJscript, the type attribute specifies java script, to adhere to the ECMA Script standard] Line 13 contains the XHTML comment tag <! - -, some older Web browsers do not supportscripting. In such browsers, the actual text of a script often will display in the Web page. Toprevent this from happening, many script programmers enclose the script code in an XHTMLcomment, so that browsers which do not support scripts ignore the scripts. The syntax used is asfollows:<script type = “text / java script”><!- -script code here VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 17
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH/ / - -></script> When a browser that does not support scripts encounters the preceding code, it ignore the<script> and </script> tags and the script code in the XHTML comment. Browsers that dosupport scripting will inter prêt the Java Script code as expected. [ Note Some browsers requirethe Java Script single – line comment / / before the ending XHTML comment delimiter (- - >) tointerpret the script properly.] Lines 14-15 instruct the browser’s Java Script interpreter to perform an action, namely, todisplay in the Web page the string of characters contained between the double quotation(“)marks. A string is come times called a character string, a message or a string literal. We referto characters between double quotation marks generically as strings. Individual white spacecharacters between words in a string are not ignored by the browser. However, if consecutivespaces appear in a string, browsers condense then to a single space. Also, in most cases, browsersignore leading white space characters (i.e., white space at the beginning of a string). Line 14-15 use the browser’s document object, which represents the XHTML document thebrowser is currently displaying. The document object allows a script programmer to specify textto display in the XHTML document. The browser contains a complete set of objects that allowscript programmers to access and manipulate every element of and XHTML document. In the nextseveral chapters, we over view some of these objects. Chapter 13-18 provide in – depth coverage ofmany more objects that a script programmer can manipulate. An object resides in the computer’s memory and contains information used by the script.The term object normally implies that attributes (data) and behaviours ( methods) are associatedwith the object. The object’s method use the attributes’ data to perform useful actions for the clientof the object (I.e., the script that calls the methods). A method may require additional information(arguments) to perform its action; this information is enclosed in parentheses after the name of themethod in the script. In lines 14-15, we call the document object’s write in method to write a lineof XHTML markup in the XHTML document. The parentheses following the method name writeln contain the arguments that method write ln requires (in this case, the string of XHTML that thebrowser is to display). Method write ln instructs the browser to display the argument string. If thestring contains XHTML elements, the browser displays the phrase welcome to Java ScriptProgramming ! as an h1- level XHTML heading, because the phrase is enclosed in an h1 element. The code elements in lines 14-15, including document. Write ln its argument in theparentheses ( the string) and the semicolon (;), together are called a Statement. Every statementshould end with a semicolon (also known as the statement terminator), although this practice isnot required by Java Script. Line 17 indicates the end of the script.4. Explain the 3 selection statement in detail with example.i) If selection statementii) If elseiii) While repetition statementVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 18
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH A selection structure is used to choose among alternative courses of action in a program.For example, suppose that the passing grade on an examination is 60 (out of 100). Then thepseudocode statement If student’s grade is greater than or equal to 60 Print “Passed” Determines whether the condition “student’s grade is greater than or equal to 60” is true orfalse. If the condition is true, then “Passed” is printed, and the next pseudocode statement in orderis “ performed” (remember that pseudocode is not a real programming language). If the conditionis false, the print statement is ignored, and the next pseudocode statement in order is performed.Note that the second line of this selection structure is indented. Such indentation is optional, but itis highly recommended, because it emphasizes the inherent structure of structured programs. TheJava Script interpreter ignores white space characters – blanks, tabs and new lines used forindentation and vertical spacing. Programmers insert these white space characters to enhanceprogram clarity.if ( student Grade >= 60) document. Write in (“Passed”); Note that the Java Script code corresponds closely to the pseudocode. This similarity is thereason that pseudocode is a useful program – development tool. The statement in the body of theif statement outputs the character string “Passed” in the XHTML document. The flow chart in fig. illustrates the single – selection if statement. This flowchart containswhat is perhaps the most important flow charting symbol – the diamond symbol (or decisionsymbol), which indicates that a decision is to be made. The decision symbol contains anexpression, such as a condition, that can be either true or false. The decision symbol has to flowlines emerging from it. One indicates the path to follow in the program when the expression inthe symbol is true; the other indicates the path to follow in the program when the expression isfalse. A decision can be made on any expression that evaluates to a value of Java script’s Booleantype (i.e., any expression that evaluates to true or false). grade >=60 Print “passed” falseVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 19
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Fig. Flow charting the single – selection if statement. Note that the if statement is a single – entry/ single – exit control structure. We will soonlearn that the flow charts for the remaining control structures also contain ( besides small circlesymbols and flow lines) only rectangle symbols, to indicate the actions to be performed, anddiamond symbols, to indicate decisions to be made. This type of flow chart represents the action /decision model of programming. We can envision eight bins, each containing only the control structures of one of the eighttypes. These control structures are empty. Nothing is written in the rectangles or in the diamonds.The programmer’s task, then, is to assemble a program from as many of each type of controlstructure as the algorithm demands, combining the control structures in only two possible ways(stacking or nesting), then filling in the actions and decisions in a manner appropriate for thealgorithm. We will discuss the variety of ways in which action and decisions may be written. The if selection statement performs an indicated action only when the conditions evaluatesto true; otherwise, the action is skipped. The if …else selection statement allows the programmerto specify that different action is to be performed when the conditions is true than when thecondition is false. For example, the pseudocode statement If student’s grade is greater than or equal to 60 Print “Passed” Else Print “Failed”. Prints passed if the student’s grade is greater than or equal to 60 and prints Failed if thestudent’s grade is less than 60. In either case, after printing occurs, the next pseudocode statementin sequence (i.e., the next statement after the whole if …else structure) is performed. Note that thebody of the Else part of the structure is also indented. The indication convention you choose should be applied carefully throughout yourprograms ( both in pseudocode and in Java script). It is difficult to read programs that do not useuniform spacing conventions.The preceding pseudocode if …Else statement may be written in Java script asIf ( student Grade >=60) document. Write ln (“Passed”);else document. write ln (“Failed”); The flow chart in fig. nicely illustrates the flow of control in the if ….else statement. Onceagain, note that the only symbols in the flow chart ( besides small circles and arrows) areVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 20
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHrectangles ( for actions) and a diamond ( for a decision). We continue to emphasize this action/decision model of computing. Imagine again a deep bin containing as many empty double –selection structures as might be needed to build a Java Script algorithm. The programmer’s job isto assemble the selection structures ( by stacking and nesting) with other control structurerequired by the algorithm and to fill in the empty rectangles and empty diamonds with actionsand decisions appropriate to the algorithm’s implementation. false grade >=60 True Print “Failed” Print “passed” Flow charting the double – selection if ….else statement. Java Script provides an operator, called the conditional operator(?:), that is closely relatedto the if …else statement. The operator ?: is Java script’s only ternary operator – it takes threeoperands. The operands together with the ?: from a conditional expression. The first operand is aBoolean expression. The second is the value for the conditional expression if the conditionevaluates to true and the third is the value for the conditional expression if the condition evaluatesto false. For example, the statement Document. write ln ( Student Grade >=60? “passed”:”Failed”); Contains a conditional expression that evaluates to the string “Passed” if the conditionstudent Grade >= 60 is true and evaluates to the string “Failed” if the condition is false. Thus, thisstatement with the conditional operator performs essentially the same operation as the precedingif …else statement. the precedence of the conditional operator is low, so the entire conditionalexpression is normally placed in parentheses to ensure that it evaluates correctly.Nested if … else statements test for multiple cases by placing if …else statements inside if…elseVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 21
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHstatements. For example, the following pseudocode statement will print A for exam grades greaterthan or equal to 90, B for grades in the range 80 to 89, C for grades in the range 70 to 79, D forgrades in the range 60 to 69 and F for all other grades: If student’s grade is greater than or equal to 90 Print “A”ElseIf student’s grade is greater than or equal to 80Print “B”ElseIf student’s grade is greater than or equal to 70Print “C”ElseIf student’s grade is greater than or equal to 60Print”D”ElsePrint “F”This pseudocode may be written in Java script asIf ( Student Grade >=90)document. Write ln (“A”);elseIf (student Grade >=80);Document. write ln(“B”)elseIf (student Grade >=70);Document. write ln(“C”)elseIf (student Grade >=60);Document. write ln(“D”)elseDocument. write ln(“F”)If student Grade is greater than or equal to 90, the first four conditions will be true, but only thedocument. write in installment after the first test will execute. After that particular document.write ln executes, the else part of the outer if … else statements is skipped.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 22
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHMost Java Script programmers prefer to write the preceding if structure asIf ( grade >=90)document. write ln (“A”);else If ( grade >=80)document. write ln (“B”);else If ( grade >=70)document. write ln (“C”);else If ( grade >=60)document. write ln (“D”);elsedocument. write ln (“F”); The two forms are equivalent. The latter form is popular because it avoids the deepindentation of the code to the right. Such deep indentation often leaves little room on a line,forcing lines to be split and decreasing program readability. It is important to note that the Java Script interpreter always associates an else with theprevious if, unless told to do otherwise by the placement of braces ({ }). This situation is referred toas the dangling – else problem. For example,If (X>5) If (y>5) document. write ln (“x and Y are >5”);else document. writeln (“x” is <= 5”);appears to indicate with its indentation that if x is greater than 5, the if structure in its bodydetermines whether y is also greater than 5. If so, the body of the nested if structure outputs thestring “x and y are >5”. Otherwise, it appears that if X is not greater than 5, the else part of the if… else structure outputs the string “x is <=5”.Beware! The preceding nested if statement does not execute as it appears. The interpreter actuallyinterprets the preceding statement asIf (x>5) If (y>5) Document . writeln (“x and y are >5”);Else Document .write ln (“x is <=5”);VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 23
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH In which the body of the first if statement is a nested if …. Else statement. This statementtests whether x is greater than 5. if so, execution continues by testing whether y is also greater than5. if the second condition is true, the proper string – “x and y are > 5 “ – is displayed. However, ifthe second condition is false, the string “x is <=5” is displayed, even though we know that x isgreater than 5.To force the preceding nested if statement to execute as it was intended originally, the statementmust be written as follows:If (x>5){ if (y>5) document . write ln (“x and y are >5”);}else document. write ln(“x is <=5”); The braces ({}) indicate to the interpreter that the second if statement is in the body of thefirst if statement and that the else is matched with the first if statement. In Exercise you willinvestigate the dangling – else problem further. The if selection statement expects only one statement in its body. To include severalstatements in the body of an if, enclose the statements in braces ({ and }). A set of statementscontained within a pair of braces is called block (sometimes known as a compound statement).The following example includes a block in the else part of an if ….else statement:If ( grade >=60) Document.write ln(“Passed”);Else{ document.write ln (“Failed < br/>”): document.write ln(“You must take this course again.”);}In this case, if grade is less than 60, the program executes both statements in the body of the elseand printsFailed.You must take this course again.Note the braces surrounding the two statements in the else clause. These braces are important.Without them, the statementDocument.write ln (“You must take this course again.”);VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 24
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHWould be outside the body of the else part of the if and would execute regardless of whether thegrade is less than 60. Syntax errors (e.g., when one brace in a block in left out of the program) are caught by theinterpreter when it attempts to interpret the code containing the syntax error. A logic error (e.g.,the one caused when both braces around a block are left out of the program) also has its effect atexecution time. A fatal logic error causes a program to fail and terminate prematurely. A nonfatallogic error allows a program to continue executing, but the program produces incorrect results.A repetition structure (also known as a loop) allows the programmer to specify that script is torepeat an action while some condition remains true. The pseudocode statement While there are more items on my shopping list Purchase next item and cross it off my list Describes the repetitions that occurs during a shopping trip. The condition “there are moreitems on my shopping list” may be true or false, if it is true, then the action “Purchase next itemand cross it off my list” is performed. This action will be performed repeatedly while the conditionremains true. The statement(s) contained in the While structure may be a single statement or ablock. Eventually, the condition becomes false ( i.e., when the last item on the shopping list hasbeen purchased and crossed off the list). At this point the repletion terminates, and the firstpseudocode statement after the repetition structure executes.As an example of a while statement, consider a program segment designed to find the first powerof 2 large than 1000, Variable product begins with the value 2. the statement is as follows:Var product = 2;While ( product <= 1000 )Product =2* product; When the while statement finishes executing, product contains the result 1024. Theflowchart in fig. illustrates the flow of control of the preceding while repetition statement. Onceagain, note that (besides small circles and arrows) the flowchart contains only a rectangle symboland a diamond symbol. True Product = 2 * product Product <=1000 FalseVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 25
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Fig. Flowcharting the while repetition statement When the script enters the while statement, product is 2. the script repeatedly multipliesvariable product by 2. So product takes on the value 4,8,16,32,64,128,256,512 and 1024successively. When product becomes 1024, the condition product <= 1000 in the while statementbecomes false. This terminates the repetition, with 1024 as product’s final value. Executioncontinues with the next statement after the while statement. [Note: If a while statement’s conditionis initially false, the body statement(s) will never execute.] The flowchart clearly shows the repetition. The flow line emerging from the rectanglewraps back to the decision, which the script tests each time through the loop until the decisioneventually becomes false. At this point, the while statements exits, and control passes to the nextstatement in the program.5. Explain in detail about the counter controlled repetition.Consider the following problem statement: A class of ten students took a quiz. The grades (integers in the range 0 to 100) for this quiz are available to you. Determine the class average on the quiz. The class average is equal to the sum of the grades divided by the number of students (10 inthis case). The algorithm for solving this problem on a computer must input each of the grades.Perform the averaging calculation and display the result. Let us use pseudocode to list the actions to execute and specify the order in which theactions should execute. We use counter – controlled repetition to input the grades one at a time.this techniques uses a variable called a counter to control the number of times a set of statementsexecutes. In this example, repetition terminates when the counter exceeds 10. In this section, wepresent a pseudocode algorithm (fig.) and corresponding program (fig.) In the next section, weshow how to develop pseudocode algorithms. Counter – controlled repetition often is calleddefinite repetition. Because the number of repetitions is known before the loop begins executing. Note the references in the algorithm to a total and a counter. A total is a variable in which ascript accumulates the sum of a series of values. A counter is a variable a script uses to count – inthis case, to count the number of grades entered. Variables that store totals should normally beinitialized to zero before they are used in a program.Set total to zeroSet grade counter to oneWhile grade counter is less than or equal to tenIn put the west gradeAdd the grade into the totalAdd one to the grade counter VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 26
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHSet the class average to the total divided by tenPrint the class averageFig. pseudocode algorithm that uses counter – controlled repetition to solve the class averageproblem. 1. <?xml version = “1.0”?> 2. <100CTYPE html PUBLIC “//w3c//DTD XHTML 1.0 Strict // EN’ 3. http://www.w3.org/TR/xhtmll/DTD/xhtmll-strict.dtd > 4. 5. <!- - Fig. average html - - > 6. <!- - Class Average program - - > 7. 8. <html xmlns = “http: //www.w3.org/1999/xhtml”> 9. <head> 10. <title> Class Average program</title> 11. 12. <script type =”text/javascript”> 13. <!- - 14. var total, // sum of grades 15. grade counter, // number of grades entered 16. grade value, // grade value 17. average, // average of all grades 18. grade; // grade typed by user 19. 20. // initialization phase 21. total = 0; // clear total 22. grade Counter = 1; // prepare to loop 23. 24. // processing phase 25. while (grade Counter <= 10) { // loop 10 times 26. 27. // prompt for input and read grade from user 28. grade = window. Prompt( enter integer grade:’, “0”); 29. 30. // convert grade from a string to an integer 31. grade value = parseInt ( grade ); 32. 33. // add grade value to total 34. total = total + grade value; 35. 36. // add 1 to grade counter 37. grade counter = grade counter +1; 38. } 39.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 27
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 40. // Termination phase 41. average = total /10; //calculate the average 42. 43. // display average of exam grades 44. document. write ln( 45. “<hl>Class average is “+average + “</h1>”); 46. // - - > 47. </script> 48. 49. </head> 50. <body> 51. <p>Click Refresh ( or Reload) to run the script again <p> 52. </body> 53. </html>This dialog is displayed 10 times user input is 100.88, 93,55,68,77,83,95,73 and 62 Fig. Counter –controlled repetition to calculate a class average (part 2 ot 2). Lines 14-18 declare variables total, grade Counter, grade value, average and grade. Thevariable grade will store the string the user types into the prompt dialog. The variable grade valuewill store the integer value of the grade the user enters in a prompt dialog. Lines 21-22 are assignment statements that initialize total to 0 and grade Counter to 1. Notethat variables total and grade Counter are initialized before they are used in a calculation.Uninitialized variables used in calculations result in logic errors and produce the value NaN(not anumber). Line 25 indicates that the while statement continues iterating while the value of gradeCounter is less than or equal to 10. Line 28 corresponds to the pseudocode statement “input thenext grade.” The statement displays a prompt dialog with the prompt “Enter integer grade:’ onVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 28
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHthe screen. After the user enters the grade. Line 31 converts it from a string to an integer. We mustconvert the string to an integer in this example; otherwise, the addition statement in line 34 will bestring- concentration statement rather than a numeric sum. Next, the program updates the total with the new grade value entered by the user. Line 34adds grade value to the previous value of total and assigns the result to total. This statementseems a bit strange, because it does not follow the rule of algebra. Keep in mind that Java Scriptoperator precedence evaluates the addition (+) operation before the assignment (=) operation. thevalue of the expression on the right side of the assignment operator always replaces the value ofthe variable on the left side of the assignment operator. The program now is ready to increment the variable grade Counter to indicate that a gradehas been processed and to ready the next grade from the user. Line 37 adds 1 to grade Counter, sothe condition in the while statement will eventually become false and terminate the loop. Afterthis statement executes, the program continues by testing the condition in the while statement inline 25. If the condition is still true, the statements in lines 28-37 repeat. Otherwise the programcontinues execution with the first statement in sequence after the body of the loop (i.e., line 41). Line 41 assigns the results of the average calculation to variable average. Lines 44-45 write aline of XHTML text in the document that displays the string “Class average is “ followed by thevalue of variable average as an <h1> head in the browser. Execute the script in Internet Explorer by double clicking the XHTML document (fromWindows Explorer). This script reads only integer values from the user. In the sample programexecution in fig. the sum of the values entered (100,88,93,55,68,77,83,95,73 and 62) is 794. Althoughthe script reads only integers, the averaging calculation in the program does not produce aninteger. Rather, the calculation produces a floating – point number (i.e., a number containing adecimal point). The average of the 10 integers input by the user in this example is 79.4. Java Script actually represents all numbers as floating – point numbers in memory.Floating- point numbers often develop though division, as shown in this example. When wedivide 10 by 3, the result 3.3333333…., with the sequence of 3s repeating infinitely. The computerallocates only a fixed amount of space to hold such a value, so the stored floating – point value canbe only an approximation. Despite the fact that floating – point numbers are not always 100%precise, they have numerous applications. For example, when we speak of a “normal” bodytemperature of 98.6, we do not need to be precise to a large number of digits. When we view thetemperature on a thermometer and read it as 98.6, it may actually be 98.5999473210643. The pointhere is that few applications require high – precision floating – point values, so calling thisnumber simply 98.6 is fine for most applications.6. Explain in detail about the Top down step wise refinement.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 29
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHLet us generalize the class average problem. Consider the following problem: Develop a class – averaging program that will process an arbitrary number of grades each time the program is run.In the first class – average example, the number of grades (10) was known in advance. In thisexample, no indication is given of how many grades the user will enter. The program mustprocess an arbitrary number of grades. How can be program determine when to stop the input ofgrades? How will it know when to calculated and is play the class average? One way to solve this problem is to use a special value called a sentinel value (also called asignal value, a dummy value or a flag value) to indicate the end of data entry. The user types ingrades until all legitimate grades have been entered. Then the user types the sentinel value toindicate that the last grade has been entered. Sentinel – controlled repetition is often calledindefinite repetition, because the number of repetitions is not known before the loop beginsexecuting. Clearly, one must choose a sentinel value that cannot be confused with an acceptable inputvalue. Because grades on a quiz are normally nonnegative integers from 0 to 100, -1 is anacceptable sentinel value for this problem. Thus, an execution of the class – average programmight process a stream of inputs such as 95,96,75,74,89 and -1. The program would computer andprint the class average for the grades 95,96,75,74 and 89 (-1 is the sentinel value, so it should notenter into the average calculation). We approach the class – average program with a technique called top-down, stepwiserefinement, a technique that is essential to the development of well – structured algorithms. Webegin with a pseudo code representation of the top: Determine the class average for the quiz The top is a single statement that conveys the overall purpose the program. As such, thetop is, in effect, a complete representation of a program. Unfortunately, the top rarely conveys asufficient amount of detail from which to write the Java Script algorithm. Therefore we must begina refinement process. First,. We divide the top into a series of smaller tasks and list them in theorder in which they need to be performed, crating the following fits refinement: Initialize variables Input, sum up and count the quiz grades Calculate and print the class averageHere, only the sequence structure is used; the steps listed are to be executed in order, one after theother. To proceed to the next level of refinement (the second refinement), we commit to specificvariables. We need running total of the numbers, a count of how many numbers have beenVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 30
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHprocessed, a variable to receive the string representation of each grade as it is input, a variable tostore the value of the grade after it is converted to an integer and a variable to hold the calculatedaverage. The pseudocode statement Initialize variablesMay be refined as follows: Initialize total to zero Initialize grade Counter to zero Note that only the variables total and grade Counter are initialized before they are used; thevariables average, grade and grade value ( for the calculated average, the user input and theinteger representation of the grade, respectively) need not be initialized, because their values aredetermined as they are calculated or input. The pseudocode statement Input, sum up and count the quiz grades Requires a repletion structure (a loop) that successively inputs each grade. We do not knowin advance how many grades are to be processed, so we will use sentinel – controlled repetition.The user at the key board will enter legitimate grades, one at a time. after entering the lastlegitimate grade, the user will enter the sentinel value. The program will test for the sentinelvalue. The program will test for the sentinel value after the user enters each grade and willterminate the loop when the sentinel value is encountered. The second refinement of thepreceding pseudocode statement is then Input the first grade (possibly the sentinel) While the user has not as yet entered the sentinel Add this grade into the running total Add one to the grade counter Input the next grade (possibly the sentinel) Note that in pseudocode, we do not use braces around the pseudocode that forms the bodyof the wile structure. We simply indent the pseudocode under the while, to show that it belongs tothe body of the while. Remember, pseudocode is only an informal program- development aid. The pseudocode statement Calculate and print the class averageMay be refined as follows: If the counter is not equal to zero Set the average to the total divided by the counter Print the averageElseVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 31
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Print “No grades were entered” Note that we are testing for the possibility of division by zero – a logic error that, ifundetected, would cause the program to produce invalid. The complete second refinement of thepseudocode algorithm for the class – average problem is shown in fig.Initialize total to zeroInitialize grade Counter to zeroInput the first grade ( possibly the sentinel)While the user has not as yet entered the sentinelAdd this grade intro the running totalAdd one to the grade counterInput the next grade (possibly the sentinel)If the counter is not equal to zero Set the average to the total divided by the counterPrint the averageElsePrint “No grades were entered”Fig. Sentinel – controlled repetition to solve the class – average problem The pseudocode algorithm in fig. solves the more general class-averaging problem. Thisalgorithm was developed after only two refinements. Sometimes more refinements. Sometimesmore refinements are necessary. Figure shows the Java Script program and a sample execution. Although each grade is aninteger, the averaging calculation is likely to produce a number with a decimal point ( a realnumber). In this example, we seen that control structure may be stacked on top of one another (insequence) just as a child stacks building blocks. The while statement ( line 33-46) is followedimmediately by an if …else statement ( lines 49-57) in sequence. Much of the code in this programis identical to the code in fig. so we concentrate in this example on the new features. Line 23 initializes grade Counter to 0, because no grades have been entered yet. Rememberthat the program uses sentinel – controlled repetition. To keep an accurate record of the number ofgrades entered. The script increments grade Counter only after processing a valid grade value. 1. <?xml version =”1.0”?> 2. <! DOCTYPE html PUBLIC”-//W3C//DTD DHTML 1.0 Strict // EN” 3. “http:/www.w3.org/TR/xhtml 1/DTD/xhtml 1- strict.dtd”> 4.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 32
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 5. <!- - fig. average 2, html 6. <!- - sentinel – controlled Repetition - - > 7. 8. <html xmlns=http://www.w3.org/1999/xhtml> 9. <head> 10. <title> class Average Program: 11. Sentinel – controlled Repetition </title> 12. 13. Z<script type =”text/javascript”> 14. <! - - 15. var grade counter, // number of grades entered 16. grade value, // grade value 17. total, // sum of grades 18. average, // average of all grades 19. grade; // grade typed by user 20. 21. // Initialization phase 22. total =0; 23. grade Counter = 0; // prepare to loop 24. 25. // Processing phase 26. // prompt for input and read grade from use n 27. grade = window.prompt( 28. “Enter Integer Grade, -1 to quite:’, “0”); 29. 30. // convert grade from a string to an integer 31. grade value – parseInt (grade); 32. 33. while (gradevalue !=-1){ 34. // add gradevalue to total 35. total = total + grade value; 36. 37. // add 1 to grade counter 38. grade counter = grade counter +1; 39. 40. // prompt for input and read grade from user 41. grade = window. Prompt( 42. “Enter Integer Grade, -1 to Quit:”, “0”); 43. 44. // convert grade from a string to an integer 45. grade value = parselnt ( grade); 46. } 47. 48. // Termination phaseVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 33
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 49. if ( grade Counter !=0){ 50. average = total / grade Counter; 51. average = total / grade Counter; 52. 53. // display average of exam grades 54. document. write ln( 55. } 56. else 57. document. writeln ( “<p>No grade were entered </p>”): 58. // 59. </script> 60. </head> 61. 62. <body> 63. <p> Click Refresh ( or Reload) to run the script again </p> 64. </body> 65. </html> Fig. Sentinel – controlled repetition to calculate a class averageThis dialog is displayed four times user input is 97,88,72 and -1 Fig. Sentinel – controlled repetition to calculate a class average. Note the difference in program logic for sentinel – controlled repetition as compared withthe counter – controlled repetition in fig. In counter –controlled repetition, we read a value fromthe user during each iteration of the while statement’s body for the specified number of iterations.In sentinel – controlled repletion, we read one value ( lines 27-28) and convert it to an integer ( line31) before the program reaches the while statement. the script uses this value to determinewhether the program’s flow of control should enter the body of the while statement. if the whilestatement’s condition is false (i.e., the user typed the sentinel as the first grade), the script ignoresthe body of the while statement (i.e., no grades were entered). If, on the other hand, the conditionis true, the body begins execution and processes the value entered by the user (i.e., adds the valueVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 34
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHto the total in line 35). After processing the value, the script increments grade Counter by 1 ( line38)), inputs the next grade from the user (lines 41-42) and converts the grade to an integer ( line45), before the end of the while statement’s body. When the script reaches the closing right brace(}) of the body in line 46, execution continues with the next test of the condition of the whilestatement ( line 33), using the new value just entered by the user to determine whether the whilestatement’s body should execute again. Note that the next value always is input from the userimmediately before the script evaluates the condition of the while statement. this order allows usto determine whether the value just entered by the user is the sentinel value before processing it(i.e., adding it to the total). If the value entered is the sentinel value, the while statementterminates and the script does not add the value to the total.Note the block in the while loop in fig. without the braces, the last four statements in the body ofthe loop would fall out side of the loop, causing the computer to interpret the code incorrectly, asfollows:While ( grade value !=-1)// add gradevalue to totaltotal = total + gradevalue;// add 1 to grade Countergrade Counter = grade Counter +1;// prompt for input and read grade from usergrade = window. Prompt(“Enter integer Grade, 1 to quite:’, “0”);//convert grade from a string to an integergrade value = parselnt (grade );This interpretation would cause an infinite loop in the program if the user does not input thesentinel – 1 as the input value in lines 27-28 (i.e., before the while statement).7. Discuss in detail how the top – down step wise refinement for Nested control structures. Let us work through another complete problem. We will once again formulate thealgorithm using pseudocode and top-down, stepwise refinement, and we will write acorresponding Java Script program.Consider the following problem statement: A college offers a course that prepares students for the state licensing exam for real estatebrokers. Last year, several of the students who completed this course took the licensingexamination. Naturally, the college wants to know how well its students did on the exam. Youhave been asked to write a program to summarize the results. You have been given a list of these10 students. Next to each name is written a 1 if the student passed the exam and a 2 if the studentVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 35
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHfailed.Your program should analyze the results of the exam as follows: 1. Input each test result (i.e., a 1 or a 2). Display the message “ Enter result” on the screen each time the program requests another test result. 2. Count the number of test results of each type. 3. Display a summary of the test results indicating the number of students who passed and the number of students who failed. 4. If more than eight students passed the exam, print the message “Raise tuition”.After reading the problem statement carefully, we make the following observations about theproblem: 1. The program must process test results for 10 students. A counter – controlled loop will be used. 2. Each test results is a number – either a 1 or 2. Each time the program reads a test result, the program must determine whether the number is a 1 or a 2. We test for a 1 in our algorithm. If the number is not a 1, we assume that it is a 2. ( An exercise at the end of the chapter considers the consequences of this assumption.) 3. Two counters are used to keep tack of the exam results – one to count the number of students who passed the exam and one to count the number of students who failed the exam. After the program processes all the results, it must decide whether more than eightstudents passed the exam. Let us proceed with top-down, stepwise refinement. We begin with apseudocode representation of the top: Analyze exam results and decide whether tuition should be raisedOnce again, it is important to emphasize that the top is a complete representation of the program,but that several refinements are necessary before the pseudocode can be evolved naturally into aJava Script program. Our first refinement is as follows: Initialize variables Input the ten exam grads and count passes and failures Pint a summary of the exam results and decide whether tuition should be raised Here, too, even though we have a complete representation of the entire program, furtherrefinement is necessary. We now commit to specific variables. Counters are needed to record thepasses and failures: a counter will be used to control the looping process, and a variable is neededto store the user input. The pseudocode statement. Initialize variablesMay be refined as follows:VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 36
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Initialize passes to zero Initialize failures to zero Initialize student to oneNote that only the counters for the number of passes, the number of failures and the number ofstudents are initialized. The pseudocode statement Input the ten quiz grades and count passes and failures requires a loop that successivelyinputs the result of each exam. Here, it is known in advance that there are precisely 10 examresults, so counter- controlled looping is appropriate. Inside the loop (i.e., nested within the loop),a double- selection structure will determine whether each exam result is a pass or a failure andwill increment the appropriate counter accordingly. The refinement of the preceding pseudocodestatement is then while student counter is less than or equal to ten Input the next exam result If the student passed Add one to passesElse Add one to failures Add one to student counterNote the use of blank lines to set off the if ….Else control structure to improve programreadability. The pseudocode statement.Print a summary of the exam results and decide whether tuition should be raisedmay be refined as follows:Print the number of passesPrint the number of failuresIf more than eight students passed Print”Raise tuition” The complete second refinement appears in fig. Note that blank lines are also used to set offthe While statement for program readabilityInitialize passes to zeroInitialize failures to zeroInitialize student to oneWhile student counter is less than or equal to tenInput the next exam resultVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 37
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHIf the student passedAdd one to passesElseAdd one to failuresAdd one to student counterPrint the number of passesPrint the number of failuresIf more than eight students passedPrint “Raise tuition”Fig. Examination – results problem pseudocode. The pseudocode is now refined sufficiently for conversion to Java Script. The Java Scriptprogram and two sample executions are shown in fig. 1. <?xml version =”1.0”?> 2. <! DOCTYPE html PUBLIC”-//W3C//DTD XHTML 1.0 Strict // EN” 3. “http:/www.w3.org/TR/xhtml 1/DTD/xhtml 1- strict.dtd”> 4. 5. <!- - fig. analysis 2, html - - > 6. <!- - Analyzing Exam Results - - > 7. 8. <html xmlns=http://www.w3.org/1999/xhtml”> 9. <head> 10. <title> Analysis of Examination Results </title> 11. 12. <script type =”text/javascript”> 13. <! - - 14. // initializing variables in declarations 15. var passes =0, // number of passes 16. Failures =0, // number of Failures 17. Student =1, // student counter 18. result ; // one exam result figure. Examination- results Calculation program in Java Script. 19. 20. // process 10 students; counter – controlled Toop 21. while (student <= 10) { 22. result = window. Prompt( 23. “ Enter result (1-pass, Z- fail)”, “0”); 24. 25. If ( result = = “1”) 26. passes = passes +1;VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 38
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 27. else 28. failures = failures +1; 29. 30. student = student +1; 31. } 32. 33. // termination phase 34. document write ln (“<h1>Examination Results </h1>”); 35. document written ln ( 36. “ passed ;” + passes +”<br/>failed:”+failures); 37. 38. if ( passes > 8) 39. document. write ln (“<br />Raise Tuition”); 40. //- - > 41. </script> 42. 43. <head> 44. <body> 45. <p> Click Refresh (or Reload) to run the script again </p> 46. </body> 47. </html>This dialog is displayed 10 times. User input is 1,2,1,1,1,1,1,1,1,1, and 1. Fig: Examination- results calculation program in Java script.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 39
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHThe dialog is displayed 10 times user input is 1,2,1,2,2,1,2,2,1, and 1. Fig. Examination- results Calculation program in Java script. Lines 15-18 declare the variable s used to process the examination results. Note that Javascript allows variable initialization to be incorporated into declarations ( passes is assigned 0,failures is assigned 0 and student is assigned 1). Some programs may require initialization at thebeginning of each repetition; such initialization would normally occur in assignment statements. The processing of the exam results occurs in the while statement in lines 21-31. Note thatthe if … else statement in lines 25-28 in the loop tests only whether the exam result was 1; itassumes that all other exam results are 2. normally, you should validate the values input by theuser (i.e., determine whether the values are correct). In the exercises, we ask you to modify thisexample to validate the input values to ensure that they are either 1 or 2.8. (I) Write a Java Script statement or a set of statement to accomplish each of the followingtasks:a) Sum the odd integers between 1 and 99. Use a for statement Assume that the variables sumand count have been declared.b) Calculate the value of 2.5 raised to the power of 3. Use the pow method.c) Print the integers from 1 to 20 by using a while loop and the counter variable x. Assume thatVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 40
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHthe variable X has been declared, but not initialized. Print only five integers per line [Hint: Usethe calculation X%5. when the value of this expression is 0, use document. write (“<br/>”) tooutput a line break in the XHTML document.]d) Repeat exercise (C) but using a for statement. a) sum=0; for ( count =1; count <= 99; count +=2) sum +=count; b) Math.pow(2,5,3) c) X=1; While (x<=20){ Document. write (“<br/>”); ++X; } d) For (x=1;x<=20;X++){ Document.write(x+””); If(x%5= =0) Document.write(“<br/>”); } or for (x=1;x<=20;x++) if (x%5 ==0) document. write (x+”<br/>”); else document. write (X+””);(II) Find the error in each of the following code segments, and explain how to correct it: a) x=1; while (x<=10); X++; } b) for (y= .1;y!=1.0;y+=.1) document. write (y+””); c) Switch (n) { Case 1: Document. write ln (“The number is 1”); Case 2: Document. write ln ( “The number is 2”);VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 41
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Break; Default; Document . write ln (“The number is not 1 or 2”); Break; } d) The following code should print the values from1 to 10: n=1; While (n<10) Document. writeln(n++); a) Error: The semicolon after the while header causes an infinite loop, and there is a missing left brace. Correction: Replace the semicolon by a {, or remove both the ; and the }. b) Error: Using a floating – point number to control a for repetition statement may not work, because floating – point number are represented approximately by most computers. Correction: use an integer, and perform the proper calculation to get the values you desire For (y=1;y!=10;y++) Document. writeln(y/10); c) Error: Missing break statement in the statements for the first case. Correction and a break statement at the end of the statement for the first case. Note that this missing statement is not necessarily an error if the programmer wants the statement of case 2: to execute every time the case1; statement executes. d) Error: Improper relational operator used in the while repetition – continuation condition. Correction: use <= rather than <, or change 10 to 11.9. Explain in detail about structured programming. Just as architects design buildings by employing the collective wisdom of their profession,so should programmers design programs. Our field is younger than architecture, and ourcollective wisdom is considerably sparser. We have learned that structured programmingproduces programs that are easier to understand than unstructured program and thus are easierto test, debug, modify and even prove correct in a mathematical sense. Flow charts reveal the structured nature of programs or the lack thereof. Connectingindividual flowchart symbols arbitrarily can lead to unstructured programs. Therefore, theprogramming profession has chosen to combine flow chart symbols to form a limited set ofcontrol structures and to build structured programs by properly combining control structures intwo simple ways. For simplicity, only single – entry/single-exit control structures are used- that is, there isonly one way to enter and one way to exit each control structure. Connecting control structures insequence to form structured programs is simple: the exit point of one control structure isconnected to the entry point of the next control structure (i.e., the control structure are simplyplaced one after another in a program). We have called this process control structure stacking.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 42
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHThe rules for forming structured programs also allow for control structures to be nested. Figuresummarizes Java script’s control structures. Small circles are used in the figure to indicate thesingle entry point and the single exit point of each structure. Fig. single entry / single – exit sequence, selection and repetition structures. Figure shows the rules for forming properly structured programs. The rules assume thatthe rectangle flowchart symbol may be used to indicate any action. Including input/ output.[Note: An oval flowchart symbol indicate the beginning and end of a process.] Applying the rules in fig. always results in a structured flowchart with a neat building –block – like appearance. For example, repeatedly applying rule 2 to the simplest flowchart (fig.)results in a structured flowchart containing many rectangles in sequence (fig.) Note that Rule 2generates a stack of control structures; so let us call rule 2 the stacking rule.Rules for Forming structured programs 1. Begin with the “simplest flowchart” (fig) 2. Any reactance (action) can be replaced by two rectangles (actions) in sequence. 3. Any rectangle (action) can be replaced by any control structures (sequence, if, if … else, switch, while, so …. While or for). 4. Rules 2 and 3 may be applied as often as you like and in any order. Fig. Forming rules for structured programs.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 43
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Fig. Simplest flow chart Rule 2 Rule 2 Rule 2 . . . Fig. Repeatedly applying Rule 2 of fig. to the simplest flowchart. Rules 3 is called the nesting rule. Repeatedly applying Rule 3 to the simplest flowchartresults in a flowchart with nearly nested control structures. For example, in fig. the reactance in Rule 3the simplest flowchart is first replaced with a double – selection (fi…else) structure. Then Rule 3 isapplied again to both of the rectangle in the double – selection structure by replacing each ofthese rectangles with double – selection structure. The dashed box around each of the double –selection structures represents the rectangle in the original simplest flow chart that was replaced. Rule 3 Rule 3VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 44
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Fig. Applying Rule 3 of fig. to the simplest flow chart Rule 4 generates larger, more involved and more deeply nested structures. the flow chartsthat emerge from applying the rules in fig. constitute the set of all possible structured flow chartsand thus the set of all possible structured programs. The beauty of the structured approach is that we use only seven simple single – entry/single – exit prices and assemble them in only two simple ways. Figure shows the kinds of stackedbuilding blocks that emerge from applying rule 2 and the kinds of nested building blocks thatemerge from applying the Rule 3. The figure also shows the kind of overlapped building blocksthat cannot appear in structured flowcharts (because of the elimination of the go to statement). Stacked building blocks Nested building blocks Over lapping building blocks (illegal in structured programsVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 45
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Fig. Stacked, nested and overlapped building blocks.If the rules in fig. are followed, an unstructured flow chart ( like the one in fig.) cannot be crated. Ifyou are uncertain about whether a particular flowchart is structured, apply the rules of fig. inreverse to try to reduce the flowchart to the simplest flowchart. If the flowchart is reducible to thesimplest flowchart, the original flow chart is structured; other wise, it is not. Fig. unstructured flow chartStructured programming promotes simplicity. Bohm and Jacopini have given us the result thatonly three forms of control are needed: • Sequence • Selection • RepetitionSequence is trivial. Selection is implemented in one of three ways: • If statement ( single selection) • If …else statement ( double selection) • Switch statement (multiple selection) In fact, it is straight forward to prove that the if statement is sufficient to provide any formof selection; everything that can be done with the if …else statement and the switch statement canbe implemented by combining if statements (although perhaps not as smoothly).Repetition is implemented in one of four ways: • While statement • Do…while statementVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 46
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH • For statement • For….in statement It is straight forward to prove that the while statement is sufficient to provide any form ofrepetition. Everything that can be done with the do…while statement and the for statement can bedone with the while statement (although perhaps not as elegantly).Combining these results illustrates that any form of control ever needed in a Java Script programcan be expressed in terms of: • Sequence • If statement ( selection) • While statement ( repetition) These control structures can be combined in only two ways – stacking and nesting. Indeed.Structured programming promotes simplicity. In the chapter, we have discussed the composition of programs from control structurescontaining actions and decisions. We will introduce another program – structuring unit, called thefunction. We will learn to compose large programs by combining functions that are composed ofcontrol structures. We will also discuss how functions promote software reusability.10. Discuss in detail about programmer defined functions with an example program. The programmer can write functions to define specific tasks that may be used at manypoints in a script. These functions are referred to as programmer-defined functions. The actualstatements defining the function are written only once and are hidden from other functions. A function is invoked (i.e., made to perform its designated task) by a function call. Thefunction call specifies the function name and provides information (as arguments) that the calledfunction needs to perform its task. A common analogy for this structure is the hierarchical form ofmanagement. A boss (the calling function, or caller ) asks a worker (the called function) toperform a task and return (i.e., report back) the results when the task is done. The boss functiondoes not know how the worker function performs its designated tasks. The worker may call otherworker functions, and the boss will be unaware of this situation. We will soon see how this“hiding” of implementation details promotes good software engineering. Figure shows the bossfunction communicating with several worker functions in a hierarchical manner. Note that worker1 acts as a “boss” function to worker 4 and worker 5, and worker4 and workder5 report back toworker1. Relationship among functions may be other than the hierarchical structure shown in thisfigure.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 47
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH boss worker 1 worker 2 worker 3 worker 4 worker 5 Fig. Hierarchical boss- function/ worker-function relationship Functions ( and methods) are invoked by writing the name of the function ( or method),followed by a left parenthesis, followed by the argument(s) of the function ( or method), if any,followed by a right parenthesis. For example, a programmer desiring to convert a string stored invariable input value to a floating – print number and add it to variable total, might write Total += parsefloat (input value); When this statement executes, JavaScript function parseFloat converts the string containedin the parentheses (stored in variable input value in this case) to a floating – point value and addsvalue to total. The variable input value is the argument of the parse-Float function. FunctionParseFloat takes a string representation of a floating- point number as an argument and returnsthe corresponding floating –point numeric value.Function ( and method) argument may be constants, variables or expressions. If sl-“22.3”and52=”45”, then the statement Total += parseFloat ( s1+s2);Evaluates the expression s1+s2, concatenates the strings s1 and s2 ( resulting in the string“22.345”), converts the result into a floating- point number and adds the floating – point numberto variable total.Programmer-Defined Functions Functions allow the programmer to modularize a program. All variable declared infunction definitions are local variables-this means that they are known only in the function inwhich they are defined. Most functions have a list of parameters that provide the means forcommunicating information between functions via function calls. A function’s parameters are alsoconsidered to be local variables. When a function is called the arguments in the function call areVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 48
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHassigned to the corresponding parameter in the function definition. There are several reasons for modularizing a program with functions. The divide andconquer approach makes programs development more manageable. Another reason is softwarereusability (i.e., using existing functions as building blocks to create new programs). With goodfunction naming and definition. Programs can be created from standardized functions rather thanbuilt by using customized code. For example, we did not have to define how to convert strings tointegers and floating – point numbers – Java Script already provides function parselnt to covert astring to an integer and function parseFloat to convert a string to floating-point number. a thirdreason is to avoid repeating code in a program. Code that is packages as a function can beexecuted from several locations in a program by calling the function.Function Definitions Each script we have presented thus far in the text has consisted of a series of statements andcontrol structures in sequence. These scripts have been executed as the browser loads the Webpage and evaluates the <head> section of the page. We now consider how programmers writetheir own customized functions and call them in a script.Programmer – Defined Function square Consider a script (fig) that uses a function square to calculate the squares of the integers from 1to 10. [Note: we continue to show many examples in which the body element of the XHTMLdocument is empty and the document is created directly by Java Script. In later chapters, we showmany examples in which Java Scripts interact with the elements in the body of a document.1 1. <?xml version =”1.0”?> 2. <! DOCTYPE html PUBLIC”-//W3C//DTD XHTML 1.0 Strict // EN” 3. “http:/www.w3.org/TR/xhtml 1/DTD/xhtml 1- strict.dtd”> 4. 5. <!- - fig. square Int.html - - > 6. <!- - Square function 7. 8. <html xmlns=http://www.w3.org/1999/xhtml”> 9. <head> 10. <title> A programmer – Defined square function </title> 11. 12. <script type =”text/javascript”> 13. <! - - 14. document . write ln( 15. “<hl> square the numbers from 1 to 10</h1>”); 16. 17. // square the numbers from 1 to 10 </h1>”); 18. for ( var x=1; x<= 10 19. document. write ln (“The square of “+x+” is + 20. square ( X ) + “<br/>”);VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 49
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 21. 22. // the following square function’s body is executed 23. // only when the function is explicitly called. 24. 25. // square function definition 26. function square 27. { 28. return y*Y; 29. } 30. //-- - > 31. </script 32. 33. </head ><body></body> 34. </html> Fig. programmer – defined function square. The for statement in lines 18-20 outputs XHTML that displays the results of squaring theintegers from 1 to 10. Each iteration of the loop calculates the square of the current value of controlvariable x and outputs the result by writing a line in the XHTML document. Function square isinvoked, or called, in line 20 with the expression square (X). When program control reaches thisexpression, the program calls function square ( defined in lines 26-29). The ( ) represent thefunction- call operator, which has high precedence. At this point, the program makes a copy ofthe value of X (the argument) and program control transfers to the first line of function square.Function square receives the copy of the value of x and stores it in the parameter Y. Then squarecalculates Y*Y. The result is passed back to the point in line 20 where square was invoked. Lines19-20 concatenate “ The square of , the value of x, “ is “, the value returned by function square anda <br /> tag and write that line of text in the XHTML document. this process is repeated isrepeated 10 times. The definition of function square ( lines 26-29) shows that square expects a single parameterVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 50
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHY. function square uses this name in its body to manipulate the value passed to square from line20. the return statement in square passes the result of the calculation y*y back to the callingfunction. Note that java Script keyword var is not used to declare variables in the parameter list ofa function. In this example, function square follows the rest of the script. When the for statementterminates, Java Script will no continue to flow sequentially into function square. A function mustbe called explicitly for the code in its body to execute. Thus, when the for statement terminates inthis example, the script terminates.The format of a function definition isFunction function name (parameter-list){ declarations and statements} The function name is any valid identifier. The parameter – list is a comma – separated listcontaining the names of the parameters received by the function when it is called (remember thatthe arguments in the function call are assigned to the corresponding parameter in the functiondefinition). There should be one argument in the function call for each parameter in the functiondefinition. If a function does not receive any values, the parameter – list is empty (i.e., the functionname is followed by an empty set of parentheses). The declarations and statements within bracesform the function body. There are three ways to return control to the point at which a function was invoked. If thefunction does not return a result, control returns when the program reaches the function endingright brace or by executing the statement Return;If the function does return a result, the statement return expression;returns the value of expression to the caller. when a return statement is executed, control returnsimmediately to the point at which the function was invoked.Programmer-Defined Function maximumThe script in our next example (fig.) uses a programmer – defined function called maximum todetermine and return the largest of three floating-point values. 1. <?xml version =”1.0”?> 2. <! DOCTYPE html PUBLIC”-//W3C//DTD XHTML 1.0 Strict // EN” 3. “http:/www.w3.org/TR/xhtml 1/DTD/xhtml 1- strict.dtd”>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 51
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 4. 5. <!- - fig. maximum html - - > 6. <!- - maximum function 7. 8. <html xmlns=http://www.w3.org/1999/xhtml”> fig. programmer – defined maximum function. 9. <head> 10. <title> finding the maximum of three values </title> 11. 12. <script type =”text/javascript”> 13. <! - - 14. var input 1= 15. window. Prompt ( “Enter first number “, “0”); 16. var input 2= 17. window. Prompt ( “Enter second number “, “0”); 18. var input 3= 19. window. Prompt ( “Enter third number “, “0”); 20. 21. var value 1 = parse Float ( input 1 ); 22. var value 2 = parse Float ( input 2 ); 23. var value 3 = parse Float ( input 3 ); 24. 25. var maxvalue = maximum ( value 1, value 2, value 3); 26. 27. document. write ln (“First number :”+ value + 28. “<br/>second number “+value 2 + 29. “<br/>third number “+value 3 + 30. “<br/>maximum is :”+max value ); 31. 32. // maximum method definition (called from line 25) 33. Function maximum (x,y,z) 34. { 35. return math. Max (x, math. Max (y,z)); 36. } 37. // 38. </script> 39. 40. </head> 41. <body> 42. <p>Click refresh ( or Reload) to run the script again </p> 43. </body> 44. </html>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 52
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Fig. Programmer – defined maximum function The three floating – point values are input by the user via prompt dialogs (lines 14-19).Lines 21-23 use function parseFloat to convert the strings input by the user to floating-pointvalues. The statement in line 25 passes the three floating – point values to function maximum(defined in lines 33-36). Which determines the largest floating-point value. This value is returnedto line 25 by the return statement in function maximum. The value returned is assigned to variablemax value. Lines 27-30 concatenate and display the three floating – point values input by the userand the max value. Note the implementation of the function maximum ( lines 33-36). The first line indicatesthat the function’s name is maximum and that the function takes three parameter (x, y and z) toaccomplish its task. Also, the body of the function contains the statement which returns the largestof the three floating – point of the function contains the statement which returns the largest of thethree floating- point values, using two calls to the Math object’s max method. First, method Math,max is invoked with the values of variables y and z to determine the large of the two values. Next,the value of variable x and the result of the first call to Math. Max is returned to the point at whichmaximum was invoked (i.e., line 25). Note once again that the script terminates beforesequentially reaching the definition of function maximum. The statement in the body of functionmaximum executes only when the function is invoked form line 25.11. Explain the scope rules & Global functions of Java Script in detail with necessary exampleVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 53
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHprograms. Each identifier in a program also has a scope. The scope of an identifier for a variable orfunction is the portion of the program in which the identifier can be referenced. Global variablesor script – level variables (i.e., variables declared in the head element of the XHTML document)are accessible in any par of a script and are said to have global scope. Thus every function in thescript can potentially use the variables. Identifiers declared inside a function have function (or local) scope and can be used only inthat function. Function scope begins with the opening left brace ({) of the function in which theidentifier is declared and ends at the terminating right brace (}) of the function. Local variables of afunction and function parameters have function scope. If a local variable in a function has thesame name as a global variable, the global variable is “hidden” from the body of the function. The script in figure demonstrates the scope rules that resolve conflicts between globalvariables and local variables of the same name. This example also demonstrates the event on load,which calls an event handler when the <body> of the XHTML document is completely loaded intothe browser window.1 <?xml version = “1.0”?>2 <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”3 http://www.w3.org/TR/xhtml1/DTD/xhtml1-scrict.dtd>45 <!-- Figure:scoping.html -- >6 <!—local and Global Variables -- >78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <title>A Scoping Example</title>1112 <script type = “text/javascript”>1314 var x = 1; // global variable1516 function start ( )17 {18 var x = 5; //variable local to function start1920 document.writeln(“local x in start is “ + x);2122 functionA( ); // functionA has local x23 functionB( ); // functionB uses global variable x24 functionA( ); // functionA reinitializes local x25 functionB( ); // global variable x retains its valueVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 54
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH2627 document.writeln(28 <p>local x in start is “+x+ “</p” ) ;29 }3031 function functionA( )32 {33 var x = 25; // initialized each time34 // functionA is called3536 document.writeln( “<p>local x in functionA is “+37 x +” after entering functionA” );38 ++x;39 document.write(“Cbr />local x in functionA is “+40 x + “before exiting functionA” + </p>” );41 }4243 function functionB( )44 {45 document.writeln( “<p>global variable x is” + x +46 on entering functioB” );47 x * = 10;48 document.writeln( “<br /> global variable x is” + x +49 x + on exiting functionB” +”</p>” );50 }51 // 52 </script>5354 </head>55 <body onload = “start( )” ></body>56 </html>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 55
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure: Scoping example (Part 2 of 2) Global variable x (line 14) is declared and initialized to 1. This global variable is hiddenany block (or function) that declares a variable named x. Function start (line 16) declares a localvariable x (line 18) and initializes it to 5. This variable is output in a line of XHTML text to showthat the global variable x is hidden in start. The script defines two other functions – functionAand functionB – that each take no arguments and return nothing. Each function is called twicefrom function start. Function functionA defines local variable x (line 33) and initializes it to 25. WhenfunctionA is called, the variable is output in a line of XHTML text to show that the global variableis hidden in functionA; then the variable is incremented and output in a line of XHTML text againbefore the function is exited. Each time this function is called, local variable x is re-created andinitialized to 25. Function functionB does not declare any variable. Therefore, when it refers to variable x,the global variable x is used. When functionB is called, the global variable is output in a line ofXHTML text, multiplied by 10 and output in a line of XHTML text again before the function isexited. The next time function functionB is called, the global variable has its modified value, 10.Finally, the program outputs local variable x in start in a line of XHTML text again, to show thatnone of the function calls modified the value of x in start, because the functions all referred tovariables in other scope.JavaScript Global Functions JavaScript provides seven functions that are available globally in a JavaScript. We havealready used two of these functions – parseInt and parseFloat. The global funcitons aresummarized in figure. Global Description functionVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 56
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH escape This function takes a string argument and returns a string in which all spaces, punctuation, accent characters and any other character that is not in the ASCII character set are encoded in a hexadecimal format that can be represented on all platforms. eval This function takes a string argument representing JavaScript code to execute. The JavaScript interpreter evaluates the code and executes it when the eval function is called. This function allows JavaScript code to be stored as strings and executed dynamically. isFinite This function takes a numeric argument and returns true if the value of the argument is not NaN, Number.POSITIVE_INFINITY or Number.NEGATIVE_INFINITY; otherwise, the function returns false. isNaN This function takes a numeric argument and returns true if the value of the argument is not a number, otherwise, it returns false. The function is commonly used with the return value of parseInt or parseFloat to determine whether the result is a proper numeric value. parseFloat This function takes a string argument and attempts to convert the beginning of the string into a floating – point value. If the conversion is unsuccessful, the function returns Nan; otherwise, it returns the converted value (e.g., parseFloat (“abc123.45”) returns Nan, and parseFloat(“123.45abc” returns the value 123.45 parseInt This function takes a string argument and attempts to convert the beginning of the string into an integer value. If the conversion is unsuccessful, the function returns NaN; otherwise, it returns the converted value (e.g., parseInt (“abc123”) returns NaN, and parseInt (“123abc”) returns the integer value 123). This function takes an optional second argument, from 2 to 36, specifying the radix (or base) of the number. Base 2 indicates that the first argument string is in binary format, base 8 indicates that the first argument string is in octal format and base 16 indicates that the first argument string is in hexadecimal format, for more information on binary octal and hexadecimal number. unescape This function takes a string as its argument and returns a string in which all characters previously encoded with escape are decoded. Figure: JavaScript Global functions Actually, the global functions in figure are all part of JavaScript’s Global object. The Globalobject contains all the global variables in the script, all the user – defined functions in the scriptand all the functions listed in figure. Because global functions and user – defined functions arepart of the Global object, some JavaScript programmers refer to these functions as methods. Wewill use the term method only when referring to a function that is called for a particular object(e.g, Math.random ( )). As a JavaScript programmer, you do not need to use the Global objectdirectly; JavaScript uses it for you.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 57
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH12. Write a program for a Factorial Calculation with Recursive Function? Explain Recursion. The programs we have discussed thus far are generally structured as functions that call oneanother in a disciplined, hierarchical manner. For some problems, however, it is useful to havefunctions call themselves. A recursive function is a function that calls itself, either directly orindirectly through another function. Recursion is an important topic discussed at length in upper– level computer science courses. We present a simple example of recursion. We consider recursion conceptually first; then we examine several programs containingrecursive functions. Recursive problem – solving approaches have a number of elements incommon. A recursive function is called to solve a problem. The function actually knows how tosolve only the simplest case(s), or base case(s). If the function is called with a base case, thefunction returns a result. If the function is called with a more complex problem, the functiondivides the problem into two conceptual pieces – a piece that the function knows how to process(the base case) and a piece that the function does not know how to process. To make recursionfeasible, the later piece must resemble the original problem, but be a slightly simpler or slightlysmaller version of the original problem. Because this new problem looks like the originalproblem, the function invokes (calls) a fresh copy of itself to go to work on the smaller problem;this invocation is referred to as a recursive call, or the recursion step. The recursion step alsonormally includes the keyword return, because its result will be combined with the portion of theproblem the function knew how to solve to form a result that will be passed back to the originalcaller. The recursion step executes while the original call to the function is still open (i.e., it has notfinished executing). The recursion step can result in many more recursive calls as the functiondivides each new subproblem into two conceptual pieces. For the recursion eventually toterminate, each time the function calls itself with a slightly simpler version of the originalproblem, the sequence of smaller and smaller problems must converge on the base case. At thatpoint, the function recognizes the base case, returns a result to the previous copy of the functionand a sequence of returns ensures up the line until the original function call eventually returns thefinal result to the caller. This process sounds exotic when compared with the conventionalproblem solving we have performed to this point. As an example of these concepts at work, let uswrite a recursive program to perform a popular mathematical calculation.The factorial of a nonnegative integer n, written n! ( and pronounced “n factorial”), is the product n. (n-1). (n-2) ……1Where 1! Is equal to 1 and 0! Is defined as 1. For example, 5! Is the product 5 . 4 . 3 . 2 . 1, which isequal to 120. The factorial of an integer (number in the following example) greater than or equal to zerocan be calculated interatively (nonrecursively) using a for statement, as follows:VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 58
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH var factorial = 1; for (var counter = number; counter >= 1; --counter) factorial *= counter;A recursive definition of the factorial function is arrived at by observing the followingrelationship: n! = n. (n-1)!For example, 5! Is clearly equal to 5* 4!, as is shown by the following equations: 5! = 5 . 4 . 3 . 2 . 1 5! = 5 . (4 . 3 . 2 . 1) 5! = 5 . (4!) The evaluation of 5! Would proceed as shown in figure. Figure (a) shows how thesuccession of recursion calls proceeds until 1! Is evaluated to be 1, which terminates the recursion.Figure (b) shows the values returned from each recursion call to its called until the final value iscalculated and returned. Figure uses recursion to calculate and print the factorials of the integers 0 to 10. Therecursive function factorial first tests (line 26) to see if a terminating condition is true (i.e., ifnumber less than or equal to 1). If number is indeed less than or equal to 1, factorial returns 1, nofurther recursion is necessary and the function returns. If number is greater than 1, line 29expresses the problem as the product of number and the value returned by a recursive call tofactorial evaluating the factorial of number – 1. Note that factorial (number – 1) is a slightlysimpler problem than the original calculation, factorial (number). Final value = 120 5! 5! Over5 * 24 =building returned 5! = lapping 120 is blocks (illegal in structured programs 5 * 4! 5 * 4! 4! = 4 * 6 = 24 is returned 4 * 3! 4 * 3! 3! = 3 * 2 = 6 is returned 3 * 2! 3 * 2! 2! = 2 * 1 = 2 is returned 2 * 1! 2 * 1! Rule 3 1 returnedVEL TECH VEL TECH MULTI TECH 1 VEL TECH HIGH TECH 1 59 (a) Procession of recursive calls. (b) Values returned from each recursive call Figure: Recursive evaluation of 5!
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH1 <?xml version = “1.0”?>2 <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN’3 http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>45 <! -- Figure: FactorialTest.html -->6 <! – Recursive factorial example -->78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <title>Recursive Factorial Function</title>1112 <script language = “javascript”>13 document.writeln( “<h1>Factorials of 1 to 10</h1>” );14 document.writeln(15 “<table border = ‘1’ width = ‘100%’>” );1617 for ( var i = 0; i <= 10; i++ )18 document.writeln ( “<tr><td>” +i +” !</td><td>” +19 factorial ( i ) + “</td></tr>” );2021 document.writeln ( “</table>” );2223 // Recursive definition of function factorial24 function factorial( number )25 {26 if ( number <= 1 ) // base case27 return 1;28 else29 return number * factorial ( number – 1 );30 }31 </script>32 </head><body></body>33 </html> Figure: Factorial calculation with a recursive functionVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 60
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure: Factorial calculation with a recursive function Function factorial (lines 24 – 30) receives as its argument the value for which to calculate thefactorial. As can be seen in the screen capture in figure, factorial values become large quickly.Because JavaScript uses floating – point number representations, we are able to calculate factorialsof larger numbers.13. i) Locate the error in each of the following program segments and explain how to correct it: (a) method g ( ) { Document.writeln ( “Inside method g” ); } (b) // This function should return the sum of its arguments function sum( x, y ) { var result; result = x + y; } (c) function f( a ); { Document.writeln( a ); }(a) Error: method is not the keyword used to begin a function definition Correction: Change method to function.(b) Error: The function is supposed to return a value, but does not. Correction: Delete variable result, and either place the statement return x + y; In the function or add the following statement at the end of the function body:VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 61
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH return result;(c) Error: The semocolon after the right parenthesis that encloses the parameter list. Correction: Delete the semicolon after the right parenthesis of the parameter listii) Write a complete JavaScript program to prompt the user for the radius of the sphere, and callfunction sphereVolume to calculate and display the volume of the sphere. Use the statement volume = ( 4.0 / 3.0 ) * Math.PI * Math.pow( radius, 3 );to calculate the volume. The user should input the radius through an XHTML text field in a<form> and click an XHTML button to initiate the calculation.The following solution calculates the volume of a sphere using the radius entered by the user.1 <?xml version = “1.0”?>2 <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional //EN’3 http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>45 <!—Exercise 10.6; volume.html -->67 <html xmlns = http://www.w3.org/1999/xhtml>8 <head>9 <title>Calculating Sphere Volumes</title>1011 <script type = “text/javascript”>12 <!--13 function displyVolume( )14 {15 var radius = parseFloat( myForm.radiusField.value );16 window.status = “Volume is” + sphereVolume( radius );17 }1819 function sphereVolume( r )20 {21 return (4.0 / 3.0) * Math.PI * Math.pow( r, 3);22 }23 // -- >24 </script>2526 </head>2728 <body>29 <form name = “myForm” action = “”>30 Enter radius of sphere<br />VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 62
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH31 <input name = “radio Field” type = “text” / >32 <input name = “calculate” type = “button” value =33 “Calculate” onclick = “displayvolume( )” />34 </form>35 </body>36 </html>14. What are Arrays with an example program? Explain how to create and initialize arrays. An array is group of memory locations that all have the same name and normally are of thesame type (although this attribute is not required in JavaScript). To refer to a particular location orelement in the array, we specify the name of the array and the position number of the particularelement in the array. Figure shows an array of integer values named C. This array contains 12 elements. Anyone of these elements may be referred to by giving the name of array followed by the positionnumber of the element in square brackets ( [ ] ). The first element in every array is the zerothelement. Thus, the first element of array C is referred to as C[ 0 ], the second element of array C isreferred to as C [ 1 ], the seventh element of array C is referred to as C [ 6 ] and, in general, the ithelement of array C is referred to as C [i – 1]. Array names follow the same conventions as otheridentifiers. The position number in square brackets is called a subscript (or an index). A subscriptmust be an integer or an integer expression. If a program uses an expression as a subscript, thenthe expression is evaluated to determine the value of the subscript. For example, if we assumethat variable a is equal to 5 and that variable b is equal to 6, then the statement C [ a + b } + = 2;Adds 2 to array element c [ 11 ]. Note that a subscripted array name is a left – hand – sideexpression – it can be used on the left side of an assignment to place a new value into an arrayelement.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 63
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Name of array C[ 0 ] -45 Rule 2 C[ 1 ] Rule 3 6 C[ 2 ] 0 C[ 3 ] 72 Rule 2 . C[ 4 ] . 1543 . C[ 5 ] -89 C[ 6 ] 0 Rule 2 C[ 7 ] 62 Rule 3 -3 C[ 8 ] 1 C[ 9 ] Position number (index or 6453 subscript) of the element C[ 10 ] within array C 78 C[ 11 ] Let us examine array C in figure more closely. The array’s name is C. The length of array C Figure: Array with 12 elementsis 12 and is determined by the following expression: C.length Every array in JavaScript knows its own length. The array’s 12 elements are referred to asC[ 0 ], C[ 1 ], C[ 2 ], ……, C[ 11 ]. The value of C[ 0 ] is – 45, the value of C[ 1 ] is 6, the value ofC[ 2 ] is 0, the value of C[ 7 ] is 62 and the value of C[ 11 ] is 78. To calculate the sum of the valuesVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 64
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHcontained in the first three elements of array C and store the result in variable sum, we wouldwrite sum = C[ 0 ] + C[ 1 } + C[ 2 }; To divide the value of the seventh element of array C by 2 and assign the result to thevariable x, we would write x = C[ 6 ] / 2; The brackets that enclose the array subscript are a JavaScript operator. Brackets have thesame level of precedence as parentheses. The chart in figure shows the precedence andassociativity of the operators introduced to this point in the text. They are shown from top tobottom in decreasing order of precedence, alongside their associativity and type. Operators Associativity Type () []. left to right highest ++ -- ! right to left unary multiplicativ */% left to right e +- left to right additive < <= > >= left to right relational == != left to right equality && left to right logical AND || left to right logical OR ?: right to left conditional = += -= right to left assignment *= /= %= Figure: Precedence and associativity of the operators discussed so forDeclaring and Allocating Arrays Arrays occupy space in memory. Actually, an array in JavaScript is an Array object. Theprogrammer uses operator new to allocate dynamically (request memory for) the number ofelements required by each array. Operator new creates an object as the program executes byobtaining enough memory to store an object of the type specified to the right of new. The processof creating new objects is also known as creating an instance or instantiating an object, andoperator new is known as the dynamic memory allocation operator. Arrays are allocated withnew because arrays are considered to be objects, and all objects must be created with new. Toallocate 12 elements for integer array C, use the statement var C = new Array( 12 );VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 65
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHThe preceding statement can also be performed in two steps, as follows: var C; // declares the array C = new Array( 12 ); // allocates the arrayWhen arrays are allocated, the elements are not initialized. Memory may be reserved for several arrays by using a single declaration. The followingdeclaration reserves 100 elements for array b and 27 elements for array x: var b = new Array( 100 ), x = new Array( 27 );Examples Using Arrays This section presents several examples of creating and manipulating arraysCreating and Initializing Arrays The script in figure uses operator new to allocate an Array of five elements and an emptyarray. The script demonstrates initializing an Array of existing elements and also shows that anArray can grow dynamically to accommodate new elements. The Array’s values are displayed inXHTML tables. [Note: Many of the scripts are executed in response to the <body>’s onloadevent].1 <?xml version = “1.0’?>2 <!DOCTYPE html PUBLIC “-//W3C/DTD XHTML 1.0 Strict//EN’3 http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>45 <!-- Figure: InitArray.html -->6 <!-- Initializing an Array -->78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <title>Initializing an Array</title>1112 <script type = “tex/javascript”>13 <!--14 // this function is called when the <body> element’s15 // onload event occurs16 function initializeArrays( )17 {18 var n1 = new Array( 5 ); // allocate 5 – element Array19 var n2 = new Array( ); // allocate empty Array20VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 66
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH21 // assign values to each element of Array n122 for ( var i = 0; i < n1.length; ++i )23 n1[ 1 ] = i;2425 // create and initialize five-elements in Array n226 for ( i = 0; i < 5; ++i )27 n2[ i ] = i;2829 outputArray( “Array n1 contains”, n1 );30 outputArray( “Array n2 contains”, n2 );31 }3233 // output “header” followed by a two-column table34 // containing subscripts and elements of “theArray”35 function outputArray( header, theArray )36 {37 document.writeln( “<h2>’ + header + “</h2>” );38 document.writeln( “<table/border = ”1” width = “ +39 “”100% “>” );4041 document.writeln( “<thead><thewidth = ”100” “ +42 “align = ”left” >subscript</the>” +43 “<the align = ”left“>value</the></thead><tbody>” );4445 for ( var i = 0; i < theArray.length; 1++ )46 document.writeln( <tr><td>” + i + “</td><td>” +47 theArray[ i ] + “</td></tr>” );4849 document.writeln( “</tbody></table>” );50 }51 // - - >52 </script>5354 </head><body onload = “initializeArrays( )”></body>55 </html>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 67
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure: Initializing the elements of an array (Part 2 of 2) Function initializeArrays (defined in lines 16 – 31) is called by the browser as the eventhandler for the <body>’s onload event. Line 18 creates Array n1 as an array of five elements. Line19 creates Array n2 as an empty array. Lines 22 – 23 use a for statement to initialize the elements of n1 to their subscript numbers(0 to 4). Note the use of zero-based counting (remember, array subscript start at 0) so that the loopcan access every element of the array. Note too the use of the expression n1.length in thecondition for the for statement to determine the length of the array. In this example, the length ofthe array is 5, so the loop continues executing as long as the value of control variable i is less than5. for a five-element array, the subscript values are 0 through 4, so using the less than operator, <,guarantees that the loop does not attempt to access an element beyond the end of the array. Lines 26 – 27 use a for statement to add five elements to the Array n2 and initialize eachelement to its subscript number (0 to 4). Note that Array n2 grows dynamically to accommodatethe values assigned to each element of the array. Lines 29 – 30 invoke function outputArray (defined in lines 35 – 50) to display the contentsof each array in an XHTML table. Function outputArray receives two arguments – a string to beoutput before the XHTML table that displays the contents of the array and the array to output.Lines 37 – 43 output the header string and begin the definition of the XHTML table with twocolumns: Subscript and value. Lines 45 – 47 use a for statement to output XHTML text thatdefines each row of the table. Once again, not the use of zero-based counting so that the loop canVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 68
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHaccess every element of the array. Line 49 terminates the definition of the XHTML table. If the values of an Array’s elements are known in advance, the elements of the Array can beallocated and initialized in the declaration of the array. There are two ways in which the initialvalues can be specified. The statement var n = [ 10, 20, 30, 40, 50 ];uses a comma-separated initializer list enclosed in square brackets ([ and ]) to create a five-elementArray with subscripts of 0, 1, 2, 3 and 4. The array size is determined by the number of values inthe initializer list. Note that the preceding declaration does not require the new operator to createthe Array object – this functionality is provided by the interpreter when it encounters an arraydeclaration that includes an initializer list. The statement var n = new Array( 10, 20, 30, 40, 50 );also creates a five-element array with subscripts of 0, 1, 2, 3 and 4. In this case, the initial values ofthe array elements are specified as arguments in the parentheses following new Array. The size ofthe array is determined by the number of values in parentheses. It is also possible to reserve aspace in an Array for a values to be specified later by using a comma as a place holder in theinitializer list. For example, the statement var n = [ 10, 20, 30, 40, 50 ];creates a five – elements array with no values specified for the third element (n[ 2 ]).15. Discuss in detail how linear search & Binary search can be performed in arrays.Searching Arrays: Linear Search and Binary Search Often, a programmer will be working with large amounts of data stored in arrays. It maybe necessary to determine whether an array contains a value that matches a certain key value. Theprocess of locating a particular element value in an array is called searching.Searching an Array with Linear Search In the script in figure function linearSearch (defined in lines 38 – 45) uses a for statementcontaining an if statement to compare each element of an array with a search key (lines 40 – 42). Ifthe search key is found, the function returns the subscript value (line 42) of the element to indicatethe exact position of the search key in the array. [Note: The loop in the linearSearch functionterminates, and the function returns control to the caller as soon as the return statement in its bodyexecutes.] If the search key is not found, the function returns a value of -1. The function returnsthe value – 1 because it is not a valid subscript number.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 69
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH1 <?xml version = “1.0”?>2 <!DOCTYPE html PUBLIC “-//W3c//DTD XHTML 1.0 Strict//EN’3 http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>45 <! -- Figure: LinearSearch.html -->6 <! -- Linear Search of an Array -- >78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <title>Linear Search of an Array</title>1112 <script type = “text/javascript”>13 <! --14 var a = new Array( 100 ); //create an Array1516 // fill Array with even integer values from 0 to 19817 for ( var i = 0; i < a.length; ++i )18 a[ i ] = 2 * i;1920 // function called when “Search” button is pressed21 function buttonPressed( )22 {23 var searchKey = searchForm.inputVal.value;2425 //Array a is passed to linearSearch even though it26 // is a global variable. Normally an array will27 // be passed to a method for searching.28 var element = linearSearch( a, parseInt( searchKey ) );2930 if ( element ! = -1 )31 searchForm.result.value=32 “Found value in element “+ element:33 else34 searchForm.result.value = “Value not found”;35 }3637 // Search “theArray” for the specified “key” value38 function linearSearch( theArray, key )39 {40 for ( var n = 0; n < theArray.length; ++n )41 if ( theArray[ n ] = = key )42 return n;4344 return -1;VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 70
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH45 }46 // -- >47 </script>4849 </head>5051 <body>52 <form name = “searchForm” action = “”>53 <p>Enter integer search key<br / >54 <input name = “inputVal” type = “text” />55 <input name = “search” type = “button” value = “Search”56 onclick = “buttonPressed( )” /><br /></p>5758 <p>Result<br />59 <input name = “result” type = “text” size = “30” /></p>60 </form>61 </body>62 </html> Figure: Linear Search of an Array (Part 2 of 2) If the array being searched is not in any particular order, it is just as likely that the valuewill be found in the first element as the last. On average, therefore, the program will have tocompare the search key with half the elements of the array.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 71
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH The program contains a 100 – element array (defined in line 14) filled with the even integersfrom 0 to 198. The user types the search key in a text field (defined in the XHTML form in lines 52– 60) and clicks the Search button to start the search. [Note: The array is passed to linearSearcheven though the array is a global script variable. We do this because arrays are normally passedto functions for searching.]Searching an Array with Binary Search The linear – search method works well for small arrays or for unsorted arrays. However,for large arrays, linear searching is inefficient. If the array is sorted, the high – speed binary –search technique can be used. After each comparison, the binary search algorithm eliminates half of the elements in thearray being searched. The algorithm locates the middle array element and compares it to thesearch key. If they are equal, the search key has been found and the subscript of that element isreturned. Otherwise, the problem is reduced to searching half of the array. If the search key isless than the middle array element, the first half of the array is searched; otherwise, the secondhalf of the array is searched. If the search key is not the middle element in the specified subarray(piece of the original array), the algorithm is repeated on one quarter of the original array. Thesearch continues until the search key is equal to the middle element of a subarray or until thesubarray consists of one element that is not equal to the search key(i.e., the search key is notfound). In a worst – case scenario, searching an array of 1023 elements will take only 10comparisons using a binary search. Repeatedly dividing 1024 by 2 (because after each comparisonwe are able to eliminate half of the array) yields the value 512, 256, 128, 64, 32, 16, 8, 4, 2 and 1.The number 1024 (210) is divided by 2 only ten times to get the value 1. Dividing by 2 is equivalentto one comparison in the binary search algorithm. An array of one million elements takes amaximum of 20 comparisons to find the key. An array of 1 billion elements takes a maximum of30 comparisons to find the key. When searching a sorted array, this is a tremendous increase inperformance over the linear search that required comparing the search key to an average of halfthe elements in the array. For a 1 billion – element array, this is the difference between an averageof 500 million comparisons and a maximum of 30 comparisons! The maximum number ofcomparisons needed for the binary search of any sorted array is the exponent of the first power of2 greater than the number of elements in the array. Figure presents the iterative version of function binarySearch (lines 42 – 66). FunctionbinarySearch is called from line 32 of function buttonPressed (lines 20 – 39) – the event handler forthe Search button in the XHTML form. Function binarySearch receives two arguments – an arraycalled theArray (the array to search) and key (the search key). The array is passed to binarySearcheven though the array is global variable. Once again, we do this because an array is normallypassed to a function for searching. If key matches the middle element of a subarray (line 57),middle (the subscript of the current element) is returned, to indicate that the value was found andthe search is complete. If key does not match the middle element of a subarray, the low subscriptVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 72
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHor the high subscript (both declared in the function) is adjusted, so that a smaller subarray can besearched. If key is less than the middle element (line 59), the high subscript is set to middle – 1and the search is continued on the elements from low to middle – 1. If key is greater than themiddle element (line 61), the low subscript is set to middle + 1 and the search is continued on theelements from middle + 1 to high. These comparisons are performed by the nested if ….. elsestatement in lines 57 – 62.1 <?xml version = “1.0”?>2 <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”3 http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd>45 <! -- Figure BinarySearch.html -- >6 <! – Binary Search -- >78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <title>Binary Search</title>1112 <script type = “text/javascript”>13 <! --14 var a = new Array( 15 );1516 for ( var i = 0; i < a, length; ++i )17 a[ i ] = 2 * i;1819 // function called when “Search” button is pressed20 function buttonPressed( )21 {22 var searchKey = searchForm.inputVal.value;2324 searchForm.result.value =25 “Portions of array searchedn”;2627 // Array a is passed to binarySearch even though it28 // is a global variable. This is done because29 // normally an array is passed to a method30 // for searching.31 var element =32 binarySearch( a, parseInt( searchKey ) );VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 73
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH3334 if ( element != -1 )35 searchForm.result.value +=36 “nFound value in element “ + element;37 else38 searchForm.result.value += “nValue not found”;39 }4041 // Binary search42 function binarySearch( theArray, key )43 {44 var low = 0; // low subscript45 var high = theArray.length – 1; // high subscript46 var middle; // middle subscript4748 while ( low <= high ) {49 middle = ( low + high ) / 2;5051 // The following line is used to display the52 // part of theArray currently being manipulated53 // during each iteration of the binary54 // search loop.55 buildoutput( theArray, low, middle, high );5657 if ( key == theArray[ middle ] ) // match58 return middle;59 else if ( key < theArray[ middle ] )60 high = middle – 1; // search low end of array61 else62 low = middle + 1; // search high end of array63 }6465 return – 1; // searchKey not found66 }6768 // Build one row of output showing the current69 // part of the array being processed.70 function buildoutput( theArray, low, mid, high )71 {72 for ( var i = 0; i < theArray.length; i++ ) {73 if ( i < low | | i > high )74 searchForm.result.value += “ “;75 // mark middle element in output76 else if ( i = = mid )VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 74
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH77 searchForm.result.value += theArray[ i ] +78 ( theArray[ i ] < 10 ? “* “: “* “ );79 else80 searchForm.result.value += theArray[ i ] +81 ( theArray[ i ] < 10? “ “ : “ “ );82 }8384 searchForm.result.value += “n”;85 }86 // -- >87 </script>88 </head>8990 <body>91 <form name = “searchForm” action = “ “>92 <p>Enter integer search key<br / >93 <input name = “inputVal” type = “text” / >94 <input name = “search” type = “button” value =95 “Search” onclick = “buttonPressed( )” /><br /></p>96 <p>Result<br />97 <textarea name = “result” rows = “7” cols = “60”>98 </textarea></p>99 </form>100 </body> Figure: Binary search of an array This program uses a 15 – element array (defined at line 14). The first power of 2 greaterthan the number of elements is 16 (2 4), so binarySearch requires at most four comparisons to findVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 75
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHthe key. To illustrate this, line 55 calls method buildoutput (declared in lines 70 – 85) to outputeach subarray during the binary – search process. Method buildoutput marks the middle elementin each subarray with an asterisk (*) to indicate the element with which the key is compared. Nomatter what search key is entered, each search in this example results in a maximum of four linesof output – one per comparison.16. What do you mean by String Object? What are the methods of String objects?String Object In this section, we introduce JavaScript’s string – and character – processing capabilities.The techniques discussed here are appropriate for processing names, addresses, credit cardinformation, and similar items.Fundamentals of Characters and Strings Characters are the fundamental building blocks of JavaScript programs. Every program iscomposed of a sequence of characters grouped together meaningfully that is interpreted by thecomputer as a series of instructions used to accomplish a task. A string is a series of characters treated as a single unit. A string may include letters, digitsand various special characters, such as+, -, *, /, and $. JavaScript supports the set of characterscalled Unicode®, which represents a large portion of the world’s commercially viable languages. Astring is an object of type String. String literals or string constants (often called anonymous stringobjects) are written as a sequence of characters in double quotation marks or single quotationmarks, as follows: “John Q. Doe” (a name) ‘9999 Main Street’ (a street address) “Waltham, Massachusetts”(a city and state) ‘(201) 555 – 1212’ (a telephone number) A String may be assigned to a variable in a declaration. The declaration var color = “blue”;initializes variable color with the string object containing the string “blue”. Strings can becompared with the relational operators (<, <=, > and >=) and the equality operators (== and ! =).Methods of the String ObjectVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 76
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH The String object encapsulates the attributes and behaviors of a string of characters. TheString object provides many methods (behaviors) for selecting characters from a string, combiningstrings (called concatenation), obtaining substrings of a string, searching for substrings within astring, tokenizing strings (i.e., splitting strings into individual words) and converting strings to alluppercase or lowercase letters. The string object also provides several methods that generateXHTML tags. Figure summarizes many string methods. Figure demonstrate some of thesemethods. Method DescriptioncharAt( index ) Returns a string containing the character at the specified index. If there is no character at the index, CharAt returns an empty string. The first character is located at index 0.charCodeAt( index Returns the Unicode value of the character at the specified index. If there) is no character at the index, charCodeAt returns NaN (not a number).concat( string ) Concatenates its argument to the end of the string that invokes the methods. The string invoking this method is not modified; instead a new string is returned. This method is the same as adding two strings with the string concatenation operator + (e.g... s1.concat( s2 ) is the same as s1 + s2).fromCharCode( val Converts a list of Unicode values into a string containing theue1, value2, ......) corresponding characters.index0f( substring, Searches for the first occurrence of substring starting from position indexindex ) in the string that invokes the methods. The method returns the starting index of substring in the source string of -1 if substring is not found. If the index argument is not provided, the method begins searching from index 0 in the source string.lastIndex0f( substr Searches or the last occurrence of substring starting from position indexing, index ) and searching toward the beginning of the string that invokes the method. The method returns the starting index of substring in the source string or -1 if substring is not found. If the index argument is not provided, the method begins searching from the end of the source string.slice( start, end ) Returns a string containing the portion of the string from index start through index end. If the end index is not specified, the method returns a string from the start index to the end of the source string. A negative end index specifies an offset from the end of the string starting from a position one past the end of the last character (so -1 indicates the last character position in the string).split( string ) Splits the source string into an array of strings (tokens) where its string argument specifies the delimiter (i.e., the characters that indicate the end of each token in the source string).substr( start, Returns a strong containing length characters starting from index start inlength ) the source string. If length is not specified, a string containing characters from start to the end of the source string is returned.substring( start, Returns a string containing the characters from index start up to but notend ) including index end in the source string.toLowerCase( ) Returns a string in which all uppercase letters are converted to lowercase VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 77
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH letters. Non – letter characters are not changed.toUpperCase( ) Returns a string in which all lowercase letters are converted to uppercase letters. Non – letter characters are not changed.toString( ) Returns the same string as the source string.Value( ) Returns the same string as the source string.Methods thatgenerate XHTML Wraps the source string in an anchor element (<a></a<) with name as thetags anchor name.anchor( name )blink( ) Wraps the source string in a <blink></blink> elementfixed( ) Wraps the source string in a <tt></tt> elementlink( url ) Wraps the source string in an anchor element (<a></a>) with url as the hyperlink location.strike( ) Wraps the source string in a<strike></strike> elementsub( ) Wraps the source string in a <sub></sub> elementsup( ) Wraps the source string in a <sup></sup> element. Figure: String object methods17. Explain in detail about the XHTML Markup methods of the string object and the dateobject. The script in figure demonstrates the String object’s methods that generate XHTML markuptags. When a String object invokes a markup method, the method wraps the String’s contents inthe appropriate XHTML tag. These methods are particularly useful for generating XHTMLdynamically during script processing.1 <?xml version = “1.0”>2 <!DOCTYPE html PUBLIC “//W3C//DTD XHTML 1.0 Strict//EN”3 http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>45 <! -- Figure MarkupMethods.html -- >6 <! – XHTML markup methods of the String object -- >78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <title>XHTML Markup Methods of the String Object</title>1112 <script type = “text/javascript”>13 <! --14 var anchorText = “This is an anchor”,15 blinkText = “This is blinking text”,16 fixedText = “This is monospaced text”,17 linkText = “Click here to go to anchorText”,18 strikeText = “This is strike out text”,VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 78
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH19 subText = “subscript”,20 supText = “superscript”;2122 document.writeln( anchorText.anchor( “top” ) );23 document.writeln( “<br />” + blinkText.blink( ) );24 document.writeln( “<br />” + fixedText.fixed( ) );25 document.writeln( “<br />” + strikeText.strike( ) );26 document.writeln(27 “<br />This is text with a” + subText.sub( ) );28 document.writeln(29 “<br />This is text with a” + supText.sup( ) );30 document.writeln(31 “<br />” + linkText.link( “#top” ) );32 // -- >33 </script>3435 </head><body></body>36 </html> Figure: String object XHTML markup methods Lines 14 – 20 define the strings that call each of the XHTML markup methods of the Stringobject. Line 22 uses String method anchor to format the string in variable anchorText (“This is ananchor”) as <a name = “top”> This is an anchor</a>The name of the anchor is the argument to the method. This anchor will be used later in theexample as the target of a hyperlink. Line 23 calls String method blink to make the string blink in the Web page by formattingthe string in variable blinkText (“This is blinking text”) as <blink> This is blinking text</blink> [Note: The blink tag works in most versions of Netscape and in the Mozilla Web browserVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 79
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHInternet Explorer, however, and many other browsers do not support blink] Line 24 uses String method fixed to display text in a fixed – width font by formatting thestring in variable fixedText (“This is monospaced text”) as <tt> This is monospaced text</tt> Line 25 uses String method strike to display text with a line through it by formatting thestring in variable strikeText (“This is strike out text”) as <strike>This is strike out text</strike> Lines 26 – 27 use String method sub to display subscript text by formatting the string asvariable subText (“subscript”) as <sub>subscript</sub> Note that the resulting line in the XHTML document displays the word subscript smallerthan the rest of the line and slightly below the line. Lines 28 – 29 call String method sup to displaysuperscript text by formatting the string in variable supText (“superscript”) as <sup>superscript</sup> Note that the resulting line in the XHTML document displays the word superscript smallerthan the rest of the line and slightly above the line. Lines 30-31 use String method link to create a hyperlink by formatting the string an variablelinkText (“Click here to go to anchorText”) as <a href = “#top”>Click here to go to anchorText</a> The target of the hyperlink (#top in this example) is the argument to the method and can beany URL. In this example, the hyperlink target is the anchor created in line 22. If you make yourbrowser window short and scroll to the bottom of the Web page, then click this link, the browserwill reposition to the top of the Web page.Date Object JavaScript’s Date object provides methods for date and time manipulations. Date and timeprocessing can be performed based on the computer’s local time zone or based on World TimeStandard’s Coordinated Universal Time (abbreviated UTC) – formerly called Greenwich MeanTime (GMT). Most methods of the Date object are summarized in figure. Method DescriptionVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 80
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH getDate( ) Returns a number from 1 to 31 representing the day of the getUTCDate( ) month in local time or UTC getDay( ) Returns a number from 0 (Sunday) to 6 (Saturday) getUTCDay( ) representing the day of the week in local time or UTC getFullYear( ) Returns the year as a four – digit number in local time or getUTCFullYear( ) UTC getHours( ) Returns a number from 0 to 23 representing hours since getUTCHours( ) mid night in local time or UTC. getMilliseconds( ) Returns a number from 0 to 999 representing the number getUTCMilliSeconds( ) of milliseconds in local time or UTC, respectively. The time is stored in hours, minutes, seconds and milliseconds. getMinutes( ) Returns a number from 0 to 59 representing the minutes getUTCMinutes( ) for the time in local time or UTC getMonth( ) Returns a number from 0 (January) to 11(December) getUTCMonth( ) representing the month in local time or UTC getSeconds( ) Returns a number from 0 to 59 representing the seconds for getUTCSeconds( ) the time in local time or UTC getTime( ) Returns the number of milliseconds between January 1, 1970 and the time in the Date object. getTimezoneOffset( ) Returns the difference in minutes between the current time on the local computer and UTC – previously known as Greenwich Mean Time(GMT). setDate( val ) Sets the day of the month (1 to 31) in local time or UTC. setUTCDate( val ) setFullYear( y, m, d) Sets the year in local time or UTC. The second and third setUTCFullYear(y, m, d) arguments representing the month and the date are optional. If an optional argument is not specified, the current value in the Date object is used. setHours( h, m, s, ms ) Sets the hour in local time or UTC. The second, third and setUTCHours( h, m, s, ms fourth arguments, representing the minutes, seconds and ) milliseconds, are optional. If an optional argument is not specified, the current value in the Date object is used. setMilliSeconds( ms ) Sets the number of milliseconds in local time or UTC. setUTCMilliseconds( ms ) setMinutes( m, s, ms ) Sets the minute in local time or UTC. The second and setUTCMinutes( m, s third arguments, representing the seconds and ms ) milliseconds, are optional. If an optional argument is not specified, the current value in the Date object is used. setMonth( m, d ) Sets the month in local time or UTC. The second setUTCMonth( m, d ) argument, representing the date, is optional. If the optional argument is not specified, the current date value in the Date object is used. setSeconds( s, ms ) Sets the second in local time or UTC. The second setUTCSeconds( s, ms ) argument, representing the milliseconds, is optional. IfVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 81
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH this argument is not specified, the current millisecond value in the Date object is used. setTime( ms ) Sets the time based on its argument – the number of elapsed milliseconds since January 1, 1970. toLocalString( ) Returns a string representation of the date and time in a form specific to the computer’s locale. For example, September 13, 2001 at 3:42:22 PM is represented as 09/13/01 15:47:22 in the United States and 13/09/01 15:47:22 in Europe toUTCString( ) Returns a string representation of the date and the time in the form: 19 September 2001 15:47:22 UTC toString( ) Returns a string representation of the date and time in a form specific to the locate of the computer (Monday September 19 15:47:22 EDT 2001 in the United States). valueof( ) The time in number of milliseconds since midnight, January 1, 1970. Figure: Date Object Methods The script of figure demonstrates many of the local time zone methods in figure. Line 14creates a new Date object. The new operator allocates the memory for the Date object. The emptyparentheses indicate a call to the Date object’s constructor with no arguments. A constructor is aninitializer method for an object. Constructors are called automatically when an object is allocatedwith new. The Date constructor with no arguments initializes the local computer’s Date objectwith the current date and time.1 <?xml version = “1.0”?>2 <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML1.0 Strict//EN”3 http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd>45 <! -- Figure: DateTime.html -- >6 <! -- Date and Time Methods -->78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <title>Date and Time Methods</title>1112 <script type = “text/javascript”>13 <! --14 var current = new Date( );1516 document.writeln(17 “<h1>string representations and valueof</h1>” );18 document.writeln( “toString: “+current.toString( ) +19 “<br />toLocalString: “+current.toLocalString( ) +VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 82
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH20 “<br />toUTCString: “+ current.toUTCString( ) +21 “<br />valueof: “+current.valueof( ) );2223 document.writeln(24 “<h1>Get methods for local time zone</h1>” );25 document.writeln( “getDate: “+current.getDate( ) +26 “<br />getDay: “+current.getDay( ) +27 “<br />getMonth: “+ current.getMonth( ) +28 “<br />getFullYear: “+current.getFullYear( ) +29 “<br />getTime: “+ current.getTime( )+30 “<br />getHours: “+current.getHours( ) +31 “<br />getMinutes: “+ current.getMinutes( ) +32 “<br />getSeconds: “+current.getSeconds( )+33 “<br />getMillSeconds: “+34 current.getMilliSeconds ( )+35 “<br />getTimezoneOffset: “+36 current.getTimezoneOffset( ) );3738 document.writeln(39 “<h1>Specifying arguments for a new Date</h1>” );40 var anotherDate = new Date( 2001, 2, 18, 1, 5, 0, 0 );41 document.writeln( “Date: “+anotherDate );4243 document.writeln(44 “<h1>Set methods for local time zones</h1>” );45 anotherDate.setDate( 31 );46 anotherDate.setMonth( 11 );47 anotherDate.setFullYear( 2001 );48 anotherDate.setHours( 23 );49 anotherDate.setMinutes( 59 );50 anotherDate.setSeconds( 59 );51 document.writeln(“Modified date: “+anotherDate );52 // -- >53 </script>5455 </head><body></body>56 </html>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 83
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure: Date and time methods of the Date object Figure: Date and Time methods of the Date object Lines 18 – 21 demonstrate the methods toString, toLocalString, toUTCString and valueOf.Note that method valueOf returns a large integer value representing the total number ofmilliseconds between midnight. January 1, 1970 and the date and time stored in Date objectcurrent. Lines 25 – 36 demonstrate the Date object’s get methods for the local time zone. Note thatmethod getFullYear returns the year as a four-digit number. Note as well that methodgetTimeZoneOffset returns the difference in minutes between the local time zone and UTCtime(i.e., a difference of four hours in our time zone when this example was executed). Line 40 demonstrates creating a new Date object and supplying arguments to the Dateconstructor for year, month, date, hours, minutes, seconds and milliseconds. Note that the hour,minutes, seconds and milliseconds arguments are all optional. If any one of these arguments isVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 84
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHnot specified, a zero is supplied in its place. For the hours, minutes and seconds arguments, if theargument to the right of any of these arguments is specified, it too must be specified (e.g., if theminute’s argument is specified, the hour’s argument must be specified; if the millisecondsargument is specified, all the arguments must be specified) Lines 45 – 50 demonstrate the Date object set methods for the local time zone. Date objectsrepresent the month internally as an integer from 0 to 11. These values are off by one from whatyou might expect (i.e., 1 for January, 2 for February, ...... and 12 for December). When creating aDate object, you must specify 0 to indicate January, 1 to indicate February ....... and 11 to indicateDecember. The date object provides two other methods that can be called without creating a new dateobject – Date.parse and Date.UTC. Method Date.parse receives as its argument a stringrepresenting a date and time, and returns the number of milliseconds between midnight, January1, 1970 and the specified date and time. This value can be converted to a Date object with thestatement. var theDate = new Date( numberOfMilliseconds );Which passes to the date constructor the number of milliseconds since midnight, January 1, 1970for the Date objectMethod parse converts the string using the following rules: • Short dates can be specified in the form MM – DD – YY, MM – DD – YYYY, MM/DD/YY or MM/DD/YYYY. The month and day are not required to be two digits. • Long dates that specify the complete month name (e.g., “January”), date and year can specify the month, date and year in any order. • Text in parentheses within the string is treated as a comment and ignored. Commas and white space characters are treated as delimiters. • All month and day names must have at least two characters. The names are not required to be unique. If the names are identical, the name is resolved as the last match (e.g., “Ju” represents “July” rather than “June”). • If the name of the day of the week is supplied, it is ignored. • All standard time zones (e.g., EST for Eastern Standard Time), Coordinated Universal Time (UTC) and Greenwich Mean Time (GMT) are recognized. • When specifying hours, minutes and seconds, separate each by colons. • When using a 24-hour – clock format, “PM” should not be used for times after 12 noon. Date method UTC returns the number of milliseconds between midnight, January 1, 1970and the date and time specified as its arguments. The arguments to the UTC method include therequired year, month and date, and the optional hours, minutes, seconds and milliseconds. If anyof the hours, minutes, seconds or milliseconds arguments is not specified, a zero is supplied in itsplace. For the hours, minutes and seconds arguments, if the argument to the right of any of thesearguments in the argument list is specified, that argument must also be specified (e.g., if theVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 85
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHminutes argument is specified, the hours argument must be specified; if the millisecondsargument is specified, all the arguments must be specified). As with the result of Date parse, theresult of Date UTC can be converted to a Date object by creating a new Date object with the resultof Date UTC as its argument.18. (1) Discuss in detail about the document object (2) Window objects with necessary example programs.Document Object JavaScript provides the document object for manipulating the document that is currentlyvisible in the browser window. The document object has many useful properties and methods,such as methods document. Write and document. Writeln, which have both been used in priorJavaScript examples. Figure shows the methods and properties of the document objects that areused in this chapter. A more comprehensive list of properties and methods can be found at thejavaScript reference URL located in Section 12.11, Web Resources. Method or Property Description Write ( string ) Writes the string to the XHTML document as XHTML code. Writeln( string ) Writes the string to the XHTML document as XHTML code and adds a newline character at the end. document.cookie This property is a string containing the values of all the cookies stored on the user’s computer for the current document. See Section Using Cookies. document.lastModified This property is the date and time that this document was last modified. Fig: Important document object methods and properties.Window Object JavaScript’s window object provides methods for manipulating browser windows. Thefollowing script shows many of the commonly used properties and methods of the window objectand uses them to create an interesting Web site that spans multiple browser windows. Figureallows the user to create a new, fully customized browser window by completing an XHTML formand clicking the submit button. The script also allows the user to add text to the new window andredirect the window to a different URL.1 <?xml version = “1.0” encoding = “utf-8”?>2 <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”3 ‘http”//www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>45 <!- - >Fig. 12.13: window.html - - >6 <!- - > Using the window object - - >VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 86
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <title>Using the window object</title>1112 <script type = “text/javascript”>13 <! - -14 var childWindow; // variable to control the child window1516 function creatChildWindow ( )17 {18 // these variables all contain either “yes” or “no”19 // to enable or disable a feature in the child window20 var toolbar // specifty if toolbar will appear in child window21 var menuBar; // specifty if menubar will appear in child window22 var location; // specify if address bar will appear in child window23 var scrollBars; // specify if status bar will appear in child window.24 var status; // specify status bar will appear in child window25 var resizable; // specify if the child window will be resizable2627 // determine whether the Tool Bar checkbox is checked28 if ( toolBarCheckBox.checked )29 toolBar = “yes” ;30 else31 toolBar = “no”3233 // determine whether the Menu Bar( )checkbox is checked34 if ( menuBarCheckBox.checked )35 menuBar = “yes”;36 else37 menuBar = “no”;3839 // determine whether the Address Bar checkbox is checked40 if ( locationCheckBox.checked )41 location = “yes”;42 else43 location = “no”;4445 // determine whether the Scroll Bar checkbox is checked46 if ( scrollBarsCheckBox.checked )47 scrollBars = “yes”;48 else49 scrollBars = “no”;50VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 87
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH51 // determine whether the Status bar checkbox is checked52 if ( statusCheckBox.checked )53 status = “yes”;54 else55 status = “no”;5657 // determine whether the Resizable checkbox is checked is checked58 if ( resizableCheckBox.checked )59 resizable = “yes”;60 else61 resizable = “no”;6263 // display window with selected features64 childwindow = window.open ( “”,””,” resizable = “ + resizable +65 “,toolbar = “+toolbar + “, menubar = “ + menuBar +66 “status = “ +status +”, location = “ + lcoation +67 “, scrollbars = “ + scrollbars );6869 // disable buttons70 closeButton.disabled = false;71 modifyButton.disabled = false;72 getURLButton.disabled = false;73 setURLBUtton.disabled = false;74 } // end function createChildWindow7576 // insert text from the textbox into the child window77 function modifyChildWindow( )78 {79 if ( childWindow.closed )80 alert ( “You attempted to interact with a closed window” );81 else82 childWindow.document.write( textForChild.value );83 } // end function modifyChildWindow8485 // close the child window86 function closeChildWindow ( )87 {88 if ( childWindow.closed )89 alert ( “Your attempted to interact with a closed window” );90 else91 childWindow.close( );9293 closeButton.disabled = true;94 modifyButton.disabled = true;VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 88
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH95 getURLButton.disabled = true;96 setURLButton.disabled = true;97 } // end function closeChildWindow9899 // copy the URL of the child window into the parent window’s myChildURL100 function getChildWindowURL( )101 {102 if ( childWindow.closed )103 alert( “You attempted to interact with a closed window” );104 else105 myChildURL.value = childWindow.location;106 } // end function getChildWindowURL107108 //set the URL of the child window to the URL109 // in the parent window’s myChildURL110 function setChildWindowURL( )111 {112 if ( childWindow.closed )113 alert( “You attempted to interact with a closed window” )”114 else115 childWindow.location = myChildURL.value;116 } // end function setChildWindow URL117 // - ->118 </script>119120 </head>121122 <body>123 <h1>Hello, This is the main window<h1>124 <p>please check the features to enable for the child window<br/>125 <input id = “toolBarCheckBox” type = “checkbox” value = “”126 checked = “checked” />127 <label>Tool Bar</label>128 <input id = “menuBarCheckBox” type = “checkbox” value = “”129 checked = “checked”130 <label>Menu Bar</label>131 <input id = “locationCheckBox” type = “checkbox” value = “”132 checked = “checked” />133 <label>Address Bar</label><br/>134 <input id = “scrollBarsCheckBox” type = ‘checkbox” value = “”135 checked = “checked” />136 <label>Scroll Bars</label>137 <input id = ‘statusCheckBox” type = “checkbox” value = “”138 checked = “checked” />VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 89
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH139 <label>Status Bar<label>140 <input id = “resizableCheckBox” type = “checkbox” value = “”141 checkd = “checked” />142 <label>Resizable<lable><br/></p>143144 <p> Please enter the text that you would like to display145 in the child window<br />146 <input id = “textForChild” type = “text”147 value = “<h1> Hello, I am a child window</h1><br>”/>148 <input id = “createButton type = “button”149 value = “Create child Window” onclick = “createChildWindow( )” />150 <input id= “modifyButton” type = “button” value = “Modify Child Window”151 onclick = “modifyChildWindow ( )” disabled = “disabled”/>152 <input id = “closeButton” type = “button” value = “Close Child Window”153 onclick = “closeChildWindow( )” disabled = “disabled” /></p>154155 <p>The other window’s URL is: <br/>156 <input id = “myChildURL” type = “text” value = “/”/>157 <input id = “setURLButton” type = “button” value = “Set child URL”158 onclick = “setChildWindowURL ( )” aisabled = “disabled” />159 < in[ut id = “getURLButton” type = “button value = “Get URL From child160 onclick = “getChildwindowURL ( )” disabled = “disabled”/></p>161162 </body>163 </html>Figure. Using the Window object to create and modify child window (Part 2,3&4 of 4)VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 90
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure: Using the window object to create and modify child windows (Part 4 of 4) The script starts in line 12. Line 14 declares a variable to refer to the new window. We willrefer to the new window as the child window because it is created and controlled by the main, orparent, window in this script,. Lines 16-74 define the function createChild-window, whichdetermines the features that have been selected by the user and creates a child window with thosefeatures (but does not add any content ot the window). Lines 20-25 declare several variables tostore the status of the checkboxes on the page. Lines 28-61 set each variable to “yes” or “no” basedon whether the corresponding checkbox is checked or unchecked. The statement in lines 64-67 usesthe window object’s open method to create the requested child window. Method open has threeparameters. The first parameter is the URL of the page to open in the new window, and the secondparameter is the title of the window. In our example, we pass window, open empty strings as thefirst two parameter values because we want the new window to open a blank page with no title.The third parameter is a string of comma-separated, all-lowercase feature names, each followed byan=sign and either ‘yes” or ‘no” to determine whether that feature should be displayed in the newwindow. If any of these parameters are omitted, the browser will default to a new windowcontaining an empty page, no title and all features visible. Lines 70-73 enable the buttons formanipulating the child window-these are initially disabled when the page loads. Lines 77-83 define the function modifyChildWindow, which adds a line of text to the contentof the child window. In line 79, the script determines whether the child window is closed. FunctionVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 91
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHmodifychildwindow uses property childWindow.closed to obtain a Boolean value that is true ifchildWindow is closed and false if the window is still open. If the window is closed, an alert box isdisplayed notifying the user that the window is currently closed and cannot be modified. If thechild window is open, line 82 obtains text from the textForChild textbox (lines 146-147) in theXHTML form in the parent window and uses the child’s document.write method to write this textto the child window. Function closeChildWindow (lines 86-97) also determines whether the child window isclosed before proceeding. If the child window is not open, the script displays an alert box tellingthe user that the window is already closed. If the child window is open, line 91 closes it using thechildWindow. Close method. Lines 93-96 disable the buttons that interact with the child window. Function getChildWindowUrl (lines 100-106) obtains the URL displayed in the child windowand copies it into the myChildURL textbox in the parent window. The function first determines thestatus of the window. If the child is closed, then the script displays an alert box to the user. If thewindow is still open, then the script copies property childWindow.location-which contains a stringrepresentation of the window’s current URL-to the myChildURL textbox in the parent window.Software Engineering Observation 12.4 Window. location is a property that always contains a string representation of the URLdisplayed in the current window. Most Web browsers will only allow a script to access thewindow.location property of another window if the script is running on the same Web sit as thepage in the other window. Function setChildWindowURL (lines 110-116) copies the contents of the myChildURLtextbox to the location property of the child window. If the child window is open, line 115 setsproperty location of the child window to the string in the my childURL textbox. This action changesthe URL of the child window and is equivalent to typing a new URL into the window’s address barand clicking Go. The script ends in line 118. Lines 122-162 contain the body of the XHTML document,comprising a form that contains checkboxes, buttons, textboxes and form field labels. The scriptuses the form elements defined in the body to obtain input from the user. In lines 149, 151, 153, 158and 160, the Web page specifies the onclick attribute of an XHTML button. The property onclickdefines what will occur when the user clicks the button. In this example, each button is set to call acorresponding JavaScript function when clicked. Line 163 closes the XHTML document. Figure: contains a list of some commonly used methods and properties of the windowobject. Method or Property Descriptionopen (url, name, options ) Creates a new window with the URL of the window set to url, the name set to name, and the visible features set by the string passed in asVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 92
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH option.prompt( prompt, Displays a dialog box asking the user for input. The text of the dialogdefault ) is prompt, and the default value is set to default. close ( ) Closes the current window and deletes its object from memory.focus ( ) This method gives focus to the window (i.e., puts the window in the foreground, on top of any other open browser windows).blur( ) This method takes focus away from the window (i.e., puts the window in the background).window. document This property contains the document object representing the document currently inside the window.window.closed This property contains a Boolean value that is set to true if the window is closed, and false if it is not.window.opener This property contains the window object of the window that opened the current window, if such a window exists. Figure:Important window object methods and properties.19. Discuses how cookies are used for personalizing web pages with appropriate examples.Using Cookies: Cookies provide Web developers with a tool for personalizing Web pages. A cookie is apiece of data that is stored on the user’s computer to maintain information about the client duringand between browser sessions. A Web site may store a cookie on the client’s computer to recorduser preferences or other information that the web site can retrieve during the client’s subsequentvisits. For example, a web site can retrieve the user’s name from a cookie and use it to display apersonalized greeting. Microsoft Internet Explorer stores cookies as small text files on the client’s hard drive.When a user visits a web site, the browser locates any cookies written by scripts on that site andmakes them available to any scripts located on the site. Note that cookies may only be accessed byscripts located on the server from which they originated (i.e., a cookie set by a script onamazon.com can only be read by other scripts on amazon.com). Cookies are accessible in JavaScript through the document object’s cookie property.JavaScript treats a cookie as a string of text. Any standard string function or method canmanipulate a cookie. A cookie has the syntax “identifier=value”, where identifier is any validJavaScript variable identifier, and value is the value of the cookie variable. When multiple cookiesexist for one web site, identifier-value pairs are separated by semicolons in the document. cookiestring. Cookies differ from ordinary strings in that each cookie has an expiration date after whichthe web browser deletes it. This date can be defied by setting the expires property in the cookiestring. If a cookie’s expiration date is not set, then the cookie expires by default after the userVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 93
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHcloses the browser window. A cookie can be deleted immediately by setting the expires propertyto a data and time in the past. Figure uses a cookie to store the user’s name and displays a personalized greeting. Thisexample improves upon the functionality in the dynamic welcome page example of figure byrequiring the user to enter a name only during the first visit to the web page. On each subsequentvisit, the script can display the user name that is stored in the cookie. Line 12 is the beginning of the script. Lines 14-15 declare the variables needed to obtain thetime, and line 16 declares the variable that stores the name of the user. Lines 18-29 contain thesame if …..else statement used in figure to display a time-sensitive greeting. 1. <?xml version = “1.0”?> 2. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” 3. http://www.w3.org/TR/xhtml 11/DTD/xhtml 11.dtd> 4. 5. <! - - fig: cookie.html --> 6. <! - -Using Cookies --> 7. 8. <html xmlns = http://www.w3.org/1999/xhtml> 9. <head> 10. <title> Using Cookies </title> 11. 12. <script type = “text/javascript”> 13. <! – 14. var now = new Date (); //current date and time 15. var hour = now.getHours (); //current hour (0-23) 16. var name; 17. 18. if ( hour < 12 ) // determine whether it is morning 19. document.write ( “<h1> Good Morning, “ ); 20. else 21. { 22. hour = hour – 12 ; // convert from 14 hour clock to PM time 23. 24. // determine whether it is afternoon or evening 25. if ( hour < 6 ) 26. document. write ( “ <h1>Good Afternoon, “ ); 27. else 28. document. write ( “<ht> Good Evening, “ ); 29. } 30. 31. // determine whether there is a cookie 32. if ( document. cookie)VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 94
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 33. { 34. // convert escape characters in the cookie string to their 35. // english notation 36. var myCookie = un escape( document. cookie); 37. 38. // split the cookie into tokens using = as delimiter 39. var cookieTokens = myCookie.split (“=”); 40. 41. // set name to the part of the cookie that follows the = sign 42. name = cookieTokens [ 1 ]; 43. } 44. else 45. } 46. // if there was no cookie then ask the user to input a name 47. name = window.prompt (“please enter your name”, GalAnt”); 48. 49. //escape special characters in the name string 50. // and add name to the cookie 51. document. cookie = “name” +escape (name); 52. } 53. 54. document.writeln( 55. name + “,welcome to JavaScript programming! </h1>”); 56. document.writeIn ( “<a href = ” JavaScro[t:wrpmgPerson () ” >”+ 57. “Click here if you are not “ + name + “</a>”); 58. 59. // reset the document’s cookie if wrong person 60. function wrongPerson() 61. { 62. //reset the cookie 63. document. cookie= “name-null + 64. “expires=Thu, 01-Jam-95 00:00:01 GMT”; 65. 66. // after removing the cookie reload the page to get a new name 67. location.reload(); 68. } 69. 70. //--> 71. </script> 72. </head> 73. 74. <body> 75. <p> Click Refresh (or Reload) to run the script again </p> 76. </body>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 95
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 77. <//html> Figure: Using cookies to store user identification data (part 3 of 3) Lines 32-69 contain the code used to manipulate the cookie. Line 32 determines whether acookie exists on the client computer. The expression document. Cookie evaluates to true if acookie exists. If a cookie does not exist, then the script prompts the user to enter a name (line 47).The script creates a cookie containing the string “name=”, followed by a copy of the user’s nameproduced by the built-in JavaScript function escape (line 51). The function escape converts anynon-alphanumeric characters, such as spaces and semicolons, in a string to their equivalenthexadecimal escape sequences of the form “%XX,” where XX is the two-digit hexadecimal ASCIIvalue of a special character. For example, if name contains the value “Luna Tic”, the statementescape (name) evaluates to “Luna% 20 Tic”, because the hexadecimal ASCII value of a blank spaceis 20. it is a good idea to always escape cookie values before writing them to the client. Thisconversion prevents any special characters in the cookie from being misinterpreted as having aspecial meaning in the code, rather than being a character in a cookie value. For instance, asemicolon in a cookie value could be misinterpreted as a semicolon separating two adjacentidentifier –value pairs. Applying the function un escape to cookies when they are read out of thedocument. cookie string converts the hexadecimal escape sequences back to English characters fordisplay in a web page.Good Programming Practice: Always store values in cookies with self-documenting identifiers. Do not forget to includethe identifier followed by an =sign before the value being stored. If a cookie exists (i.e., the user has been to the page before), then the script parses the username out of the cookie string and stores it in a local variable. parsing generally refers to the act ofsplitting a string into smaller, more useful components. Line 36 uses the JavaScript function unVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 96
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHescape to replace all the escape sequences in the cookie with their equivalent English –languagecharacters. The script stores the unescaped cookie value in the variable myCookie contains astring of the form “name =value”. We call split on myCookie with =as the delimiter to obtain thecookie Tokens array, with the first element equal to the name of the identifier and the secondelement equal to the value of the identifier. Line 42 assigns the value of the second element in thecookie tokens array (i.e., the actual value stored in the cookie) to the variable name. lines 54-45and the personalized greeting to the web page using the user’s name stored in the cookie. The web page provides users with the option of resetting the cookie, which is useful in casesomeone new is using the computer. Lines 56-57 create a hyperlink that, when clicked, calls theJavaScript function wrong Person (lines 60-68). Lines 63-64 set the cookie name to null and theexpires property to January 1, 1995 (thought any date in the past will suffice). Internet Explorerdetects that the expires property is set to a date in the past and deletes the cookie from the user’scomputer. The next time this pave loads, no cookie will be found. The reload method of thelocation object forces the page to refresh, and unable to find an existing cookie, the script promptsthe user to enter a new name. UNIT – II PART – A1. What is the use of Dynamic HTML Object Model? The Dynamic HTML Object Model gives Web authors great control over the presentation oftheir pages by giving then access to all the elements on their Web page. The whole Web page –elements, forms, frames, tables, etc. – is represented in a object hierarchy. Using scripting, anauthor is able to retrieve and modify any properties or attributes of the Web page dynamically.2. What do you mean by object referencing? The simplest way to reference an element is by using the element’s id attribute. Theelement is represented as an object, and its various XHTML attributes become properties that canbe manipulated by scripting. Figure uses the technique to read the Inner Text property of aelement. 1. <?xml version ≈ “ 1.0 “?> 2. <! DOCTYPE html PUBLIC “-//WBC//DTD XHTML 1.0 Strict//EN” 3. “http: / / www.w3.org/TR/ xhtm l 1/DTD/ xhtml 4. 1 ∼ strict. Dtd “> 5. 6. <! ∼∼fig,13.1: reference. html ∼∼ >VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 97
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 7. <! ∼∼ object Model Introduction ∼∼ > 8. 9. <html xmlns ≈ “http://www.w3.org/1999/xhtml “> 10. <head> 11. <title> object Modle < /title> 12. 13. <script type ≈ “text/javascript”> 14. <! ∼∼ 15. function start ( ) 16. { 17. alert ( pText. innerText); 18. pText.innerText = “Thanks for. Coming. ; 19. } 20. // ∼∼> 21. </script> 22. 23. </head> 24. 25. < body on load = “start ( )”> 26. <p id ≈ “pText”> Wel come to our Web page! </p> 27. </body> 28. </html>3. What are collections? Give eg? 1. Collections are basically arrays of related objects on a page. There are several special collections in the object model 2. The all collection contains all the XHTML elements in a document 3. The length property of the a collection specifies the size of the collection. 4. Property inner HTML is similar to property inner Text, but it can include XHTML formatting. 5. Every element has its own all collection consisting of all the elements contained in the element. 6. The children collection of an element contains only the element’s direct child elements. For example, an html element has only two children: the head element and the body element. 1. <script type ≈ “text / javascript”> 2. <! ∼∼ 3. var elements = “”;VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 98
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 4. 5. function start ( ) 6. { 7. for (var loop = 0; l oop < document. a ll. length; ++ l oop ) 8. elements += “<bc /> + document. all[l oop] . tagName; 9. 10. pText. innerHTML += elements; 11. alert (elements); 12. } 13. // ∼∼ > 14. </script> 1. <script type ≈ “text/javascript”> 2. <! ∼∼ 3. var elements = “<ul >”; 4. 5. function child( object) 6. { 7. var loop = 0; 8. 9. elements += “<li>” + object.tagName + “<ul>; 10. 11. for (loop = 0; loop < object. Children. length; loop ++) 12. { 13. if ( object. children [loop]. children. length) 14. child ( object. children [loop]); 15. else 16. elements +=”<li>” + 17. object. children[loop]). tagName + 18. “</li>”; 19. } 20. 21. elements += “</ul>” + “</li>”; 22. } 23. // ∼∼ > 24. </script>4. Write a program to represent an element’s style property. An element’s style can be changed dynamically. Often such a change is made in response touser events, Figure is a simple example of changing styles in response to user input. 1. <?xml version ≈ “1.0”?> 2. < ! DOCTYPE html PUBLIC “-/ /W3C/ /DTD. EHTML 1.0 Strict//EN”VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 99
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 3. “http: / / www. W3. org/TR/xhtml1/DTD/xhtml 1- strict.dtd”> 4. 5. < ! ∼∼ fig 13.4: dynamicstyle. html 6. < ! ∼∼ Dynamic Styles 7. 8. <html xmlns ≈ “http: / / www. W3. org / 1999 / xhtml”> 9. < head > 10. < title> object Model< / totle> 11. 12. < script type ≈ “ text/ javascropt”> 13. ∼∼ > 14. function start ( ) 15. { 16. var input Color = prompt( 17. “Enter a color name for the “ + 18. “ background of this page”, “ “ ); 19. document. body. style. background Color = input Color; 20. } 21. / / ∼∼ > 22. < / script > 23. < / head > 24. 25. < body on load ≈ “start ( )” > 26. < p> Welcome to out Web site! </p> 27. < / body > 28. </html>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 100
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure: Dynamic styles (part 1of 2 ) Function start (lines 14-20) prompts the user to enter a color name, then sets the back groundcolor to that value. [Note: An error occurs if the value entered is not a valid color. See AppendixB, XHTML Colors, for further information.] we refer to the back ground color as document. body.style background Color – the body property of the document object refers to the body element.We then use the style property ( a property of most XHTML elements) to set the background -color CSS property. (This is referred to as background Color in JavaScript, to avoid confusionwith the subtraction (-) operator. This naming convention is consistent for most CSS properties.For example, borderwidth correlates to the border-width CSS property, and font Familycorrelates to the font-family CSS property.5. What is Dynamic Positioning in DHTML? An important feature of Dynamic HTML is dynamic positioning, in which XHTML elementscan be positioned with scripting. This is done by declaring an element’s CSS position property tobe either abso lute or relative, and then moving the element by manipulating any of the top, left,right or bottom CSS properties.6. What does the function set interval do? What are the parameters of this function? Set-Interval is used to continuously up data an elements contentVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 101
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH i. Function set interval takes two parameters – a function name and how often to call it. ii. Function set timeout takes the same parameters as set interval, but instead waits the specified amount of time before calling the named function only once. iii. There are also JavaScript functions for stopping the set Timeout and set interval timers – the clear timeout and clear interval functions. To stop a specific timer, the parameter yo9u pass to either of these functions should be the value that the corresponding set time function returns.7. Fill in the blanks for each of the following statements. i. The ____________ property refers to the text inside an element ii. The _____________ property refers to the text inside an element, including XHTML tags iii. The ____________ property refers to the text and XHTML inside an element and the enclosing XHTML tags iv. The ____________ property contains the number of elements in a collection. v. An element’s CSS position property must be set to _________ or _____________ in order to reposition it dynamically. vi. The ________ property contains the name of the browser viewing the Web page. vii. The ______________ property contains the version of the browser viewing the Web page. viii. The ______________ collection contains all the img elements on a page. ix. The _____________ object contains information about the sites that a user previously visited. x. CSS properties may be accessed using the ____________ object.8. Explain how the event model of DHTML works.1. The event model allows scripts to respond to user actions and change a page accordingly. Thismakes Web applications responsive and user friendly and can greatly lessen serve load but cancause compatibility problems.2. With the even model, scripts can respond to a user moving the mouse, scrolling up or down thescreen or entering keystrokes. Content becomes more dynamic, and interfaces become moreintuitive.9. With an example program and explain the working of on click event. When the user clicks a specific item with the mouse, the on click event fires. WithJavaScript, we are able to respond to on click and other events. Figure is an example of simple VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 102
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHevent handling for the on click event. The script beginning in lines 15-16 introduces a new notation. Using the for property of thescript element allows you to specify the element to which the script applies. In this case, pararepresents the p element in line 26. when the event specified in the event attribute occurs for theelement with id specified in the for attribute, the statements in the script execute. Line 26 sets theid for the p element to para. Attribute id specifies a unique identifier for an XHTML element.When the on click event for this element fires, the script in lines 15-20 executes. 1. <? Xml version ≈ “1.0” ?> 2. <! DOCTYPE html PUBLIC “ - / / W3C/ / DTD XHTML 1.0 Transitional / / EN” 3. “http://www.w3.org/TR/xhtml1/DTD/xhtml 1- transitional. dtd”> 4. 5. <!∼∼ fig14.1 :on click. html ∼∼> 6. <!∼∼ Demonstrating the on click event ∼∼> 7. 8. <html xmlns ≈ “http: // www. W3.org/1999/ xhtml”> 9. < head> 10. < title> DHTML Event Model – on click < / title > 11. 12. <!∼∼ The for attribute declares the script for ∼∼> 13. <!∼∼ a certain element, and the event for a ∼∼> 14. <!∼∼ certain event. 15. <script type ≈ “text/Javascript” for ≈ “para” 16. event ≈ “ on click”> 17. 18. alert ( “Hi there”); 19. / / ∼∼> 20. < / script > 21. </head> 22. 23. < body> 24. 25. <!∼∼ The id attribute gives a unique identifier ∼∼> 26. <p id ≈ “ para” > Click on this text ! < /p> 27. 28. <!∼∼ you can specify event handless in line ∼∼> 29. < input type ≈ “ button” value ≈ “ Click Me!” 30. on click ≈ “alert ( ‘Hi again’) /> 31. 32. < / body. 33. </jtml>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 103
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure: Triggering an on click event (part 2 of 2)10. Explain the event on load with an example program. The on load event fires whenever and element finishes loading successfully (i.e., all itschildren are loaded). Frequently, this event is used in the body element to initiate a script after thepage loads into the client. Figure uses the on load event for this purpose. The script called by theon load event updates a timer that indicates how many seconds have elapsed since the documentwas loaded 1. <? xml version ≈ “ 1.0” ? > 2. <! DOCTYPE html PUBLIC “-/ / W3C / / DTD XHTML 1.0 Strick / / EN” 3. “http://www.w3.org/TR/xhtml1/ DTD/xhtml 1- strict. dtd”> 4. 5. <!∼∼fig. 14.2: on load html ∼∼> 6. <!∼∼ Demonstrating the on load event ∼∼> 7. 8. <html xmlns ≈ “http://www.w3.org/1999/xhtml”> 9. <head. 10. <title> DHTML Event Model – on load </title>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 104
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 11. < script type ≈ “ tect/javascript”> 12. <!∼∼ 13. var seconds = 0; 14. 15. function start Timer ( ) { 16. / / 1000 milli seconds ≈ 1 second 17. window. set Interval ( “up date time ()”, 1000); 18. } 19. 20. function update Time () { 21. seconds++; 22. soFar. Inner Text = seconds; 23. } 24. / / ∼∼ > 25. < /script > 26. </head> 27. 28. < / body on load ≈ “ start Timer ( ) “> 29. 30. < p > Seconds you have spent viewing this page so far: 31. < strong id ≈ “ so far” > 0 < / strong ></p> 32. 33. </body > 34. </html> Figure: Demonstrating the on load event (Part 2 of 2)11. What is the use of onerror event? 1. You can use the onerror event to write error-handling code.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 105
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 2. The syntax window. onerror = function Name specifies that function Name runs if the onerror event is triggered in the window object. 3. Error handlers can accept three parameters from the onerror event (one of the few events that passes parameters to event handler). The onerror event passes the type of error that occurred, the URL of the file that hand the error and the line number on which the error occurred.12. What does the event object do? What are the properties of it? 1. The event object contains information about the triggered the event. 2. Property srcElement of the event object refers to the element that triggered the event. 3. The off set X and off set Y properties of the event object give the location of the mouse cursor relative to the top-left corner of the object on which the event was triggered. 4. Note that when you move the mouse cursor over an element like an image, the off set X and off set Y properties change to the element’s coordinate system.13. What is event bubbling? Event bubbling is the process whereby event fired in child elements “bubble” up to theirparent elements for handling. If you intend to handle an event in a child element, you might needto cancel the bubbling of that event in the child element’s event-handling code by using the cancelbubble property of the event object.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 106
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure: Event Bubbling (part 2 of 2 )14. What are fillers and Transitions? 1. Applying filters to text and images causes changes that are persistent. 2. Transitions are temporary phenomena; applying a transition allows you to transfer from one page to another with a pleasant visual effect, such as a random dissolve. 3. Filters and transitions do not add content to your pages – rather, they present existing content in an engaging manner to help hold the user’s attention. 4. Each of the visual effects achievable with filters and transitions is programmable, so these effects can be adjusted dynamically by programs that respond to user-initiated events like mouse clicks and keystrokes. 5. When Internet Explorer renders your page, it applies all the special effects and does this while running on the client computer without lengthy waits for files to download from the server.15. How does Flip Filter work? Explain with a sample program. The flipv and fliph filters mirror text or images vertically and horizontally. Figuredemonstrates these effects, using both filters to flip text. 1. <? xml version = “1.0” ? > 2. < ! DOCTYPE html Public “-//W3C//DTD XHTML 1.0 Strict//EN” 3. “http://www.w3.org/TR/xhtnl 1-strict.dtd “ > 4. 5. <!—fig: flip html --> 6. < ! – Using the flip filers --> 7. 8. <html xmlns = “http://www.w3.org/1999/xhtml” >VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 107
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 9. < head > 10. < title > The flip filter < / title > 11. 12. < style type = “ text/css” > 13. body { background – color : # CCRRCC } 14. 15. table { font –size: 3em; 16. font- family : Arial, sans-serif; 17. background – color : # FFCCCC; 18. border –style: ridge; 19. border-collapse: collapse } 20. 21. td { border-style: groove; 22. padding: lex } 23. </style> 24. </head//. 25. 26. <body> 27. 28. < table> 29. 30. <tr> 31. <!—Filters are applied in sty re declaration -- > 32. <td style = “filter: fliph” > Text < /td> 33. < td > Text </td> 34. </tr> 35. 36. <tr> 37. < ! – More than one filter can be applied at once -- > 38. <td style = “filter : flipv fliph” > Text < /td> 39. <td style = “filter : flipv” > Text < /td> 40. </tr> 41. 42. </table> 43. 44. </body> 45. </html>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 108
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure: Using the flipv and fliph filters (part 2 of 2) Line 32 applies a filter using the style attribute. The value of the filter property is the nameof the filter. In this case, the filter is fliph, which filps the affected object horizonatally. Line 38 applies more than one filter at once by specifying multiple filters separated byspaces as the value of the filter attribute. In this case, the flipv filter is also applied, whichvertically flips the object to which the filter is applied.16. Explain how Transparency effects can be achieved using chroma filter.Transparency with the chroma filter: The chroma filter applies transparency effects dynamically, without using a graphics editorto hard-code transparency into the image. Figure alters the transparency of an image, using objectmodel scripting based on a user selection from a select element. 1. < ? xml version = “1.0”?> 2. <! DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional //EN” 3. “http: / / www.w3.org/TR/xhtml 1/DTD/xhtml 1-transitional. dtd” > 4. 5. <! - – fig: chroma-html --> 6. <! – Applying transparency using the chroma filter --> 7. 8. < html xmlns = http://www.w3.org/1999/xhtl > 9. < head > 10. < title > Chroma Filter </title> 11. 12. <script type = “text/javascript”> 13. <! – 14. function changecolor ( theColor ) 15. { 16. if ( theColor ) { 17. / / if the user selected a color. parse theVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 109
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 18. // value to hex and set the filter color 19. chromaImg. filters (“chroma”). Color = theColor; 20. chromaImg. filters (“chroma”). enabled = true; 21. } 22. else // if the user selected “None” 23. // disable the filter 24. chromaImg. Filters (“chroma”). enabled = fa;se; 25. } 26. //--> 27. </script. 28. </head> 29. 30. <body> 31. 32. <h1>Chroma Filter: </h1> 33. 34. <img id = “chromaImg” src = “trans.gif” style = 35. “posistion “ absolure; filter: chroma’ alt= 36. “ Transparent Image” /> 37. 38. < form action =” “ > 39. <! -- The onchange event fires when --> 40. <! -- selection is changed --> 41. < select on change = “ change color (this value )> 42. < option value = “ “ > None </ option> 43. < option value = “# 00FFFF” > Cyan < / option > 44. < option value = “# FFFF00” > Yellow </option > 45. < option value = “#FF00FF” > Magenta</option > 46. < option value = “# 000000” selected = “ selected” > 47. Black</option> 48. </select> 49. </form> 50. 51. </body> 52. < / html >VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 110
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure: Changing values of the chroma filter (part 2 of 2) Line 19 sets the filter properties dynamically using JavaScript. In this case, the value of theselect drop-down list (lines 41-48) is a string containing the color value. This value is passed as anargument to function changecolor (lines 14-25). Line 20 turns on the filter. Each filter has a property named enabled. If this property is setto true, the filter is applied. If it is set to false, the filter is not applied. Line 24 indicates that thefilter is disabled if the user selected None (line 42) from the drop-down list. Line 41 introduces the event on change. This event fires whenever the value of a form fieldchanges. In this example, an on change event occurs when the user makes a new selection in thecolor select drop –down list. The expression this, value represents the currently selected value inthe select GUI component, which is passed to function change color.17. Write a DHTML script to apply the mask filter to an image. Applying the mask filter to an image allows you to create an effect in which an element’sbackground is a solid color and its foreground is transparent, so the image or color behind itshows through. This is known as an image mask. Figure adds the mask filter to a div element(lines 20-26) which overlaps an image (lines 28-29). The foreground of the div element (the textinside it ) is transparent. So you can see the background image through the letter in theforeground. Line 21 sets the color parameter for the mask filter Parameters are always specified inthe format param = value. 1. <?xml version = “1.0” ?> 2. <! DOCTYPE html PUBLIC “ - //W3C / / DTD XHTML 1.0 Transitional // EN” 3. “ http://www.w3.org/TR/xhtml 1/DTD/ xhtml 1- transitional. dtd “ > 4. 5. <! -- Fig : mask . html -- > 6. <! – Placing a mask over an image -- > 7. 8. <html xmlns = http://www.w3.org/1999/xhtml>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 111
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 9. < head > 10. <title> Mask Filter </title> 11. </head> 12. 13. <body> 14. 15. <h1>Mask Filter </h1> 16. 17. <! – Filter parameters are specified in parentheses, --> 18. <! -- in the form paraml = valuel, param 2 = value 2, -- > 19. < ! - - etc, -- > 20. < div style = “ position: absolute: top: 125; left: 20: 21. filter: mask ( color = # CCFFFF)” . 22. <h1 style = “font – family: canner, mono space” > 23. Aa Bb Cc Dd EeFfGg HhIiJi< br / > 24. KkLlMmNnOoPpQqRrSsTt 25. </h1> 26. </div> 27. 28. <img src = “gradient. Gift” width = “ 400 “ height = “ 200 “ 29. alt = “Image with Cradient Effect” / > 30. </body> 31. </html> Figure: Using the mask filter18. What are the three image filters and give their functions? The three image filters discussed in this section apply simple image effects to images ortext. The invert filter applies a negative image effect – dark areas become light and light areasbecome dark. The gray filter applies a grayscale image effect, in which all color is stripped fromthe image and all that remains is brightness data. The x-ray filter applies an x-ray effect, whichVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 112
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHbasically is an inversion of the grayscale effect.19. Write a simple DHTML program to use the shadow filter. A simple filter that adds depth to your text is the shadow filter. This filter creates ashadowing effect that gives your text a three-dimensional appearance. 1. <? Xml version = “1.0”?> 2. <! DOCTYPE html PUBLIC “-//w3c//DTD XHTML 1.0 Strict //EN” 3. “http://www.w3.org/TR/xhtml 1/DTD/xhtml 1-strict.dtd> 4. 5. <! – Fig : shadow.html --> 6. <! – Applying the shadow filter --> 7. 8. <html xmlns = “ http://www.w3.org/1999/xhml”> 9. < head> 10. < title > Shadow Filter </title> 11. 12. < script type = “ text/javascript”> 13. <!— 14. var shadow Direction = 0; 15. 16. function start () 17. { 18. window. setInterval ( “runDemon ()”, 500); 19. } 20. 21. function runDemo () 22. { 23. shadow Text. innerText = 24. “Shadow Direction: “+shadow Direction % 360; 25. shadow Text. Filters (“shadow). direction = 26. (shadowDirection % 360); 27. shadowDirection +=45; 28. } 29. //--> 30. </script> 31. </head> 32. 33. <body onload = “ start () “ > 34. 35. <h1 id = “shadowText” style = “ position: absolute; top: 25; 36. jeft: 25; padding: 10 filter: shadow (direction = 0, 37. color = red ) > Shadow Direction: 0</h1>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 113
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 38. </body> 39. </htm1> Figure: Applying a shadow filter to text (part 2 of 2) Line 35-37 apply the shadow filter to text. Property direction of the shadow filterdetermines in which direction the shadow effect is applied – this can be set to one of eightdirections expressed in angular notation: 0 (up), 45 (above-right), 90 (right), 135 (below-right), 180(below), 225 (below-left), 270 (left) and 315 (above-left). Property color specifies the color of theshadow that is applied to the text. Lines 23-27 in function run-Demo cycle thought the directionproperty values from 0 to 315, and update property inner Text of the h1 element (shadow Text) tomatch the current shadow direction. Note that we apply a padding CSS style to the h1 element (line 36). Otherwise, the shadoweffect is partially cut off by the border of the element. Increasing the padding provides greaterdistance between the text and the border of the element, allowing the full effect to be displayed20. What is the use of alpha filter? What are the properties of this filter? Internet Explorer 6 allows you to create the same effect dynamically using the alpha filter.The alpha filter is also used for transparency effects not achievable with the chroma filter. Lines 26-29 apply the alpha filter to a div element containing an image. The style propertyof the filter determines in what opacity style is applied. Opacity refers to the color saturation of animage. The various style values create different transitions from opaque to transparent. A stylevalue of 0 applies uniform opacity, a value of 3 applies a rectangular gradient. The opacity and finish opacity properties are both percentages that determine at whatpercent opacity the specified gradient starts and finishes, respectively. Additional attributes arestart X, start Y, finish X and finish Y. These specify at what X-Y coordinates the gradient startsVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 114
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHand finishes in that element.21. What are the functions of i) glow filter ii) blur filter iii) wave filter? 1. The glow filter allows you to add an aura of color around your text. The color and strength can both be specified. 2. The blur filter creates an illusion of motion by blurring text or images in a certain direction. The blur filter can be applied in any of eight directions, and its strength can vary. The add property, when set to true, adds a copy of the original image over the blurred image, creating a more subtle blurring effect. The is expressed in angular form (as with the shadow filter). The strength property determines how strong the blurring effect is. 3. The way filter allows you to apply sine-wave distortions to text and images on your Web pages. 4. The add property, as in the case of the blur filter, adds a copy of the text or image, but underneath the filtered effect. The add property is useful when applying the wave filter to images. The freq property determines the frequency of the wave applied – that is, how many complete sine waves are applied in the affected area. Increasing this property would create a more pronounced wave effect, but makes the text harder to read. The phase property indicates the hase shift of the wave. Increasing this property does not modify any physical attributes of the wave, but merely shifts it in space. This property is useful for creating a gently waving effect. The last property, strength, is the amplitude of the sine wave that is applied.22. What is the fuction of Drop shadow filter? 1. The drop shadow filter creates a blacked-out version of the image, and places it behind the image, offset by a specified number of pixels. 2. The off x and off y properties of the drop shadow filter determine by how many pixels the drop shadow offsets. The color property specifies the color of the drop shadow23. Explain the working of the light filter with an example. 1. The light filter is one of the most powerful and advanced filters available in Internet Explorer 6. It allows you to simulate the effect of a light source shining on your page. 2. The light filters add point method adds a point light source – a source of light which emanates from a single point and radiates in all directions. The first two parameters set the x-y coordinates at which to add the point source. The next parameter sets the high of the point source. This simulates how far above the surface the light is situated. Small values create a small but high-intensity circle of light on the image, while large values cast a circle of light which is darker, but spreads over a greater distance. The next threeVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 115
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH parameters specify the RGB value of the light in decimal. The last parameter is a strength percentage. 3. The move light method up dates the position of a light source. The first parameter is the index of the light source on the page. Multiple light sources have index numbers assigned to them in the order they are added. The next two parameters specify the x-y coordinates to which we should move the light source. The next two parameters specifies the height to which we move the light source. Setting the last parameter to 1 indicates that the values we are using are absolute. To move your light source by relative amounts instead, use a value of 0 for the last parameter of the move light function.24. What is DSO give an example? To bind external data to XHTML elements, Internet Explorer employs software capable ofconnecting the browser to live data sources. These are known as Data Sour Objects (DSOs).There are several DSOs available in IE6 – in this chapter we discuss most popular DSO – TheTabular Data Control (TDC).25. What is the function of (TDC) Tabular Data Control? 1. The Tabular Data Control (TDC) is an Active X control that can be added to the page with an object tag. 2. When a Web page is loaded with data-bound elements, the client retrieves the data from the data source specified by the TDC. The data is then formatted for display on the Web page and remains accessible on the client.26. What is the use of the object Tag? 1. An object tag inserts an Active X Tabular Data Control. The classid attribute specifies the Active X control identifier. 2. The param tag specifies parameters for the object in the object tag. The name attribute is the parameter name and the value attribute is the value. The Data URL parameter is the URL of the data source. The Use Header parameter specifies that the first line of the data file is to have a header row when set to true. The Text Qualifier parameter sets the text qualifier of the data. The field Delim parameter sets the field delimiter of the data.27. How does the sort property of the Active x control works? 1. The Sort property of the Active X control determines the column by which the data is sorted. Once the sort property is set, call the reset method to display the data in its new sort order. By default, a column will be sorted in ascending order- to sort in descending order, the column name is preceded by a minus sign (-)VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 116
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 2. Setting the Sort property of the TDC using a param tag instead of scripting is useful for providing an initial sorting order.28. What is the use of window object & document object in DHTML? i. Window object represents browser window and provides access to the document object contained in the window. ii. Document object represents the XHTML document rendered in a window and provides access to every element in the XHTML document and allows dynamic modification to the document.29. Explain how binding is done to a table. To bind a table, add the data attribute to the opening table tag. Then add the data fld (datafield) attribute to span tags that reside in the table cells. IE iterates through the data file & creates atable row for each row it finds). PART – B1. Explain in detail about the frames collection & Navigator object in the necessary samples. One problem that you might run into while developing applications is communicationbetween frames. The referencing we have used certainly allows for access to objects and XHTMLelements on the same page, but what if those elements and objects are in different frames? Figure.and Figure. solve this problem by using the frames collection.1 <?xm1 version = “1.0”?>2 <!DOCTYPE htm? PUBLIC”-//W3C//DTD XHTML 1.0 Frameset //EN”3 http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd>45 <!—Fig.13.7: index.html -->6 <!—Using the frames collection -->78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <title>Frames collection</title>11 </head>1213 <frameset rows = “100 *”>14 <frame src = “top.html” name = “upper” />15 <frame src = “”name = “lower” />16 </frameset>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 117
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH1718 </html> Fig. frameset file for cross-frame scripting.1 <?xml version = “1.0”?>2 <!DOCTYPE html PUBLIC //w3c//DTD XHTML 1.0 strict//EN”3 “http://www.w3.org/TR/Xhtml/DTD/xhtml-strict,dtd>45 <!—Fig.13.8: top,html -- >6 <!—Cross-frame scripting -- >78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <title> The frames collection</title>1112 <script type = “text/javascript”>13 <!—14 function start ( )15 {16 var text = prompt ( “What is your name?”, );17 parent.frame ( “lower”).document.write(18 “<h1>Hello, “+ text + “</h1>”);19 }20 // -- >21 </script>22 </head>2324 <body onload = “start ( ) “ >25 <hl>Cross-frame scripting!</hl>26 </body>27 </html> Fig. Accessing other frames. (Part 1 of 2 )VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 118
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Fig. Accessing other frames (Part 2 of 2) Line 17-18 (Fig.13.8) apply changes to the lower frame. To reference the lower frame, wefirst reference the parent frame of the current frame, then use the frames collection. We use a newnotation here-frames (“lower”) – to refer to the element in the frames collection with an id or nameof lower. The <frame> tag for the lower frame appears second in the XHTML file or Fig. so theframe is second in the frames collection. We then use the familiar document. Write method in thatframe to update with the user input from our prompt in line 16 of Fig. 13.8.Error-Prevention Tip 13.1 Internet Explorer 6 only allows cross-frame scripting between pages under the samedomain (i.e., the same Web server). This precaution ensures that a Web page cannot be modifiedfrom outside its domain. If script interaction is attempted between pages under differentdomains, Internet Explorer will display a permission error. For instance, an error will occur if apage at ao 1. com (in one frame) attempts to alter prices listed on a page at amazon.com (in adifferent frame) because the pages are under different domains.Navigator Object One of the most appealing aspects of the Internet is its diversity. Unfortunately, standardsare sometimes compromised because of this diversity. The two most popular browsers currentlyon the market. Netscape can Microsoft’s Internet Explorer, have many features that give the Webauthor great control over the browser, but many of their features are incompatible. Each,VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 119
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHhowever, that is viewing the page. This allows Web authors to determine which browser the userhas-this is especially important when the uses browser-specific features, because it allows theauthor to redirect users to pages that their browsers can display properly. Figure. demonstrates away to determine the type of browser that requests the document navigator. Html andappropriately redirects users to either an Internet Explorer or Netscape-compatible (i.e., Netscape,Mozilla, etc.) version of the page.1 <?xml version = “1.0”?>2 <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”3 “htto://www.w3.org/TR/xhtml 1/DTD/xhtml 1-strict.dtd”>45 <!- - Fig.13.9: navigator html -- >6 <!- - Using the navigator object -- >78 <html xmlns = http://www.w3. org/1999/xhtml”>9 <head>10 <title> The navigator object</tittle>1112 <script type = “text/javascript”>1314 function start ( )15 {16 if (navigator, appname= = “Microsoft Internet Explorer”)17 {18 if ( navigator.appVersion.substring(1,0) >= (“4”)19 document.locatior = newIEversion html;20 else21 document.location = “old eversion html;22 }23 else24 document.location = “NSversion.html;25 }26 // -- >27 </script>28 </head>2930 <body onlaod = “start ( )”>31 <p>Redirecting your browser to the appropriate page,32 please wait …<p>33 </body>34 </html> Figure. Using the navigator object to redirect users. ( Part 1 of 2)VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 120
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Fig. Using the navigator object to redirect users. (Part 2 of 2.) When the page loads, the on load event calls functions start (line 14-25), which checks thevalue of the property navigator, appName. This property of the navigator object contains thename of the browser application (for IE, this property is “Microsoft Interenet Explorer”;forNetscape, itg is “Netscape”). If the browser viewing this page is not Internet Explorer, in line 24we redirect the browser to the document “NSversion.html” by assigning the document name toproperty document. Location-the URL of the document being viewed. When a script assignsdocument. Location a new URL, the browser immediately switches Web pages. Line 18 checks the version of an IE browser with the navigator, appVersion property. Thevalue of appVersion is not a simple integer, however—it is string containing other information,such as the operating system of the user’s computer. For example, the appversion of IE6 onWindows XP is 4.0 (compatible; MSIE 6.0; windows NT 5.0) Therefore, the script uses method substring to retrieve the first character of the string,which is the actual version number. If the version number is 4 or greater, we redirect to newIEversion.html. Otherwise, we redirect the browser to oldIEversion.html.Portability Tip 13.2 Always make provisions for other browsers if you are using a browser-specific technologyor feature on your Web page. As we see here, the navigator object is crucial in providing browser-specific pages so that asmany users as possible can view your site properly. A similar technique to the one shown herecan be used to detect the use of other browsers, too, such as Opera. Please see javascriptkit.Com/javatutors/navigator.shtml for information on using the navigator objects to detect otherbrowsers.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 121
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH2. Explain the DHTML object model in detail. The Dynamic HTML Object Model provided by Internet Explorer allows a scriptprogrammer to access every element in an XHTML document. Literally every element in adocument is represented by a separate object. The diagram in Fig. shows many of the importantobjects and collections supported in Internet Explorer, The table in Fig. provides a briefdescription of each object and collection in the diagram inn Fig. For a comprehensive listing of all the objects and collections supported by InternetExplorer, browse the Microsoft HTML and DHTML Reference Web site. msdn.microsoft.com/workshop/author/dhtml/reference/dhtml_ reference_entry.asp This site provides detailed information on HTML, Dynamic HTML and Cascading StyleSheets technologies. The DHTML References section of this site provides detailed descriptions ofevery object, event and collection used inn DHTML. Another valuable Web resource is the W3C’s Document Object Model (DOM)Specifications site, www.w3.org/DOM/DOMTR windowwhich provides technical reports on the standard Document Object Model that underliesMicrosoft’s Dynamic HTML. This site presents the W3C standards that make cross-browser andcross-platform scripting of XHTML documents possible. document all frames document anchors history document applets navigator body plugins location embeds event filters screen forms images Key links Object plugins CollectionVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH scripts 122 StyleSheets
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Fig. DHTNL Object Model. Object or collection DescriptionObjects window Represents the browser window and provides access to the document object contained in the window. If the window contains frames a separate to the document rendered in the frame. Frames are considered to be subwindows in the browser.document Represents the XHTML document rendered in a window. The document object provides access to every element in the XHTML document.body Provides access to the body element of an XHTML document.history Keeps track of the sites visited by the browser user. The object provides a script programmer with the ability to move forward and backward through the visited sites, but for security reasons does not allow the actual site URL to be manipulated.navigator Contains information about the Web browser, such as the name of the browser, the version of the browser, the operating system on which the browser is running and other information that can help a script writer customize the user’s browsing experience.location Contains the URL of the rendered document. When this object is set to a new URL, the browser immediately switches (navigates) to the new location.event Can be used in an event than handler to obtain information about the event that occurred (e.g., the mouse x-y coordinates during a mouse event).screen Contains information about the computer screen for the computer on which the browser is running. Information such as the width and height of the screen in pixels can be used to determine the size which elements should be rendered in a Web page.Collections all Many objects have an all collection that provides access to every element contained in the object. For example, the body object’s all collection provides access to every elements in the body element of an XHTML document.anchors Collection contains all the anchor elements (a) that have a name or id attribute. The elements appear in the collection in the order they were defined in the XHTML document.applets Contains all the applet elements in the XHTML document. Currently, the most common applet elements are JavaTM applets.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 123
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHembeds Contains all the embed elements in the XHTML document.forms Contains all the form elements in the XHTML document. The elements appear in the collection in the order they were defined in the XHTML document.frames Contains window objects that represent each frame in the browser window. Each frame is treated as its own subwindow.images Contains all the img elements in the XHTML document. The elements appear in the collection in the order they were defined in the XHTML document.links Contains all the anchor elements (a) with an href property. This collection also contains all the area elements that represent links in an image map.plugins Like the embeds collection, this collection contains all the embed elements in the XHTML document.scripts Contains all the script elements in the XHTML document.styleSheet Contains styleSheet objects that represent each style element in the XHTML document and each style sheet included in the XHTML document via link. Fig. Objects in the Internet Explorer 6 Object Model. (Part 2 of 2)3. How does the Event “ onmousemove” gets fired and explain the properties of the event?Tracking the Mouse with Event onmou semove Event onmousemove fires repeatedly whenever the user moves the mouse over the Webpage. Figure uses this event to update a coordinate display that gives the position of the mouse inthe coordinate system of the object containing the mouse cursor.1 <?xml version = “1.0”?2 <?DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”3 http://www.w3.org/TR/xhtml/DTD/xhtml-transitional.dtd>45 <!—Fig.14.4 onmousemove.html6 <!—Demonstrating the onmousemove event78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <title> DHTML Event Model – onmousemove event </title>11 <script type = “text/javascript”>1213 function updateMouseCoordinates ( )14 {15 Coordinates.innerText = event.scrCElement.tagName+16 + event.offsetX+ +event.offsetY +VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 124
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH17 }18 //-->19 </script>20 </head>2122 <body style = “back-groundcolor: wheat”23 onmousemove = updateMouseCoordinaters ( )”>2425 <span id = coordinate > (0, 0) </span><brl/>26 <img src = “deitel.gif”style = “position: absolute;27 top; 100; left:100” alt = “daitel” />2829 </body>30 </html> Fig. Demonstrating the onmousemove event (Part 2 of 2 ) Our event handling in this example occurs in lines 15-16. The event object (line 15) containsinformation about the triggered event. Property srcElement references the element that triggeredthe event. The script uses tagName to retrieve the element’s name and display it in the inner Text(line 15) of the span called coordinates (line 25). The offset X and offset Y properties of the event object give the location of the mousecursor relative to the top-left corner of the object on which the event was triggered. Note thatwhen you move the cursor over the image, the coordinate display changes to the image’scoordinate system. This is because the onmousemove event occurs over the image. Figure listsseveral other event object properties. The properties of the event object contain information aboutany events that occur on your page and are used to create Web pages that are truly dynamic andresponsive to the user. Property of event Descriptionaltkey This value is true if the Alt key was pressed when event fired.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 125
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHbutton Returns which mouse button was pressed by user (1:left-mouse button, 2:right-mouse button, 3:left and right button, 4:middle button, 5:left and middle buttons, 6:right and middle buttons, 7:all three buttons).cancelBubble Set to false to prevent this event from bubbling.clientX/clienty The coordinates of the mouse cursor inside the client area (i.e., the active area where the Web page is displayed, excluding scrollbars, navigation buttons, etc.).ctrlkey This value is true if the Ctr/key was pressed when event fired.offsetX/offsetY Coordinates of the mouse cursor relative to the object that fired the event.propertyName The name of the property that changed in this event.recordset A reference to a data field’s recordset (see Chapter 16, Data Binding).returnValue Set to false to cancel the default browser action.screenXscreenY The coordinates of the mouse cursor on the screen coordinate system.shiftkey This value is true if the Shift key was pressed when event fired.srcElement A reference to the object that fired the event.type The name of the event that fired.x/y The coordinates of the mouse cursor relative to this element’s parent element. Fig. Some event object properties.4. Discuss the working of on focus, on blur onsubmit and on rest events in form processingwith appropriate examples.Form Processing with on focus and on blur The on focus and on blur events are particularly useful when dealing with form elementsthat allow user input (Fig.). The on focus event fires when an element gains focus (i.e., when theuser clicks a form field or uses the Tab key to move between form elements), and on blur fireswhen an element loses focus, which occurs when another control gains the focus. In line 30, scriptchanges the text inside the text box in the upper-right corner based on the messageNum passed tohelpText (lines 28-31). The elements of the form, for example in lines 39-40, each pass a differentvalue to the helpText function when they gain focus and the on focus event is fired. Whenelements lose focus, they all pass the value 6 to helpText so that helpBox can display the defaultmessage, which is stored in the last element of the array.1 <?xml version = “1.0”?>2 <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional // EN”3 http://www.w3.org/TR/xhtml1/DTD/xhtml-transitional .dtd>45 <!- - Fig. 14.7: onfocusblur.html -->6 <!- - Demonstrating the onfocus and onblur events -->VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 126
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH78 <html xmlns = http://www.w3.or/1999/xhtml>9 <head>10 <title> DHTML Even Model – onfocus and onblur </tittle>11 <sript type = “text/javascript”>12 <! - -13 var helpArray =14 [ “Enter your name in this input box”,15 “Enter your email address in this input box.” +16 “in the format user@domain”,17 “Check this box if you liked our site”,18 “In this box, enter any comments you would” +19 “like us to read”,20 “This button submits the form to the” +21 “server-side script”,22 “This button clears the form”,23 “This textarea provides context-sensitive” +24 “help.Click on any input field or use the TAB” +25 “key to get more information about the” +26 “input field” ];2728 function helpText ( messageNum)29 {30 myForm.helpBox.value = helpArray[ messageNum ]31 }32 // - - >33 </script>34 </head>3536 <body>3738 <form id = “myForm” action = “”>39 Name:<input type = “text” name = name40 onfocus = “helpText (0)” onblur = “helpText (6)”/><br />41 Email: <input type = “text” name = “email”42 onfocus = “helpText (1)” onblur = “helpText (6)” /><br />43 Click here if you like this site44 <input type = “checkbox” name = “like” onfocus =45 “helpText(2)” onblur = “helpText (6)” />< br />Mhr />4647 Any comments? <br />48 <textarea name = “comments” rows = “5” cols = 45”49 onfocus = “helpText (3)” onblur = “helpText (6)”></textarea>50 <br />VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 127
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH51 <input type = “submit” value = “Submit” onfocus =52 “helpText (4)” onblur = “helpText (6)” />53 <input type = reset” value = “Reset” onfocus =54 helpText (5) onblur = helpText(6)” />5556 <textarea name = helpBox” style = “position: absolute”57 right;0:top:0” readonly = “true” row = “4” cols = “45”>58 This textarea provides context-sensitive help.click on any input field59 or use the Tab key to get more information about the input field.60 </textarea>61 </form>6263 </body>64 </html> Fig. Events on focus and on blur (Part 2 of 2)More Form processing with onsubmit and onreset Two more useful events for processing forms are onsubmit and onreset. These events firewhen a form is submitted or reset, respectively (Fig.14.8). The function formsubmit (lines 35-40)executes in response to the user submitting the form (i.e., clicking the Submit button or pressingthe Enter key). Line 36 sets the event’s returnValue property to false, which cancels the defaultaction of the event on the element (i.e., for the browser to submit the form). Line 38 pops up adialog asking the user to confirm the action about to take place. If the user clicks OK, functionconfirmreturns true. Line 39 then sets the returnValue back to true, because the user hasconfirmed that the formshould indeed be submitted. If the user clicks Cancel, confirm returnsfalse, and the form is not submitted. [Note: When the confirmation dialog pops up, focus shiftsfrom the clicked button to the dialog. Thus, the button’s onblur event fires, and the text in thehelpBox text area returns to the default text until the confirmation dialog closes and focus returnsVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 128
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHto the button.] Function formReset (lines 42-47) behaves similarly to formSubmit.1 <?xml version = “1.0”?>2 <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”3 http://www.w3.or/Tr/xhtml/DTD/xhtml-transitional.dtd>45 <!- - Fig.14.8: onsubmitreset. html -->6 <!- - Demonstrating the onsubmit and onreset events -- >78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <title>11 DHTML Event Model – onsubmit and onreset events12 </title>13 <script type = “text/javascript”>14 <! - -15 var helpArray =16 [ “Enter your name in this input box”,17 “Enter your email address in this input box, +18 “in the format user@domain”,19 “Check this box if you liked our site,20 “In this box, enter any comments our would” +21 “like us to read”,22 “This button submits the form to the” +23 “server-side script”,24 “This button clears the form”,25 “This textarea provides context sensitive +26 “help. Click on any input field or use the Tab” +27 “key to get more information about” +28 “the input field” ];2930 function helpText ( messageNum )31 {32 myForm.helpBox.value = helpArray [ messageNum];33 }3435 function formSubmit ( ) {36 window.event.returnValue = false;3738 if ( confirm ( “Are you sure you want to submit?”) )39 window.event.returnValue = true;40 }4142 function formReset ( ) {VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 129
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH43 window.event.returnValue = false;4445 if ( confirm( “Are you sure you want want to reset?” ) )46 window.event.returnValue = true;47 }48 // - ->49 </script>50 </head>5152 <body>5354 <form id= myForm” onsubmit = formsubmit ( )”55 onreset = formRese ( )” action = “”>56 Name: <input type = “text” name = “name”57 onfocus = “helpText (0)” onblur = “helpText (6) “/><br />58 Email: <input type = “text” name = “email”59 onfocus = “helpText (1)” onblur = “helpText (6)” /><br />60 Click here if you like this site61 <input type = “Checkbox” name = “like” onfocus =62 “helpText(2)” onblur = “helpText (6)” /><hr />6364 Any comments?<br />65 <textarea name = “comments” rows = “5” cols = “45”66 onfocus = “helpText (3)” onblur = “helpText (6)”></textarea>67 <br />68 <input type = “submit” value = “submit” onfocus69 “helpText(4)” onblur = “Reset” onfocus =70 <input type = “reset value = “Reset” onfocus =71 “helpText(5)” onblur = “helpText (6)” />7273 <textarea name = “helpBox” style= “position: absolute;74 right:0: top:0” readonly = “true” rows = “4” cols = “45”>75 This textarea provides context-sensitive help. Click on any input field76 or use the Tab key to get more information about the input field.77 </textarea>78 <form>7980 </body>81 </html>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 130
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure. Events onsubmit and onreset (Part 3 of 3)5. With reference to an example program explain the power of Event bubbling.Event Bubbling Event bubbling is the process whereby events fired in child elements “bubble” up to theirparent elements. When a child event is fire, the event is first delivered to the child’s eventhandler, then to the parent’s event handler. This might result in event handling that was notintended. If you intend to handle an event in a child element, you might need to cancel thebubbling of the event in the child element’s event-handling code by using the cancel Bubbleproperty of the event object, as shown in Figure. Clicking the first p element (line 34) first triggers a call to paragraphClick with a falseargument, then, because line 27 registers the onclick event for the document, documentClick isalso called. This occurs because the onClick event bubbles up to the document level. This isprobably not the desired result. Clicking the second p element (line 35) passes a value of true tofunction par5agraphClick, so that the if statement in line 23 executes its body, which disables theevent bubbling for this event by setting the cancel Bubble property of the event object to true.1 <?xml version = “1.0”?>2 <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”3 http://www.w3.org/TR/xhtml1/DTD/xhtml-strict.dtd>45 <!- - Fig.14.9: bubbling.html - - >6 <! - -Disabling event bubbling - - >78 <html xmlns = http://www/w3.org/1999/xhtml>9 <head>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 131
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH10 <title>DHTML Event Model – Event Bubbling<tittle>1112 <script type = “text/javascript”>13 <!- -14 function documentClick ( )15 {16 alert ( “You clicked in the document” );17 }1819 function paragraphClick ( value )20 {21 alert ( “Your clicked the text”);2223 if ( value )24 event.cancelBubble = true;25 }2627 document.onclick = documentClick;2829 </script>30 </head>3132 <body>3334 <p onclick = “paragraphClick ( false )”> Click here! </p>35 <p onclick = “paragraphClick ( true )”> Click here, too! </p>36 </boxy>37 </html>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 132
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure. Event bubbling (part 2 of 2)6. Explain in detail how illusion of motor can be create by using the blur filter.Creating Motion with blur The blur filter creates and illusion of motion by blurring text or images in a certaindirection. As we see in Figure, the blur filter can be applied in any of eight directions, and itsstrength can vary.1 <?xml version = “1.0”?>2 <!DOCTYPE html PUBLIC”-//w3c//DTD XHTML 1.0 Transitional//EN”3 “http://www.w3.org/TR/xhtml1-transitional-dtd”>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 133
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH45 <! - - Fig.5.8: blur.html - - >6 <!- - The blur filter - - >78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <title>Blur Filter</title>11 <script type = “text/javascript”>12 <! - -13 var strengthIndex = 1;14 var blurDirection = 0;15 var upDown = 0;16 var timer;1718 function reBlur ( )19 {20 blurImage.filters ( ).direction =21 document.forms ( ).Direction.value;22 blurImage. filters ( ). strength =23 document.forms ( ).strength.value;24 blurImage.filters ( ).add =25 document.forms( ).Addbox.checked;26 }2728 function startDemo ( )29 {30 timer = window.setInterval ( “runDemo ( )”, 5 );31 }3233 function runDemo ( )34 {35 document.forms( “myForm” ). strength.value =36 strengthIndex;37 document.forms( “myForm” ).Direction.value =38 ( blurDirection % 360 );3940 if ( strengthIndex = = 35 strengthIndex = = 0 )41 upDown = !upDown;4243 blurImage.filters ( “blur” ). strength =444546 if ( strengthIndex = = 0 )47 blurImage.filteres ( “blur” ).direction =VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 134
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH48 ( ( blurDirection += ) %360);49 }50 // - ->51 </script>52 </head>5354 <body>55 <form name = “myForm” action = “”>5657 <table border = “1” style = “background-color: #CCFFCC”>58 <caption>Blur filter controls </caption>5960 <tr>61 <td>Direction:</td>62 <td><select name = “Direction”>63 <option value = “0”>above</option>64 <option value = “45”>above-right</option>65 <option value = “90”>right</option>66 <option value = “135”>below-right</option>67 <option value = “180”>below</option>68 <option value = “225”>below-left</option>69 <option value = “270”>left</option>70 <option value = “315”>above-left</option>71 </select></td>72 </tr>7374 <tr>75 <td>Strength:</td>76 <td>input name = “Strength” size = “3” type “text”77 maxlength = “3” value = “0” /></td>78 </tr>7980 <tr>81 <td>Add original?</td>82 <td><input type = “checkbox” name = “Addbox” /></td>83 </tr>8485 <tr>86 <td aligh = “center” colspan = “2”>87 <input type = “buton” value = “Apply”88 onclick = “reBlur ( );”/></td>89 </tr>9091 </tr>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 135
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH92 <td colspan = “2”>93 <input type = “button” value = “Start demo”94 onclick = “startDemo ( );” />95 <input type = “button” value = “Stop demo”96 onclick = window.clearInterval ( timer );” /></td>97 </tr>9899 </table>100 </form>101102 <div id = “blurImage” style = “position: absolute;103 top: 0; left: 300; padding: 0; filter: blur (104 add = 0, direction = 0, strength = 0 );105 background-color: white;”>106 <img alighn = “middle” src = “shapes.gif”107 alt = “Shapes” />108 </div>109110 </body>111 </html> Figure. Using the blur filter (Part 2 of 3)VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 136
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure. Using the blur filter (Part 3 of 3 ) The three properties of the blur filter are add, direction and strength. The add property,when set to true, adds a copy of the original image over the blurred image, creating a more subtleblurring effect; Fig. demonstrates the contrast between setting this to true and to false. The direction property determines in which direction the blur filter is applied. This isexpressed in angular form (as we saw in Fig. with the shadow filter). The strength propertydetermines how strong the blurring effect is. Lines 24-25 assign to the add property of the blur filter the Boolean checked property of theAdd original? Checkbox-if the box is checked, the value is true. Lines 47-48 increment the direction property whenever the strength of the blur filter is 0(i.e., wherever an iteration has completed). The value assigned to the direction property cyclesthrough all the multiples of 45 between 0 and 360.7. Discuss in detail the working of Drop shadow & light filters.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 137
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHAdvanced Filters: drop Shadow and light Two filters that apply advanced image processing effects are the drop Shadow and lightfilters. The dropShadow filter, as you can probably tell, applies an effect similar to the dropshadow we applied to our images with Photoshop Elements inn Chapter 3-it creates a blacked-outversion of the image, and places it behind the image, offset by a specified number of pixels. The light filter is the most powerful and advanced filter available inn Internet Explorer 6. Itallows you to simulate the effect of a light source shining on your page. With scripting, this filtercan be used with dazzling results. Fig. combines these two filters to create an interesting effect.1 <?xml version = “1.0”?>2 <!DOCTPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”3 http://www.w3.org/TR/xhtml/DTD/xhtml-transitional-dtd>45 <!- - Fig. 15.10: dropshadow.html -->6 <!- - Using the light filter with the dropshadow filter - - >78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <title>DHTML dropshadow and light Filters</title>1112 <script type = “text/javascript”>13 <! - -14 function setlight ( )15 {16 dsImg.filters( “light” ).addpoint ( “150,150,17 125, 255,255, 255,100 );18 }1920 function run ( )21 {22 eX = event.offsetX;23 eY = event.offsetY;2425 xCoordinate = math.round (26 eX-event.srcElement.width / 2,0 );27 yCoordinate = Math.round (28 eY-event.srcElement.height / 2,0 );2930 dsImg.filters ( “dropShadow” ).offx =31 xCoordinate / -3;32 dsImg.filters ( “dropShadow” ).offy =33 yCoordinate / -3;VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 138
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH3435 dsImg.filters ( “light” ).moveLight (36 0, ex, ey, 125, 1 );37 }38 // - - >39 </script>40 </head>4142 <body onlaod = “setlight ( )” style = “background-color:green”>4344 <img id = “dsImg” src = “circle.gift”45 style = “top: 100; left: 100; filter: dropShadow (46 offx = 0, offy = 0, color = black ) light ( )”47 onmousemove = “run ( )” alt = “Circle Image” />4849 </body>50 </html> Figure. Applying light filter with a dropShadow ( Part 1 of 2 ) Figure: Applying light filter with a dropShadow (Part 2 of 2 ) Let us begin by examining the dropShadiw filter. In lines 44-47, we apply the drop-shadowfilter to our image. The offx and offy properties determine the number of pixels by which thedrop shadow is offset. The color property specifies the color of the drop shadow. Note that wealso declare the light filter in line 46, although we do not give it any initial parameters-all theparameters and methods of the light filter are set by scripting. Lines 16-17 call the addpointmethod of the light filter. This adds a point light source-a source of light which emanates from asingle point and radiates in all directions. The first two parameters (150, 150) set the x-ycoordinates at which to add the point source. In this case we place the source at the center of theimage, which is 300-by-300 pixels. The next parameter (125) sets the height of the point source.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 139
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHThis simulates how far above the surface the light is situated. Small values create a small buthigh-intensity circle of light on the image, while large values cast a circle of light which is darker,but spreads over a greater distance. The next three parameters (255, 255, 255) specify the color ofthe light inn RGB format. In this case we set the light to a color of white. The last value (100) is astrength percentage-we set our light in this case to radiate with 100% strength. This point light source creates a pleasant lighting effect, but it is static. We can usescripting to animate the light source in response to user actions. We use the onmousemove event (line 47 ) to have the light source follow the mouse cursor as the user moves it over the image. Therun function (lines 20-37) animates both the dropshadow filter and the light filter in response touser actions. First we set the variables xCoordinate and yCoordinate to the distance between thecurrent cursor position (eX and eY, which were set to event.offsetX and event.offsetY in lines 22-23) and the middle of the image (event.srcElement.width/2 or event.srcElement. height /2). Lines20-33 set the offx and offy properties of the dropShadow filter relative to the current x-ycoordinates of the image. We divide by – 3 to create an effect of height (shadows cast by objectsfar from light sources only move a small amount when the light source moves by a largeramount). Note that the negative number causes the drop shadow to be applied in the oppositedirection from the mouse movement. Lines 35-36 then call the moveLight method to update the position of the light source aswell. The first parameter (0) is the index of the light source on the page. Multiple light sourceshave index numbers assigned to them in the order in which they are added. The next twoparameters (event.offsetX,eventY) specify the x-y coordinates to which we should move the lightsource. In this case, we keep the light source at the same level as when we declared it. The lastparameter (1) indicates that the values we are using are absolute. To move the light source byrelative amounts instead, use a value of 0 for the last parameter of the moveLight function. As you can see, combining the dropShadow and light filters creates a stunning effect thatresponds to user actions. The point source is not the only type of light source available for thelight filter. Figure. demonstrates the use of a cone light source for illuminating an image.1 <?xml version = “1.0”?>2 <!DOCTYPE html PUBLIC” -//W3C//DTD XHTML 1.0 Transitional//EN”3 “http://www.w3.org/TR/xhtml/DTD/xhtml-transitional dtd>45 <!- - Fig.15.11: conelight html -->6 <!- - Automating the cone light source - - >78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head><title>Cone lighting </title>1011 <script type = “text/javascript”>12 var upDown = true;13 var counter = 0;VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 140
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH14 var moverate = 2;1516 function setLight ( )17 {18 marquee.filteres ( “light” ).addCone( 0, marquee.height,19 marquee.width/2, 30,255, 150, 255, 50, 15 );20 marquee.filters (“light”).addCone( marquee.width,21 marquee.height. 8, 200, 30, 150, 255, 255, 50, 15 );22 marquee.filters ( “light”).addCone(marquee.width /2,23 marquee.height, 4, 200, 100, 255, 150, 50, 50 );2425 window.setInterval ( “display ( )”, 100);26 }2728 function display ( )29 {30 counter++;3132 if ( ( counter % 30 ) = = 0 )33 upDown = !upDown;3435 if ( ( counter % 10 ) = = 0 )36 moveRate *= -1;3738 if ( upDown ) {39 marquee.filters ( “light” ).moveLight (40 0, -1, -1, 3, 0 );41 marquee.filteres ( “light” ).moveLight(42 1,1, -1, 3, 0 );43 marquee.filters ( “light” ).moveLight(44 2, moveRate, 0, 3, 0);45 }46 else {47 marquee.filters( “light” ).moveLight (48 0, 1, 1, 3, 0 );49 marquee.filters( “light” ).moveLight (50 1, -1, 1, 3, 0 );51 marquee.filters ( “light” ).moveLight (52 2, moveRate, 0, 3, 0 );53 }54 }55 </script>56 </head>57 <body style = “background—color; #000000”VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 141
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH58 onload = “setLight ( )”>5960 <img id = “marquee” src = “marquee.gif”61 style = “filter: light: position: absolute: left: 25;62 top: 25” alt = “Deitel movie marquee” />6364 </body>65 </html> Figure. Dynamic cone source lighting (Part 2 of 2 ) Lines 18-19 add our first cone light source, using the addCone method. The parameters ofthis method are similar to the addPoint method. The first two parameters specify the x-ycoordinates of the light source, and the third parameter specifies the simulated height above thepage at which the light should be placed. The next two parameters (marquee. width / 2,30) arenew-they specify the x-y coordinates at which the cone source is targeted. The next threeparameters (255, 150, 255) specify the RGB value of the light’s color just as we did in the addPointmethod. The next parameter (50) specifies the strength of the cone source in a percentage (alsoequivalent to the strength parameter in the addPoint method). The last value (15) specifies thespread of the light source in degrees (this can be set in the range 0-90). In this case we set thespread of the cone to 15 degrees, illuminating a relatively narrow area. In lines 39-40, we use the moveLight method once again. When used on cone sources, themoveLight method moves the target of the light. In this case, we set the last parameter to 0 tomove the light by a relative amount, not an absolute amount, as we did in Fig.8. Explain in detail how a simple Data Binding can be performed with an example program.Simple Data Binding The Tabular Data Control is an ActiveX control that is added to a page with the objectelement. Data is stored in a separate file (e.g., Fig.) and not embedded in the XHTML document.Figure demonstrates a simple use of data binding with the TDC to update the contents of a spanelement. The data file used by this example is listed in Figure.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 142
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH1 @ColorName@ | @ColoHexRGBValue@2 @aqua@ | @#00FFFF@3 @black@ | @#000000@4 @blue@ | @#0000FF@5 @fuchsia@ | @#FF00FF@6 @gray@ | @#808080@7 @green@ | @#008000@8 @lime@ | @#00FF00@9 @maroon@ | @#800000@10 @navy@ | @#000080@11 @olive@ | @#808000@12 @purple@ | @#800080@13 @red@ | @#FF0000@14 @silver@ | @#C0C0C0@15 @teal@ | @#008080@16 yellow@ | @#FFFF00@17 @white@ | @#FFFFFF@Fig. XHTML color table data (HTMLStandardColors.txt)1 <?xml version = “1.0”?>2 <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 strict//EN”3 http://www.w3.org/TR/xhtml/DTD/xhtml-strict dtd>45 <!- - Fig.16.2: introdatabind.html6 <!- - Simple data binding and recordset manipulation - ->78 <html xmlns = http://www.w3.org/1999/xhtml>9 <head>10 <tittle>Intro to Data Binding</title>1112 <!- - This object element inserts an ActiveX control - - >13 <!- - for handling and parsing our data. The PARAM - - >14 <!- - tags give the control starting parameters -->15 <!- - such as URL -->16 <object id = “Colors”17 classid = “CLSID:333C7BC4-460F-1100-BC04-0080C7055A83”>18 <param name = “DataURL” value =19 “HTMLStandrardColors.txt”/>20 <param name = “UseHeader” Value = “TRUE” />21 <param name = “TextQualitier value = “@” />22 <param name = “FieldDelim” value = “|” />23 </object>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 143
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH2425 <script type = “text/javascript”>26 <!- -27 var recordSet = Colors.recordset;2829 function displayRecordNumber( )30 {31 if ( !recordSet.E0F )32 recordNumber.innerText =33 recordSet.absolutePosition;34 else35 recordNumber.innerText = “ “;36 }3738 function forward( )39 {40 recordSet.MoveFirst ( );4142 if ( recordSet.E0F )43 recordSet.MoveFirst ( );4445 colorSample.style.backgroundColor =46 colorRGB.innerText;47 displayRecordNumber ( );48 }49 //- - .50 </script>51 </head>5253 <body onload = “displayRecordNumber ( )” onclick = “forward ( )”>5455 <h1>XHTML Color Table</h1>56 <h3>Click anywhere in the browser window57 to move forward in the recordse.</h3>58 <p><strong>Color Name: </strong>59 <span id = “colored” style = “font—family:monospace”60 datasrc = “#Colors” datafld = “ColorName></span><br />6162 <strong>Color RGB Value:</strong>63 <span id = “ColorRGB” style = “font-family: monospace”64 datasrc = “#Colors” datafld = “ColorHexRGBValue”>65 </span><br />6667 Current;y viewing record numberVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 144
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH68 <span id = “recordNumber” style = “font-weight:900”>69 </span><br />7071 <span id = “colorSample” style = “background color: aqua;72 color: 888888; font-size 30pt”>Color Sample73 </span></p>74 </body>75 </html> Figure. Simple data binding (Part 2 of 3 ) Figure. Simple data binding (Part 3 of 3 ) Line 1 of Fig. begins our data file with a header row. This row specifies the names of thecolumns of data (ColorName and ColorHexRGBValue). Data in each field is enclosed in textVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 145
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHqualifiers (@) and each field is separated with a field delimiter (|). Lines 21-22 in Fig. indicate tothe Tabular Data Control the text qualifier and field delimiter symbols chosen for use in this datasource. The object element (lines 16-23 in Fig.) inserts the Tabular Data Control-one of the MicrosoftActiveX controls built into Internet Explorer 6. Attribute Classid specifies the ActiveX control toadd to the Web page-here we use he classid of the Tabular Data Control (i.e., the fixed value ofCLSID:333C7BC4-460F-11D0-BC04-0080C7055A83). Each Active control has a unique classid. The param tag specifies parameters for the object in the object element. Attribute name isthe parameter name, and attribute value is the value. Parameter DataURL is the URL of the datasource (HTMLStandardColors.txt). [Note: The DataURL can be any fully qualified URL, a relativepath or an absolute path.] Parameter UseHeader, when set to true, specifies that the first line ofour data file has a header row.Common Programming Error Forgetting to set the UseHeader parameter to TRUE when you have a header row in yourdata source is an error that can cause problems in referencing columns. The third parameter, TextQualifier, sets the text qualifier of our data (in this case to @). Atext qualifier is the character palced on both ends of a field. The fourth parameter, fieldDelim, setsthe field delimiter of our data (in this case to | ). The field delimiter is the character separatingdifferent data fields. Lines 59-60 bind the data to a span element. The datasrc attribute refers to the TDC object’sid (Colors, in this case) preceded by a hash mark (#), and the datafld attribute specifies the nameof the field to bind it to (ColorName, in this case). This places the data contained in the firstrecord (i.e., row) of the ColorName column into the span element. So far, we only have a static display of data. We can update it dynamically with somesimple scripting. Line 27 assigns the recordset property of the Colors object (our TDC objectelement) to the variable recordSet. A recordset is simply a set of data-in our case, it is the datafrom our HTMLStandardColors. Txt data source. When the user clicks in the page, line 41 callsthe MoveNext method of the recordSet object to move the recordset to the next row in the datasource. This automatically updates the span to which we bound our data. Note that line 42determines whether the Boolean E0F property of the recordSet is true. If true, it indicates that theend of the data source has been reached. If E0F is true, line 43 calls the MoveFirst method tomove to the first recordset in the file. The function displayRecordNumber (defined in lines 29-36) is called when the body loads(as indeated by line 53) or whenever we move in the recordset (line 47). This function updates therecord number displayed on the page. If we have not yet reached the end of the data, lines 32-33VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 146
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHchange the inner Text property of the recordNumber span element (defined in lines 68-69) suchthat this element’s text correctly reflets our current position in the recordset (i.e., the value of theabsolutePosition property of the recordSet object). If we have somehow moved past the end of therecordset (though function forward prevents this), we display a blank space to indicate no recordis currently displayed.9. Write a DHTML program for moving within a Recordset and explain it in detail.Moving within a Recordset Most applications will probably need more functionality than simply moving forward in arecordset. Figure. demonstrates creating a user interface for navigating the data source of Figure. The switch in lines 31-64 evaluates the value passed to move when the user clicks one of thebuttons in lines 93-103. The two new functions we use are MoveLast and Moveprevious, whichmove to the last recordset and the mpreceding recordset, respectively. Lines 43 and 54 determineif the beginning (B0F) or end (E0F) of the recordset has been reached. If so, the recordset moves tothe last or first record, respectively.1 <?xml version = “1.0”?>2 <!D0CTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”3 http://www.w3.org/TR/xhtml/xhtml-tranitional dtd>45 <!- - Fig.16.3: moving html - ->6 <!- - Moving through a recordset - - >78 <html xmlns = http://www/w3: org/1999/xhtml>9 <head>10 <title>Dynamic Recordset Viewing</title>11 <object id = “Colors”12 classid = “CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83”>13 <param name = “DataURL” value =14 “HTMLStandardColors.txt” />15 <param name = “UseHeader” value = “TRUE” />16 <param name = “TextQualifier” value = “@” />17 <param name = “FieldDelim” Value = “|” />18 </object>1920 <script type = “text/javascript”>21 <!- -22 var recordSet = Colors.recordset;2324 function update ( )25 {26 hlTitle.style.color = colorRGB.innerText;27 }VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 147
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH2829 function move ( whereto )30 {31 switch ( whereTo ) {3233 case “first”:34 recordSet.MoveFirst( );35 update ( );36 break;3738 // If recordset is at beginning, move to end39 case “previous”:4041 recordSet. MovePrevious( );4243 if ( recordSet.B0F )44 recordSet.MoveLast ( );4546 update( );47 break;4849 // If recordset is at end, move to beginning.50 case “next”:5152 recordSet.MoveNext ( );5354 if ( recordSet.E0F )55 recordSet,MoveFirst( );5657 update( );58 break;5960 case “last”:61 recordSet.MoveLast( );62 update( );63 break;64 }65 }66 //- ->67 </script>6869 <style type = “text/css”>70 inpuy { background-color: khaki;71 color: green;VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 148
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH72 font-weight:bold }73 </style>74 </head>7576 <body style = “background-color:darkkhaki”>7778 <h1 style = “color: black” id = “hlTitle”>79 XHTML Color Table</h1>80 <span style = “position: absolute; left: 200; width: 270:81 border-style:groove; text-align:center:82 bockground-color: cornsilk; padding: 10”>83 <strong> Color Name: </strong>84 <span id = “ColorName” style = “font-family: monospace”85 datasrc = “#Colors” datafld = “ColorName”>ABC</span>86 <br />8788 <strong>Color RGB Value: </strong>89 <span id = “ColorRGB” style = “font-family: monospace”90 datasrc = “#Colors” datafld = “ColorHexRGBValue”>ABC91 </span><br />9293 <input type = “button” value = “First”94 onclick = “move( ‘first’ );” />9596 <input type = “button” value = “Previous”97 onclick = “move” ( ‘previous’ );” />9899 <input type = “button” value = “Next”100 onclick = “move( ‘next’ );” />101102 <input type = “button” value = “Last”103 onclick = “move( ‘last’ );” />104 </span>105106 </body>107 <h/tml> Figure. Moving through a recordset using JavaScript (Part 1 & 2 of 3)VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 149
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure: Moving through a recordset using JavaScript ( Part 3 of 3 )10. Write a program to perform the binding of an image element.Binding to an img: Many different types of XHTML elements can be bound to data sources. One of the moreinteresting elements in which to bind data is the img element. Figure lists a data source thatcontains image file names. Figure binds an img element to the data sources shown in figure. Lines 59-60 bind the data source to an img element. When binding to an img element,VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 150
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHchanging the record set up dates the src attribute of the image. The script used to move throughthe record set in this example is almost identical to that of the previous example. Clicking any ofthe navigation buttons in this example, however, changes the image displayed on screen, ratherthan the background color of the page. i. image ii. numbers/0. gif iii. numbers/1. gif iv. numbers/2. gif v. numbers/3. gif vi. numbers/4. gif vii. numbers/5. gif viii. numbers/6. gif ix. numbers/7. gif x. numbers/8. gif xi. numbers/9. gif fig. images.txt data source file for figure. 1. <? xml version = “1.0”?> 2. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional // EN” 3. http://www.w3.org/TR/xhtml1/DTD/xhtml 1-transitional. dtd”> 4. 5. <! -- fig: bindimg. html --> 6. <! -- Binding data to an image --> 7. 8. <html xmlns = http://www.w3.org/1999/xhtml> 9. <head> 10. <title> Binding to a img</title> 11. 12. < object id = “Images” 13. classid =”CLSID:333C7BC4-460F-1100BCO4-0080C7055A83”> 14. <param name = “DataURL” value = “images txt” /> 15. < param name = “Use Header” value = “True” /> 16. </object> 17. 18. <script type = ”text/javascript”> 19. <!— 20. recordSet =Images. record set; 21. 22. function move( where To) 23. { 24. switch( where To ) { 25.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 151
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 26. case “first”: 27. recordSet. MoveFirst(); 28. break; 29. 30. case “previous”: 31. 32. recordSet.MovePrevious(); 33. 34. if ( recordSet. BOF ) 35. recordSet. MoveLast(); 36. 37. break; 38. 39. case “next”: 40. 41. recordSet.MoveNext (); 42. 43. if (recordSet. EOF ) 44. recordSet. MoveFirst (); 45. 46. bread; 47. 48. case “last”: 49. recordSet.MoveLast(); 50. break; 51. } 52. } 53. //--> 54. </script> 55. </head> 56. 57. <body> 58. 59. <img datasrc = “#Images” datafld = “image” alt = “Image” 60. style = “posicion: relative; left: 45px” /><br /> 61. 62. < input type = “ button” value = “First” 63. onclick = “move ( ‘first’);” /> 64. 65. <input type = “ button” value = “previous” 66. onclick = “move ( ‘previous’ ); “ /> 67. 68. < input type = “ button” values = “Next” 69. onclick = “move( ‘next’ ) ; “ />VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 152
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 70. 71. < input type = “ button” values = “Last” 72. onclick = “move( ‘last’ ) ; “ /> 73. 74. </body> 75. </html> Figure: Binding data to an img element (part 3 of 3)11. Discuss in detail with a sample program to perform binding of data to a table element.Binding to a table: Binding data to a table element is perhaps the most important feature of data binding. Thisis done somewhat differently from the data binding we have seen so far. Figure binds the data infigure to a table element. 1. <?xml version = “1.0”?> 2. <! DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” 3. “http://www.w3.org/TR/xhtml1-strict.dtd “> 4. 5. <! – fig. tablebind. html --> 6. <! -- Using Data Binding with tables --> 7. 8. <html xmlns = http://www/w3/org/1999/xhtml> 9. <head> 10. <title> Data Binding and Tables </title> 11. <object id = “Colors” 12. classid = “CLSID:333C7BC4-460F-11D0-BC04-0080C7055A83”> 13. <param name = “DataURL” value = 14. “HTMLStandardColors.txt” /> 15. <param name = “UseHeader” value = “TRUE” /> 16. < param name = “TextQualifier” value = “@” />VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 153
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 17. < param name = “FieldDelim” value =”1” /> 18. </ object > 19. </ head> 20. 21. < body style = “background –color: darkseagreen”> 22. 23. <h1> Binding Data to a <code> table </code>< /h1> 24. 25. <table datasrc = “#Colors” style = “border-style: ridge; 26. border- color: darkseagreen; 27. background-color: light cyan”> 28. 29. <thead> 30. <tr style = “background –color: mediums lateblue”> 31. <th>Color Name</th> 32. <th>Color RGB Value </th> 33. </tr> 34. </thead> 35. 36. <tbody> 37. <tr style = “background – color: lightsteelblue”> 38. <td><span datafld = “ColorName” ></span><td> 39. <td><span datafld = “ColorHexRGBValue” 40. style = “font- family: monospace” ></span></td> 41. </tr> 42. </tbody> 43. 44. < / table > 45. 46. < / body > 47. </html> Figure: Binding data to a table element (part 2 of 2)VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 154
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Lines 25-27 begin binding to the table by adding the datasrc attribute to the opening tabletag. We complete the data binding in lines 38-39 by adding the datafld attribute to span elementsthat reside in the table cells. Note that in the file we only have one row of table cells-InternetExplorer iterates through the data file and creates a table row for each record it finds.12. Write a DHTML program to sort the data in a table using the sort property.Sorting table data: If your are manipulating a large data source, you client will probably need some way tosort the data. This is accomplished with the sort property of the TDC. 1. >?xml version = “1.0” ?> 2. <! DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN” 3. http://www.w3.org/TR/xhtml 1/DTD/xhtl 1-strict.dtd> 4. 5. <! --fig : sorting. html --> 6. <! – Sorting. table data --> 7. 8. <html xmlns = http://www.w3.org/1999/xhtml> 9. <head> 10. <title> Data Binding and Tables</title> 11. <object id =” Colors” 12. classid = “CLSID:333C7BC4-460F-1100-BC04-0080C7055A83”> 13. <param name “DataURL” value = 14. “HTMLStandardColors.txt” /> 15. <param name = “Use Header” value =”TRUE” /> 16. <param name = “TextQualifier” value = “@” /> 17. <param name = “ FieldDelim” value = “l” /> 18. </ object> 19. </head> 20. 21. <body style = “background – color: darkseagreen”> 22. 23. <h1>Sorting Data</h1> 24. 25. <table datasrc = “#Colors” style = “border-style: ridge; 26. border-color: darkseagreen; 27. background-color: lightcyan”> 28. < caption> 29. Sort by: 30. 31. <select onchange = “Colors Sort = this.value;VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 155
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 32. Colors.Reset();”> 33. <option value = “ColorName”>Color Name (Ascending) 34. </option> 35. <option value = “ColorName”>Color Name (Descending) 36. </option> 37. <option value = “ColorHexRCBValue” > Color RGB Value 38. (Ascending)</option> 39. <option value = “ColorHexRCBValue” > Color RGB Value 40. (Descending) </option> 41. </select> 42. </caption> 43. 44. <thead> 45. <tr style = “background-color: mediums lateblue”> 46. <th>Color Name </th> 47. <th>Color RGB Value </th> 48. </tr> 49. </thead> 50. 51. <tbody> 52. <tr style = “background – color: lightsteelblue”> 53. <td><span datafld = “ColorName” ></span></td> 54. <td><span datafld = “ColorHexRGBValue” 55. style = “font-family:monospace” ></span><td> 56. </tr> 57. </tbody> 58. 59. </table> 60. 61. </body> 62. </html>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 156
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure: Sorting data in a table (part 2 of 2) Lines 31-32 set up the on change event that will enable us to sort our data by specifying thevalue of the TDC’s sort property (i.e., Colors. Sort). This example sets property Sort to the value ofthe selected option tag (this. Value) when the on change event is fired. javaScript keyword thisrefers to the element in which the statement resides (i.e., the select element). Therefore, the valueproperty refers to the currently selected option tag. After setting the sort property to the specificcolumn to use for sorting, we invoke the Reset method of the TDC to display the data in its neworder. Lines 33-40 set the value attributes of the option tags to the column names in our data file.By default, a column is sorted in ascending order. To sort in descending order, the column nameis preceded by a minus sign (-). UNIT – III PART – A1. Explain how Audio & Video files can be incorporated into web pages. Creating audio and video to incorporate into Web pages often requires complex andpowerful software, such as Adobe TM After Effects ® or Macromedia TM Director ®. Audio and video can be used in Web pages in a variety of ways. Audio and video files canbe embedded in a Web page or placed on a Web server so that they can be downloaded “on-demand”. A variety of audio and video file formats are available for different uses. Common video file formats include MPEG (Moving Pictures Experts Group), Quick Time,VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 157
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHRealOne Player, AVI (Audio Video Interleave) and MJPEG (Motion JPEG). Audio formats includeMP3 (MPEG Layer 3) MIDI (Musical Instrument Digital Interface), WAV (Windows Waveform)and AIEF (Audio Interchange File Format – Macintosh only).2. What is the use of bgsound element? Explain the four properties of it. The bgsound element has four key properties – src, loop, balance and volume. To changethe property values via a script, assign a scripting name to the bgsound element’s id property. The src property specifies the URL of the audio clip to be played. Internet Explorersupports a wide variety of audio formats. The loop property specifies the number of times the audio clip will play. The default value-1 specifies that the audio clip should loop until the user browses to a different Web page or clicksthe browser’s Stop button. A positive integer indicates the exact number of times the audio clipshould loop. Negative values (except – 1) and zero values for this property cause the audio clip toplay once. The balance property specifies the balance between the left and right speakers. The valuefor this property is between -10000 (sound only from the left speaker) and 10000 (sound only fromthe right speaker). The default value, 0, indicates that the sound should be balanced between thetwo speakers. The volume property determines the volume of audio clip. The value for this property isbetween – 10000 (minimum volume) and 0 (maximum volume). The default value is 0.3. What is the use of image element? What are its properties? The img element enables both images and videos to be included in a Web page. The srcproperty indicates that the source is an image. The dynsrc (i.e., dynamic source) property indicatesthat the source is a video clip. Property start indicates when the video should start playing(specify file open to play when the clip is loaded or mouseover to play when the user firstpositions the mouse over the video).4. Explain how the object element functions. The object element is used to embed ActiveX controls in Web pages. The width and heightproperties specify the width and height in pixels that the control occupies in the Web page.Property classid specifies the unique ActiveX control ID for the ActiveX control. Parameters can be passed to an ActiveX control by placing param elements between theobject element’s <object> and </object> tags. Each parameter is specified with a param elementthat contains a name property and a value property.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 158
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH5. Define Microsoft Agent. Microsoft Agent is a technology for interactive animated characters in a Windowsapplication or World Wide Web page. These characters allow users of your application to interactwith the application by using more natural human communication techniques. The control acceptsboth mouse and keyboard interactions, speaks (if a compatible text-to-speech engine is installed).With these capabilities, your Web pages can speak to users and can respond to their voicecommands. The Microsoft Agent control provides four preprogrammed characters – Peedy the Parrot,Genie, Merlin and Robby the Robot. The Lernout and Hauspie Tru Voice Text to Speech (TTS) engine is used by the MicrosoftAgent ActiveX control to speak the text that Microsoft Agent displays. The Microsoft Agent control’s characters collection stores information about the charactersthat are currently available for use in a program. Method Load of the Characters collection loadscharacter data. The method takes two arguments-a name for the character that can be used later tointeract with that character and the URL of the character’s data file.6. What is the use of character object? A character object is used to interact with the character. Method Character of the Characterscollection receives as its argument the name that was used to download the character data andreturns the corresponding Character object. The Character object’s Get method downloads character animations and states. Each state has animation effects associated with it. When the character enters a state (e.g.the Showing state), the state’s associated animation plays. Character method MoveTo moves the character to a new position on the screen. MethodShow displays the character. Method plays the specified animation. Method Speak speaks itsstring argument. If there is a compatible TTS engine installed, the character displays a bubblecontaining the next and audibly speaks the text as well.7. Explain how Microsoft Agents can be used to recognize voice commands. To enable Microsoft Agent to recognize voice commands, a compatible voice-recognitionengine, such as the Microsoft Speech-Recognition engine, must be installed. The voice commands that the user can use when interacting with a character must beVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 159
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHregistered in the Character object’s Commands collection. The Commands collection’s Add method registers each voice command.8. Explain how can you embed a RealOne Player object in a web page. A RealOne Player object can be embedded (with the embed element) in a Web page to addstreaming media to a Web page. The type attribute specifies the MIME type of the embedded file.The width and height attributes specify the dimensions the control will occupy on the page. Theautostart attribute determines whether the audio should start playing when the page loads. Thecontrols attribute specifies which controls are available to the user. Setting controls to Defaultplaces all the control buttons on screen. The src attribute specifies the location of the streamingaudio. RealOne Player method SetSource sets the source URL of the audio stream to be played.Method DoPlayPause toggles between pausing and playing the stream.9. What is SMIL? Where it is used? SMIL is an XML-based description language that organizes static and dynamic text, audioand video to occur simultaneously or sequentially. A SMIL document specifies the source (i.e., the URL) and presentation of multimedia elements. RealOne Player is one application capable of rendering SMIL documents. Apple’sQuicktime plug-in also plays SMIL in both Windows and Mac OS environments.SMIL is the W3C-recommended method of embedding audio and video in a Web page. Various transitions can be used when changing images in a SMIL document using thetransition element. The type and dur attributes of each transition element specify its transitiontype and duration, respectively. The id attribution assigns a unique id to each transition. We can embed a SMIL document in a Web page using the embed element.10. What is SVG? What is the role of SVG in Vector Graphics? Scalable Vector Graphics (SVG) markup language describes vector graphic data for JPEG,GIF and PNG formats so that they may be distributed over the Web efficiently. GIF, JPEG and PNG file formats store images as bitmaps. Bitmaps describe the color ofevery pixel in an image and can take a long time to download. Because of the method in whichbitmap information is stored, images of these file types cannot be enlarged or reduced without aloss of image quality.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 160
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Vector graphics are produced by mathematical equations that describe graphicalinformation in terms of lines, curves, and so on. Not only do images rendered by vectors requireless bandwidth, they can be easily scaled and printed without loss of image clarity. Animationscreated with vector graphics have significantly smaller file sizes than those created by sequencingof bitmap images. SVG is an XML vocabulary comparable to the other XML vocabularies presented inchapter, XML (e.g., MathML and MusicXML). Thus, SVG documents can be scripted, searchedand dynamically created.11. What is the function of the attributes? i) View Box ii) Animate element. The element path is used to create the outline of a shape in SVG. Attribute style can alterthe attributes of the shape. The animate element allows us to animate single or grouped SVG elements. The attributeattributeName of the animate element specifies the attribute to be altered, and the attributeTypedetermines the type of attribute being altered.12. What is the Web Server? Give example. Web server – responds to client requests (typically from a Web browser) by providingresources such as XHTML documents. For example, when users enter a Uniform Resource Locator(URL) address, such as www. deicel.com, into a Web browser, they are requesting a specificdocument from a Web server. The Web server maps the URL to a resource on the serer (or to a fileon the server’s network) and returns the requested resource to the client. During this interaction,the Web server and the client communicate using the platform-independent Hypertext TransferProtocol (HTTP), a protocol for transferring requests and files over the Internet (i.e., between Webservers and Web browsers). Our Web-server discussion introduces Microsoft Internet Information Services (IIS) and theopen-source Apache Web server.13. What is the use of get & post request? A get request typically gets (or retrieves) information from a server. Common uses of getrequests are to retrieve an HTML document or an image, or to fetch search results based on a user-submitted search term.A get request sends information to the server as part of the URL.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 161
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHA post request typically posts (or sends) data to a server. Common sets of post requests are tosend information to a server, such as authentication information or data from a form that gathersuser input.The post method sends form data as an HTTP message, not as part of the URL. Browsers often cache Web pages for quick reloading. Browsers typically do not cache theserver’s response to a post request, because the next post might not return the same result.14. What is Multi-tier Application? A Web server typically is part of a multi-tier application – sometimes referred to as an n-tierapplication. A multi-tier application divides functionality into separate tiers. The three-tierapplication contains an information tier, a middle tier and a client tier. The information tier maintains data for the application in a database. The middle tier implements business logic and presentation logic to control interactionsbetween application clients and application data. A Web server is a middle-tier application. Thistier often is divided into its two logical components, hence the term n-tier application. The client tier is the application’s user interface. The client interacts with the middle tier tomake requests and to retrieve data from the information tier. The client then displays dataretrieved from the middle tier to the user.15. What are the two Web servers used?Microsoft Internet Information Services (IIS) is an enterprise-level Web server. The Apache Web server, maintained by the Apache Software Foundation, is the mostpopular Web server in use today and runs on many platforms. A virtual directory is an alias for an existing directory on a local machine. In its default configuration, Apache supports Perl and Python documents stored in the cgi-bin directory, whereas XHTML and PHP documents are stored in the htdocs directory (the defaultWeb-content directory in Apache).16) What is E-Commerce? E-commerce involves exchanges among customers, business partners and vendors. E-business is composed of these same elements, but also includes operations that are handled withinthe business itself.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 162
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH17) What is EDI Electronic Data Interchange (EDI) standardizes business forms, such as purchase ordersand invoices, so that companies can share information electronically with customers, vendors andbusiness partners.18) What PR &CRM ? Public relations (PR) keeps customers and employees current on the latest informationabout products, services and internal and external issues, such as company promotions andconsumer reactions. • Customer relationship management (CRM) focuses on providing andmaintaining quality service for customers.19) What is SSL? The Secure Sockets Layer (SSL) protocol is commonly used to secure communication on theInternet and the Web. SSL uses public-key technology and digital certificates to authenticate theserver in a transaction and to protect private information as it passes from one party to anotherover the Internet.20) What is Defamation? Defamation is the act of injuring another’s reputation, honor or good name through falsewritten or oral communication. Defamation has of two forms, slander and libel. Slander is spokendefamation, whereas libelous statements are written or spoken in a context in which they havelongevity and pervasiveness that exceed slander.21) What is i) Pull Strategy ii)Push Strategy?i. A pull strategy assumes that people will request that specific information be sent to their wireless devices in real time.ii. A push strategy is enacted when marketing messages requested by the recipient are not delivered to wireless devices in real time.22) Give the applications of client side scripting.Client side scripting is used for i. Validation ii. Intercircuitry iii. Browser Access iv. Web page enhancement with active x controls, DHTML & Java applets.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 163
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH23. What is the function of embed element? The embed element embeds a media clip in a webpage. A GUI can be displayed to give theuser control over the media clip and it enables the user to play, pause & stop the media clip tospecify the volume and to move forward and backward quickly through the clip.24. What is the purpose of ebusiness? An ebuiness can offer personalization, effective customer service & streamlined supplychain management.25. What is branding? A brand is typically defined as a name, logo or symbol that identifies a company’s productsor services. PART – B1. Discuss in detail about the demonstration of background audio with bgsound. The bgsound element has four key properties – src. Loop, balance and volume. To changethe property values via a script, assign a scripting name to the bgsound element’s id property. The src property specifies the URL of the audio clip to be played. Internet Explorersupports a wide variety of audio formats. The audio clip specified with bgsound’s src property can be any type supported by InternetExplorer. The loop property specifies the number of times the audio clip will play. The default value– 1 specifies that the audio clip should loop until the user browses to a different Web page orclicks the browser’s Stop button. A positive integer indicates the exact number of times the audioclip should loop. Negative values (except -1) and zero values for this property cause the audio clipto play once. The balance property specifies the balance between the left and right speakers. The valuefor this property is between – 10000 (sound only from the left speaker) and 10000 (sound onlyfrom the right speaker). The default value, 0, indicates that the sound should be balanced betweenthe two speakers. Scripting cannot set bgsound’s property balance.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 164
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH The volume property determines the volume of the audio clip. The value for this propertyis between 10000 (minimum volume) and 0 (maximum volume). The default value is 0. The volume specified with bgsound property volume is relative to the current volumesetting on the client computer. If the client computer has sound turned off, the volume propertyhas no effect. On most computers, the minimum audible volume for bgsound property volume is a valuemuch greater than – 10000. This value depends on the machine. The XHTML document in figure demonstrates the bgsound element and scripting theelement’s properties. This example’s audio clip comes from the Microsoft Developer Network’sdownloads site, msdn.microsoft.com/downloads/default.asp This site contains many free images and sounds. 1. <?xml version = “1.0”?> 2. <!DOCTYPE html PUBLIC “-//W3C// DTD XHTML 1.0 Transitional//EN” 3. “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> 4. 5. <! --Fig. : BackgroundAudio.html --> 6. <! -- Demonstrating the bgsound element --> 7. 8. <html xmlns = http://www.w3.org/1999/xhtml> 9. <head><title>The bgsound Element</title> 10. <bgsound id = “audio” src = 11. http://msdn.microsoft.com/downloads/sounds/jazzgos.mid 12. loop = “1”></bgsound> 13. 14. <script type = “text/javascript”> 15. <! -- 16. function changeProperties() 17. { 18. var loop = parseInt ( audioForm.loopit.value ); 19. if ( ( loop >= -1 ) ) { 20. audio.loop = ( isNaN( loop ) ? 1 : loop ); 21. } else { 22. alert( “Please enter a integern” + 23. “greater than or equal to -1.” ); 24. } 25. 26. var vol = parseInt ( audioForm.vol. value ):VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 165
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 27. if ( ( vol >= -10000 ) && ( vol <= 0 ) ) { 28. audio.volume = ( isNaN( vol ) ? 0 : vol ); 29. } else { 30. alert( “please enter an integern” + 31. “between -10000 and 0.” ); 32. } 33. } 34. 35. function stopSound() 36. { 37. if ( audioForm.stopButton.value == “Stop Sound” ) 38. { 39. audio.src = “”; 40. audioForm.stopButton.value = 41. “Start Sound”; 42. } else { 43. audio.src = 44. http://msdn.microsoft.com/downloads/sounds/jazzgos.mid; 45. audioForm.stopButton.value = 46. “Stop Sound”; 47. } 48. } 49. // --> 50. </script> 51. </head> 52. 53. <body> 54. <h1>Background Music via the bgsound Element</h1> 55. <h2>jazz Gospel</h2> 56. 57. This sound is from the free sound downloads at the 58. <a href = 59. http://msdn.microsoft.com/downloads/default.asp> 60. Microsoft Developer Network</a> downloads site. 61. <hr /> 62. Use the fields below to change the number of iterations 63. and the volume for the audio clip<br /> 64. Press <strong>Stop</strong> to stop playing the sound. 65. <br />Press <strong>Refresh</strong> to begin playing 66. the sound again. 67. 68. <form name = “audioForm” action = “ “> 69. <p>Loop [-1 = loop forever]</p> 70. <input name = “loopit” type = “text” value = “1” />VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 166
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 71. <br />Volume [-10000 (low) to 0 (high)] 72. <input name = “vol” type = “text” value = “0” /><br /> 73. <input type = “button” value = “Set Properties” 74. onclick = “changeProperties()” /> 75. 76. <input type = “button” value = “Stop Sound” 77. id = “stopButton” onClick = “stopSound()” />, 78. </form> 79. </body> 80. </html> Fig. Demonstrating background audio with bgsound The code in lines 10-12 specifies the media source. The loop property specifies that theaudio clip plays only once. The balance and volume attributes are omitted, so they default to 0.[Note: The bgsound element should be placed in the head section of the XHTML document.] Function changeProperties (lines 16-33) is called in line 74when the Set Properties button isclicked. Lines 18-24 reach the new value for property loop from the form’s loopit text field,convert the value to an integer and set the new property value by assigning a value to audio, loop(where audio is the id of the bgsound element and loop is a property). Lines 26-32 read the new value for the volume property from the form’s vol text field,convert the value to an integer and set the new property value by assigning a value toaudio.volume (where volume is the scripting name of the property). Function stopSound (lines 35-48) stops the audio clip from playing when the user clicks theStop Sound button (lines 76-77). Line 39 changes the audio element’s src attribute to an emptystring “”. Clicking the button again changes the src attributes back to its original value (lines 43-44).VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 167
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH2. Write a Javascript program for adding Audio or Video with the embed Element.Adding Audio or Video with the embed Element So far, we have used elements bgsound and img to embed audio and video in a Web page.In both cases, viewers of the page have little control over the media clip. In this section, weintroduce the embed element, which embeds a media clip (audio or video) into a Web page. Theembed element displays a graphical user interface (GUI) within the browser window that givesthe user direct control over the media clip. A browser encountering a media clip in an embedelement launches an application that can play it. For each media type, users can set a preferredplayer. For example, if the media clip is a .wav file (i.e., a Windows Wave file), Internet Explorertypically uses the Windows Media Player ActiveX control to play the clip. The Windows MediaPlayer has a GUI that enables users to play, pause and stop the media clip. Users can also controlthe volume of audio and move forward and backward through the clip using the GUI. The embed element is supported by both Microsoft Internet Explorer and Netscape, but it isnot part of the XHTML 1.1 recommendation. Documents written in XHTML using the embedelement should render properly in either browser, though errors may occur when one tries tovalidate the document using the World Wide Web Consortium’s XHTML 1.1 Validation Service. The XHTML document in figure modifies the wave filter example. This example uses anembed element to add audio to the Web page. 1. <?xml version = “1.0”?> 2. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” 3. http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd> 4. 5. <! -- Fig. : EmbeddedAudio.html --> 6. <! -- Background Audio via the embed Element --> 7. 8. <html xmlns = http://www.w3.org/1999/xhtml> 9. <head> 10. <title>Background Audio via the embed Element</title> 11. <style type = “text/css”> 12. span { width: 600} 13. .big { color: blue; 14. font-family: sans-serif; 15. font-size: 50pt; 16. font-weight: bold } 17. </style> 18. 19. <script type = “text/javascript”> 20. <! --VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 168
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 21. var TimerID; 22. var updown = true; 23. var str = 1; 24. 25. function start() 26. { 27. TimerID = window.setInterval (“wave()”, 100 ); 28. } 29. 30. function wave() 31. { 32. if ( str > 23 | | str < 1 ) 33. updown = !updown; 34. 35. if ( updown ) 36. str++; 37. else 38. str--; 39. 40. wft.filters( “wave” ).phase = str * 20; 41. wft.filters( “wave” ).strength = str; 42. } 43. / / --> 44. </script> 45. </head> 46. 47. <body onload = “start()”> 48. <h1>Background Audio via the embed Element<h1> 49. <p>Click the text to stop the script.</p> 50. 51. <p class = “big” align = “center”> 52. <span onClick = “Window.Clear Interval( Timer ID ) 53. id = “wft” style = “filter:wave( 54. add = 0, freq = 3, light = 0, phase = 0, strength = 5)”>” 55. WAVE FILTER EFFECT</p></span> 56. 57. <p>These controls can be used to control the audio.</p> 58. <embed src = “humming.wav” loop = “true”></embed> 59. </body> 60. </html>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 169
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Fig. Embedding audio with the embed element Line 58 uses the embed element to specify that the audio file humming. wav should beembedded in the Web page. The loop property indicates that the media clip should loopindefinitely. The width and height properties define the size of the controls for the sound clip. Bydefault, the GUI for the media player is displayed. To prevent the GUI from appearing in the Webpage, add hidden = “true” to the embed element. To manipulate the element, specify a scriptingname by adding the id property to the embed element. The embed element can specify video clips as well as audio clips. Figure demonstrates anembedded video. The embed element that loads and plays the video is located in line 18. 1. <?xml version = “1.0”?> 2. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” 3. http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd> 4. 5. <! -- Fig. : EmbeddedVideo.html --> 6. <! -- Video.via the embed Element --> 7. 8. <html xmlns = http://www.w3.org/1999/xhtml> 9. <head> 10. <title>Video via the embed Element</title> 11. </head> 12. 13. <body> 14. <h1>Displaying a Video using the embed Element</h1> 15. <h2>Car Driving in Circles</h2> 16. 17. <table> 18. <tr><embed src = “car_hi.wmv” loop = “false”VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 170
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 19. width = “240” height = “176”> 20. </embed></td> 21. </tr></table> 22. <hr /> 23. This page plays the video once. <br /> 24. Use the controls on the embedded video player to play the 25. video again. 26. </body> 27. </html> Fig. Embedding video with the embed element3. Discuss in detail how ActiveX controls play a vital role to embed the windows media player. ActiveX controls enhance the functionality of Web pages with interactivity. In this section,we embed the Windows Media Player ActiveX control in a Web page, so that we can access a widerange of media formats supported by the Windows Media Player. The Windows Media Playerand other ActiveX controls are embedded into Web pages with the object element. The XHTML document in figure demonstrates how to use the object element to embed twoWindows Media Player ActiveX controls in the Web page. One of the controls plays a video. Theother control plays an audio clip. 1. <?xml version = “1.0”?> 2. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” 3. http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd> 4. 5. <! -- Fig.: MediaPlayer.html --> 6. <! -- Embedded Media Player Objects --> 7. 8. <html xmlns = http://www.w3.org/1999/xhtml> 9. <head><title>Embedded Media Player Objects</title> 10. <script type = “text/javascript” 11. <! -- 12. var videoPlaying = true; 13.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 171
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 14. function toggleVideo( b ) 15. { 16. videoPlaying = !videoPlaying; 17. b.value = videoPlaying ? 18. “Pause Video” : “Play Video”; 19. videoPlaying ? 20. VideoPlayer.Play() : VideoPlayer.Pause(); 21. } 22. // --> 23. </script> 24. </head> 25. 26. <body> 27. <h1> 28. Audio and video through embedded Media Player objects 29. </h1> 30. <hr /> 31. <table> 32. <tr><td valign = “top” align = “center”> 33. <object id = “VideoPlayer” width = “200” height = “225” 34. classid = 35. “CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95”> 36. <param name = “FileName” value = 37. “car_hi.wmc” /> 38. <param name = “AutoStart” value = “true” /> 39. <param name = “ShowControls” value = “false” /> 40. <param name = “loop” value = “true” /> 41. </object></td> 42. <td valign = “bottom” align = “center”> 43. <p>Use the controls below to control the audio clip.</p> 44. <object id = “AudioPlayer” 45. classid = 46. “CLSID:22d6f312 b0f6-11d0-94ab-0080c74c7e95”> 47. <param name = “FileName” value = 48. “http://msdn.microsoft.com/downloards/sounds/carib.mid /> 49. <param name = “AutoStart” value = “true” /> 50. <param name = “loop” value = “true” /> 51. </object></td></tr> 52. 53. <tr><td valign = “top” align = “center”> 54. <input name = “video” type = “button” value = 55. “Pause Video” onclick = toggleVideo( this )” /> 56. </td></tr> 57. </table>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 172
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 58. </body> 59. </html>Fig. Using the object element to embed the Windows Media Player ActiveX Control in a Webpage When the body of this document loads, two instances of the Windows Media PlayerActiveX control are created. The object element in lines 33-41 creates a Media Player object for thefile car_hi.wmv (the source is specified in line 37). Line 33 indicates the start of the embeddedobject definition. The id property specifies the scripting name of the element (i.e., VideoPlayer).The width and height properties specify the width and height, in pixels, that the controls occupyin a Web page. In lines 34-35, property classid specifies the ActiveX control ID for the WindowsMedia Player. ActiveX controls have unique classids that identify them. For more informationabout ActiveX controls, visit www. active-x.com. Lines 36-40 specify parameters that are passed to the control when it is created in the Webpage. Each parameter is specified with a param element that has name and value properties. TheFileName parameter specifies the file containing the media clip. The AutoStart parameter is aboolean value indicating whether or not the media clip plays when it is loaded. The ShowControlsparameter is a boolean value indicating whether the Media Player controls should be displayed.The Loop parameter is a boolean value indicating whether the Media Player should play themedia clip indefinitely. The object element in lines 44-51 embeds another Media Player object in the Web page. ThisMedia Player plays the MIDI file carib.mid (specified with the FileName parameter). A MIDI(Musical Instrument Digital Interface) file is a sound file that conforms to the MIDI standard fordigital music playback. The Media Player starts playing the clip when it is loaded (specified bysetting the AutoStart parameter to true) and loops the audio clip indefinitely (specified by settingthe Loop parameter to true).VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 173
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH The script in lines 10-23 controls the media player. Clicking Pause Video calls functiontoggleVideo (line 14). The button is defined in the XHTML form in lines 54-55. The onclick eventsets the toggleVideo function as the event handler passes this as an argument for the function. thisserves as a pointer to the element from which it is passed – in this case, the input.element. Thisevent changes the button text in lines 17-18. Lines 19-20 use the boolean variable videoPlaying todetermine whether to call VideoPlayer’s Play method or Pause method, which play or pause thevideo clip, respectively.4. Explain the Working of RealOne Player object with necessary example. A RealOne Player object may be embedded into a Web page to enhance the page withstreaming audio and video. RealOne Player can also be delivered as a browser plug-in on multipleplatforms. Figure demonstrates streaming audio and video in a Web page by embedding twoRealOne Player objects in the page using embed elements. Users can select from two differentsources; this selection then calls a JavaScript function which invokes RealOne Player methods toplay the selected video stream. Viewing the following example requires that RealOne Player beinstalled. This software is available as a free download from RealNetworks atwww.real.com/player. The embed elements in lines 39-43 and lines 45-49 embed the RealOne Player plug-ins forvideo and audio, respectively, into the page. The type attribute specifies the MIME type of theembedded file, which in this case is the MIME type for streaming video or audio. (Remember thatMIME is a standard for specifying the format of content so the browser can determine how tohandle the content). The width and height attributes specify the dimensions of the space thecontrol occupies on the page. The autostart attribute determines whether the media starts playingwhen the page loads (for this example, we set it to false for both elements). The controls attributespecifies which controls users can access (e.g., Play button, Pause button and Volume Control).Setting attribute controls to ImageWindow in line 41 produces a video window. Setting controls toDefault in line 47 creates a control bar featuring the standard control buttons. A list of availablecontrols can be found at: www.audiovideoweb.com/embed_real_html.htm We do not set the src attribute of the embed element. Normally, the src is set to the locationof the streaming media, but in this example, we use JavaScript to change the source dynamicallybased on user selections. 1. <?xml version = “1.0”?> 2. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” 3. “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> 4. 5. <! -- Fig. : StreamingMedia.html --> 6. <! -- Embedding RealOne Player into an XHTML page --> 7. 8. <html xmlns = “http://www.w3.org/1999/xhtml”>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 174
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 9. <head> 10. <title>Live Media!</title> 11. 12. <script type = “text/javascript”> 13. <! -- 14. var locations = 15. [“http://www.noaanews.ooaa,gov/video/naturalworld.ram”, 16. “http://www.nasa.gov/ram/35037main_.ram”] 17. 18. function change ( loc ) 19. { 20. videoControl.SetSource( locations[ loc ] ); 21. videoControl.DoPlayPause(); 22. } 23. // --> 24. </script> 25. </head> 26. 27. <body> 28. 29. <p>Pick from my favorite video streams: 30. 31. <select id = “streamSelect” onchange = 32. “change( this,value )”> 33. <option value = “”>Select a station</option> 34. <option value = “0”>NOAA</option> 35. <option value = “1”>NASA</option> 36. </select></p> 37. 38. <br /> 39. <embed id = “videoControl” src = “” 40. type = “audio/x-pn-realaudio-plugin”width = “275” 41. height = “200” controls = “ImageWindow” 42. console = “streamingAudio” 43. autostart = “false” /> 44. <br /> 45. <embed id = “audioControl” src = “” 46. type = “audio/x-pn-realaudio-plugin” width = “275” 47. height = “40” controls = “ControlPanel” 48. console = “streamingAudio 49. autostart = “false” /> 50. 51. </body> 52. </html>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 175
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Fig. Embedding RealOne Player in a Web page. (Courtesy of RealNetworks, Inc.) Now that the player is embedded in the Web page, we use scripting to activate thestreaming media. The select menu (line 31) lists two live media streams, corresponding to the twoentries in the array locations (defined in line 14), which contain the actual URLs for the live videofeeds. When the selection changes, function change (line 18) is called by the onchange event. Thisfunction calls methods SetSource and DoPlayPause of the RealOne Player object. MethodSetSource sets the source URL of the audio stream to be played. Then, method DoPlayPausetoggles between pausing and playing the stream. [Note: In this example, the stream is initiallypaused because no source was specified in the embed element. Thus, the stream begins playing inresponse to the call to DoPlayPause]. To view more streaming media, visit the following sites: www.noaa.gov www.nasa.gov www.streamingmedia.com/radio/ To learn more about programming with RealOne Player, visit the RealPlayer DevZone at Service.real.com/help/library/guides/extend/embed.htm A few years ago, broadcasting personal streaming audio or video required a dedicatedserver and expensive software. Today, open-source software, such as Darwin Streaming Serverand RealNetwork’s Helix Universal Server G2, provide “home-made” servers, such as Linux orApache running on a PC, with streaming capability. These applications are available for downloadfrom www.shareware.com. With limited server-processor power and Internet bandwidth,however, this type of setup cannot support the same number of streams and bit rates as adedicated streaming server. VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 176
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH5. Explain in detail about SMIL with necessary example.Synchronized Multimedia Integration Language (SMIL) The Synchronized Multimedia Integration Language (SMIL, pronounced “smile”) enablesWeb document authors to coordinate the presentation of a wide range of multimedia elements.SMIL is an XML-based description language that organizes static and dynamic text, audio andvideo to occur simultaneously or sequentially. Like Flash, SMIL provides a time reference for allinstances of text and media. A SMIL document specifies the source (i.e., the URL) and presentationof multimedia elements. In XHTML, multimedia elements are autonomous entities that cannotinteract without complicated scripts. In SMIL, multimedia elements can work together, enablingdocument authors to specify when and how multimedia elements appear in a document. RealOnePlayer is one application capable of rendering SMIL documents. Apple’s Quicktime plug-in alsoplays SMIL in both Windows and Mac OS environments. SMIL is the W3C recommended method of embedding audio and video in a Web page. The example in figure is a SMIL document that displays jpg images for a variety of JavaHow to Program book covers. The images are displayed sequentially, and soun accompanies eachimage. 1. <smil xmlns= “http:/www.w3.org/2000/SMIL20/CR/Lanuage”> 2. 3. <! -- Fig. : exampleSMIL.smil --> 4. <! -- Example SMIL Document --> 5. 6. <head> 7. <layout> 8. <root-layout height = “300” width = “280” 9. background-color = “#bbbbee” title = “Example” /> 10. 11. <region id = “image1” width = “177” height = “230” 12. top = “35” left = “50” background-color = “#bbbbee” /> 13. </layout> 14. 15. <transition id = “wipeForward” dur = “2s” type = “barWipe” /> 16. <transition id = “wipeBackward” dur = “2s” type = “barWipe” 17. subtype = “topToBottom” /> 18. 19. <transition id = “fadeIn” dur = “2s” type = “fade” 20. subtype = “fadeFromColor” fadeColor = “#bbbbee” /> 21. 22. <transition id = “fadeOut” dur = “2s” type = “fade”VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 177
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 23. subtype = “fadeToColor” fadeColor = “#bbbbee” /> 24. 25. <transition id = “crossFade” type = “fade” subtype = “crossfade” 26. dur = “2s” /> 27. 28. </head> 29. <body> 30. <seq> 31. <par> 32. <img src = “book1, jpg” region = “image1” 33. transIn = “wipeForward” transOut = “wipeForward” 34. alt = “book1” dur = “6s” fill = “transition” 35. fit = “fill /> 36. <audio src = “bounce.au” dur = “.5s”/> 37. </par> 38. <par> 39. <img src = “book2.jpg” region = “image1” transIn = “fadeIn” 40. transOut = “fadeOut” alt = “book2” dur = “6s” 41. fit = “fill” fill = “transition” /> 42. <audio src = “bounce.au” dur = “.5s”, /> 43. </par> 44. <par> 45. <img src = “book3.jpg” region = “image1” 46. transIn = “wipeBackward” transOut = “fadeOut” 47. alt = “book3” dur = “6s” fit = “fill” 48. fill = “transition” /> 49. <audio src = “bounce.au” dur = “.5s” /> 50. </par> 51. <par> 52. <img src = “book4.jpg” region = “image1” transIn = “crossFade” 53. transOut = “fadeOut” alt = “book4” dur = “6s” 54. fit = “fill” fill = “transition” /> 55. <audio src = “bounce.au” dur = “.5s” /> 56. </par> 57. <par> 58. <img src = “book5.jpg” region = “image1” 59. transIn = “wideForward” transOut = “wipeBackward” 60. alt = “book5” dur = “6s” fit = “fill” 61. fill = “transition” /> 62. <audio src = “bounce.au” dur = “.5s” /> 63. </par> 64. <par> 65. <img src = “book6.jpg” region = image1” 66. transIn = “crossFade” alt = “book6” dur = “6s”VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 178
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 67. fit = “fill” fill = “transition” /> 68. <audio src = bounce.au” dur = “5s” /> 69. </par> 70. </seq> 71. 72. </body> 73. </smil> Fig. SMIL document with images and sound Element head (lines 6-28) contains all the layout information (lines 7-13) and definestransitions for the document. Lines 8-9 set the document size, color and title using element root-layout. Lines 11-12 set aregion for displaying objects (e.g., images) using element region. Attribute id is a unique identifierfor each region. Attributes width and height specify the size of the region, and attributes top andleft provide its relative position. Attribute background-color sets the color of the region’sbackground. Lines 15-26 initialize various transitions that will be used when changing the image. Thetype and dur attributes of each transition element specify its transition type and duration,respectively. The id attribute assigns a unique id to each transition. Line 29 begins the body, which encloses the content of the document. Line 30 starts elementseq (short for sequential), which sets its child elements to execute sequentially (i.e., in the orderthat they appear in the document). A par (short for parallel) element (starting in line 31) sets itschild elements to execute simultaneously. Lines 32-35 show element img. Which references an image. Attribute src contains thelocation of the image, and attribute alt provides a description of the image. Attribute regionspecifies the region in which an image displays; a fit value of fill sets the image to fill the entireregion. Attribute dur describes how long the image appears on the screen (e.g. one second).Attribute transIn and transOut each reference the id assigned to a specific transition. transIndeteremines the transition leading into the image, and transOut specifies the transition as theimage changes. RealNetworks provides a list of SMIL transitions atwww.realnetworks.com/resources/samples/transitions.html. Line 36 contains element audio,which references audio file bounce.au. The remaining elements in the document (lines 38-69)display different images and play the same audio file. We can embed a SMIL document in a Web page using the method described in Section.Visitors to a Web site need the RealOne Player plug-in to view SMIL content. The plug-in isinstalled with RealOne Player, which, as previously mentioned, is available as a free downloadfrom RealNetworks at www.real.com/player. Figure uses an embedded RealOne Player image window to view our example SMILdocument. In lines 14-18 we use the embed element to add the SMIL document to the Web page.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 179
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHThe many attributes of this tag determine how our SMIL document is displayed. First, set the srcattribute in line 14 by giving it the location of the SMIL file. The file is located in the same folder asthe XHTMAL document, so the path is simply the name of the file: exampleSmil.smil. The controlsattribute in line 15 is set to ImageWindow, hiding the controls from users. The type attribute inline 16 allows the specification of the MIME type for the embedded object. In this case, we set typeto audio/x-pn-realaudio-plugin to inform the browser that the RealOne Player plug-in shoulddisplay the SMIL file. Users are not provided GUI controls, so the autostart attribute is set to truein line 17 to start the movie as soon as the page loads. 1. <?xml version = “1.0”?> 2. <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” 3. “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd> 4. 5. <! -- Fig. : SMILexample.html --> 6. <! – embedding SMIL with RealOne Player --> 7. 8. <html xmlns = “http://www.w3.org/1999/xhtml”> 9. <head> 10. <title>Embedding SMIL with RealOne Player</title> 11. </head> 12. <body> 13. <div style = “text-align:center”> 14. <embed src = “exampleSMIL.smil” 15. controls = ImageWindow” 16. type = “audio/x-pn-realaudio-plugin” 17. width = “280” height = “300” autostart = “true”> 18. </embed> 19. </div> 20. <body> 21. </htmlVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 180
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Fig: Using RealOne Player plug-in to display a SMIL document6. Discuss in detail about SVG markup language with an example SVG document.Scalable Vector Graphics (SVG) Scalable Vector Graphics (SVG) markup language describes vector graphic data for JPEG,GIF and PNG formats so that they may be distributed over the Web efficiently. The GIF JPEG andPNG file formats store images as bitmaps. Bitmaps describe the color of every pixel in an imageand can take a long time to download. Because of the method in which bitmap information isstored, images of these file types cannot be enlarged or reduced without a loss of image quality. Vector graphics are produced by mathematical equations that describe graphicalinformation in terms of lines, curves, and so on. Not only do images rendered by vectors requireless bandwidth, but they can be easily scaled and printed without loss of image clarity.Animations created with vector graphics have significantly smaller file sizes than those created bysequencing of bitmap images. SVG is an XML vocabulary, comparable to the other XML vocabularies (e.g., MathML andMusicXML). Thus, SVG documents can be scripted, searched and dynamically created. Both Internet Explorer and Netscape intend to provide native support for SVG in the yearfuture. Currently, Adobe provides a plug-in for Internet Explorer (IE Version 4.0 or higher forWindows and Version 5.0 or higher for Mac) and for Netscape (Version 4.0 or higher for bothWindows and Mac) that enables SVG documents to be rendered directly in those browsers. TheSVG plug-in is available free of charge from Adobe at www. adobe.com/svg. Figure presents an SVG document that displays animated shapes in a browser. We use theAdobe plug-in to view the document in Internet Explorer 6.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 181
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 1. <?xml version = “1.0”?> 2. 3. <! -- Fig. : shapes.svg --> 4. <! -- Simple example of SVG --> 5. 6. <svg viewBox = “0 0 300 300” width = “300” height = “300”> 7. 8. <! -- Generate a background --> 9. <g> 10. <path style = “fill: #eebb99” d = “M0, 0, h300 v300 h-300 z”/> 11. </g> 12. 13. <! -- Circle shape and attributes --> 14. <g> 15. 16. <circle style = “fill: green;” cx = “150 “ cy = “150” r = “50”> 17. <animate attributeName = “opacity” attributeType = “CSS” 18. from = “0” to = “1” dur = “6s” /> 19. </circle> 20. 21. <! -- Rectangle shape and attributes --> 22. 23. <rect style = “fill: blue: stroke: white” 24. x = “50” y = “0” width = “100” height = “100” 25. <animate attributeName = “y” begin = “mouseover” dur = “2s” 26. values = “0; -50; 0; 20; 0; -10; 0; 5; 0; -3; 0; 1; 0” /> 27. </rect> 28. 29. <! -- Text value and attributes --> 30. 31. <text style = “fill: red; font-size: 24pt” 32. x = “25” y = “250” > Welcome to SVG! 33. <animateColor attributeName = “fill” 34. attributeType = “CSS” values = “red;blue;yellow;green;red” 35. dur = “10s” repeatCount = “indefinite”/> 36. </text> 37. </g> 38. </svg>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 182
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Fig. SVG document example Line 6 contains the root element svg for the SVG document. Attribute viewBox sets theviewing area for the document. The first two numbers in the string are the x-and y-coordinates ofthe upper-left corner of the viewing area, and the last two numbers are the width and height of theviewing area. Attribute width specifies the width of the image, and attribute height specifies theheight of the image. Element g groups elements of an SVG document. Line 10 uses element path to create theoutline of the box that serves as the background of the image. Attribute styles uses CSS propertyfill to fill the inside of the box with the color #eebb99. Attribute d defines the points of the box.Property M specifies the starting coordinates (0, 0) of the path. Property h specifies that the nextpoint is horizontally aligned with the current point and spaced 300 pixels to the right of thecurrent point (300, 0). Property v specifies that the next point is vertically aligned with the currentpoint and is spaced 300 pixels below it (300, 300). Property h then places a point 300 pixels to theleft of the current point. Property z sets the path to connect the first and last points, thus closingthe box. Lines 14 – 37 group three elements: a circle, a rectangle and a text element. Lines 16 – 19create a circle with element circle. The circle has a center at (150, 150) and a radius (attribute r) of50 pixels. The circle is filled green, with 50% opacity. The animate element contained within thecircle element specifies an opacity transformation from 0 (completely transparent) to 1 (completelyopaque) over a period of two seconds, determined by the dur attribute. The attributeattributeName of the animate element specifies the attribute to be altered, such as opacity and theattributeType determines the type of attribute being altered. We set attributeType to CSS becausewe are altering a CSS property. Lines 23 – 27 use element rect to creat a rectangle. The rectangle’s upper-left point isdetermined using attributes x and y. Attribute width sets the width of the rectangle, and attributeheight sets the height of the rectangle. Element animate (lines 25-26) adjusts the rectangle’s y valueover a two-second period (specified by the dur attribute) each time the user rolls over theVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 183
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHrectangle with the mouse (specified by attribute begin = “mouseover”). Attribute values specifiesthe y values between which the rectangle oscillates. Lines 31 – 36 create text in the SVG image with element text. The format of the text isdefined using attribute style. In this case, the text is initially colored red, with a font size of 24point. The associated animateColor element (lines 33-35) creates a colorchanging effect in the text.The text’s fill attribute varies between the colors specified by attribute values over ten seconds. Figure contains a more complex SVG image that simulates the Earth and Moon rotatingaround the Sun. This example also uses SVG’s animation feature. 1. <?xml version = “1.0”?> 2. 3. <! -- Fig. : planet.svg --> 4. <! -- Planetary motion with SVG --> 5. 6. <svg viewBox = “-500 -500 1000 1000”> 7. <g id = “background”> 8. <path style = “fill: black” 9. d = “M -2000 -2000 H 2000 V 2000 H -2000 Z” /> 10. </g> 11. 12. <circle id = “sun” style = “fill: yellow” 13. cx = “0” cy = “0” r = “100” /> 14. 15. <g> 16. <animateTransform attributeName = “transform” 17. type = “rotate” dur = “80s” from = “0” to = “360” 18. repeatCount = “indefinite” /> 19. 20. <circle id = “earth” style = “fill: blue” 21. cx = “400” cy = “0” r = “40” /> 22. 23. <g transform = “translate( 400 0 )”> 24. <circle id = “moon” style = “fill: white” 25. cx = “70” cy = “0” r = “10”> 26. <animateTransform attributeName = “transform” 27. type = “rotate” dur = “20s” from = “360” 28. to = “0” repeatCount = “indefinite” /> 29. </circle> 30. </g> 31. </g> 32. </svg>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 184
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Line 8 – 9 create a box for the background that is much larger than the viewable size.Attribute d has properties H and V that specify absolute coordinates for the path. Thus, thecoordinates of the box are (-2000, -2000), (2000, -2000), (2000, 2000) and (-2000, 2000). Lines 12 – 13 create a yellow circle with a radius of 100 pixels at coordinate (0, 0) torepresent the Sun. Line 15 defines element g, which groups together the circles representing theEarth and Moon. Lines 16-18 use element animateTransform, which changes the attribute of theparent element (i.e., element g) specified in attribute attributeName (i.e., attribute transform).Attribute type defines the property of the attribute that changes (i.e. rotate). The initial and finalvalues of the transformation are set by attributes from and to. Attribute dur sets the time (i.e. 80seconds) within which the change from the initial to the final values should occur, and attributerepeatCount sets the number of times to perform this transformation. In our example, we rotatethe group element, which contains the circle elements earth and moon, from 0 degrees to 360degrees in 80 seconds, repeating the rotation indefinitely (i.e. continuously). Fig. SVG document with animated elements Lines 20 – 21 create a blue circle with a radius of 40 pixels at coordinates (400, 0). When theVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 185
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHgroup rotates, this circle’s center stays at a distance of 400 pixels from the origin (0, 0). Line 23 uses element g to group the circle element that represents the Moon. This elementhas attribute transform, which translates (shifts) the group element 400 pixels to the right, thuscentering the group on the blue circle. Please refer to the SCG specification, available atwww.w3.org/TR/2003/REC-SVG11-20030114 / for information on other transformations. Thewhite circle (the Moon) in lines 24-25 has a child animateTransform element in lines 26-28 thatrotates the Moon 360 degrees counterclockwise around the Earth every 20 seconds.7. Explain in detail about HTTP Request Types.HTTP Request Types The two most common HTTP request types (also known as request methods) are get andpost. A get request typically gets (or retrieves) information from a server. Common uses of getrequests are to retrieve an HTML document or an image, or to fetch search results based on a user-submitted search term. A post request typically posts (or sends) data to a server. Common uses ofpost requests are to send information to a server, such as authentication information or data froma form that gathers user input. An HTTP request often posts data to a server-side form handler that processes the data. Forexample, when a user performs a search or participates in a Web-based survey, the Web serverreceives the information specified in the XHTML form as part of the request. Get requests andpost requests can both be used to send form data to a Web server, yet each type sends theinformation differently. A get request sends information to the server as part of the URL (e.g., www.search-engine.com/search?name=value), where search is the name of a server-side form handler, name isthe name of a variable in an XHTML form and value is the value assigned to that variable. Noticethe ? in the preceding URL. A? separates the query string from the rest of the URL in a get request.A name/value pair is passed to the server with the name and the value separated by an equal sign(=). If more than one name/value pair is submitted, each pair is separated by an ampersand (&).The server uses data passed in a query string to retrieve an appropriate resource from the server.The server then sends a response to the client. A get request may be initiated by submitting an XHTML form whose method attribute isset to “get”. Suppose a search engine’s Web page contains a form element with theattributesmethod = “get” and action = “search”, and that includes a text field named“searchTerm”. A search for the term “Massachusetts” might send a get request for the URLwww.searchengine.com/search?searchTerm=Massachusetts. The server would then perform asearch for the value Massachusetts and return a Web page containing search results to the user. A post request is specified in an XHTML form by the method “post”. The post methodsends form data as an HTTP message, not as part of the URL. Because a get request limits theVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 186
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHquery string (i.e., everything to the right of the ?) to 2048 characters, it is often necessary to sendlarge pieces of information using the post method. The post method is also sometimes preferredbecause it hides the submitted data from the user by embedding it an HTTP message. If a formsubmits several hidden input values along with user-submitted data, the post method mightgenerate the URL www.searchengine.com/search . The form data still reaches the server and isprocessed in a similar fashion to a get request but the user does not see the exact information sent. The data sent in a post request is not part of the URL and cannot easily be seen by the user.Forms that contain many fields are submitted most often by a post request. Sensitive form fields,such as passwords, usually are sent using this request type. Browsers often cache (save on disk) Web pages so they can quickly reload the pages. Ifthere are no changes between the last version stored in the cache and the current version on theWeb, this helps speed up your browsing experience. The browser first asks the server if thedocument has changed or expired since the date the file was cached. If not, the browser loads thedocument from the cache. Thus, the browser minimizes the amount of data that must bedownloaded for you to view a Web page. Browsers typically do not cache the server’s response toa post request, because the next post might not return the same result. For example, in a survey,many users could visit the same Web page and respond to a question. The survey results couldthen be displayed for the user. Each new response changes the overall results of the survey. When you use a Web-based search engine, the browser normally supplies the informationyou specify in an HTML form to the search engine with a get request. The search engine performsthe search, then returns the results to you as a Web page. Such pages are often cached by thebrowser in case you perform the same search again. As with post requests, get requests can supplyparameters as part of the request to the Web server.8. How does a Web server play a vital role in a Multi-tier Application and make a comparisonof client side scripting verses server side scripting? A Web server is part of a multi-tier application, sometimes referred to as an n-tierapplication. Multi-tier applications divide functionality into separate tiers (i.e., logical groupingsof functionality). Tiers can be located on the same computer or on separate computers. Figurepresents the basic structure of a three-tier application. The information tier (also called the data tier or the bottom tier) maintains data for theapplication. This tier typically stores data in a relational database management system (RDBMS).We discuss RDBMS in further detail Database: SQL, MySQL, DBI and ADO.NET. For example, aretail store may have a database for product information, such as descriptions, prices andquantities in stock. The same database also may contain customer information, such as usernames, billing addresses and credit-card numbers.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 187
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Fig. Three-tier application model The middle tier implements business logic and presentation logic to control interactionsbetween application clients and application data. The middle tier acts as an intermediary betweendata in the information tier and the application clients. The middle-tier controller logic processesclient requests from the top tier (e.g., a request to view a product catalog) and retrieves data fromthe database. The middle-tier presentation logic then processes data from the information tier andpresents the content to the client. This layer often is divided into its (two logical components,hence the term n-tier application. Business logic in the middle tier enforces business rules and ensures that data is reliable(i.e., edited for appropriateness) before updating the database or presenting data to a user.Business rules dictate how clients can and cannot access application data and how applicationsprocess data. The middle tier also implements the application’s presentation logic. Webapplications typically present information to clients as XHTML documents (older applicationspresent information as HTML). The client tier, or top tier, is the application’s user interface. Uses interact directly with theapplication through the client tier, which is typically a Web browser, keyboard and mouse. Theclient interacts with the middle tier to make requests and to retrieve data from the informationtier. The client then display the data retrieved from the middle tier to the user. The client tiernever directly interacts with the information tier.Client-Side Scripting versus Server-Side Scripting In earlier, we focused on client-side scripting with JavaScript. Client-side scripting validatesuser input, accesses the browser and enhances Web pages with Dynamic HTML, ActiveX controlsand Java applets (client-side Java programs that execute in a browser). Client-side validationreduces the number of requests that need to be passed to the server. Interactivity allows users tomake decisions, click buttons, play games, and so on-making the Web-site experience moreinteresting. Client-side scripts can access the browser, use features specific to the browser andmanipulate browser documents.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 188
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Client-side scripting does have limitations, such as browser dependency; the browser orscripting host must support the scripting language. Another issue is that client-side scripts areviewable to the client (e.g., by using the View menu’s Source option in Internet Explorer). SomeWeb developers do not advocate this because users potentially can view proprietary scriptingcode. Sensitive information, such as passwords or other personally – identifiable data, should notbe stored or validated on the client. JavaScript is the most popular client-side scripting language and is supported by bothMicrosoft Internet Explorer and Netscape Navigator. To conserve server resources and minimize Internet traffic and delays, perform as muchprocessing as possible on the client side. Programmers have greater flexibility when using server-side scripts. Scripts executed onthe server often generate custom responses for clients. For example, a client might connect to anairline’s Web server and request a list of all flights from Boston to San Antonio betweenSeptember 19th and November 5th. The server queries the database, dynamically generates XHTMLcontent containing the flight list and sends the XHTML to the client. This technology allows clientsto obtain the most current flight information from the database by connecting to an airline’s Webserver. Server-side scripting languages have a wider range of programmatic capabilities than theirclient-side equivalents. For example, server-side scripts often can access the server’s file directorystructure, whereas client-side scripts cannot access the client’s directories. Server-side scripts also have access to server-side software that extends server functionality– Microsoft Web servers use ISAPI (Internet Server Application Program Interface) Extensions andApache Web servers use modules. Components and modules range from programming languagesupport to counting the number of Web page hits.9. What is IIS? How it is used for maintaining the Internet Information Services?Microsoft Internet Information Service (IIS) Microsoft Internet Information Services (IIS) is an enterprise-level Web server that isincluded with several versions of Windows. Installing IIS on a machine allows that computer toserve documents. For instructions on how to install IIS, please visitwww.deitel.com/books/iw3HTP3/index.html. The remainder of this section assumes that eitherIIS 5.0 or IIS 6.0 is installed on a system. The following two subsections explain how to configure IIS 5.0 and IIS 6.0 to servedocuments via HTTP. If you are using Windows 2000 or Windows XI. If you are using a version ofWindows newer than Windows XP.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 189
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHMicrosoft Internet Information Services (IIS) 5.0 After installation, start the Internet Services Manager by opening the Control Panel, doubleclicking the Administrative Tools icon and double clicking the Internet Services Manager icon.This opens the Internet Information Services window (Figure) – the administration program forIIS 5.0. Alternatively, typing inetmgr at the Start menu’s Run... command prompt opens theInternet Services Manager. Place the documents that will be requested from IIS either in thedefault directory (i.e., C:Inetpubwwwroot) or in a virtual directory. A virtual directory is analias for an existing directory that resides on the local machine (e.g., C:) or on the network. Whena server is accessed from a Web browser, only the virtual directories are visible to the client. In the Internet Information Services window, the left pane contains the Web server’sdirectory structure. The name of the machine running IIS (e.g., carpenterant) is listed underInternet Information Services. Clicking the + symbol to the left of the machine name displaysDefault FTP Site, Default Web Site and Default SMTP Virtual Server. The Default FTP Site is a File Transfer Protocol (FTP) site; the Default Web Site is an HTTPsite. Although FTP and HTTP permit transferring documents between a computer and a Webserver, FTP provides a faster and more persistent connection between the client and the Webserver than HTTP. HTTP is used most frequently to request documents from Web servers. FTP isoften used for transferring large files across the Internet. The Default SMTP Virtual Server allowsyou to create a Simple Mail Transfer Protocol (SMTP) server for sending electronic mail (e-mail). Fig. Internet Information Services window of Internet Services Manager (IIS 5.0) Expand the Default Web Site directory by clicking the + to the left of it. In this directory, wewill create a virtual directory for the HTTP Web site. The Default Web Site sub directories arevirtual directories. Most Web documents are placed in the Web Server’s Webpub (Webpublishing) directory. For this example, we create our virtual directory in the Webpub virtualdirectory. To create a virtual directory within this directory, right click Webpub, select New, thenVirtual Directory. This starts the Virtual Directory Creation Wizard, which guides users throughcreating a virtual directory. To begin, click Next in the Virtual Directory Creation Wizard welcome dialog. In theVirtual Directory Alias dialog, enter a name for the virtual directory and click Next. We use theVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 190
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHname Test, although the virtual directory may have any name provided that it does not conflictwith an existing virtual directory name. Fig. Virtual Directory Creation Wizard welcome dialog Fig. Virtual Directory Alias dialog of the Virtual Directory Creation Wizard In the Web Site Content Directory dialog, enter the path for the directory containing thedocuments that clients will view. We created a directory named C: Examples that serves ourdocuments, although any existing directory would be appropriate. If necessary, select the BrowseVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 191
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHbutton to navigate to the desired directory. Click Next. The Access Permissions dialog presents the virtual directory security level choices. Choosethe access level appropriate for a Web document. The Read option allows users to read anddownload files located within the directory. The Run scripts (such as ASP) option allows scripts torun in the directory. The Execute (such as ISAPI applications or CGI) option allows applications torun in the directory. The Write option allows a Web page to write to files on the server. TheBrowse option allows users to see a full list of the files in the folder through a Web browser. Bydefault, Read and Run scripts are enabled. Click Next. Fig. Web Site Content Directory dialog of the Virtual Directory Creation Wizard Fig. Access Permissions dialog of the Virtual Directory Creation Wizard Click Finish to complete the creation of the virtual directory and exit the Virtual DirectoryVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 192
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHCreation Wizard. The newly created virtual directory, Test, is now located under the Webpubvirtual directory. Now the IIS server is configured to serve documents through the Rest virtualdirectory. The URL http://localhost/WebPub/ChapterTest now references theC:ChapterExamples directory. To start IIS so it can serve content, right click Default Web Site and select Start. If you needto stop IIS right click Default Web Site (or Default FTP site or Default SMTP Virtual Server) andselect Stop. The Web server is not available to serve content if it is stopped.Microsoft Internet Information Services (IIS) 6.0 After installation, start the Internet Information Services (IIS) Manager by opening theControl Panel, double clicking the Administrative Tools icon and double clicking the InternetInformation Services (IIS) Manager icon. This opens the Internet Information Services (IIS)Manager window – the administration program for IIS 6.0. Place the documents that will berequested from IIS either in the default directory (i.e., C:inetpubwwwroot) or in a virtualdirectory. A virtual directory is an alias for an existing directory that resides on the local machine(e.g., C:) or on the network. When a server is being accessed from a Web browser only the virtualdirectories are seen by the client. Fig. Internet Information (IIS) Services Manager window (IIS 6.0) In the Internet Information Services (IIS) Manager window, the left pane contains the Webserver’s directory structure. The name of the machine running IIS (e.g., CARPENTERANT) islisted under Internet Information Services. Clicking the + symbol to the left of the machine namedisplays Application Pools, Web Sites, Web Server Extensions and Default SMTP Virtual Server. The Application Pools and Web Server Extensions folders contain tools for configuringadvanced features of IIS 6.0. The Default SMTP Virtual Server allows you to create a Simple MailTransfer Protocol (SMTP) server for sending electronic mail (e-mail).VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 193
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Expand the Web Sites directory by clicking the + to the left of it. This should displayDefault Web Site and Administration. Expand the Default Web Site directory by clicking the + tothe left of it. Any subdirectories in this directory refer to virtual directories. By default, none exist.For this example, we create a virtual directory from which we request our documents. To create avirtual directory, right click Default Web Site, select New and then Virtual Directory. This startsthe Virtual Directory Creation Wizard, which guides users through the virtual directory creationprocess. Fig. Virtual Directory Creation Wizard welcome dialog To begin, click Next in the Virtual Directory Creation Wizard welcome dialog. In theVirtual Directory Alias dialog, enter a name for the virtual directory and click Next. We use thename ChapterTest, although the virtual directory may have any name provided that it does notconflict with an existing virtual directory name. Fig. Virtual Directory Alias dialog of the Virtual Directory Creation Wizard In the Web Site Content Directory dialog, enter the path for the directory containing theVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 194
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHdocuments that clients will view. We created a directory named C:ChapterExamples that servesour documents, although any existing directory would be appropriate. If necessary, select theBrowse button to navigate to the desired directory, Click Next. The Access Permissions dialog presents the virtual directory security level choices. Choosethe access level appropriate for a Web document. The Read option allows users to read anddownload files located within the directory. The Run scripts (such as ASP) option allows scripts torun in the directory. The Execute (such as ISAPI applications or CGI) option allows applications torun in the directory. The Write option allows a Web page to write to files on the server. TheBrowse option allows users to see a full list of the files in the folder through a Web browser. Bydefault, Read and Run scripts are enabled. Click Next. Fig. Web Site Content Directory dialog of the Virtual Directory Creation Wizard Fig. Access Permissions dialog of the Virtual Directory Creation Wizard Click Finish to complete the creation of the virtual directory and exit the Virtual DirectoryCreation Wizard. The newly created virtual directory, ChapterTest, is now located in the DefaultWeb Site. Now the IIS server is configured to serve documents ChapterTest now references theVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 195
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHC:ChapterExamples directory. To start IIS, right click Default Web Site and select Start. To stop IIS, right click Default WebSite (or Default SMTP Virtual Server) and select Stop.10. Discuss in detail about the Apache Web server.Apache Web server The Apache Web server, maintained by the Apache Software Foundation, is currently themost popular Web server because of its stability, efficiency, portability, security and small size. Itis an open-source product (i.e., software that can be freely obtained and customized) that runs onUNIX, Linux, Mac OS X, Windows and numerous other platforms. To obtain the Apache Web server for a variety of platforms, visithttpd.apache.org/download.cgi. The CD that accompanies this book includes Apache 2.0.47 forWindows. For instructions on installing this version of the Apache Web server, please visit http://httpd.apache.org/docs-2.0/platform/windows.html After installing the Apache Web server, start the application. From the Start menu, selectPrograms>Apache HTTPD Server>Control Apache Server> Start. If the server starts successfully,a command-prompt window opens stating that the service is starting. To stop the Apache Webserver, from the Start menu, select Programs > Apache HTTPD Server> Control Apache Server >Stop. Fig. Apache Web server starting. (Courtesy of The Apache Software Foundation, http://www.apache.org/.) All documents that will be requested from an Apache Web server must either be in thedefault directory (i.e., C:Program FilesApache GroupApache2htdocs) or in a directory forwhich an Apache Web server alias is configured. An alias is Apache’s version of a Microsoft IISvirtual directory. It is a pointer to an existing directory that resides on the local machine or on thenetwork. Instead of using an administrative utility or set of wizards, we configure the Apache Webserver by editing the httpd.conf file. This file contains all the information that the Apache Webserver needs to run correctly and serve Web documents. The httpd.conf file is located in the confsubdirectory of Apache’s installation directory. To edit this file, either go to the conf directory inthe Apache Web server directory and open the httpd.conf in a text editor, or go to the Start menu VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 196
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHand select Programs > Apache HTTP Server [version number] > Configure Apache Server > Editthe Apache httpd.conf Configuration File. The httpd.conf file opens in Notepad. httpd.conf is alarge text file with all of Apache Web server’s configuration information. In this file, any line thatstarts with a # is a comment that explains the various configuration options. Place a small comment near any changes you make to the Apache httpd.conf file. An introductory comment at the top of the httpd.conf file explains how the file isorganized. After this comment, the configuration information starts with the most important,global settings. These should have been configured correctly by the Apache installer. Scroll downin the file until you have reached the section titled Aliases. This section begins with the followingtext: # Aliases: Add here as many aliases as you need.... To create an alias, we add the following lines below the comment. #This alias is for the examples used in Chapter Alias /ChapterTest “C:/ChapterExamples” This creates an alias called ChapterTest that points to the physical directoryC:ChapterExamples. We use the name ChapterTest, but any name that does not conflict with anexisting alias is allowed. We created a directory named C:ChapterExamples that serves ourdocuments, although any existing directory would be appropriate. Note that in both the name ofthe alias and the path of the directory to which the alias points we must use forward slashes (/),not back slashes (). If you place a forward slash (/) at the end of the alias name, Apache will require this slashto be present when a document is requested from the server. For example, if you name youralias /myExamples/, then a user request for http://localhost/myExamples will not work asexpected. The user will need to request http://localhost/myExamples/to access the alias. If theforward slash (/) is not placed at the end of the alias name. Apache will not require this slash, andwill work as expected whether or not it is present in the request. With the alias line added to the httpd.conf file, the Apache Web server is set up to serve ourWeb document from the C:ChapterExamples directory. We need to restart the server so that ourchanges to httpd.conf file will take effect. Then we will be ready to request documents from theApache Web server. To restart the server, we must first stop it and start it again. Please refer to thebeginning of this section for instructions on how to stop and start the Apache Web server.11) Discuss in detail about the different modes of Online Payments. Secure electronic funds transfer (EFT) is crucial to e-commerce. Credit-card payments,digital cash and e-wallets, smart cards, micropayments and electronic bill presentment andVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 197
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHpayment are methods for conducting online transactions. Many companies offer products,software and services that enable monetary transactions on the Web.Credit-Card Payment Although credit cards are a popular form of online payment, many people resist onlinecredit-card transactions because of security concerns. Customers fear credit-card fraud bymerchants and third parties. However, most credit cards, such as Visa® , Mastercard® andAmerican Express® , have features that enable secure online and offline payments. To acceptcredit-card payments, a merchant must have a merchant account with a bank. Traditionalmerchant accounts accept only point-of-sale (POS) transactions, that is, transactions that occurwhen customers present credit cards at stores. However, the growth of e-commerce has resultedin the establishment of specialized Internet merchant accounts that handle online credit-cardtransactions. These consist of card-not-present (CNP) transactions. For example, when users makecredit-card purchases through the Internet, they can provide the card numbers and expirationdates, but the merchant does not see the actual cards involved in the transactions.Amerchantaccount can be established through either a bank or a third-party service.19Digital Cash and e-Wallets Digital cash is one example of digital currency. It is stored electronically and can be used tomake online electronic payments. Digital-cash accounts are similar to traditional bank accounts;consumers deposit money into digital-cash accounts for use in digital transactions. Often, digitalcash is used in conjunction with other payment technologies, such as digital wallets. In addition toproviding a payment alternative for customers with security concerns regarding online credit-cardtransactions, digital cash allows people who do not have credit cards to shop online (see thePayPal feature).PayPal, Inc. PayPal ( www.paypal.com) was founded in 1998 as an intermediate solution for userspurchasing products and services online. PayPal allows customers to conduct transactions on theInternet quickly and easily without any need to submit credit-card or back account informationevery time they wish to spend money on the Web. To use PayPal, users are required to establishan account using a credit card or backed by their account at a financial institution. Once anaccount is set up, users can, among other things, purchase products or services online, pay bills,and transfer money to other people via PayPal’s partner Web sites. PayPal currently has over 30million users in 38 different countries and is one of the leading businesses that conduct andcontrol online payment.20 eBay, the largest auction site on the Internet, purchased PayPal inOctober 2002 for $1.5 billion. eBay now uses PayPal to conduct its auction transactions over theInternet.21 To facilitate the credit-card order process, many companies are introducing electronicwallet services. E-wallets keep track of billing and shipping information so that it can be enteredVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 198
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHwith one click at participating merchants’ sites. E-wallets also store e-checks, ecash and credit-cardinformation for multiple cards.Micropayments Merchants are required to pay a fee for each credit-card transaction they process, whichbecomes costly when customers purchase inexpensive items. Sometimes, the cost of an item isactually lower than the standard transaction fee, causing the merchant to incur losses.Micropayments (payments that generally do not exceed $5) enable ways for nominally pricedproducts and services (e.g., music, pictures, texts or videos) to be sold profitably over the Web. Forinstance, a phone bill is essentially an aggregation of micropayments that are charged periodicallyat set intervals to justify the transaction fee. To offer micropayment processing, some companieshave formed strategic partnerships with telephone carriers and utility companies. In 2002, contentpurchased through micropayments grew faster than any other category of fee-based content, assales grew ten times over the previous year to $3 million, and spending for content in the thirdquarter of 2002 alone was up 132% over the preceding year to $56 million.22 e-Fact 38.338.3Smart Cards A smart card generally looks like a credit card and can serve many different functions, fromauthentication to data storage. The most popular smart cards are memory cards andmicroprocessor cards. Memory cards are similar to floppy disks. Microprocessor cards are similarto small computers, with operating systems, security and storage. Smart cards also have differentinterfaces with which they interact with reading devices. One type of interface is a contactinterface, in which a smart card is inserted into a reading device and physical contact between thedevice and the card is necessary (For example American Express® ’s Blue). The alternative to thismethod is a contactless interface, in which data is transferred to a reader via an embeddedwireless device in the card, without the card and the device having to make physical contact.24 Contactless cards are convenient for transportation services, such as automatic tollpayments. A contactless smart card, when placed in a device in a car, will charge the user’saccount as he or she drives through toll booths (such as FAST LANE® , E-ZPassSM used inMassachusetts and New York, respectively and FasTRAK™ used in California).25 Smart cardsstore credit-card numbers, personal contact information, and so on. Each smart card is used incombination with a personal identification number ( PIN). This application provides two levelsof security by requiring the user to both possess a smart card and know the corresponding PIN toaccess the information stored on the card. As an added measure of security, some microprocessorcards will delete or corrupt stored data if malicious attempts at tampering with the card occur. Inaddition, smart cards can require users to enter passwords, thus offering a higher level of securitythan credit cards. Information maintained on smart cards can be designated as “read only” or as“no access.” The cards can also be enhanced with additional security features, such as encryptionand photo identification.12) Discuss in detail about the E-Business Model.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 199
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH The transition of a business into an e-business provides many benefits. An e-business canoffer personalization, effective customer service and streamlined supply-chain management (thestrategic management of distribution channels and the processes that support them). In thissection, we explore the different types of businesses operating on the Internet, and introduce thetechnologies needed to build and run an e-commerce Web site. Although the term “e-commerce”is relatively new (it was coined in the early 1990s), large corporations have been conducting defacto e-commerce for decades by networking their computing systems with those of businesspartners and clients. For example, the banking industry uses Electronic Funds Transfer (EFT) totransfer money between accounts. In addition, many companies employ Electronic DataInterchange (EDI), which facilitates the standardization of such business forms as purchase ordersand invoices, allowing companies to share information with customers, vendors and businesspartners electronically. Many companies are using XML to enhance or improve EDI as well (XMLis discussed later in this chapter and in Chapter 20). Until recently, e-commerce was feasible onlyfor large companies. However, by using the Internet and the Web, even the smallest businessescan use EDI. Amazon.com® , eBay® , Yahoo!® and other e-commerce sites have assisted indefining industry categories and business models on the Web. Entrepreneurs starting e-businessesand people interested in e-commerce should be aware of the various e-business models currentlyin use. In the subsections that follow, we review the storefront model, the auction model, dynamicpricing models, the portal model and other Web business models.Storefront Model. The storefront model is what many people think of when they hear the word “e-business.”By providing a combination of transaction processing, security, online payment and informationstorage, the storefront model enables merchants to sell their products online. This model is a basicform of e-commerce in which buyers and sellers interact directly. To conduct storefront e-commerce, merchants must organize online product catalogs, take orders through their Web sites,accept payments securely, send merchandise to customers and manage customer data (such ascustomer profiles). They must also market their sites to potential customers through variousmedia. Examples include www.gap.com, www.restaurant.com, www.walmart.com,www.barnesandnoble.com and more.Shopping-Cart Technology One of the most commonly used e-commerce enablers is the shopping cart. This order-processing technology allows customers to accumulate items they wish to buy as they browse ane-business Web site. (See the Amazon.com feature.) Support for the shopping cart is provided by aproduct catalog, which resides on the merchant server in the form of a database. The merchantserver is the data storage and management system employed by the merchant. Often, a networkof computers performs all the functions necessary to run a Web site. A database is a section of themerchant server designed to store and report on large amounts of information. For example, adatabase for an online clothing retailer would typically include such product specifications asitem description, size, availability, shipping information, stock level and on order information.Databases also store customer information, including names, addresses, credit-card data and pastVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 200
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHpurchases. The Amazon.com feature contains further information regarding these technologiesand their implementations. Most Web sites that conduct e-business over the Internet today useshopping-cart technology, including www.eddiebauer.com®, www.kbtoys.com,www.niketown.com, www.sears.com and www.jcrew.com.Auction Model The Web offers a wide variety of auction sites, as well as sites that search auction sites topinpoint the lowest prices on available items. Usually, auction sites act as forums through whichInternet users can assume the role of either seller or bidder. Sellers can post items they wish tosell, the minimum prices they require to sell the items and deadlines to close the auctions. Somesites allow users to provide additional information, such as a photograph or a description of anitem’s condition. Bidders may search the site for items they are seeking, view the current biddingactivity and place bids—usually in designated increments. Some sites automate the biddingprocess by allowing bidders to submit the maximum prices they will pay for auction items. Onsuch sites, an electronic system continues bidding for a bidder until the bidder wins the auction orthe auction surpasses the bidder’s maximum bid price. One of the most popular auction sites onthe Web today is eBay ( www.ebay.com). (Auction technology is explained in more depth in theeBay feature.) The reverse-auction model allows buyers to set prices that sellers compete tomatch, or even beat. One example of a reverse-auction site is priceline.com, which is a popular sitefor purchasing airline tickets and making travel reservations. Usually, Priceline can processbuyers’ bids within one hour. A faster bidding option is available to sellers who are willing to setreserve prices. Although a reserve price is the lowest price that a seller will accept, the seller canset a reserve price that is higher than the minimum bid.Portal Model Portal sites offer visitors the chance to find almost anything they are looking for in oneplace. They often provide news, sports and weather information, as well as the ability to searchthe Web. When most people hear the word “portal,” they think of search engines. Search enginesare horizontal portals, or portals that aggregate information on a broad range of topics. Otherportals are more specific, offering a great deal of information pertaining to a single area of interest;such portals are called vertical portals. Online shopping is a popular feature of many majorportals. Sites such as About.com® , altavista.com and Yahoo.com® provide shopping pages thatlink users to thousands of sites carrying a variety of products. Portals that link consumers toonline merchants, online shopping malls and auction sites provide several advantages. Theseportals help users collect information on products and services, thus facilitating comparisonshopping. Portals also allow users to browse independently owned storefronts—a capability thatsome online shopping malls fail to provide. For example, Yahoo! permits users to browse a varietyof sites while maintaining the convenience of paying through their Yahoo! account.Name-Your-Price Model The name-your-price business model empowers customers by allowing them to state theVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 201
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHprice they are willing to pay for products and services. Many e-businesses that offer this servicehave formed partnerships with leaders of various industries, such as travel, lending and retail.The online business passes each customer’s price request to an appropriate industry partner, whodecides whether to sell the product or service to the customer at the stated price. A customerwhose price is rejected can offer another price. However, if a price is accepted, the customer isobligated to make the purchase. For example, Priceline.com allows users to submit prices they arewilling to pay for airline tickets. However, before the request is submitted, users must enter theirpurchasing information, so that if their price is accepted by one of Priceline.com’s affiliate airlines,the user is required to purchase the ticket. On average, the user receives an e-mail response withinone hour indicating whether the request is accepted or denied. If no affiliates are willing to offeran airline ticket to a user’s destination for the specified price, the user can change the price andresubmit the bid. Many e-businesses use intelligent agents (e.g., shopping bots) to enhance theirWeb sites. Intelligent agents are programs that search, arrange and analyze large amounts of data.Shopping bots can scour data contained within a single database or search the entire Web to findproducts and prices.Comparison-Pricing Model The comparison-pricing model allows customers to poll various merchants in search of thelowest price for a desired product or service. Comparison-pricing sites often generate revenuefrom partnerships with merchants. For example, Travelocity.com allows users to search multiplecarriers and merchants for the best prices on airfares, hotels, rental cars, and other products. Otherexamples of Web sites that offer these services include www.shopping.com, www.pricewatch.comand www.froogle.com (see the Froogle feature). Although such sites can be convenient, usersshould be careful when employing these services, because they might not be getting the bestprices available on the Web. Some services promote the products of merchants with which theyhave partnerships.Bartering Model Another popular e-business model is bartering, or the offering of one item in exchange foranother. ITEX.com (formerly Ubarter.com™ ) allows individuals and companies to trade productsthrough its site. At the site, traders make initial offers with the intention of bartering until theyreach final agreements with buyers. To conduct most transactions using this business model onthe Web, potential customers send their pricing preferences to the merchant, who evaluates theoffers. Final agreements often involve a combination of bartering and monetary payment. UNIT – IV PART - A1) What is ASP and Give the features of ASP?VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 202
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 1. An ASP file has the file extension.asp and contains XHTML tags and scripting code. 2. Although other languages, like JavaScript, can be used for ASP scripting, VBScript is the most widely used. 3. ASP is a Microsoft-specific technology for sending dynamic Web content to the client. 4. An Active Server Page processes the request (which often includes interacting with a database) and returns the results to the client—normally in the form of an XHTML document, but other data formats (e.g., images, binary data) can be returned as well. 5. When a client requests an ASP document, it is loaded into memory and parsed (top to bottom) by a scripting engine named asp.dll. Script code is interpreted as it is encountered. 6. Active Server Pages provide several built-in objects to offer programmers straightforward methods for communicating with a Web browser, gathering data sent by an HTTP request and distinguishing between users.2) Mention the ASP Objects and their use. The Request object is commonly used to access the information passed by a get or postrequest. The Request object also provides access to cookies are stored on a client’s machine. TheResponse object sends information such as XHTML and text to the client. The Server objectprovides access to methods and properties on the server. Scripting delimiters <% and %>wrapped around the VBScript code indicate that the scripting code is executed on the server, notthe client. The optional @LANGUAGE processing directive indicates that the scripting engineneeded to interpret the scripting code. The Request object retrieves the form data posted to an ASPdocument. The application object provides two collections that is used to access the variables andobjects that are stored in the global application space. The session object provides two collectionsthat we can use to access the variables and object that are stored in the user’s local session space.3) What is FSO.Where it is used? File System Objects (FSOs) provide the programmer with the ability to manipulate files,directories and drives. FSOs also allow the programmer to read and write text and are an essentialelement for Active Server Pages that persist data.FSOs are objects in the Microsoft ScriptingRuntime Library. FSO types include FileSystemObject, File, Folder, Drive and TextStream. Theprogrammer can use FileSystemObjects to create directories, move files, and determine whether aDrive exists. The File object gathers information about files, manipulate files and open files. TheFolder object manipulates and gathers information about directories. The Drive object gathersinformation about drives.4) What is Session Tracking. How it is performed using the session object? The server performs session tracking by keeping track of when each client visits a site. Thefirst time a client connects to the server, he or she is assigned a unique session ID. When the clientmakes additional requests, the session ID is compared with the session IDs stored in the server’smemory. Active Server Pages use the Session object to manage sessions.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 203
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH5) What are Server Side Includes? Server-side includes can contain any type of information. Text files and XHTML files aretwo of the most common server-side include files. By convention, server-side include (SSI) filesend with the .shtml extension. Server-side includes are an excellent technique for reusing XHTML,Dynamic HTML, scripts and other programming elements.6) What are cookies? Cookies are small files sent by an Active Server Page as part of a response to a client.Cookies store information on the client’s computer for retrieval later in the same browsing sessionor in future browsing sessions. Developers often use data stored in cookies to customize Webpages.7) How ASP processes the Request & Response of a Client & Server. When an Active Server Page receives a request, the header includes the request type (e.g.,get or post) and cookies stored on the client machine by the server. When the server formulates itsresponse, the header information includes any cookies the server wants to store on the clientComputer. Depending on the maximum age of the cookie, the Web browser either maintains it forthe duration of the browsing session (i.e., until the user closes the Web browser) or stores it on theclient computer for future use.8) What is ADO and UDA? Active Server Pages can communicate with databases through ADO (ActiveX DataObjects). • The architecture of Microsoft Universal Data Access (UDA) can support high-performance data access to relational data sources, nonrelational data sources andmainframe/legacy data sources. ActiveX Data Objects (ADO) are simple object models thatprovide uniform access to any data source by interacting with OLE DB.9) Define I) Web Application ii) Web Serveri) Web applications are typically three-tier distributed applications, consisting of a user interface,business logic and database access.ii) Web servers contain the business logic that manipulates data from databases andcommunicates with client Web browsers.10) What is the function of the Err object in the session of a Cookie? When an error occurs in the script, Err object’s Number property contains an integerVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 204
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHrepresenting, which VBScript error has occurred. If an expiration date is not set for a cookie whenit is created, it is treated as a session cookie (i.e., it is destroyed when the browser is closed). Thecookie remains on the client’s machine until it expires, at which time the browser deletes it.11) How will you instantiate a server object?Server-side ActiveX components are instantiated by passing the name of the component as astring to the Server object’s method CreateObject.12. Define i) Data base system ii) Data base iii) Database management system iv) Relational Database i) Data base system provide file – processing capabilities and organize data in a manner that facilitates Sophisticated queries. ii) A data base is an integrated collection of centrally controlled data. iii) A data base management system (DBMS) provides mechanisms for storing and organizing data in a manner that is consistent with the data bases format. It enables programmers to access and store data without worrying about the internal representation of databases. iv) Relational Databases: Relational data base is composed of tables in lows and columns. Which allows relationships among items of data. It uses a language called as SQL to perform queries and to manipulate data some of the enterprise-level relational database systems include Microsoft SQL server oracleTM, Sybase, DB2, Informix and MySQL.13. What is i) primary key ii) foreign key of a table A table’s primary key uniquely identifies each row in the table. Every row must have avalue in the primary key – Rule of Entity Integrity and the value must be unique. A foreign key is a column (or set of columns) in a table which must match the primary keyof another table. The foreign key helps maintain the Rule of Referential Integrity – every value in aforeign key must appear in another table’s primary key. Foreign keys enable information frommultiple tables to be joined and presented to the user.14. Give the format of a selection query based in on the criteria with an eg. SQL uses the optional WHERE clause to specify the selection criteria for the query. Thesimplest query with selection criteria isVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 205
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH SELECT # FROM Table Name WHERE criteria The condition in the WHERE clause can contain operators <,>,<=,>=,=,<> and LIKEOperators LIKE matches a string using the wild card characters asterisk (*) and question mark (?).15. Write the query format for arranging the items in ascending and descending order. Query results can be arranged in ascending or descending order using the optional ORDERBY clause. The simplest form of an ORDER BY clause is SELECT * FROM Table Name ORDER BY column ASC SELECT * FROM Table Name ORDER BY column DESC In which ASC specifies ascending (lowest to highest) order. DESC specifies descending(highest to lowest) order and column represents the column used for sorting purposes.16. Give the SQL format for Insertion, updation and deletion.The basic form of an INSERT SQL statement is INSERT INTO Table name ( column Name1, column Name2, …) VALUES ( ‘value’, ‘ value2, …..) Where Table Name is the table in which the data will be inserted. Each column name to beupdated is specified in a comma-separated list in parentheses. The value for each column isspecified after the SQL keyword VALUES in another comma – separated list in parentheses.A basic UPDATE SQL statement has the form UPDATE Table Name SET column Name1=value1, column Name2=value2,… WHERE criteria In which Table Name is the table to update. The individual columns to update are specified(followed by an equal sign and a new value in single quotes) after the SET keyword, and theWHERE clauses determines that rows to update. Row(s) can be permanently deleted from an existing table by using the DELETE statement.the simplest form of a DELETE statement is DELETE FROM Table Name WHERE criteria In which Table Name is the table that contains the rows to be deleted, and the WHEREclauses determines the rows to be deleted.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 206
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH17. Give the features of MySQL. MySQL is a scalable, robust and enterprise – level relational database management system(RDBMS). It provides multithreading capabilities, supports a variety of programming languagesand handles large databases. MySQL is not a true open – source product. 1. Multithreading capabilities that enable the database to perform multiple tasks concurrently, allowing the server to process client requests efficiently. 2. Support for various programming languages (C,C++,Java,Perl, PHP, Coldfusion, Python, etc.). Later chapters demonstrate how to access a MySQL data base from perl (Chapet25), PHP (Chapter 26) and Python (Chapter 35). 3. Implementations of MySQL are available for Windows, Mac OS X, Linux and UNIX. 4. Full support of functions and operators within the SELECT and WHERE clauses of an SQL query that allow users to manipulate data. 5. The ability to access tables form different database by using a single query, increasing the efficiency of retrieving accurate and necessary information. 6. The ability to handle large data bases (e.g., tens of thousands of tables with millions of rows).18. What is primary key. How it enforces the Entity Integrity? A table’s primary key uniquely identifier each row in table. Every row must have a value inthe primary key, and the value must be unique. This is known as the Rule of Entity Integrity.19. What is foreign key. How does it maintain the rule of referential Integrity.Foreign key - a column or set of columns which must match the primary key of another table(e.g., publisher ID in the Publishers table). Programmers specify foreign keys when creating atable. The foreign key helps maintain the Rule of Referential Integrity: Every foreign-key valuemust appear in another table’s primary key. Foreign keys enable information from multiple tablesto be joined together for analysis purposes. A one-to-many relationship exists between a primarykey and its corresponding foreign keys. This means that foreign – key value can appear many timein its own table, but must appear exactly once as the primary key of another table.20. Mention some of the SQL keywords used to form a SQL query. SQL keyword Description SELECT Selects (retrieves) columns form one or more tables. FROM Specifies tables form which to get columns or delete rows. Required in every SELECT and DELETE statement. WHERE Specifies criteria that determine the rows to be retrieved.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 207
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH INNER JOIN Joins row from multiple tables to produce a single set of rows GROUP BY Specifies criteria for grouping rows. ORDER BY Specifies criteria for ordering rows. INSERT Inserts data into a specified table UPDATE Updates data in a specified table DELETE Deletes data from a specified table CREATE Creates a new table DROP Deletes an existing table. COUNT Returns the number of records that satisfy given search criteria.21. Give an example query to combine the ‘where’ and order By clause.The WHERE and ORDER BY clauses can be combined in one query. For example, the query SELECT isbn, title, edition Number, copyright, price FORM Titles WHERE title LIKE ‘*How to Program’ ORDER BY title ASCreturns the ISBN, title, edition number, copyright and price of each book in the Titles table thathas a title ending with “How to Program”; it lists these rows in ascending order by title.22. How will you perform merging of data from multiple Tables. It is necessary for analysis purposes to merge data form multiple tables into a single set ofdata. Referred to as Joining the tables, this is accomplished via an INNER JOIN operation in theSELECT query. An INNER JOIN merges rows from two or more tables by testing for matchingvalues in a column that is common to the tables. The simplest format of an INNER JOIN clause is: SELECT column Name1, column Name2,… FROM table 1 INNER JOIN table2 ON table1, column Name = table 2, column Name The ON part of the INNER JOIN clause specifies the columns from each table that arecompared to determine which rows are combined. For example, the following query produces alist of authors accompanied by the ISBN numbers for books written by each author: SELECT first Name, last Name, isbn FROM Authors INNER JOIN Author ISBN ON Authors, author ID= Author ISBN. Author ID ORDER BY last Name, first Name The query combines the first Name and last Name columns from table Authors and theVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 208
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHisbn column form table Author ISBN, sorting the results in ascending order by last Name and firstName. Note the use of the syntax table Name. column Name in the ON part of the INNER JOIN.This syntax ( called a qualified name) specifies the columns from each table that should becompare to joint he tables.23. What is XML? XML is a widely supported open technology (i.e., nonproprietary technology) forelectronic data exchange and storage. XML is actually a language used to create other markuplangauages to describe data in a structured manner. XML document contain only data, not formatting instructions, so applications that processXML documents must decide how to manipulate or display the document’s data. For example, aPDA ( personal digital assistant) may render an XML document differently than a wireless phoneor a desktop computer. Programmers use Extensible Style sheet Language (XSL) to specifyrendering instructions for different platforms.24. What is DTD? DTDs define the structural rules for an XML document. An XML document does notrequire a DTD, but validating XML parsers can use a DTD to ensure that an XML document hasthe proper structure. The DTD reference ( line 6) contains three items: the name of the rootelement that the DTD specifies (letter), the key word SYSTEM (which denotes an External DTD –a DTS declared in a separate file), and the DTD’s name add location (i.e., letter, dtd in the currentdirectory). DTD documents typically end with the . dtd extension. If an XML document conforms to its DTD or schema, then the XML document is valid.Parsers that cannot check for document conformity against the DTD / Schema are non validatingparser. If an XML parser (validating or non validating) can successfully process an XML parser(validating or nonvalidating) can successfully process an XML document that does not have aDTD /Schema. The XML document is well formed (i.e., it is syntactically correct). BY definition, avalid XML document is also a well – formed document.25. What do you mean by XML Namespace? An XML namespace is a collection of element and attribute names. Each namespace has aunique name that provides a means for document authors to unambiguously refer to elementswith the same name (i.e., prevent collisitions). For example, <subject >Math</subject>and <subject> thrombosis</subject>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 209
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHuse element subject to mark up a piece of data. However, in the first case the subject is somethingone studies in school, whereas in the second case the subject is in the field of medicine.26. Explain with an example program that XML is a technology used for structuring data. With XML, a document author can create elements that describe data precisely. As in theXHTML markup seen throughout the book, tags delimit the start and end of each element in anXML document.XML Markup for a News Article In fig. we mark up a simple news article using tags. The tags used in the example do not comefrom any specific markup language. Instead, we chose the tag names and markup structure thatbest describe the data. A programmer can invent tags to mark up data. 1. <?xml version =”1.0”?> 2. 3. <!- - fig. article xml 4. <!- - Article structured with XML 5. 6. <article> 7. 8. <title>simple XML</title> 9. 10. <date> July 15,2003</date> 11. 12. <author> 13. <first Name>Carpenter</first Name> 14. <last Name > Cal</ last Name 15. </author> 16. 17. <summary > XML is pretty easy. </ summary> 18. 19. <content> Once you have mastered XHTML, XML is easily 20. learned. You must remember that XML is not for 21. displaying information but for managing information 22. </content> 23. 24. </article> fig. News article marked up with XML We begin with the optional XML declaration in line 1. Value version indicates the XMLVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 210
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVersion to which the document conforms. The current XML Standard is version 1.0. The WorldWide Web Consortium may release new versions of XML as it evolves to meet the requirements ofdifferent fields. Comments ( lines 3-4) in XML use the same syntax as XHTML. Every XML document mustcontain exactly one root element that encompasses all other elements. In fig. article (line 6) is theroot element. The lines that precede the root element are the XML prolog. The prolog in thisexample is lines 1-5 XML element and attribute names can be of any length and may containletters, digits, underscores, hyphens and periods, however, XML names must begin with either aletter or an under score. Element title (line 8) contains text that describes the article’s title (i.e., simple XML).Similarly date ( line 10), author ( lines 12-15), summary ( line 17) and content ( lines 19-22) containtext that describes the date, author summary and content of the document, respectively. Any element (e.g., article or author) that contains other elements is a container element.Elements inside a container element are child elements (or children) of that container element. Note that the XML document in fig. does not contain formatting information for the article.This is because DML is a technology for structuring data. Formatting and displaying data from anXML document are application specific.27. Explain about the attribute list in a DTD. The ATTLIST attribute-list declaration in a DTD defines an attribute. Keyword #IMPLIEDspecifies that if the parser finds an element without the attribute, it can choose an arbitrary valueor can ignore the attribute. Keyword #REQUIRED specifies that the attribute must be in thedocument, and keyword #FIXED species that the attribute must have the given fixed value.Keyword CDATA specifies that an attribute contains a string that the parser should not process asmarkup. Keyword EMPTY specifies that the element does not contain any text.28. What is Schema and define the element tag? Schemas use XML syntax and are XML documents that programs can manipulate (e.g., addelements, remove elements) like any other XML document. In XML Schema, the element tag defines an element to be included in an XML documentstructure. Attributes name and type specify the element’s name and data type, respectively. Anyelement that contains attributes or child elements must define a type – called a complex type – thatdefines each attribute and child element.29. Give the functions of the attributes.i) minOccurs ii) maxOccursVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 211
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Attribute minOccurs specifies the minimum number of occurrences for an element.Attribute maxOccurs specifies the maximum number of occurrences for an element.30. What is role of URI in Namespaces? XML allows document authors to create their own tags, so naming collisions (i.e., differentelements that have the same name) can occur. Namespaces enable document authors to preventcollisions among elements in an XML document. Namespace prefixes prepended to element and attribute names specify the namespace inwhich the element or attribute can be found. Each namespace prefix has a corresponding uniformresource identifier (URI) that uniquely identifies the namespace. By definition, a URI is a series ofcharacters that differentiates names. Document authors can create their own namespace prefixes.Document authors can use virtually any namespace prefix, except the reserved namespace prefixxml.31. What is the use of i) MathML markup ii) CML (Chemical Markup) iii) MusicXML iv) RSS. i) MathML markup describes mathematical expressions. ii) Chemical Markup Language (CML) marks up molecular and chemical information. iii) MusicXML provides markup for musical notation. It simplifies the exchange of musical scores over the Internet. It is also a format for translating between the many other popular music formats. iv) RSS is a popular, simple XML format designed to share headlines and Web content.32. Explain the structure of a DOM tree. A DOM tree has a single root node that contains all the other nodes in the document. Eachnode is an object that has properties, methods and events. Properties associated with a nodeprovide access to the node’s name, value, and child nodes. Methods allow developers to create,delete and append nodes, load XML documents, and so on. The XML parser exposes thesemethods and properties as a programmatic library called an Application Programming Interface(API). A node that contains other nodes (called child nodes) is a parent node. Nodes that are peersare sibling nodes. A node’s descendent nodes include its children, its children’s children and soon. A node’s ancestor nodes include its parent, its parent’s parent and so on.33. Define i) SAX ii) XSL Document. SAX is an alternative method for parsing XML documents that uses an event-based model-SAX-based parsers generate notifications called events as the parser parses the document.Software programs can “listen” for these events to retrieve specified data from the document.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 212
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Extensible Stylesheet Language (XSL) documents specify how programs should render anXML document data. A subset of XSL-XSLTransformations (XSLT) – provides elements that definerules for transforming data from one XML document to produce another XML document (e.g.,XHTML).34. Define SOAP. The Simple Object Access Protocol (SOAP) is an XML-based protocol that allowsapplications to communicate easily over the Internet using XML documents called SOAPmessages. Every SOAP message contains an envelope – a structure for describing a method call. ASOAP message’s body contains either a request or a response.35. What does a Web service do? Web services encompass a set of related standards that can enable computer applications tocommunicate and exchange data over the Internet.36. What is Servlet Socket Layer? It is developed by Netscape communications. Here a non properiatary protocol is used toseucre the communicatation between 2 computers where the sender’s message is passed to asocket which receive & transmit information over a N/W. the socket interprets the messagethorugh TCP/IP. PART - B1. What is Distributed Bases? Discuss in detail how Database Interfaces are used for accessingrelational Databases.Introduction to DBI Databases have become a crucial part of distributed applications – programs that dividework across multiple computer systems. For instance, one computer might be responsible formanaging a Web site and another for a database management system. A distributed applicationuses both computers to retrieve a result set from a database and display it on another computer-typically called a client. Relational databases (e.g., MySQL, Microsoft Access, Oracle) have many differentimplementations. A software program, called a driver, helps programs access a database. Eachdatabase implementation requires its own driver, and each driver can have a different syntax. Tosimplify the use of multiple databases, an interface provides uniform access to all databasesystems. Various programming languages provide programmatic libraries (called databaseinterfaces) for accessing relational databases. This section provides a brief overview of databaseinterfaces for Perl, PHP and Python. Each of the chapters on these languages demonstrates the VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 213
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHmanipulation of MySQL databases.Perl Database Interface The Perl Database Interface (DBI) enables users to access relational databases from Perlprograms. Database vendors create derivers that can receive interactions through DBI and processthem in a database-specific manner. DBI is database independent, so it allows for easy migrationfrom one DBMS to another. DBI is the most widely used interface available for databaseconnectivity in Perl. DBI uses object-oriented interfaces, known as handles. Figure describes three differenthandle types-driver handles, database handles and statement handles. A driver handle can beused to create any number of database handles, and a database handle can be used to create anynumber of statement handles. Data object handle Description Driver handle Encapsulates the driver for the database; rarely used in a Perl script. Encapsulates a specific connection to a database; can send SQL Database handle statements to a database. Encapsulates specific SQL statements and the results returned from Statement handle them. Fig. Data object handles for Perl DBIPHP dbx module In PHP, an XHTML –embedded scripting language, the database interface is referred to as adbx module. The dbx module does not interact with a database directly. It interacts with one ofseveral database-specific module, which performs the actual database operations. Currently, thedbx module supports MySQL, PostgreSQL, Microsoft SQL Server, Oracle, Sybase, FrontBase andODBC (Open Database Connectivity) databases. [Note: ODBC is Microsoft’s original generic APIfor relational database access.] The seven dbx functions are listed in figure. dbx function Description dbx_connect Opens a connection/database dbx_close Closes an open connection/database. Reports any error messages from the last function call in the dbx_error module. dbx_query Executes a query and returns the results. dbx_sort Sorts a result by a custom sort function. dbx_compare Compares two rows and sorts them. dbx_escape_string Escapes a string for use in an SQL query. Fig. Data objects for PHP dbx modulesPython DB-APIVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 214
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH In Python, the database interface is referred to as DB-API (database applicationprogramming interface). The DB-API, which consists of Connection data objects and Cursor dataobjects, is portable across several databases. A Python programmer creates a Connection dataobject using connect ( parameter ), where database-dependent parameters specify options for theconnection to the database. Connection data objects access the database through four methods:close, commit, rollback and cursor. Figure describes these methods. Connection method Description close Closes the connection to the database. Commits a transaction (i.e., saves changes to the commit database). rollback Exits a pending transaction without saving changes. cursor Returns a new Cursor object for the current connection. Fig. Connection data object methods for Python DB-API The cursor method returns Cursor data objects, which manipulate and retrieve data. Figurelists some of the methods and attributes that constitute Cursor data objects. Cursor method Description Returns the number of rows affected by the last execute rowcount method call. close Closes the Cursor object. execute ( operation ) Executes a database query or statement. executemany Executes a database query or statement against a set of (operation, parameters. parameters) fetchone Returns the next row of a query result. Returns a set of rows-defined in the parameter-from a query fetchmany (size) result. fetchall Returns all the rows of a query result.2. Explain in detail about the ADO.NET Object Model.ADO.NET Object Model The ADO.NET object model provides an API for accessing database systemsprogrammatically. ADO.NET was created for the NET framework and is the next generation ofActiveX Data Objects (ADO), which was designed to interact with Microsoft’s Component ObjectModelTM (COM) framework. The primary namespaces (i.e., groups of classes) for ADO.NET are system.Data,VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 215
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHSystem.Data.0leDb and system.Data.SqlClient. These namespaces contain classes for working withdatabases and other types of data sources (e.g., XML files). Namespace System.Data is the rootnamespace for the ADO.NET API. Namespaces System.Data.0leDb and System.Data.SqlClientcontain classes that enable programs to connect with and modify data sources. NamespaceSystem.Data.0leDb contains classes that are designed to work with any data source, whereas theSystem.Data.SqlClient namespace contains classes that are optimized to work with Microsoft SQLServer 2000 databases. Instances of class System.Data.DataSet, which consist of a set of DataTables andrelationships among them, represent a cache of data-data that a program stores temporarily inlocal memory. The structure of a DataSet mimics the structure of a relational database. Anadvantage of using class DataSet is that it is disconnected – the program does not need a persistentconnection to the data source to work with the data in a DataSet. The program connects to the datasource only during the initial population of the DataSet and then to store any changes made in it.Hence, the program does not require any active, permanent connection to the data source. Instances of class 0leDbConnection of namespace System.Data.0leDb represent aconnection to a data source. Instances of class 0leDbDataAdapter connect to a data source throughan instance of class 0leDbConnection and can populate DataSets with data from a data source. Instances of class 0leDbCommand of namespace System.Data.0leDb represent an arbitrarySQL command to be executed on a data source. A program can use instances of class0leDbCommand to manipulate a data source through an 0leDbConnection. The programmer mustclose the active connection to the data source explicitly once no further changes are to be made.Unlike DataSets, 0leDbCommand objects do not cache data in local memory. We have introduced database management systems, the relational database model, SQL,MySQL, DBI and ADO.NET. We will use these technologies throughout the remaining chapters ofthe book to build interactive, database-intensive Web applications.3. Discuss in detail about the features of XML. The World Wide Web Consortium’s (W3C) XML Working Group developed XML(Extensible Markup Language), which is derived from Standard Generalized Markup Language(SGML), in 1996. XML is a widely supported open technology (i.e., nonproprietary technology) forelectronic data exchange and storage. XML is actually a language used to create other markuplanguages to describe data in a structured manner. XML documents contain only data, not formatting instructions, so applications that processXML documents must decide how to manipulate or display the document’s data. For example, aPDA (personal digital assistant) may render an XML document differently than a wireless phoneor a desktop computer. Programmers use Extensible Stylesheet Language (XSL) to specifyrendering instructions for different platforms.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 216
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH XML permits document authors to create markup for virtually any type of information.This extensibility enables document authors to create entirely new markup languages fordescribing data such as mathematical formulas, chemical molecular structures, music, news andrecipes. Some XML-based markup languages include XHTML, MathML (for mathematics),VoiceXMLTM (for speech), SMILTM (synchronous Multimedia Integration Language – formultimedia presentations), CML (Chemical Markup Language – for chemistry) and XBRL(Extensible Business Reporting Language – for financial data exchange). These markup languagesare called XML vocabularies. XML elements describe data, so XML-processing programs can search, sort, manipulateand render XML documents using technologies such as the Extensible Stylesheet Language (XSL).Some other XML-related technologies are XPath (a language for accessing parts of an XMLdocument). XSL-FO (an XML vocabulary used to describe document formatting) and XSLT (alanguage for transforming XML documents into other XML documents). XML documents are highly portable. Viewing or modifying an XML document – whichtypically ends with the .xml filename extension – does not require special software. Any texteditor that supports ASCII/Unicode characters can open XML documents for viewing andediting. One important characteristic of XML is that it is both human readable and machinereadable. Processing an XML document requires a software program called an XML parser (or XMLprocessor). Most XML parsers are available at no charge and for a variety of programminglanguages (e.g., Java, Perl, C++). Parsers check an XML document’s syntax and enable softwareprograms to process marked-up data. XML parser can support the Document Object Model(DOM) or the Simple API for XML (SAX). DOM-based parsers build tree structures containing XML document data in memory. SAX-based parsers process XML documents and generate events when the parser encounters tags, text,comments, and so on. These events to contain data from the XML document. Software programscan “listen” for these events to obtain data from the XML document. Several IndependentSoftware Vendors (ISVs) have developed XML parsers. An XML document can reference a Document Type Definition (DTD) or a schema thatdefines the proper structure of the XML document. When an XML document references a DTD ora schema, some parsers (called validating parsers) can read the DTD/schema and check that theXML document follows the structure defined by the DTD/ schema. If the XML documentconforms to the DTD/schema (i.e., the document has the appropriate structure), the XMLdocument is valid. We discuss DTDs and schemas. Parsers that cannot check for documentconformity against DTDs/schemas are nonvalidating parsers. If an XML parser (validating ornonvalidating) can process an XML document successfully, that XML document is well formed(i.e., it is syntactically correct). By definition, a valid XML document also is well formed. Someprograms (e.g., an XSLT) are designed to navigate an XML document’s structure. Validating anXML document ensures that a program navigates a well-formed document. However, it isVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 217
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHpossible to run an XSL on an XML document without validating the XML document.4. How can you avoid naming collisions in XML Explain in detail with an example. XML allows document authors to create custom elements. This extensibility can result innaming collisions (i.e, different elements that each have the same name) among elements in anXML document. For example, we may use the element book to mark up data about a Deitelpublication. A stamp collector may use the element book to mark up data about a book of stamps.Using both of these elements in the same document would create a naming collision, making itdifficult to determine which kind of data each element contained. An XML namespace is a collection of element and attribute names. Each namespace has aunique name that provides a means for document authors to unambiguously refer to elementswith the same name (i.e., prevent collisions). Fir example, <subject>Math</subject>and <subject>Thrombosis>/subject>use element subject to mark up a piece of data. However, in the first case the subject is somethingone studies in school, whereas in the second case the subject is in the field of medicine.Namespace can differentiate these two subject elements. For example <school:subject>Math</school:subject>and <medical:subject>Thrombosis</medical:subject>Both school and medical are namespace prefixes. A document author places a namespace prefixand colon (:) before an element or attribute name to specify the namespace for that element orattribute. Each namespace prefix has a corresponding uniform resource identifier (URI) thatuniquely identifies the namespace. A URI is simply a string of text for differentiating names. AURI can refer to a document, a resource or any thing on the Web either by name or address. Forexample, the string urn:deitel:book could be a URI for a namespace that contains elements andattributes related to Deitel & Associates, Inc., publications. Document authors can create theirown namespace prefixes using virtually any name except the reserved namespace xml. Do not confuse URIs with URIs. URIs are a subset of URIs that locate resources based on anetwork filename concept. A URL is a path to a file on the World Wide Web A URI is simply aname.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 218
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHCommon Programming Error 20.9 Attempting to create a namespace prefix xml in any mixture of cases is an error. Figure demonstrates namespaces. In this document, namespaces differentiate two distinetelements: the file element related to text and the one related to images.1 <?xml version = “1.0”?>23 <!- - Fig.20.4: namespace.xml -->4 <!- - Demonstrating Namespaces - ->56 <text:directory xmlns:text = “urn:deitel:textInfo”7 xmlns:image = “urn:deitel”imageInfor”>89 <text:file filename = “book:xml”>10 <text:description>A book list</text:description>11 </text:file>1213 </image:file filename = “funny.jpg”>14 <image:description>A funny picture</image:description>15 <image:size width = “200” height = “100”/>16 </image:file>1718 </text:directory> Figure. Using for namespace. Xml.Software Engineering Observation 20.1 Attributes do not require namespace prefixes, because each attribute is part of an elementthat specifies the namespace prefix. Lines 6-7 use the XML-namespace reserved attribute xmlns to create two namespaceprefixes-text and image-and assign URIs to them. The element directory (line 6) is the rootelement and contains the other elements. It is a part of the text namespace Document authors must provide a unique URI to ensure that a namespace is unique. Herewe use urn:deitel:textInfo and urn:deitel:imageInfo as URIs for the text and image namespaceprefixes, respectively. Document authors commonly use universal Resource Locators (URIs) forURIs because the domain names (e.g., deitel.com) in URLs must be unique. For example. Lines 6-VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 219
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH7 could have used the namespace URIs <text:directory xmlns:text = http://www.deitel.com/xmlns-text xmlns:image = “http://www.deitel-com/xmlns-image> where URLs related to the Deitel & Associates, Inc., Web site (www.deitel.com) serve asURIs for the text and image namespace prefixes. The parser does not visit these URLs, nor dothese URLs represent actual Web pages. They simply represent a unique series of characters fordifferentiating URI names. Any string can represent a URI. For example, our image namespacecould be hgjfkdlsa4556, and thus our assignment prefix would be xmlns:image = “hgjfkdlsa4556” Lines 9-11 use the namespace prefix text for elements file and description. Note that theend tags also specify the namespace prefix text. Line 13-16 apply namespace prefix image toelements file, description and size. To eliminate the need to place namespace prefixes in each element, document authors mayspecify a default namespace for an element and its children. Figure demonstrates using a defaultnamespace (urn:deitel:textInfo) for element directory.1 <?XmL VERSION = “1.0”?>23 <!- - Fig.20.5: defaultnamespace.xml - - >4 <!- - Using Default Namespaces -->56 <directory xmlns = “urn:deitel:textInfo”7 xmlns:image = “urn:deitel:imageInfor”>89 <file filename = “book.xml”>10 <description>A book list</description>11 </file>1213 <image:file filename = :funny.jpg”>14 <image:description>A funny picture</image:description>15 <image:size width = “200” height = “100” />16 </image:file>1718 </directory> Figure. Using default namespaces. We declare a default namespace by using keyword xmlns and specifying the namespaceVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 220
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHURI (line6). Once this default namespace is in place, elements that are declared under the defaultnamespace and their children do not need namespace prefixes to be part of the default namespace.Any element that specifies a namespace prefix is not part of the default namespace. Element file(lines 9-11) is in the urn:deitel:textInfor namespace, which is the default namespace. Compare thisto Fig. where we had to prefix the file and description elements with the namespace prefix text(lines 9-11). Element file (lines 13-16) uses the namespace prefix image to indicate that this element is inthe urn:deitel:imageInfo namespace, not the default namespace. XML-based languages, such as XML Schema, Extensible Stylesheet Language (Section 20.9)and SOAP, often use namespaces.5. Write a program to markup a Simple Business Letter using XML and explain it.XML Markup for a Business Letter Now that we have seen a simple XML document, let us examine a slightly more complexXML document that marks up a business letter (Fig). As in the preceding example, we begin thedocument with the XML declaration in line 1. This explicitly states the XML version to which thedocument conforms.1 <?xml version = “1.0”?>23 <! - -Fig.20.3: letter.xml -- >4 <! - -Business letter formatted with XML - - >56 <!DOCTYPE letter SYSTEM “letter.dtd”>78 <letter>910 <contact type = “from”>11 <name>John Doe</name>12 <address1>123 Main St.</address1>13 <address2></address2>14 <city>Anytown</city>15 <state>Anystate</state>16 <zip>12345</zip>17 <phone>555-1234</phone>18 <flag gender = “M”/>19 </contact>2021 <contact type = “to”>22 <name>Joe Schmoe</name>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 221
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH23 <address1>Box 12345</address1>24 <address2>15 Any Ave.</address2>25 <city>othertown</city>26 <state>otherstate</state>27 <zip>67890</zip>28 <phone>555-4321</phone>29 <flag gender = “M”/>30 </contact>3132 <salutation>Dear Sir:</salutation>3334 <paragraph>It is our privilege to inform you about our new35 database managed with XML. This new system allows36 you to reduce the load if your inventory list server by37 having the client machine perform the work of sorting38 and filtering the data.</paragraph>39 <closing>Sincerely</closing>40 <signature>Mr. Doe</signature>4142 </letter> Figure. Business letter marked up as XML (Part 2 of 3)VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 222
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure. Business letter marked up as XML (Part 3 of 3) Line 6 specifies that this XML document references a document type definition (DTD).DTDs define the structural rules for an XML document. An XML document does not require aDTD, but validating XML parsers can use a DTD to ensure that an XML document has the properstructure. The DTD reference (line 6) contains three items: the name of the root element that theDTD specifies (letter), the keyword SYSTEM (which denotes an external DTD-a DTD declared ina separate file), and the DTD;s name and location (i.e., letter.dtd in the current directory). DTDdocuments typically end with the .dtd extension. We discuss DTDs and letter.dtd in detail inSection 20.4. The output OF Fig. shows the results of validating the document using Microsoft’s XMLValidator. Several tools (many of which are free) exist that check a document’s conformity toDTDs and schemas (discussed in Section 20.4). Visti www.w3.org/XML/ Schema.html for a listof validating tools. Microsoft’s XML Validator is available free of charge from mdn.microsoft.com/downloads/samples/Internet/xml/ xml_validator/sample.aspCommon Programming Error 20.7Overlapping XML tags is a syntax error. For example,<x><y>hello</x></y> is illegal. Root element letter (lines 8-42) contains child elements contact, salutation, paragraph,closing and signature. A contact element stores the contact’s name, address and phone number.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 223
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHThe first contact element identifies the letter’s sender. The second contact element (lines 21-30)has attribute type with value to, which indicates that this contact element identifies the letter’srecipient. Element salutation (line 32) marks up the letter’s salutation. A paragraph element (lines34-38) marks up the letter’s boxy. Elements closing (line 39) and signature (line 40) mark up theclosing sentence and the author’s signature, respectively. Line 18 introduces empty element flag, which does not contain any text. Any example ofan empty element is the line break tag <br />in XHTML. Empty element flag indicates a contact’s gender. This attribute allows us to addressthe recipient correctly either as mr. (if gender is “M”) or Ms. (if gender is “F”). Document authorscan close an empty element either by placing a slash at the end of the element (as shown in line 18)or by writing a closing tag explicitly, as in <flag gender = “F”></flag>6. What is DTD and discuss the use of element type’s attributes & relationships.Document Type Definitions The DTD in Fig. specifies the business letter’s list of element types, attributes and theirrelationships to one another. A DTD enables an XML parser to verify whether an XML documentis valid (i.e., its elements contain the proper attributes in the proper sequence). DTDs allowindependent user groups to check document structure and to exchange data in a standardizedformat. A DTD expresses the set of rules for document structure using an EBNF (ExtendedBackus Naur Form) grammar. Line 6 in Fig. reference this DTD.1 <!- - Fig.20.5: letter.dtd -->2 <!- - DTD document for letter xml -- >34 <!ELEMENT letter ( contact+, salutation, paragraph+,5 closing, signature )>67 <!ELEMENT contact ( name, address1, address2, city, state,8 zip, phone, flag)>9 <!ATTLIST contact type CDATA #IMPLIED>1011 <!ELEMENT name ( #PCDATA )>12 <!ELEMENT address1 ( #PCDATA )>13 <!ELEMENT address2 ( #PCDATA )>14 <!ELEMENT city ( #PCDATA )>15 <!ELEMENT state ( #PCDATA )>16 <!ELEMENT zip ( #PCDATA )>17 <!ELEMENT phone ( #PCDATA )>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 224
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH18 <!ELEMENT flag EMPTY>19 <!ATTLIST flag gender (M | F) “M”>2021 <!ELEMENT salutation ( #PCDATA )>22 <!ELEMENT closing ( # PCDATA )>23 <!ELEMENT paragraph ( #PCDATA )>24 <!ELEMENT signature ( #PCDATA )> Line 4’s ELEMENT element type declaration defines the rules for the element letter. In this case,letter contains one or more contact elements, one salutation element, one or more paragraphelements, one closing element and one signature element, in that sequence. The plus sign (+)occurrence indicator specifies that the DTD allows one or more occurrences of an element. Otheroccurrence indicators include the asterisk (*), which indicates an optional element that can occurany number of times, and the question mark (?), which indicates an optional element that canoccur at most once. If an element does not have an occurrence indictor, the DTD allows exactlyone occurrence. The contact element definition (line 7) specifies that element contact contains child elementsname, address1, address2, city, state, zip, phone and flag-in that order. The DTD requires exactlyone occurrence of each of these elements. Line 9 uses the ATTLIST attribute-list declaration to define an attribute (i.e., type) for thecontact element. Keyword #IMPLIED specifies that if the parser finds a contact element withouta type attribute, it can choose an arbitrary value for the attribute or ignore the attribute, and thedocument will be valid. The XML document is also valid if a contact element does not have a typeattribute. Other types of default values include #REQUIRED and #FIXED. Keyword#REQUIRED specifies that the attribute must be present in the element, and keyword #FIXEDspecifies that the attribute (if present) must have the given fixed value. For example, <!ATTLIST address zip #FIXED “01757”>indicates that attribute zip must have the value 01757 for the document to be valid. If the attributeis not present, the parser, by default, uses the fixed value that the ATTLIST declaration specifies.Keyword CDATA specifies that attribute type contains character data, which indicates that theparser will not process the data, but will pass the data to the application without modification.Software Engineering Observation 20.4 DTD syntax does not provide a mechanism for describing an element’s (or attribute’s) datatype. For example, a DTD cannot specify that a particular element or attribute can contain onlyinteger data. Keyword #PCDATA (line 11) specifies that the element can contain parsed character data(i.e., text). Parsable character data should nott contain markup characters, such as less thanVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 225
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH(<),greater than (>) and ampersand (&). The document author should replace any markupcharacter with its corresponding entity (i.e., &lt;, or &amp;). See Appendix A for a list ofcharacter entities. Line 18 creatres an empty element named flag. Keyword EMPTY specifies that the elementdoes not contain any data. Attributes commonly contain data that the empty element describes(e.g., the gender attribute of empty element flag.7. Explain in detail the working of W3C XML schema, types of XML schemas and theirattributes.W3C XML Schema Documents Schemas for specifying XML document structure and validating XML documents. Manydevelopers in the XML community believe that DTDs are not flexible enough to meet today’sprogramming needs. For example, programs cannot manipulate DTDs in the same manner asXML documents because DTDs are not themselves XML documents. These and other limitationshave led to the development of schemas. Unlike DTDs, schemas do not use EBNF grammar. Instead, schemas use XML syntax andare actually XML documents that programs can manipulate. Like DTDs schemas requirevalidating parsers. A DTD describes an XML document’s structure, not the content of its elements. Forexample, <quantity><5</quantity>contains character data. If the document that contains element quantity references a DTD, andXML parser can validate the document to confirm that this element indeed does contain PCDATAcontent, but the parser cannot validate that the content is numeric; DTDs do not provide suchcapability. So, unfortunately, the parser also considers markup such as <quantity>hello</quantity>to be valid. The application that uses the XML document that contains this markup would need totest that the data in element quantity is numeric and take appropriate action if it is not. XML Schema enables schema authors to specify that element quantity’s data must benumeric. In validating the XML document against this schema, the parser can determine that 5conform and hello does not. An XML document that conforms to a schema document is schemavalid, and a document that does not conform is invalid. Figure shows a schema-valid XML document named book, xml, and figure shows thepertinent XML Schema document (book.xsd) that defines the structure for book.xml. AlthoughVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 226
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHschema authors can use virtually any filename extension, schemas commonly use the. xsdextension. To ensure that the XML document in figure conforms to the schema in figure, we usedan online XSD schema validator at http://apps.gotdotnet.com/xmltools/xsdvalidator We used XSV (XML Schema Validator), an open – source schema validator, to validate theSchema document itself, book.xsd, and produce the output shown in figure. An online form-based version of this validator is available at www.w3.org/2001/03/webdata/xsv.1 <?xml version = “1.0”?>23 <! -- Figure: book.xml -- >4 <! -- Book list marked up as XML -- >56 <deitel.books xmlns:deitel = http://www.deitel.com/booklist>7 <book>8 <title>XML How to Program</title>9 </book>10 <book>11 <title>C How to Program</title>12 </book>13 <book>14 <title>Java How to Programs</title>15 </book>16 <book>17 <title>C++ How to Program</title>18 </book>19 <book>20 <title>Perl How to Program</title>21 </book>22 </deitel:books> Schema – valid XML document1 <?xml version = “1.0”?>23 <! -- Figure: book.xsd -- >4 <! -- Simple W3C XML Schema document -- >56 <schema xmlns = http://www.w3.org/2001/XMLSchema7 xmlns:deitel = http://www.deitel.com/booklist8 targetNamespace = http://www.deitel.com/booklist>910 <element name = “books” type = “deitel:BooksType”/>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 227
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH1112 <complexType name = “BooksType”>13 <sequence>14 <element name = : book” type = “deitel:SingleBookType”15 minoccurs = “1” maxoccurs = “unbounded”/>16 <sequence>17 </complexType>1819 <complexType name = “SingleBookType”>20 <sequence>21 <element name = “title” type = “string”/>22 <sequence>23 </complexType>24 </schema>Target: file:///usr/local/XSV/xsvlog/@11038.luploaded (Real name: C:IW3HTP3examplesch 20book.xsd) docE1t:{http://www.w3.org/2001/XMLSchema}schema validation was strict, starting with type[Anonymous]. The Schema(s) used for schema-validation had no errors No schema – validityproblems were found in the target Figure: XML Schema document for book.xml Figure contains markup describing several Deital & Associates, Inc.books. The bookselement (line 6) must have the namespace prefix deitel because the books element is a part of thehttp://www.deitel.com/bboklist namespace. Note that we also define the namespaceprefix.deitel in the same line. Figure presents the XML Schema document that specifies the structure of book.xml (figure).XML Schema documents always use the standard namespace URIhttp://www.w3.org/2201/XMLSchema. Root element schema contains elements that define theXML document structure. Line 7 binds the URI http://www.deitel.com/booklist to namespaceprefix deitel. Line 8 specifies the targetNamespace, which is the namespace of the XMLvocabulary that this schema defines. In XML Schema, the element tag (line 10) defines an element to be included in the XMLdocument structure. In other words, element specifies the actual elements that can be used tomark up data. Attributes name and type specify the element’s name and data type respectively.Possible data types include XML Schema-defined types (e.g., string, double) and user – definedtypes (e.g., BooksType, which is defined in lines 12 – 17). XML Schema provides a large numberof build – in simple types, such as date for dates, int for integers, double for floating – pointnumbers and time for times. An element’s data type indicates the data that the element maycontain.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 228
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Two categories of data types exist in XML Schema: simple types and complex types.Simple types and complex types differ in one way: Simple types cannot contain attributes or childelements; complex types can. In this example, books is defined as an element of data type deitel:BooksType (line 10)BooksType is a user-defined type in the http://www.deitel.com/bboklist namespace andtherefore must have the namespace prefix deitel. It is not an existing XML schema data type. Recall that any element (e.g. books) that contains attributes or child elements must be of acomplex type. Lines 12 – 17 use element complexType to define BooksType as a complex type thathas a child element named book. The sequence element (line 13-16) allows a programmer tospecify the sequential order in which child elements must appear. The element tag (lines 14 – 15)nested within the complexType element indicates that an element of type BooksType (e.g., books)can contain child elements named book of type deitel: SingleBookType. Attribute minoccurs = “1”specifies that elements of type BooksType must contain a minimum of one book element.Attribute maxoccurs, with value unbounded (line 15), specifies that elements of type BooksTypemay have any number of book child elements. Lines 19 – 23 define a complex type called SingleBookType. Line 21 defines element title tobe of simple type string. Recall that elements of a simple type cannot contain attributes or childelements. The closing schema tag (line 25) declares the end of the XML Schema document. We now take a closer look at types in XML Schema. Every element in XML Schema hassome type. Possible types include the build-in data types provided by XML Schema (e.g., date,time, int, string) or user – defined types (e.g., SingleBookType in figure). Recall that all types in XML Schema are classified as either simple or complex. Everysimple type defines a restriction on a built – in schema data type (e.g., string, float, time) or arestriction of a user – defined type. A restriction limits the possible values that an element canhold. Complex types are divided into two groups. Complex types can have either simple contentor complex content. Both simple content and complex content can contain attributes, but onlycomplex content can have child elements. While complex types with simple content must beextended or restricted, complex types with complex content do not have this limitation. TheSchema document in figure creates both simple types and complex types. The XML instancedocument in figure follows the structure defined in the figure schema to describe parts of a laptopcomputer.1 <?xml version = “1.0”?>23 <! -- Figure: computer.xsd -->4 <! -- W3C XML Schema docueme nt -->VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 229
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH56 <schema xmlns = http://www.w3.org/2001/XMLSchema7 xmlns:computer = http://www.deitel.com/computer8 targetNamespace = http://www.deitel.com/computer>910 <simpleType name = “gigahertz”>11 <restriction base = “decimal”>12 <minInclusive value = “2.1”/>13 </restriction>14 </simpleType>1516 <complexType name = “CPU”>17 <simpleContent>18 <extension base = “string”>19 <attribute name = “model” type = “string”/>20 </extension>21 </simpleContent>22 </complexType>2324 <complexType name = “portable”>25 <all>26 <element name = “processor” type = “computer: CPU”/>27 <element name = “monitor” type = “int” />28 <element name = “CPUSpeed” type = “computer: gigahertz” />29 <element name = “RAM” type = “int” />30 <all>31 <attribute name = “manufacturer” type = “string” />32 </complexType>3334 <element name = “laptop” type = “computer: portable”/>3536 </schema> Figure: XML Schema document for laptop.xml Line 6 declares the default namespace to be the standard XML Schema namespace (i.e., anyelements without a prefix are assumed to be in the XML Schema namespace). Line 7 binds thenamespace prefix computer to the namespace http://www.deitel.com/computer, which line 8indicates is the namespace being defined in the current document. In designing the XML tags for describing laptop computers, first we create a simple type inlines 10 – 14 using the simpleType element. We name this simpleType gigahertz because it will beused to describe the clock speed of the processor in gigahertz. Simple types are restrictions of atype typically called a base type. Line 11 declares the base type. For this simpleType, the basetype is decimal, and we restrict the value to be at least 2.1 by using the minInclusive element inline 12.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 230
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH We then declare a complexType that has simpleContent (lines 16 – 22). Remember that acomplex type with simple content cannot have child elements but can have attributes. Also recallthat complex types with simple content must extend or restrict some data type or user – definedtype. The extension element with attribute base (line 18) sets the base type to string. In thiscomplexType we extend the base type string with an attribute. The attribute element (line 19)gives the complexType an attribute named model of type string. Thus an element of type CPUmust contain string text and may contain a model attribute that is also of type string. Lastly we define the type portable, which is a complexType with complexContent (line 24 –32). Complex types with complex content are allowed to have child elements and attributes. Theelement all (line 25) encloses those elements that must each be included once in the correspondingXML instance document. These elements can be included in any order. This complex type holdsfour elements: processor, monitor, CPUSpeed and RAM. These elements are given types CPU, int,gigahertz and int, respectively. When using the types CPU and gigahertz, we must include thenamespace (http://www.deitel.com/computer) – the namespace defined in the current document(line 8). Also, portable contains an attribute defined in line 31. The attribute tag indicates thatelements of type portable contain an attribute of type string named manufacturer. Line 34 declares the actual element that uses the three types defined in the schema. Theelement is called laptop and is of type portable. We must use the namespace prefix computer infront of portable. We have created a tag named laptop that contains elements processor, monitor, CPUSpeedand RAM, and an attribute manufacturer. Putting it all together, figures uses the laptop elementtag defined in the schema. Line 6 declares the namespace prefix computer. The laptop element requires this prefixbecause it is part of the http://www.deitel.com/computer namespace. Line 7 defined thelaptop’s manufacturer attribute, and lines 9 – 12 use the element tags defined in the schema.1 <?xml version = “1.0”?23 <! -- Figure: laptop.xml -- >4 <! -- Laptop components marked up as XML -- >56 <computer:laptop xmlns:computer = http://www.deitel.com/computer7 manufacturer = “IBM”>89 <processor model = “Centrino”>Intel</processor>10 <monitor>17</monitor>11 <CPUSpeed>2.4</CPUSpeed>12 <RAM>256</RAM>1314 </computer: laptop>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 231
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Figure: XML document using the laptop tag defined in computer.xsd8. Discuss in detail about DOM and its methods with necessary examples. Althouth an XML document is a text file, retrieving data from the document usingtraditional sequential file – access techniques is neither practical not efficient, especially for addingand removing elements dynamically. As mentioned earlier, when a DOM parser successfullyparses an XML document, it creates a tree structure in memory that contains the document’s data.Figure shows the tree structure for the document article. Xml discussed in fig. This hierarchicaltree structure is a Document Object Model (DOM) tree. Each tag name (e.g., article, date, firstName) represents a node. A node that contains other nodes can have many children, but a childnode can have only one parent node. Nodes that are peers (e.g., first Name and last Name) arecalled sibling nodes. A node’s descendant nodes include its children, its children’s children andso on. A node’s ancestor nodes include its parent, its parent’s parent and so on. Fig. Tree structure for article. Xml. The DOM has a single root node, which contains all the other nodes in the document. Forexample, the root node for article. Xml (fig.) contains a node for the XML declaration. (line 1), twonodes for the comments ( lines 3-4) and a node for the root element article (line 6). Each node is an object that has properties, methods and events, Properties associated with anode include names, values and child nodes. Methods enable programs to crate. Delete andappend node, load XML documents, and so on. An XML parser exposes these methods as aprogrammatic library called an Application Programming Interface (API).DOM Methods To introduce document manipulation with the XML Document Object Model, we provide asimple scripting example that uses Java Script and Microsoft’s MSXML parser that is built intoVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 232
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHIE6. This example takes the XML document article. Xml (fig.) that marks up an article and uses theDOM API to display the document’s element names and values. Figure lists the Java script codethis manipulates this XML document and displays its content in an XHTML page. 1. <?xml version = “1.0”?> 2. <IDOCTYPE html PUBLIC” =//w3c//DTD XHTML 1.0 Transitional /EN” 3. http://www.w3.org/TR/xhtml 1/DTD/xhtml 1-Transitional .dtd > 4. <html xmlns=http://www.w3.org/1999/xhtml> 5. 6. <!- - Fig. : DOM Example. html - - > 7. <!- - DOM with Java Script 8. 9. <head> 10. <title> A DOM Example < / title> 11. </head> 12. 13. <body> 14. 15. <script type = “text/java script “language = “Java Script”> 16. <! - - 17. var xml Document = new Active X0 object ( “Microsoft . XML DOM”); 18. 19. xml Document. load ( article xml”); 20. 21. //get the root element 22. var element = xml Document. document Element; 23. 24. document. write ln ( 25. “<p>Here is the root node of the document :”+ 26. “<strong>”+element. Node Name + “</strong>”+ 27. “<br/>the following are its child elements :”+ 28. “</p><ul>”); 29. 30. // traverse all child nodes of root element 31. for ( var i=0; i<element. childNodes. Length; i++){ 32. var curNode = element. Child Nodes Item (i); 33. 34. //print node name of each child element 35. document. write ln( “<!i ><strong> “+ curNode. Node Name 36. +”</strong></1i>”); 37. } fig. Traversing article. Xml with Java Script.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 233
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 38. 39. document. write ln (“/ui>”); 40. 41. // get the first child node of result element 42. var current Node = element . first child; 43. 44. document. write ln (“<p> The first child of root node is “+ 45. “<strong>”+current node. Node Name +”</ strong>”+ 46. “<br?>whose next sibling is:”); 47. 48. // get the next shifting of first child 49. var next sib = current Node . next Sibling; 50. 51. “document. write ln(“<strong>”+ next Sib. Node Name+ 52. “</strong>.<strong > element is:”); 53. next sib. Node name + “</strong>element is:”); 54. 55. var value =next Sib. First Child; 56. 57. // print. The text value of the sibling 58. document. write ln(“<em>”+value. Node value + “</em>”+ 59. <br/>parent node of < strong> “+next Sib. Node Name+ 60. “</strong> is < strong>”+ 61. next Sib. Parent Node. Node name+”</strong> <p>”); 62. 63. </script> 64. 65. </body> 66. </html>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 234
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Traversing article. Xml with Java script Line 17 uses the Java script Active X0 object calss to instantiate (i.e., create) a MicrosoftXML Document object Model object and assign it to the reference xml Document. This objectrepresents an XML- Document DOM tree and provides methods for manipulating its data. Thestatement merely creates the object, which does not yet refer to any specific XML document.Line 19 calls the method load to load article. Xml (fig.) into memory. The MSXML parser parsesthe XML document and stores it in memory as a tree structure.Line 22 assigns the root element node ( i.e., article) to variable element. Property documentElement corresponds to the root element in the document (e.g., article).which is importantbecause this element is the reference point for retrieving all the other nodes in the document.Line 26 places the name of the root element in XHTML element strong and writes this string to thebrowser for rendering. Property node Name corresponds to the name of an element. Attribute, orso on In this particular case, element refer to the root node named article.Line 31-37 loop through the root node’s children using property child Nodes. Element. Childnodes is a Node List. A Node List is a collection of nodes. Property length returns the number ofchildren in the root element.Calling method item (line 32) accesses individual child nodes. Each node has an integer index( starting at zero) based on the order in which the node occurs in the XML document. for example,in fig. title has index 0, date has index 1, and so on. Line 32 calls method item to obtain the childnode at index 1 and assigns the node to curNode.Line 42 retrieves the root node’s first child node ( i.e., title) using property first child. Theexpression in line 42 is a more concise alternative to Var current Node = element. childNodes. Item (0); Elements title, author, summary and content are all sibling nodes Property nextSiblingreturns a node’s next sibling. Line 49 assigns current Node’s (i.e., title’s) next sibling node (i.e.,date) to reference next Sib. In addition to elements and attributes, text (e.g., Simple XML in line 8 of Fig. ) also is node.Line 55 assigns next Sib’s (i.e., date’s) first child node to value. In this case, the first child node is anext node. In line 58, property node value retrieves the value of this text node. A text node’s valueis simply the text that the node contains. Element nodes have a value of null (i.e., no value). Line61 retrieves and displays next sib’s (i.e., date’s) parent node (i.e., article). Property parent Nodereturns a node’s parent node. The tables in fig. describe important DOM methods. The primary DOM objects are Node (aVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 235
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHnode in the tree), Node List (an ordered set of nodes), Name Node Map (an unordered set ofnodes), Document (the document), Element (an element node), Attr (an attribute node), Text (atext node) and comment ( a comment node). Some methods of these objects are described in thetables.9. List out the following methods and their functions. i. Node Object methods ii. Node List Object Methods iii. NamedNode Object Methods Method DescriptiongctNodeType Returns an integer representing the node type. Returns the name of the node. If the node does not have a name, agetNodeName string consisting of # followed by the type of the node is returnedgetNodeValue Returns a string or null depending on the node type.getParentNode Returns the parent node.getChildNodes Returns a NodeList with all the children of the node.getFirstChild Returns the first child in the NodeList.getLastChild Returns the last child in the NodeList.getPreviousSibling Returns the node preceding this node, or null.getNextSibling Returns the node following this node, or nullgetAttributes Returns a NamedNodeMap containing the attributes for this node. Inserts the node (passed as the first argument) before the existing node (passed as the second argument). If the new node is already in the tree,InsertBefore it is removed before insertion. The same behavior is true for other methods that add nodes.replaceChild Replaces the second arument node with the first argument node.removeChild Removes the child node passed to it.appendChild Appends the node passed to it to the list of child nodes. Returns a NodeList of all the nodes in the subtree with the namegetElementsByTagNam specified as the first argument ordered as they would be encounterede in a preorder traversal. An optional second argument specifies either the direct child nodes (0) or any descendant (1).getChildAtIndex Returns the child node at the specified index in the child list. Appends the string passed to it to the last Node if it is a Text node,addText otherwise creates a new Text node for the string and adds it to the end of the child list. Returns true if the node passed is a parent of the node or is the nodeisAncestor itself. Fig. Node Object MethodsVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 236
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Method Description Passed an index number, returns the element node at that index.item Indices range from 0 to length – 1.getLength Returns the total number of nodes in the list. Fig. NodeList Object Methods Method Description Returns either a node in the NamedNodeMap with the specified namegetNamedItem or null. Stores a node passed to it in the NamedNodeMap. Two nodes with thesetNamedItem same name cannot be stored in the same NamedNodeMap.removeNamedItem Removes a specified node from the NamedNodeMap.getLength Returns the total numbe rof nodes in the NamedNodeMap.getValues Returns a NodeList containing all the nodes in the NamedNodeMap. Fig. NamedNodeMap Object MethodsMethod Descriptionget Document Element Returns the root node of the documentcreate Element Creates and returns an element node with the specified tag name Creates and returns an attribute node with the specified name ancreate Attribute value.create Text Node Creates and returns a text node that contains the specified text. Creates a comment to hold the specified textcreate Comment Figure: Document methods10. List out the following methods and their functions.(i) Document methods(ii) Element Methods(iii) Attribute method Method Description get Tag Name Returns the name of the element set Tag Name Changes the name of the element to the specified name get Attribute Returns the value of the specified attribute set Attribute Changes the value of the attribute passed as the firstVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 237
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH argument to the value passed as the second argument remove Attribute Removes the specified attribute get Attribute Node Returns the specified attribute node set Attribute Node Adds a new attribute not with the specified name Figure: Element methods Method Description get Value Returns the specified attribute’s value set Value Changes the value of the attribute to the specified value get Name Returns the name of the attribute Figure: Attr method Method Description get Data Returns the data contained in the node (text or comment). set Data Set the node’s data get Length Returns the number of characters contained in the node Figure: Text and Comment methods11. Discuses in detail about XSH with an example.Extensible style sheet language (XSL): Extensible Style sheet Language (XSL) documents specify how programs should renderXML document data. XSL is a group of three technologies: XSL-FO (XSL Formatting Objects)XSLT (XSL Transformations) and XPath. XSL-FO is a vocabulary for specifying formatting. XSLTis a language for transforming XML into other formats and XPath is syntax for accessing parts ofan XML document. the relationship between XML and XSL is similar to the relationship betweenXHTML and Cascading Style Sheets (CSS), although XSL is much more powerful than CSS.Document authors also can use CSS to specify formatting in formation for XML documents. Asubset of XSL-XSL Transformations – provides elements that define rules for transforming datafrom one XML document to produce a different xml document (e.g., XHTML). By convention,XSL document have the filename extension. Software Engineering Observation: Transforming an XML document using XSLT involves two tree structures: the source tree(i.e., the XML document to be transformed) and the result tree (i.e., the XML document to becreated). XPath is used to locate parts of the source tree document that match templates definedin the XSL style sheet. When there is a match (i.e., a node matches a template), the matchingVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 238
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHtemplate executes and adds its result to the result tree. When there are no more matches, theXSLT has transformed a source three into the result tree. The XSLT does not go through everynode of the source tree; it selectively navigates the source tree using XPath’s select and matchattributes. For the XSLT to function, the source tree must be properly structured. Schemas, DTSsand validating parsers can validate document structure before using XPath and XSLTs. The tablein figure lists some commonly used XSL elements. Method Description< xsl : apply – templates > Applies the templates of the XSL document to the children of the current node.< xsl : apply – templates Applies the templates of the XSL document to the children of the expression. The value of the attribute match (i.e., expression must be an XPath expression that specifies elements< xsl : template> Contains rules to apply when a specified node is matched.<xsl : value –of select = Selects the value of an XML element and adds it to the output tree of“expression”> the transformation. The required select attribute contains an XPath expression.<xsl : for-each select =“expression”> Applies a template to every node selected by the XPath specified by<xsl:sort select = the select attribute.“expression”> Used as a child element of an <xsl:apply-templates> or <xsl:for- each>element. Sorts the nodes selected by the <apply-template> or <for-each> element so that the nodes are processed in sorted order.<xsl: output> Has various attributes to define the format (e.g., xml, html), version (e.g., 1.2, 2.0), document type and media type of the output tree. Figure: XSL style sheet elements (part 2 of 2)A Simple XSL Example Figure lists an XML document that marks up various sports. The output shows the resultsof the transformation (specified in the XSLT template of figure) rendered by internet Explorer 6.the example in this section require MSXML 3.0 or higher to run. This program is included inInternet Explorer 6. for information on downloading and installing MSXML for use in a previousversion of IE, please visit Microsoft’s XML General Downloads site, msdn.microsoft.com/ downloads/lift/xml general.asp. We discuss the specific XSL document that performs thetransformation in figure1. <?xml version = “1.0”?>2. <?xml : style sheet type = “text / xst” href = “ games. xsl”?>3.4. <! -- fig: games .xml -->5. <! – sports Database -->VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 239
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH6.7. <sports>8.9. <game id = “783”>10. <name> Cricket</name>11.12. <paragraph>13. popular in commonwealth nations14. </paragraph>15. </game>16.17. < game id = “239”>18. <name> Baseball </name>19.20. <paragraph>21. Popular in America.22. </paragraph>23. </game>24.25. <game id = “418”.26. <name>Soccer (Football) </name>27.28. <paragraph>29. popular sport in the world30. </paragraph>31. </game >32.33. </sports> Figure: XML document containing a list of sports (part 2 of 2) Line 2 is a processing instruction (PI) that references the XSL style sheet games. Xsl. ItsVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 240
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHtype attribute specifies that games. Xsl is a text/xs file. A processing instruction is an application-specific piece of information embedded in an XML document. the characters >? and?> delimit aprocessing instruction. The processing instruction of line 2 provides application-specificinformation to whatever XML processor the application uses. Processing instructions consist of aPI target (e.g., xml: style sheet) and a PI vale (e.g., type = “text/xsl” href = “games.xsl”). Abrowser such as Internet Explorer uses this processing instruction to determine the XSLtransformation to apply to the XML document. when games. Xml is opened in the browser, theprocessing instruction tells it to apply games, xsl to itself and output the result.12. Explain about the water XML Based programming language in detail.WaterTM XML-Based Programming Language: Water is a general-purpose programming language that simplifies XML and Web servicesprogramming. Building Web services typically requires knowledge of XHTML, a scriptinglanguage, a database language and a server-side programming language. Water can perform thetasks of all these individual technologies. Water’s syntax (Concise XML) is a superset of XML syntax and is compatible with XMLXHTML is a subset of XML, and XML is a subset of Concise XML; consequently any XHTMLprogram is also a Water program. Concise XML simplifies the description of data and logic Inaddition, Concise XML is less verbose than XML. Thus Concise XML files are smaller than XMLfiles that contain similar data. More information about Water can be found at www.waterlanguage.org. This web site provides chapters from a book written by the creators of water andoffers a free, trial version of Clear Methods Steam, an IDE (integrated development environment)used to write Water-based services and applications. Figure presents a water application that prompts the user to input text and outputs the textin a sentence. This application has two methods that create two web pages one for input and onefor output. After running these methods, the Water program sets up and accesses a server thatexecutes this application. To run the following example, first download the Steam IDE fromwww.waterlanguage.org/install.html and install it following the on-screen instructions. Next,open concatenate.h20 in Steam and click the green Execute button located at the bottom of theapplication window. this will run the example in your browser as shown in figure 1. <! --: concatenate. h20 --> 2. <! – Form Input and Output with Water --> 3. 4. <defclass concatenate> 5. <defmethod start> 6. <FORM action = “/put Together”> 7. Type in a subject: <INPUT name = “word 1”/> 8. Type in a verb: <INPUT name = “word 2”/> 9. <INPUT type = “submit”/>VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 241
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 10. </FORM> 11. </defmethod> 12. 13. <defmethod put Together world1 word2> 14. <vector word1 “word2” “/> 15. </defmethod> 16. </defclass> 17. 18. <server concatenate port = 9090/> 19. < open_browser_window http://Tocathest:9090/> Figure: Water program that performs simple input and output Lines 4-16 define a class called concatenate. The class is out entire application. All thecontent in the defclass will be executed when the class is called. Line 5 declares a method usingdefmethod and names it start. Method start is not given any parameters. Lines 6-10 create a formusing XHTML tags. The action attribute of the FORM element (line 6) specifies the method thatthe server executes when the user clicks the submit button. When the user clicks submit, the formwill cal method putTogether. Method start returns the form as a hypertext object. We do not haveto write the XHTML code for the actual output because the server implicitly converts hypertextobjects (e.g., the form) to XHTML with a to_html function. Line 13 declares method put Together, which has two parameter: world1 and word2. word1 and word 2 are associated with the inputs of the form in method start. The body of method putTogether (line 14) creates a vector that contains word1 a space, word 2 and a period. a vector is aresizable array. putTogether returns this vector as a hypertext object. Line 18 uses the server tag to create a server on the user’s machine at the given port (i.e.,9090). The server serves the application concatenate. Line 19 then opens a browser that accessesthe server tag (i.e., concatenate). By default, the server looks for and calls method named start. Sothe first page is the form defined in method start. When the user clicks on the Submit Querybutton, the form calls the method associated with its action attribute (i.e., putTogether). Themethod PutTogether is passed word1 and word2. putTogether creates the second page andVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 242
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHoutputs the contents of the vector (i.e., word1, s space, word2 and a period). Once again, we donot have to write the XHTML code for the actual output because the server converts the hypertextobjects (e.g., the form and the vector) to XHTML. Sample input and output are shown in figure.13) What are the scoping issues in ASP applications?Scoping issues in ASP applications Scope refers to the lifetime of the variables. In ASP applications there are four levels ofscope for variables: they are 1. Global level 2. application level scope, 3. session level scope and 4.procedure level scopeGlobal level scope Global .asa file has the highest priority to set application and session – level variables.Normally the application and session level variables are created within this file. A part form thisapplication level variables, session level variables can also be created in “.asp” pages. Global .asafile can use multiple <SCRIPT> tags and multiple supported scripting languages.Application level scope In ASP, application level scope means global variable. In the sense, the variable can be usedacross multiple session. Normally application level variable are declared in the application_ onstart event.Session level Scope When a variable is created for a specific user, it is considered to have session level scope.Normally the database connection initialization and destruction are declared in the session level. Itis declared on session _ on start and session – on end event.Procedure level scope/page level The variables that are declared and used with in the ASP page will have scope within thatpage and procedure only.13) Discuss in detail the working of an ASP Document. The Active Server Pages in this chapter demonstrate communication between clients andservers via the Web’s HTTP protocol. When a server receives a client’s HTTP request, it loads thedocument (or page) requested by the client. XHTML documents are static documents.—all clientssee the same content when the document is requested. ASP is a Microsoft technology for sendingthe client dynamic Web content, including XHTML, Dynamic HTML, ActiveX controls, client-sideVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 243
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHscripts and Java applets (i.e., client-side Java programs that are embedded in a Web page). TheActive Server Page processes the request (which often includes interacting with a database) andreturns the results to the client—normally in the form of an XHTML document, but other dataformats (e.g., images, binary data) can be returned. When a client requests an ASP document, it isloaded into memory and parsed (top to bottom) by a scripting engine named asp.dll. Script codeis interpreted as it is encountered.©1981–2004, Deitel&Associates, Inc. All rights reserved. The Request object is commonly used to access the information passed by a get or postrequest. This information usually consists of data provided by the user in an XHTML form. TheRequest object provides access to information (such as cookies) that is stored on a client’s machine.This object also provides access to binary information (e.g., a file upload). The Response objectsends information, such as XHTML or text to the client.The Server object provides access to methods and properties on the server.Simple ASP ExampleIn this section, we present some simple ASP examples. The first example (Fig. 33.2) sends the Webserver’s date and time to the client as XHTML markup.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 244
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 245
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH<% @LANGUAGE = VBScript %><% Fig. 33.2 : clock.asp A simple ASP exampleOption Explicit%><% =FormatDateTime( Now, vbLongDate ) %><% =Time() %> Note the scripting delimiters <% and %> wrapped around the VBScript code—thesedelimit the scripting code that is executed on the server, not the client. Script enclosed in scriptingdelimiters is not sent to the client; it is processed by the scripting engine. However, the scriptingcode inside the delimiters can generate information that is sent to the client. Everything outside <% and %> is simply written to the client. Line 1 uses the optional @LANGUAGE processing directive to specify VBScript as thescripting language. This indicates the scripting engine needed to interpret the scripting code. Inthis chapter, we use VBScript exclusively to develop our Active Server Pages, although otherscripting languages, such as JavaScript, may be used. If the @LANGUAGE processing directive isomitted, VBScript is the default. The Option Explicit statement in line 6 indicates that the programmer must explicitlydeclare all VBScript variables. Remember that VBScript variables are implicitly declared when anew name is mentioned. This can lead to subtle errors. The Option Explicit statement, when used,must be the first VBScript scripting statement after the @LANGUAGE directive. In this particularexample, variables are not declared but the Option Explicit statement is included as a goodprogramming practice.33.1VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 246
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Line 33 calls VBScript function FormatDateTime to return a string formatted according tothe server’s date and time. This function accepts two arguments, the date and the format in whichto return the date. We call VBScript function Now to get the current date and specify thevbLongDate format, which indicates that the day, time, month and year should be displayed. Thisstatement is short for <% Call Response.Write( FormatDateTime( Now, vbLongDate ) )%> whichcalls the Response method Write to send the formatted date as text to the client. Line 37 callsVBScript function Time to get the current time on the server. Function Time returns the time inthe format hh:mm:ss.This statement is short for <% Call Response.Write( Time() ) %> which callsthe Response method Write to send the time as text to the client.14) Explain the File System Object with an Example.File System Objects ( FSOs) enable programmers to manipulate files, directories and drives. FSOsalso allow programmers to read and write text and are an essential element for Active ServerPages that persist data. We overview FSO features and then provide a livecode example that usesFSOs. FSOs are objects in the Microsoft Scripting Runtime Library. These FSO types includeFileSystemObject, File, Folder, Drive and TextStream. Each type is summarized in Fig. 33.6. The programmer can use FileSystemObjects to create directories, move files, and determinewhether a Drive exists. Figure 33.7 summarizes some common methods of FileSystemObject. TheFile object allows the programmer to gather information about files, manipulate files and openfiles. Figure 33.8 lists some common File properties and methods. Property Path contains the File’spath in long name format (the operating system does not abbreviate the name when it exceeds the8.3 format—the format in which the filename contains at most eight characters and the extensioncontains at most three characters). Property ShortName contains, if applicable, the file name inshort name format (a file name exceeding the 8.3 format is abbreviated). For example,"ABCDEFGHIJ.doc" is a file name in long name format. The same file name in short name formatmight be abbreviated as "ABCDEF~1.doc". Figure 33.12 is an Active Server Page for a guestbook that allows visitors to enter theirVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 247
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHname, e-mail address and comments. File system objects are used to write the visitor informationto a file on the server. The guestbook page displayed in the browser consists of a form (to be filledin by the user) and a list of guestbook entries (initially, there are no entries in this list). The form(lines 67–98) contains two text fields and a text area for inputting the name, e-mail addressand user comment.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 248
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 249
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 250
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Line 67 indicates that a post request occurs upon form submission. The action for the formVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 251
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHrequests the same ASP page in which the form is contained—guestbook.asp. A form’s action is notrequired to request a different document. Upon submission, guestbook.asp is requested andpasses parameter hiddenInput (lines 96–97), which has the value "true." The name hiddenInput isprogrammerdefined —developers, of course, may choose any name they prefer. We use thistechnique to determine whether this ASP page is being requested by a form submitted fromguestbook.asp. Lines 30–31 pass Request method ServerVariables the server keyAPPL_PHYSICAL_PATH to retrieve the physical path of the virtual directory where thisASP document resides. We concatenate this with the name of the file, guestbook.txt, and assignthe result to variable guestbook. Figure 33.13 lists some server variable keys. Lines 34–35 create an FSO instance (i.e., an object) and assign it to reference file-Object.When assigning an object to a reference in VBScript, keyword Set is required. We want only lines41–60 to execute only when the page is loaded with a post request.Line 38 uses the Request objectto get hiddenInput’s value and compare it to the string "true. " When this page is requested by aclient for the first time, hiddenInput has the value "" (an empty string), and lines 41–60 do notexecute. Variable hiddenInput is only assigned value "true" during the post operation, as specifiedin lines 96–97. Lines 41–42 print Thanks for your entry, followed by the user’s name. The Request object gets the value posted in the username field of the submitted form. Theuser’s submitted name and e-mail address are combined with XHTML tags and assigned to stringmailtoUrl (lines 47–49). This string, when displayed in the browser, shows the submitted name asa mailto link. Clicking this link opens an e-mail message editor with the person’s name in the To:field. Line 47 calls VBScript function Date to assign the current server date to the beginning ofmailtoUrl. The Request object is used to retrieve the values from the email field (line 48) and theusername field (line 49). The value 34 is passed to the VBScript function Chr to get a double quote( " ) character. We call this function because the interpreter would treat a double quote as the endof the mailtoUrl string. The XHTML tags are stored in mailtoUrl.Lines 54–55 call methodOpenTextFile to get a TextStream object for accessing the text file guestbook.txt. The constantvalue 8 indicates append mode (writing to the end of the file), and True indicates that the file willbe created if it does not already exist. (Read and write modes would be specified with constantVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 252
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHvalues 1 and 2 , respectively.) Lines 58–59 write text to guestbook.txt using the TextStream methodWrite-Line. After writing the text to the file, TextStream method Close is called in line 60 to closethe file.Every time a client requests this Active Server Page, lines 100–115 execute. This VBScript code displays a list of all the users who have made guestbook entries. Line102 uses FSO method FileExists to check whether the guestbook.txt file exists. If this functionreturns True, lines 106–112 execute. In line 106, guestbook.txt is opened for reading. Lines 110–111read the entries from the file and write XHTML to the client. The entire contents of guestbook.txtare read by calling TextStream method ReadAll in line 111. This text is written to the client usingResponse.Write. This text contains XHTML markup which is rendered in the client browser. TheTextStream method Close is called in line 112 to close the file. Figure 33.14 shows the contents ofguestbook.txt after two users have submitted comments.16) Explain the working of a Server Side Active X Component Using an example. Server-side script functionality is extended with server-side ActiveX components—ActiveXcontrols that typically reside on the Web server and do not have a graphical user interface. Thesecomponents make features accessible to the ASP author. Figure 33.30 summarizes some of theActiveX components included with Internet Information Services (IIS). Many Web sites sell advertising space—especially Web sites with large numbers of hits.The code in Fig. 33.31 demonstrates the AdRotator ActiveX component for rotatingadvertisements on a Web page. Each time a client requests this Active Server Page, the AdRotatorcomponent randomly displays one of several advertisements—in this example, one of five flagimages. When the user clicks a country’s flag image, the country’s corresponding Central.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 253
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 254
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 255
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 256
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Intelligence Agency (CIA) Fact book Web page is displayed. Line 29 creates an instance ofan AdRotator component and assigns it to reference rotator. Server-side ActiveX components areinstantiated by passing the name of the component as a string to the Server object’s methodCreateObject. Lines 32–33 call the Response object’s Write method to send the advertisement asHTML to the client. Method GetAdvertisement is called using reference rotator to get theadvertisements from the file config.txt (Fig. 33.32).VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 257
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH The file’s header (lines 1–4) includes the URL of the REDIRECT file, redirect.asp (Fig.33.33), the image height, image width and image border width. The asterisk (line 5) separates theheader from the advertisements. Lines 6–9 describe the first advertisement by providing theimage’s URL (i.e., the image’s location), the destination URL for redirection upon clicking the ad, avalue for the alt tag (browsers that cannot display graphics display the specified text) and anumber (between 0 and 1000) representing the ratio of time this particular image appears. Theratios must be numbers between 0 and 10,000. For example, if four ads have the ratios 6, 9, 12 and3, then the time ratios are calculated as 20% (6/30), 30% (9/30), 40% (12/30) and 10% (3/30),respectively. Lines 10–25 list the other four advertisements. File redirect.asp (Fig. 33.33) redirects the user to the country page when the ad is clicked.Each time the ad is clicked, the document redirect.asp is requested and a query string is sent withVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 258
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHthe request. The query string contains an attribute url that is equal to the destination URL found inconfig.txt for this ad. Because we are redirecting the user to a different page on the client ratherthan the server, we call Response method Redirect to redirect the user to the country page. Forexample, click the U.S. flag. The resulting behavior is equivalent to typinghttp://localhost/deitel/redirect.asp?url=http://www.odci.gov/cia/publications/factbook/geos/us.html in the browser’s Addressfield. We arbitrarily chose the names config.txt and redirect.asp . You may choose any name youprefer. The redirect file loads (into the browser) the page referenced by the ad’s URL. These filescan be placed anywhere in the publishing directory (i.e., they do not have to be under the samedirectory as rotate.asp). For example, if you put config.txt under directory X in the publishingdirectory, then Fig. 33.31 lines 32–33 would read CallResponse.Write( _flagChanger.GetAdvertisement( "/X/config.txt" ) ) Note that GetAdvertisementis passed a URL, not a physical disk path. Hence the use of the forward slash. Also note that/X/config.txt is short for http://localhost/X/ config.txt (the server is localhost, and thepublishing directory is C:Inetpubwwwroot). You can replace localhost with the IP address127.0.0.1, which also refers to the local machine. Web servers respond to a variety of clients, and as a result an ASP document often needs todetermine who the client is and what features it supports. Line 36 (Fig. 33.31) creates aBrowserType object to obtain information about the client’s browser. Line 38 checks propertyVBScript’s value to determine whether it is True. If it is, the block (lines 48–50) is written to theclient. Lines 46–52 test the JavaScript property. Line 56 passes the server variable keyHTTP_USER_AGENT to ServerVariables to obtain a string containing the client’s information. TheBrowserType object’s Browser, Version and MinorVer properties (lines 57–59) may also be usedto obtain similar client information. Line 61 tests the Cookies property’s value to determinewhether the browser supports cookies. Many popular Web sites display a hit counter that showshow many visitors the site has had. IIS provides the PageCounter ActiveX component for storingthe number of hits. Method PageHit (line 71) increments the number of hits by one, and methodHits (line 76) returns the number of hits.17) What is UDA. How the Database Connectivity is performed in ASP? Microsoft’s ActiveX Data Objects is used to enable database connectivity in ASP. Forfurther information on databases in general and a discussion of the next generation of ADO,ADO.NET, please refer to Chapter 22, Database: SQL, MySQL, DBI and ADO.NET. Thearchitecture of Microsoft Universal Data Access (UDA) can support high-performance data accessto relational data sources, nonrelational data sources and mainframe/ legacy data sources. TheUDA architecture (Fig. 33.22) consists of three primary components. The OLE DB, the core of theUDA architecture, provides low-level access to any data source. The Open Database Connectivity(ODBC) is a C programming-language library that uses SQL to access data. ActiveX Data Objects(ADO) are simple object models (Fig. 33.23) that provide uniform access to any data source byinteracting with OLE DB.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 259
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHMore specifically, the ADO object model provides objects and collections (i.e., containersthat hold one or more objects of a specific type). Figure 33.24 briefly describessome ADO objects and collections.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 260
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH18) Discuss in detail about the accessing of a Database from ASP with necessary exampleprograms. Active Server Pages can communicate with databases through ADO (ActiveX Data Objectsintroduced in the preceding section). ADO provides a uniform way for a program to connect witha variety of databases without having to deal with their specifics. Web applications are typicallythree-tier distributed applications, consisting of a user interface, business logic and databaseaccess. The user interface in such an application is often created using XHTML, Dynamic HTMLor XML. The user interface can contain ActiveX controls, client-side scripts and, in some cases,Java applets. XHTML is the preferred mechanism for representing the user interface in systemswhere portability is a concern. Because most browsers support XHTML, designing the userinterface to be accessed through a Web browser guarantees portability across all browserplatforms. The user interface can communicate directly with the middle-tier business logic byusing the networking provided automatically by the browser. The middle tier can then access thedatabase to manipulate the data. All three tiers may reside on separate computers that areconnected to a network or on a single machine. Active Server Pages, through ADO, can interactwith popular database systems.Figure 33.25 ( database.asp) is an ASP document used to connect to and query an Access database.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 261
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH For simplicity, if an error occurs while the records are being retrieved, we choose to handlethe error later in the script. Line 11 specifies that any error caused by a statement from this pointonward is ignored, and control is transferred to the statement immediately following thestatement that caused the error. Line 12 declares session variable error- String and assigns it anempty string as its value. The Server object provides a method ( CreateObject) to instantiate otherobjects (e.g., built-in objects, ActiveX components). Line 14 calls Server method CreateObject tocreate an ADODB. Connection object and Sets it to reference connection. An ADODB. Connectionobject encapsulates the functionality necessary to connect to a data source. Line 15 calls methodOpen to open the database referenced by the specified ODBC System DSN (i.e., login). Line 16calls procedure errorHandlerLog to process any errors that might have occurred in the script.Lines 25–36 define procedure errorHandlerLog. When an error occurs in the script, Err object’sNumber property contains an integer representing which VBScript error has occurred. Line 26tests whether an error has occurred. If True, lines 27– 34 assign XHTML text containing the errorVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 262
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHnumber and a message to session variable errorString. Lines 19–20 Set reference loginData to anADODB.Recordset object and call method Open to execute the query (passed by login.asp) againstthe database referenced by connection. Method Open is passed a string containing the SQL queryand the ADODB.Connection object that connection references. When Open finishes executing, theADODB.Recordset object referenced by loginData contains all the records that match the SQLquery and points to either the first record or end of file ( EOF) if no records were found. Line 21Sets session variable loginData to variable loginData referencing the ADODB.Recordset objectcontaining all the records that matched the SQL query. Line 23 calls procedure errorHandlerLogfor a second time. Note that in line 30 the error number and message are concatenated to variableerrorString to ensure that error information is added to previous errors the script has encountered.In Fig. 33.26, we show a sample error.Figure 33.27 provides an Active Server Page named login.asp, which prompts the user for a loginname and password. The login names and passwords are stored in the Access database opened indatabase.asp.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 263
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 264
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 265
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 266
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH This example uses cookies to identify users. The user’s browser must have cookies enabledto run the example. If cookies are disabled, the browser will not permit the example to write acookie to the client machine, and the example will not be able to identify the user properly.Cookies are enabled in Internet Explorer 6 by selecting Internet Options from the Tools menu,which displays the Internet Options dialog.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 267
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Click the Security tab at the top of this dialog to view the current security settings. Selectthe Custom Level... button, scroll down and find Cookies, then click Enable for both cookieoptions. The Active Server Page login.asp prompts the user for a login ID and a password, whilesubmitlogin.asp is responsible for validating the user’s login. Both submitlogin. asp and login.aspuse session variable loginFailure. If login is successful, loginFailure is set to False, and the client istransferred to instantpage.asp. If login is unsuccessful, the variable is set to True and the client istransferred back to login.asp. The page recognizes that there was an error in submitlogin.asp anddisplays the error message, because login.asp has access to session variable login- Failure. The loginID and password fields are stored in table Users inside an Access database namedlogin.mdb. For this example to perform correctly, use for username and password: bug1, bug2,bug3 or bug4. Users select their loginID from a drop-down list populated from the Users table.Note that submitlogin.asp also accesses the database to verify login information. The file submitlogin.asp writes a cookie (named loginID) to the client containing the user’sloginID string to recognize returning users and to have their loginID displayed as selected in thedrop-down list. When the user returns, login.asp reads the cookie and selects the user’s loginname from the drop-down list. Line 9 assigns the SQL query that SELECTs all the loginIDs FROM the Users table tosession variable query. We use this session variable in database.asp (Fig. 33.25) as a parameter inmethod Open to query the database for each login ID. Line 10 executes database.asp to retrieve thelogin IDs from the database. Line 36 tests whether session variable errorString has an empty stringas its value. Session variable errorString will have an empty string as its value unless an error hasoccurred in database.asp. If this returns False, line 89 calls Response method Write to print theerror message to the user. Lines 39–86 are executed only if database.asp has not returned an error.Lines 39– 41 determine whether or not the session variable loginFailure is True, indicating thatsubmitlogin.asp has detected an invalid login. If True, a message is displayed informing the client that the login attempt has failed andprompting for another login. The select statement is included to build the drop-down list ofloginIDs. Lines 57– 58 write the first option that displays "Select your name". If no other option ismarked as selected, this option is displayed when the page is loaded. The next options are theloginIDs retrieved from the database. If this is a returning user, we want to display the loginID asselected. Line 61 requests the loginID cookie. If this is the user’s first visit, or if the cookie hasexpired, Cookie returns an empty string. [ Note: It is possible for a cookie to store an empty string.If this is the case, Cookie returns the cookie contents, which is an empty string.] Otherwise, the user’s loginID is returned. Lines 61–65 call BuildReturning if loginIDcontains a login ID and call BuildNewUser. Both BuildReturning and Build-NewUser build thelogin ID options. However, BuildReturning selects the returning user’s login ID option, whereasBuildNewUser does not. BuildReturning’s While loop (lines 107–130) iterates through loginData’sVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 268
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHrecords. Recall that loginData contains the loginID column (field) of the Users table from line 101and points either to the first record or to EOF. Line 107 tests for the end of the record set,indicating that there are no further records. Line 129 increments the record set pointer to the nextrecord. Each iteration of the While loop builds an option item for the current record. Line 109simply writes the opening of the option item. Next, we test whether this option needs to beselected with the If statement in lines 120–125. Note that once we have written selected for anoption, there is no need to perform this check in further iterations —selected is written for onlyone option. The code that writes selected for an option is thus wrapped in another If statement(lines 112–126). Variable found is set to False before the loop, in line 105. Once selected is writtenfor an option, found is assigned True. Line 112 prevents the code that writes selected for an optionfrom being executed unnecessarily after an option is already selected. Lines 120–121 determinewhether the current record’s loginID field is equal to the value of the loginID cookie. If it is, lines122–124 write selected and set found to True. Line 127 sets the value for the option to the currentloginID. Finally, line 128 writes the display of this option as the current loginID. Active ServerPage submitlogin.asp (Fig. 33.28) takes the values passed to it by login.asp and checks themagainst the Users table in the database. If a match is found, the user is redirected toinstantpage.asp. If no match is found, the user is redirected back to login.asp. The user never seesor knows about submitlogin.asp because the page is pure scripting code (i.e., its entire contents areenclosed in scripting delimiters). Lines 9–13 check whether the form’s password field is empty orif the loginID field was submitted with the default value. If so, session variable loginFailure is setto True and the client is redirected back to login.asp. Lines 18–20 select all the fields from the table.The WHERE clause in this SQL statement specifies a condition on which records are selected:Only the record(s) whose loginID field has the same value as the form’s loginID field is selected. UNIT - V PART - A1) What is Servlet? Explain its Lifecycle. Servlets are normally executed by the servlet container component of a Web applicationserver. All servlets must implement the Servlet interface. The methods of interface Servlet areVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 269
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHinvoked automatically by the servlet container. • The classes and interfaces used to define servletsare found in packages javax.servlet and javax.servlet.http. A servlet’s life cycle begins when theservlet container loads the servlet into memory—normally in response to the first request to thatservlet. Before the servlet can handle the first request, the servlet container invokes the servlet’sinit method. After init completes execution, the servlet can respond to its first request. All requestsare handled by a servlet’s service method, which may be called many times during the life cycle ofa servlet. When the servlet container terminates the servlet, the servlet’s destroy method is calledto release servlet resources.2) What are the classes and methods of the Servlet Package? The servlet packages define two abstract classes that implement the interface Servlet—classGenericServlet and class HttpServlet. Most servlets extend one of these classes and override someor all of their methods with appropriate customized behaviors. • The key method in every servletis method service, which receives both a ServletRequest object and a ServletResponse object. Theseobjects provide access to input and output streams that allow the servlet to read data from theclient and send data to the client.3) What are the request methods provided by Web Based Servlets? Web-based servlets typically extend class HttpServlet. Class HttpServlet overrides methodservice to distinguish between the typical requests received from a client Web browser. The twomost common HTTP request types (also known as request methods) are get and post. ClassHttpServlet defines methods doGet and doPost to respond to get and post requests from a client,respectively. These methods are called by the HttpServlet class’s service method, which is calledwhen a request arrives at the server. Methods doGet and doPost receive as arguments anHttpServletRequest object and an HttpServletResponse object that enable interaction between theclient and the server4) Which host name can be used to test TCP/IP applications on the local computer? The server localhost (IP address 127.0.0.1) is a well-known host name on computers thatsupport TCP/IP-based networking protocols such as HTTP. This host name can be used to testTCP/IP applications on the local computer.5) What is TOMCAT? How does it works? The Tomcat server awaits requests from clients on port 8080. This port number must bespecified as part of the URL to request a servlet running in Tomcat. The client can access a servletonly if that servlet is installed on a server that can respond to servlet requests. Web servers thatsupport servlets normally have an installation procedure for servlets. Tomcat is a fully functionalVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 270
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHimplementation of the JSP and servlet standards. It includes a Web server, so it can be used as astand-alone test container for JSPs and servlets. Tomcat can be specified as the handler for JSP andservlet requests received by popular Web servers such as Apache and IIS. Tomcat also isintegrated into the Java 2 Enterprise Edition reference implementation from Sun Microsystems.6) What is Web Application? Give its Directory Structure. JSPs, servlets and their supporting files are deployed as part of Web applications. InTomcat, Web applications are deployed in the webapps subdirectory of the Tomcat installation. AWeb application has a well-known directory structure in which all the files that are part of theapplication reside. This directory structure can be set up by the Tomcat server administrator in thewebapps directory, or the entire directory structure can be archived in a Web application archivefile. Such an archive is known as a WAR file and ends with the .war file extension. If a WAR file isplaced in the webapps directory, when the Tomcat server starts up it extracts the contents of theWAR file into the appropriate webapps subdirectory structure. The Web application directorystructure is separated into a context root—the top-level directory for an entire Web application—and several subdirectories. The context root is the root directory for the Web application. All theJSPs, HTML documents, servlets and supporting files such as images and class files reside in thisdirectory or its subdirectories. The WEB-INF directory contains the Web application deploymentdescriptor ( web.xml). The WEB-INF/classes directory contains the servlet class files and othersupporting class files used in a Web application. The WEBINF/ lib directory contains Java archive(JAR) files that may include servlet class files and other supporting class files used in a Webapplication.7) How will you deploy a web application? Before deploying a Web application, the servlet container must be made aware of thecontext root for the Web application. In Tomcat, this can be done simply by placing a directory inthe webapps subdirectory. Tomcat uses the directory name as the context name. Deploying a Webapplication requires the creation of a deployment descriptor (web.xml).8) How does a HTTP get request is processed? HTTP get requests can be typed directly into your browser’s Address or Location field.Parameters are passed as name/value pairs in a get request. A ? separates the URL from the datapassed as part of a get request. Name/value pairs are passed with the name and the valueseparated by = . If there is more than one name/value pair, each name/value pair is separated by& . Method getParameter of interface HttpServletRequest receives the parameter name as anargument and returns the corresponding String value, or null if the parameter is not part of therequest.9) How do a HTTP Post request works? An HTTP post request is often used to post data from a Web-page form to a server-sideform handler that processes the data. Browsers often cache (save on disk) Web pages so they canquickly reload the pages. Browsers do not cache the server’s response to a post request. MethodVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 271
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHdoPost receives the same two arguments as doGet—an object that implements interfaceHttpServletRequest to represent the client’s request and an object that implements interfaceHttpServletResponse to represent the servlet’s response.10) What is the function of the method sendRedirect? Method sendRedirect of HttpServletResponse redirects a request to the specified URL.When a servlet uses a relative path to reference another static or dynamic resource, the servletassumes the same context root unless a complete URL is specified for the resource. Once methodsendRedirect executes, processing of the request by the servlet that called sendRedirect terminates.11) What is the function of the init method? Servlet method init takes a ServletConfig argument and throws a ServletException. Theargument provides the servlet with information about its initialization parameters that arespecified in a servlet element in the deployment descriptor. Each parameter appears in an init-param element with child elements param-name and param-value.12) List the four key components of JSP. There are four key components to JSPs—directives, actions, scriptlets and tag libraries.13) What is JSP and how does it works? JSPs normally include XHTML or XML markup. Such markup is known as fixed templatedata or fixed template text. • Programmers tend to use JSPs when most of the content sent to theclient is fixed template data and only a small portion of the content is generated dynamically withJava code. Programmers use servlets when a small portion of the content is fixed template data.JSPs normally execute as part ofaWeb server. The server often is referred to as the JSP container.When a JSP-enabled server receives the first request for a JSP, the JSP container translates that JSPinto a Java servlet that handles the current request and future requests to the JSP.The JSP containerplaces the Java statements that implement a JSP’s response in method _jspService at translationtime. The request/response mechanism and life cycle of a JSP are the same as those of a servlet .JSPs can define methods jspInit and jspDestroy that are invoked when the container initializes aJSP and when the container terminates a JSP, respectively. JSP expressions are delimited by <%=and %>. Such expressions are converted to Strings by the JSP container and are output as part ofthe response.14) What are implicit Objects? Where they are used? Implicit objects provide programmers with servlet capabilities in the context of a JavaServerVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 272
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHPage. Implicit objects have four scopes—application, page, request and session. • Objects withapplication scope are part of the JSP and servlet container application. Objects with page scopeexist only as part of the page in which they are used. Each page has its own instances of the page-scope implicit objects. Objects in request scope exist for the duration of the request. Request-scopeobjects go out of scope when request processing completes with a response to the client. Objects insession scope exist for the client’s entire browsing session.15) Explain the JSP Scripting Components. JSP scripting components include scriptlets, comments, expressions, declarations andescape sequences. Scriptlets are blocks of code delimited by <% and %>. They contain Javastatements that are placed in method _jspService when the container translates a JSP into a servlet.JSP comments are delimited by <%-- and --%>. XHTML comments are delimited by <!—and -->.Java’s end-of-line comments ( //) and traditional comments (delimited by /* and */) can be usedinside scriptlets. JSP comments and scripting language comments are ignored and do not appearin the response. AJSP expression, delimited by <%= and %>, contains a Java expression that isevaluated when a client requests the JSP containing the expression. The container converts theresult of a JSP expression to a String object, then outputs the String as part of the response to theclient. Declarations, delimited by <%! and %>, enable a JSP programmer to define variables andmethods. Variables become instance variables of the class that represents the translated JSP.Similarly, methods become members of the class that represents the translated JSP. • Specialcharacters or character sequences that the JSP container normally uses to delimit JSP code can beincluded in a JSP as literal characters in scripting elements, fixed template data and attributevalues by using escape sequences.16) What are the include mechanisms supported by JSP? JavaServer Pages support two include mechanisms—the <jsp:include> action and theinclude directive. Action <jsp:include> enables dynamic content to be included in a JavaServerPage. If the included resource changes between requests, the next request to the JSP containing the<jsp:include> action includes the new content of the resource. The include directive is processedonce, at JSP translation time, and causes the content to be copied into the JSP. If the includedresource changes, the new content will not be reflected in the JSP that used the include directiveunless that JSP is recompiled.17) Give the functions of i) JSP:forward ii) jsp:param iii)jsp:useBean.i)Action <jsp:forward> enables a JSP to forward the processing of a request to a different resource.Processing of the request by the original JSP terminates as soon as the request is forwarded.ii)Action <jsp:param> specifies name/value pairs of information that are passed to the include,forward and plugin actions. Every <jsp:param> action has two required attributes—name andvalue. If a param action specifies a parameter that already exists in the request, the new value forthe parameter takes precedence over the original value. All values for that parameter can beVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 273
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHobtained with the JSP implicit object request’s getParameterValues method, which returns anarray of Strings.iii) Action <jsp:useBean> enables a JSP to manipulate a Java object. This action can be used tocreate a Java object for use in the JSP or to locate an existing object.18) What are Directives? Give Example. Directives are messages to the JSP container that enable the programmer to specify pagesettings (such as the error page), to include content from other resources and to specify custom taglibraries that can be used in a JSP. Directives are processed at the time a JSP is translated into aservlet and compiled. Thus, directives do not produce any immediate output. The page directivespecifies global settings for a JSP in the JSP container. There can be many page directives,provided that there is only one occurrence of each attribute. The exception to this rule is theimport attribute, which can be used repeatedly to import Java packages.19. What are Tag Libraries in JSP? They are part of Tag extension that enable the programmers to create custom tags andmanipulate the JSP contents.20. What is the use of JSP container? JSP executes as a part of the web server. The server component that executes them arerefered as JSP container.21. Mention some attributes of page directives. i. language ii. Extends iii. import iv. Session v. buffer vi. Auto flash viii. Is Thread safe viii. Info ix. errorpage x. Is error page xi. Extent type22. What is i) Socketbased communication & ii) Packet based communication? i. Socket based communication : Enables applications to view networking as streams of data. The program can lead from or write a socket. ii. Packet based communication : Enable individual packets of information to be transmitted.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 274
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH PART - B1) Discuss in detail about the overview of Servlets and its architecture. The Internet offers many protocols. The HTTP ( Hypertext Transfer Protocol) that formsthe basis of the World Wide Web uses URLs ( Uniform Resource Locators) to locate resources onthe Internet. Common URLs represent files or directories and can represent complex tasks such asdatabase lookups and Internet searches. For more information on URL formats, visitwww.w3.org/Addressing. For more information on the HTTP protocol, visitwww.w3.org/Protocols/HTTP. For information on a variety of World Wide Web topics, visitwww.w3.org. JavaServer Pages technology is an extension of servlet technology. Normally, JSPsare used when most of the content sent to the client is static text and markup, and only a smallportion of the content is generated dynamically with Java code. Servlets commonly are used whena small portion of the content sent to the client is static text or markup. In fact, some servlets donot produce content. Rather, they perform a task on behalf of the client, then invoke other servletsor JSPs to provide a response. Note that in most cases servlet and JSP technologies areinterchangeable. The server that executes a servlet is referred to as theServlet container or servlet engine. Servlets and JavaServer Pages have become so popular that they are now supporteddirectly or with third-party plug-ins by most major Web servers and application servers, includingthe Sun ONE Application Server, Microsoft’s Internet Information Services (IIS), the Apache HTTPServer, BEA’s WebLogic application server, IBM’s WebSphere application server, the World WideWeb Consortium’s Jigsaw Web server, and many more. The servlets in this chapter demonstrate communication between clients and servers via theHTTP protocol. A client sends an HTTP request to the server. The servlet container receives therequest and directs it to be processed by the appropriate servlet. The servlet does its processing,which may include interacting with a database or other server-side components such as otherservlets, JSPs or Enterprise JavaBeans. The servlet returns its results to the client—normally in theVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 275
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHform of an HTML, XHTML or XML document to display in a browser, but other data formats,such as images and binary data, can be returned.2) Explain in detail about the interface servlet and Servlet Lifecycle. Architecturally, all servlets must implement the Servlet interface. As with the key appletmethods, the methods of interface Servlet are invoked by the servlet container. This interfacedefines five methods described in Fig. 36.1.All servlets must implement the Servlet interface of package javax.servlet. 36.1Method Descriptionvoid init( ServletConfig config ) The servlet container calls this method once during a servlet’sexecution cycle to initialize the servlet. The ServletConfig argument is supplied by the servletVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 276
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHcontainer that executes the servlet. ServletConfig getServletConfig() This method returns a reference to an object thatimplements interface ServletConfig. This object provides access to the servlet’s configurationinformation such as servlet initialization parameters and the servlet’s ServletContext, whichprovides the servlet with access to its environment (i.e., the servlet container in which the servletexecutes). String getServletInfo() This method is defined by a servlet programmer to return astring containing servlet information such as the servlet’s author and version. voidservice( ServletRequest request, ServletResponse response ) The servlet container calls this methodto respond to a client request to the servlet.void destroy() This “cleanup” method is called when aservlet is terminated by its servlet container. Resources used by the servlet, such as an open file oran open database connection, should be deallocated here. A servlet’s life cycle begins when the servlet container loads the servlet into memory—normally, in response to the first request that the servlet receives. Before the servlet can handlethat request, the servlet container invokes the servlet’s init method. After init completes execution,the servlet can respond to its first request. All requests are handled by a servlet’s service method,which receives the request, processes the request and sends a response to the client. During aservlet’s life cycle, method service is called once per request. Each new request typically results ina new thread of execution (created by the servlet container) in which method service executes.When the servlet container terminates the servlet, the servlet’s destroy method is called to releaseservlet resources. The servlet packages define two abstract classes that implement the interfaceServlet—class GenericServlet (from the package javax.servlet) and classHttpServlet (from the package javax.servlet.http). These classes provide default implementationsof all the Servlet methods. Most servlets extend either Generic- Servlet or HttpServlet and overridesome or all of their methods. The examples in this chapter all extend class HttpServlet, whichdefines enhanced processing capabilities for servlets that extend the functionality of a Web server.The key method in every servlet is service, which receives both a ServletRequest object and aServletResponse object. These objects provide access to input and output streams that allow theservlet to read data from the client and send data to the client. These streams can be either bytebased or character based. If problems occur during the execution of a servlet, eitherServletExceptions or IOExceptions are thrown to indicate the problem.3) Discuss in detail about the HTTP Servlet class along with its interfaces. Web-based servlets typically extend class HttpServlet. Class HttpServlet overrides methodservice to distinguish between the typical requests received from a client Web browser. The twomost common HTTP request types (also known as request methods) are get and post. A getrequest gets (or retrieves) information from a server. Common uses of get requests are to retrievean HTML document or an image. A post request posts (or sends) data to a server. Common uses of post requests typicallysend information, such as authentication information or data from a form that gathers user input,VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 277
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHto a server. Class HttpServlet defines methods doGet and doPost to respond to get and postrequests from a client, respectively. These methods are called by method service, which is calledwhen a request arrives at the server. Method service first determines the request type, then callsthe appropriate method for handling such a request. Other less common request types are beyondthe scope of this book. Methods of class HttpServlet that respond to the other request types areshown in Fig. 36.2. They all receive parameters of type HttpServletRequest and HttpServletResponse andreturn void. The methods of Fig. 36.2 are not frequently used. For more information on the HTTPprotocol, visit www.w3.org/Protocols Methods doGet and doPost receive as arguments an HttpServletRequest object and anHttpServletResponse object that enable interaction between the client and the server. The methodsof HttpServletRequest make it easy to access the data supplied as part of the request. TheHttpServletResponse methods make it easy to return the servlet’s results to the Web client.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 278
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHHttpServletRequest Interface Every call to doGet or doPost for an HttpServlet receives an object that implements interfaceHttpServletRequest. The Web server that executes the servlet creates an HttpServletRequest objectand passes this to the servlet’s service method (which, in turn, passes it to doGet or doPost). Thisobject contains the request from the client. A variety of methods are provided to enable the servlet toprocess the client’s request. Some of these methods are from interface ServletRequest—the interfacethat HttpServletRequest extends. A few key methods used in this chapter are presented in Fig. 36.3.HttpServletResponse Interface Every call to doGet or doPost for an HttpServlet receives an object that implementsinterface HttpServletResponse. The Web server that executes the servlet creates anHttpServletResponse object and passes it to the servlet’s service method (which, in turn, passes itto doGet or doPost). This object provides a variety of methods that enable the servlet to formulatethe response to the client. Some of these methods are from interface ServletResponse—theVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 279
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHinterface that HttpServletResponse extends. A few key methods used in this chapter are presentedin Fig. 36.4.4) Discuss in detail about Deploying a Web Application. JSPs, servlets and their supporting files are deployed as part of Web applications.Normally, Web applications are deployed in the webapps subdirectory of jakarta-tomcat- 4.1.27.A Web application has a well-known directory structure in which all the files that are part of theapplication reside. This directory structure can be created by the server administrator in thewebapps directory, or the entire directory structure can be archived in a Web application archivefile. Such an archive is known as a WAR file and ends with the .war file extension. IfaWAR file isplaced in the webapps directory, then, when the Tomcat server begins execution, it extracts thecontents of the WAR file into the appropriate webapps subdirectory structure. For simplicity aswe teach servlets and JavaServer Pages, we create the already expanded directory structure for allthe examples in this chapter. The Web application directory structure contains a context root—thetop-level directory for an entire Web application—and several subdirectories. These are describedin Fig. 36.8.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 280
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Configuring the context root for a Web application in Tomcat requires creating asubdirectory in the webapps directory. When Tomcat begins execution, it creates a context root foreach subdirectory of webapps, using each subdirectory’s name as a context root name. To test theexamples in this chapter, create the directory iw3htp3 in Tomcat’s webapps directory. Afterconfiguring the context root, we must configure our Web application to handle the requests. Thisconfiguration occurs in a deployment descriptor, which is stored in a file called web.xml. Thedeployment descriptor specifies various configuration parameters such as the name used toinvoke the servlet (i.e., its alias), a description of the servlet, the servlet’s fully qualified class nameand a servlet mapping (i.e., the path or paths that cause the servlet container to invoke theservlet). You must create the web.xml file for this example. Many Java Web-applicationdeployment tools create the web.xml file for you. The web.xml file for the first example in thischapter is shown in Fig. 36.9.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 281
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Lines 1–3 specify the document type for the Web application deployment descriptor andthe location of the DTD for this XML file. Element web-app (lines 5–37) defines the configuration VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 282
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHof each servlet in the Web application and the servlet mapping for each servlet. Element display-name (lines 8–11) specifies a name that can be displayed to the administrator of the server onwhich the Web application is installed. Element description (lines 13–16) specifies a description ofthe Web application that might be displayed to the administrator of the server. Element servlet(lines 19–29) describes a servlet. Element servlet-name (line 20) is the name we chose for theservlet ( welcome1). Element description (lines 22–24) specifies a description for this particularservlet. Again, this can be displayed to the administrator of the Web server. Element servlet-class(lines 26–28) specifies compiled servlet’s fully qualified class name. Thus, the servlet welcome1 isdefined by class WelcomeServlet. Element servlet-mapping (lines 32–35) specifies servlet-nameand url-pattern elements. The URL pattern helps the server determine which requests are sent to the servlet( welcome1). Thus, the relative URL we supply to the browser to invoke the servlet in thisexample is /iw3htp3/welcome1 where /iw3htp3 specifies the context root that helps the serverdetermine which Web application handles the request and /welcome1 specifies the URL patternthat is mapped to servlet welcome1 to handle the request. If the explicit server and port numberare not specified as part of the URL, the browser assumes that the form handler (i.e., the servletspecified in the action property of the form element) resides at the same server and port numberfrom which the browser downloaded the Web page containing the form. There are several URLpattern formats that can be used. The /welcome1 URL pattern requires an exact match of thepattern. You can also specify path mappings, extension mappings and a default servlet for a Webapplication. A path mapping begins with a / and ends with a /*. For example, the URL pattern/iw3htp3/example/* indicates that any URL path beginning with /iw3htp3/example/ will besent to the servlet that has the preceding URL pattern. An extension mapping begins with *. andends with a file name extension. For example, the URL pattern *.jsp indicates that any request for afile with extension .jsp will be sent to the servlet that handles JSP requests. In fact, servers with JSPcontainers have an implicit mapping of the .jsp extension to a servlet that handles JSP requests. The URL pattern / represents the default servlet for the Web application. This is similar tothe default document of a Web server. For example, if you type the URL www.deitel.com intoyour Web browser, the document you receive from our Web server is the default documentindex.html. If the URL pattern matches the default servlet for aWeb application, that servlet isinvoked to return a default response to the client. This can be useful for personalizing Webcontent to specific users. Finally, we are ready to place our files into the appropriate directories tocomplete the deployment of our first servlet for testing. There are three files we must place in theappropriate directories—WelcomeServlet.html, WelcomeServlet.class and web.xml. In thewebapps subdirectory of your jakarta-tomcat-4.1.27 directory, create subdirectory iw3htp3—thecontext root for our Web application. In this directory, create subdirectories named servlets andWEB-INF. We place our HTML files for this servlets chapter in the servlets directory. Copy theWelcomeServlet.html file into the servlets directory.In the WEB-INF directory, create thesubdirectory classes, then copy the web.xml file into the WEB-INF directory, and copy theWelcomeServlet.class file into the classes directory. [ Note: To compile your servlet, you will needto use javac’s -classpath option to specify the name and location of the file servlet.jar, which islocated in Tomcat’s commonlibs directory.] Thus, the directory and file structure under theVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 283
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHwebapps directory should be as shown in Fig. 36.10 (file names are in italics).5) Discuss in detail about Multitier Applications using JDBC. Servlets can communicate with databases via JDBC (Java Database Connectivity). JDBCprovides a uniform way for Java programs to connect with a variety of databases in a generalmanner without having to deal with the specifics of those database systems. Many of today’sapplications are three-tier distributed applications, consisting of a user interface, business logicand a database. The user interface in such an application is often created using HTML, XHTML(as shown in this chapter) or Dynamic HTML. and XHTML are the preferred mechanisms forrepresenting the user interface in systems where portability is a concern. Because HTML issupported by all browsers, designing the user interface to be accessed through a Web browserguarantees portability across all platforms that have browsers. Using the networking provided bythe browser, the user interface can communicate with the middle-tier business logic. The middletier can then access the database to manipulate the data. The three tiers can reside on separatecomputers that areconnected to a network. In multi-tier architectures, Web servers often are usedin the middle tier. Server-side components, such as servlets, execute in an application server along-side theWeb server. These components provide the business logic that manipulates data from databasesand that communicates with client Web browsers. Servlets, through JDBC, can interact withpopular database systems. Developers use SQL-based queries, and JDBC drivers handle thespecifics of interacting with each database system. The SurveyServlet of Fig. 36.20 and theSurvey.html document of Fig. 36.21 implement portions of a three-tier distributed application. Themiddle tier is SurveyServlet, which handles requests from the client browser and provides accessto the third tier—a Microsoft Access database accessed via JDBC. The servlet in this exampleallows users to vote for their favorite animals. When the servlet receives a post request from theweb browser, the servlet uses JDBC to update the total number of votes for that animal in thedatabase and returns a dynamically generated XHTML document containing the survey results tothe client.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 284
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 285
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 286
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 287
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Lines 12 and 13 begin by declaring a Connection reference to manage the databaseconnection and a Statement reference for updating the vote count for an animal, totaling all thevotes and obtaining the complete survey results. Servlets are initialized by method init, which weoverride in SurveyServlet (lines 16–35). Method init is called exactly once in a servlet’s lifetime,before any client requests are accepted. Method init takes ServletConfig argument and throws aServletException. The argument provides the servlet with information about its initializationparameters (i.e., parameters not associated with a request, but passed to the servlet for initializingthe servlet’s state). These parameters are specified in the web.xml deployment descriptor file aspart of a servlet element. Each parameter appears in an initparam element of the following form:<init-param><param-name>parameter name</param-name><param-value>parameter value</param-value></init-param> Servlets can obtain initialization parameter values by invoking ServletConfig methodgetInitParameter, which receives a string representing the name of the parameter. In this example,the servlet’s init method (lines 16–38) performs the connection to the Access database. Line 20loads the driver ( sun.jdbc.odbc.JdbcOdbcDriver,which is specified in the initialization parameter"databaseDriver"). Lines 21–22 attempt to open a connection to the animalsurvey database. Thedatabase name is specified in the initialization parameter "databaseName". The database containsone table ( surveyresults) that consists of three fields—a unique integer to identify each record( id), a string representing the survey option ( surveyoption) and an integer representing thenumber of votes for a survey option ( votes). [ Note: The examples folder for this chapter containsthe Access database ( animalsurvey.mdb) used in this example. For information on setting up anODBC Data Source Name to reference this database, please seeVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 288
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHwww.deitel.com/books/iw3HTP3/index.html.] Chapter 36 Servlets: Bonus for Java™ Developers1321. When a user submits a survey response, method doPost (lines 38–124) handles the request.Lines 61–62 obtain the survey response, then lines 66–112 attempt to process the response. Lines69–70 specify a query to increment the votes value for the record with the specified ID and updatethe database. Lines 78–80 execute the query specified in line 74 to retrieve the total number ofvotes received using SQL’s built-in sum capability to total all the votes in the surveyresults table.Then, lines 82–110 execute the query (returns all the data in the surveyresults table) specified inlines 80–81 and process the ResultSet to create the survey summary for the client. When the servletcontainer terminates the servlet, method destroy (lines 127–139) closes the Statement, then closesthe database connection. Figure 36.21 shows survey.html, which invokes SurveyServlet throughalias animalsurvey when the user submits the form.6) Explain JSP Architechture and its working with a simple JSP program. JSPs are built on top of SUN’s servlet technology. JSPs are essential an HTML page withspecial JSP tags embedded. These JSP tags can contain Java code. The JSP file extension is jsprather than htm or html. The JSP engine parses the jsp and creates a Java sevlet source file. It thencomplies the source file into a class file, this is done the first time and this why the JSp is probablyslower the first time it is accessed. Any time after this the special compiled servlet is executed andis therefore returns faster. JavaServer Pages simplify the delivery of dynamic Web content. They enable Webapplication programmers to create dynamic content by reusing predefined components and byinteracting with components using serverside scripting. JavaServer Page programmers can reuseJavaBeans and create custom tag libraries that encapsulate complex, dynamic functionality.Custom-tag libraries even enable Web-page designers who are not familiar with Java to enhanceWeb pages with powerful dynamic content and processing capabilities. In addition to the typesfor programming servlets (Chapter 36), classes and interfaces specific to JavaServer Pagesprogramming are located in packages javax.servlet.jsp and javax.servlet.jsp.tagext.Steps required for a JSP request: 1. The user goes to a web site made using JSp . the user goes to a JSP page (ending with jsp) . The web browser makes the request via the Internet. 2. The Web server gets sent to the Web server. 3. The Web server recognizes that the file required is special (.jsp) therefore passes the JSP file to the JSP Servlet Engine. 4. If the JSP file has been called the first time, the JSP file is parsed, otherwise go to step 7 5. The next step is to generate a special Servlet from the JSP file. All the HTML required is converted to printing statements, 6. The Servlet is instantiated, calling the init and service methods. 7. HTML from the Servlet output is sent via the Internet.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 289
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 8. HTML results are displayed on the user’s web browser. There are four key components to JSPs: directives, actions, scriptlets and tag libraries.Directives are messages to the JSP container that enable the programmer to specify page settings,to include content from other resources and to specify custom tag libraries for use in a JSP. Actionsencapsulate functionality in predefined tags that programmers can embed in a JSP. Actions oftenare performed based on the information sent to the server as part of a particular client request.They also can create Java objects for use in JSP scriptlets. Scriptlets, or scripting elements, enableprogrammers to insert Java code that interacts with components in a JSP (and possibly other Webapplication components) to perform request processing. Tag libraries are part of the tag extensionmechanism that enables programmers to create custom tags. Such tags enable programmers tomanipulate JSP content. These JSP component types are discussed in detail in subsequent sections.In some ways, Java Server Pages look like standard XHTML or XML documents. In fact, JSPsnormally include XHTML or XML markup. Such markup is known as fixedtemplate data orfixed-template text. Fixed-template data often help a programmer decide whether to use a servletor a JSP. Programmers tend to use JSPs when most of the content sent to the client is fixedtemplate data and only a small portion of the content is generated dynamically with Java code.Programmers typically use servlets when only a small portion of the content sent to the client isfixed-template data. In fact, some servlets do not produce content. Rather, they perform a task onbehalf of the client, then invoke other servlets or JSPs to provide a response. Note that in mostcases, servlet and JSP technologies are interchangeable. As with servlets, JSPs normally execute aspart of a Web server. The server component that executes them often is referred to as the JSPcontainer. When a JSP-enabled server receives the first request for a JSP, the JSP container translatesthat JSP into a Java servlet that handles the current request and future requests to the JSP. If thereare any errors compiling the new servlet, these errors result in translationtime errors. The JSPcontainer places the Java statements that implement the JSP’s response in method _jspService attranslation time. If the new servlet compiles properly, the JSP container invokes method_jspService to process the request. The JSP may respond directly to the request or may invokeother Web application components to assist in processing the request. Any errors that occurduring request processing are known as request-time errors. We begin our introduction to JavaServer Pages with a simple example (Fig. 37.1) in whichthe current date and time are inserted into a Web page using a JSP expression. As you can see,most of clock.jsp consists of XHTML markup. In cases like this, JSPs are easier to implement thanservlets. In a servlet that performs the same task as this JSP, each line of XHTML markup typicallyis a separate Java statement that outputs the string representing the markup as part of theresponse to the client. Writing code to output markup can often lead to errors. Most JSP editorsprovide syntax coloring to help programmers check that their markup follows proper syntax.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 290
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 291
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH The JSP of Fig. 37.1 generates an XHTML document that displays the current date and time.The key line in this JSP (line 30) is the expression <%= new java.util.Date() %> JSP expressions aredelimited by <%= and %>. The preceding expression creates a new instance of class Date (packagejava.util). When the client requests this JSP, the preceding expression inserts the Stringrepresentation of the date and time in the response to the client. We use the XHTML meta elementin line 10 to set a refresh interval of 60 seconds for the document. This causes the browser torequest clock.jsp every 60 seconds. For each request to clock.jsp, the JSP container reevaluates theexpression in line 30, creating a new Date object with the server’s current date and time.7) Discuss in detail about the Directives of JSP.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 292
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHPage Directive The page directive specifies global settings for the JSP in the JSP container. There can bemany page directives, provided that there is only one occurrence of each attribute. The onlyexception to this is the import attribute, which can be used repeatedly to import Java packagesused in the JSP. Figure 37.18 summarizes the attributes of the page directive.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 293
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 294
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHInclude Directive The include directive includes the content of another resource once, at JSP translation time.The include directive has only one attribute—file—that specifies the URL of the resource toinclude. The difference between directive include and action <jsp:include> is noticeable only if theincluded content changes. For example, if the definition of an XHTML document changes after itis included with directive include, future invocations of the JSP will show the original content ofthe XHTML document, not the new content. In contrast, action <jsp:include> is processed in eachrequest to the JSP. Therefore, changes to included content would be apparent in the next requestto the JSP that uses action <jsp:include>.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 295
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 296
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECHVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 297
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH8) Discuss in detail about the Standard Actions of JSP. The JSP standard actions (Fig. 37.5) provide JSP implementors with access to several of themost common tasks performed in a JSP, such as including content from other resources,forwarding requests to other resources and interacting with JavaBeans. JSP containers processactions at request time. Actions<jsp:include> ActionVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 298
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH JavaServer Pages support two include mechanisms—the <jsp:include> action and theinclude directive. Action <jsp:include> enables dynamic content to be included in a JavaServerPage at request time (not translation time as with the include directive). If the included resourcechanges between requests, the next request to the JSP containing the <jsp:include> action includesthe new content of the resource. On the other hand, the include directive copies the content intothe JSP once, at JSP translation time. If the included resource changes, the new content will not bereflected in the JSP that used the include directive unless that JSP is recompiled. Figure 37.6describes the attributes of action <jsp:include>. Action <jsp:forward> enables a JSP to forward request processing to a different resource.Request processing by the original JSP terminates as soon as the JSP forwards the request. Action<jsp:forward> has only a page attribute that specifies the relative URL of the resource (in the sameWeb application) to which the request should be forwarded. Q 2338 B.E./B.Tech. DEGREE EXAMINATION Sixth Semester Information Technology IF 366 – WEB TECHNOLOGY PART – A1. What is markup language? List any four markup languages.2. List the significance of the scripting language in a HTML document?3. What are the essential features of a browser?4. How an applet program is different from a java program?5. What is meant by marshaling?6. What are reserved sockets? Give two examples7. What are the advantages of XML compared to HTML?8. List the different types of JSP tags.9. What is exactly meant by information in business organization?10. What are the differences between EDI and e-mail? PART – B11. (a) (i) Describe various communication protocols used in the Internet. (ii) Explain the different types of text formatting tags available in the HTML.VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 299
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH Or (b) (i) Explain the hardware and software components of a Internet. (ii) Describe the features of the standard generalized markup language and the next generation Internet.12. (a) (i) Briefly explain HTML form control elements in detail. (ii) Explain how communication is taking between server and browser in detail. Or (b) (i) Describe importance of web services security in detail. (ii) Explain the creation CGI server side applets with an example.13. (a) (i) With a suitable example explain how a client process interact with the server objects using RMI. (ii) What are the uses of sockets? Explain the uses of different types of Socket classes in the jave.net package. Or (b) (i) Explain the various methods available in Content Handler class defined in the jave.net. (ii) Explain object serialization and deserialization with example14. (a) (i) Describe the common types of firewalls and proxy servers. Also compare and contrast firewalls and proxy servers and their security functions. (ii) Explain the different ways to include style sheet definition in a web page. Or (b) (i) Describe the different types of loops in JSP with suitable example. (ii) What are the two ways of specifying syntax for an XML page? 15. (a) (i) Describe about the technical and non-technical issues in building a electronic payment systems. (ii) Briefly explain how financial EDI payments are made and also list the standards for financial EDI. Or (b) (i) Describe the issues in customizing the Internet commerce. (ii) What is financial EDI? Describe different type of financial EDI in detail ****************** D 4219 B.E./B. Tech. DEGREE EXAMINATION, NOVEMEBER/DECEMBER 2008 Eighth Semester Information Technology IT 1451 – WEB TECHNOLOGYVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 300
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH (Regulation 2004) PART – A1. Develop a HTML page to use an image as a link to another page.2. Develop a Java Scrip page to demonstrate an If condition by which the time on your browser is less than 10; you will get “Good morning” greeting.3. Define: Data binding with its types.4. Develop a DHTML page to change the background color using mouse over event on three squares containing different colors.5. List any four disadvantages of an e-commerce system.6. Why do you use Java Script in web page designing?7. How do you provide uniform access to structured documents in diverse applications?8. What is meant by Cookie? How will you create it using ASP?9. List any three advantages of Java Servlet over JSP.10. How does a JSP work? PART – B11. (a) (i) How does the Internal work, brief with a sample application. (ii) Explain in detail about Web Client Server Architecture with a neat diagram. (iii) Write a Java Script Object to replace characters in a string. Or (b) (i) Write a Java Script Object to return the position of the first occurrence of a text in a string. (ii) Describe about the different HTML Protocols. (iii) Write a Java Script function to find the product of two arguments and return the result.12. (a) (i) Write a DHTML to shake the window of a button click. Make use of two buttons one button used to start the shaking and another button used to stop the shaking of windows (ii) Write a DHTML to expose the concept of binding of an image and table. Or (b) (i) Write a DHTML to change the background color of a button, Mouse over three colored table cells and the background color will change. (ii) Write a DHTML to dynamically insert the mask filter in an image. Use mouseVEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 301
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH over on the image. 13. (a) Provide an E-business model for a textile retail shop and brief each component with its role with a neat diagram. Or (b) Explain in detail about the following servers with its flow of processing in authentication module for an application. (i) IIS (ii) Apache.14. (a) Develop an ASP application for a Questionnaire, which has minimum of EIGHT questions. The questions and answers will be stored in a database. The questions will be posted to the client one in a page and collect the answer from the client. Evaluate the answers and inform the result score to the client in the final page. Or (b) Explain the following ASP objects with its syntax and example. (i) Session (ii) Application (iii) Request (iv) Server.15. (a) (i) Develop a JSP page to display a different image each time a user visits a page and the images are links. (ii) Develop a JSP to get the name of the parent folder of a specified path. Or (b) (i) Develop a JSP to find the type, capabilities, and version of each browser that visits your site. (ii) Develop a Java Servlet to display a different content each time a user visits a page. ***************** VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 302
    • VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH over on the image. 13. (a) Provide an E-business model for a textile retail shop and brief each component with its role with a neat diagram. Or (b) Explain in detail about the following servers with its flow of processing in authentication module for an application. (i) IIS (ii) Apache.14. (a) Develop an ASP application for a Questionnaire, which has minimum of EIGHT questions. The questions and answers will be stored in a database. The questions will be posted to the client one in a page and collect the answer from the client. Evaluate the answers and inform the result score to the client in the final page. Or (b) Explain the following ASP objects with its syntax and example. (i) Session (ii) Application (iii) Request (iv) Server.15. (a) (i) Develop a JSP page to display a different image each time a user visits a page and the images are links. (ii) Develop a JSP to get the name of the parent folder of a specified path. Or (b) (i) Develop a JSP to find the type, capabilities, and version of each browser that visits your site. (ii) Develop a Java Servlet to display a different content each time a user visits a page. ***************** VEL TECH VEL TECH MULTI TECH VEL TECH HIGH TECH 302