Beruflich Dokumente
Kultur Dokumente
UNIT – 1 NOTES
Outline
History of the Internet
Personal Computing
History of the World Wide Web
World Wide Web Consortium (W3C)
• ARPANET
– Implemented in late 1960’s by ARPA (Advanced Research
Projects Agency of DOD)
– Networked computer systems of a dozen universities and
institutions with 56KB communications lines
– Grandparent of today’s Internet
– Intended to allow computers to be shared
– Became clear that key benefit was allowing fast
communication between researchers – electronic-mail
(email)
• ARPA’s goals
– Allow multiple users to send and receive info at same time
– Network operated packet switching technique
• Digital data sent in small packages called packets
• Packets contained data, address info, error-control info and
sequencing info
• Greatly reduced transmission costs of dedicated communications
lines
– Network designed to be operated without centralized control
• If portion of network fails, remaining portions still able to route
packets
• WWW
– Allows computer users to locate and view multimedia-based
documents
– Introduced in 1990 by Tim Berners-Lee
• Internet today
– Mixes computing and communications technologies
– Makes information constantly and instantly available to
anyone with a connection
• W3C
– Founded in 1994 by Tim Berners-Lee
• Devoted to developing non-proprietary and interoperable
technologies for the World Wide Web and making the Web
universally accessible
– Standardization
• W3C Recommendations: technologies standardized by W3C
– include Extensible HyperText Markup Language (XHTML),
Cascading Style Sheets (CSS) and the Extensible Markup
Language (XML)
• Document must pass through Working Draft, Candidate
Recommendation and Proposed Recommendation phases before
considered for W3C Recommendation
Outline
Introduction
Markup Languages
Editing HTML
Common Tags
Headers
Text Styling
Linking
Images
Formatting Text With <FONT>
Special Characters, Horizontal Rules and
More Line Breaks
• HTML files
– .htm or .html extensions
– Name your files to describe their functionality
– File name of your home page should be index.html
• Errors in HTML
– Usually not fatal
• FONT element
– Add color and formatting to text
– FONT attributes:
• COLOR
– Preset or hex color code
– Value in quotation marks
– Note: you can set font color for whole document using
TEXT attribute in BODY element
Outline
Introduction
Unordered Lists
Nested and Ordered Lists
Basic HTML Tables
Intermediate HTML Tables and Formatting
Basic HTML Forms
More Complex HTML Forms
Internal Linking
Creating and Using Image Maps
<META> Tags
<FRAMESET> Tag
Nested <FRAMESET> Tags
• In this Chapter
– Lists
– Tables
– Internal linking
– Image maps
– Frames
• META tag
– Main HTML element that interacts with search engines
Outline
Introduction
Simple Program: Printing a Line of Text in a Web Page
Obtaining User Input with prompt Dialogs
Dynamic Welcome Page
Adding Integers
Memory Concepts
Arithmetic
Decision Making: Equality and Relational Operators
Web Resources
welcome.html
(1 of 1)
welcome2.html
(1 of 1)
welcome3.html
1 of 1
welcome4.html
1 of 1
\' Single quote. Used to represent a single quote character in a string. For
example,
window.alert( '\'in quotes\'' );
displays 'in quotes' in an alert dialog.
welcome5.html
(1 of 2)
Fig. 7.7 Prompt dialog displayed by the window object’s prompt method.
Addition.html
(1 of 2)
number1 45
Fig. 7.9 Memory location showing the name and value of variable number1.
number1 45
number2 72
Fig. 7.10 Memory locations after values for variables number1 and number2 have been input.
number1 45
number2 72
sum 117
Fig. 7.11 Memory locations after calculating the sum of number1 and number2.
Subtraction - p–c p - c
Multiplication * bm b * m
/ x-- x / y
Division x / y or y
or xy
Remainder % r mod s r % s
Fig. 7.12 Arithmetic operators.
2 * 5 is 10 (Leftmost multiplication)
Step 2. y = 10 * 5 + 3 * 5 + 7;
10 * 5 is 50 (Leftmost multiplication)
Step 3. y = 50 + 3 * 5 + 7;
Step 4. y = 50 + 15 + 7;
50 + 15 is 65 (Leftmost addition)
Step 5. y = 65 + 7;
65 + 7 is 72 (Last addition)
welcome6.html
(1 of 3)
• Writing a script
– Thorough understanding of problem
– Carefully planned approach
– Understand the types of building blocks that are available
– Employ proven program-construction principles
• Actions to be executed
• Order in which the actions are to be executed
• Sequential execution
– Statements execute in the order they are written
• Transfer of control
– Next statement to execute may not be the next one in sequence
• Three control structures
– Sequence structure
– Selection structure
• if
• if…else
• switch
– Repetition structure
• while
• do…while
• for
• for…in
P.Kumar, Rajalakshmi Engineering COllege 151
Control Structures
• Flowchart
– Graphical representation of algorithm or portion of
algorithm
– Flowlines
• Indicate the order the actions of the algorithm execute
– Rectangle symbol
• Indicate any type of action
– Oval symbol
• A complete algorithm
– Small circle symbol
• A portion of algorithm
– Diamond symbol
• Indicates a decision is to be made
P.Kumar, Rajalakshmi Engineering COllege 152
Control Structures
JavaScript
Keywords
break case catch continue default
delete do else finally for
function if in instanceof new
return switch this throw try
typeof var void while with
Keywords that
are reserved but
not currently
used by
JavaScript
abstract boolean byte char class
const debugger double enum export
extends final float goto implements
import int interface long native
package private protected public short
static super synchronized throws transient
volatile
Fig. 8.2 JavaScript keywords.
P.Kumar, Rajalakshmi Engineering COllege 154
if Selection Statement
• Single-entry/single-exit structure
• Indicate action only when the condition evaluates
to true
true
grade >= 60 print “Passed”
false
true
product <= 1000 product = 2 * product
false
Outline
Essentials of Counter-Controlled Repetition
for Repetition Statement
Examples Using the for Statement
switch Multiple-Selection Statement
do…while Repetition Statement
break and continue Statements
Labeled break and continue Statements
Logical Operators
Summary of Structured Programming
WhileCounter.html
(2 of 2)
Establish
initial value
of control
variable.
var counter = 1
document.writeln(
true "<p style=\"font-size: "
counter <= 7 ++counter
+ counter +
"ex\">XHTML font size " + Increment
counter + "ex</p>" ); the control
false variable.
Determine Body of loop
(this may be many
if final value
of control statements)
variable
has been
reached.
• Controlling expression
• Case labels
• Default case
true
case a case a action(s) break
false
true
case b case b action(s) break
false
.
.
.
true
case z case z action(s) break
false
default action(s)
DoWhileTest.html
(2 of 2)
action(s)
true
condition
false
• break
– Immediate exit from the structure
– Used to escape early from a loop
– Skip the remainder of a switch statement
• continue
– Skips the remaining statements in the body of the structure
– Proceeds with the next iteration of the loop
expression !expression
false true
true false
Fig. 9.17 Truth table for operator ! (logical negation).
• Flowcharts
– Reveal the structured nature of programs
• Single-entry/single-exit control structures
– Only one way to enter and one way to exit each control
structure
• Control structure stacking
– The exit point of one control structure is connected to the
entry point of the next control structure
do…while statement
T
while statement
Rep etition
F
for statement
T
T
F
Single-entry/single-exit sequence, selection and repetition structures. (1 of 3)
if…else statement
(d ouble se lec tion)
T
break
break
break
F
Se lectio n
(m ultiple selection)
switch statement
(single se lec tio n)
if statement
T
F
F
.
.
.
T
.
.
.
Single-entry/single-exit sequence, selection and repetition structures. (3 of 3)
Simplest flowchart.
.
.
.
Rule 3
Rule 3
Unstructured flowchart.
Function Definitions
Scope Rules
JavaScript Global Functions
Recursion
Recursion vs. Iteration
<html>
<head>
<script>
function about(name, age)
{
document.write("<h1> All about You</h1>");
document.write("<p>Your Name is" + name);
document.write("<p>You are" + age);
}
about("abc",95);
</script>
</head>
</html>
• Scope
– How a Variable can be accessed
– Local & Global
– Inside function is local or function scope
• Identifiers exist only between opening and closing braces
• Local variables hide global variables
function setlocal(d)
{
a=d;
alert("bis inside" + b);
return(a);
}
</script>
</body>
</html>
• Recursive functions
– Call themselves
• Recursion step or recursive call
• Part of return statement
– Must have base case
• Simplest case of problem
• Returns value rather than calling itself
– Each recursive call simplifies input
• When simplified to base case, functions return
(a) Procession of recursive calls. (b) Values returned from each recursive call.
<HTML>
<!-- volume.html -->
<HEAD>
<TITLE>Calculating Sphere Volumes</TITLE>
<SCRIPT >
function displayVolume()
{ var radius = parseFloat( myForm.radiusField.value );
window.status = "Volume is " + sphereVolume( radius ); }
function sphereVolume( r )
{ return ( 4.0 / 3.0 ) * Math.PI * Math.pow( r, 3 ); }
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME =" myForm"> Enter radius of sphere<BR>
<INPUT NAME =" radiusField" TYPE =" text">
<INPUT NAME =" calculate" TYPE =" button" VALUE =" Calculate"
ONCLICK =" displayVolume()"> </FORM> </BODY> </HTML>
P.Kumar, Rajalakshmi Engineering COllege 253
Recursion vs. Iteration
• Iteration
– Explicitly uses repetition structures to achieve result
– Terminates when loop-continuation condition fails
– Often faster than recursion
• Recursion
– Repeats through function calls
– Terminates when base case reached
– Slower due to function call overhead
• Each call generates new copy of local variables
– Easy to read and debug when modeling problem with
naturally recursive solution
Arrays
Declaring and Allocating Arrays
Examples Using Arrays
References and Reference Parameters
Sorting Arrays
Searching Arrays: Linear Search and Binary Search
Multidimensional Arrays
c[ 2 ] 0
c[ 3 ] 72
c[ 4 ] 1543
c[ 5 ] -89
c[ 6 ] 0
c[ 7 ] 62
c[ 8 ] -3
c[ 9 ] 1
Position number (index
or subscript) of the c[ 10 ] 6453
element within array c
c[ 11 ] 78
A 12-element array.
• Arrays in memory
– Objects
– Operator new
• Allocates memory for objects
• Dynamic memory allocation operator
var c;
c = new Array( 12 );
<html>
<head>
</head>
<body>
<script>
var data = [“mon, “tue”, 34, 76.34];
var len = data.length;
for(var i=0;i<len;i++)
document.write(data[i] +”,”);
</script>
</body>
</html>
• Sorting
– Important computing task
<HTML>
<HEAD>
<TITLE>Sorting an Array with Bubble Sort</TITLE>
<SCRIPT>
function start()
{ var a = [ 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 ];
document.writeln( "<H1>Sorting an Array</H1>" );
outputArray( "Data items in original order: ", a );
bubbleSort( a ); // sort the array
outputArray( "Data items in ascending order: ", a );
}
<HTML>
<HEAD> <TITLE>Linear Search of an Array</TITLE>
<SCRIPT LANGUAGE =" JavaScript">
var a = new Array( 100 ); // create an Array // fill Array with
even integer values from 0 to 198
for ( var i = 0; i < a.length; ++i ) a[ i ] = 2 * i;
// function called when "Search" button is pressed function
buttonPressed()
{
var searchKey = searchForm.inputVal.value;
<BODY>
<FORM NAME =" searchForm">
<P>Enter integer search key<BR>
<INPUT NAME =" inputVal" TYPE =" text">
<INPUT NAME =" search" TYPE =" button" VALUE ="
Search" ONCLICK =" buttonPressed()"><BR></P>
<P>Result<BR> <INPUT NAME =" result" TYPE ="
text" SIZE =" 30"></P>
</FORM> </BODY> </HTML>
Row 0 a[ 0 ][ 0 ] a[ 0 ][ 1 ] a[ 0 ][ 2 ] a[ 0 ][ 3 ]
Row 1 a[ 1 ][ 0 ] a[ 1 ][ 1 ] a[ 1 ][ 2 ] a[ 1 ][ 3 ]
Row 2 a[ 2 ][ 0 ] a[ 2 ][ 1 ] a[ 2 ][ 2 ] a[ 2 ][ 3 ]
Array name
b = new Array( 2 );
b[ 0 ] = new Array( 5 );
b[ 1 ] = new Array( 3 );
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( Returns a string containing length characters starting from index start in
start, length ) the source string. If length is not specified, a string containing characters
from start to the end of the source string is returned.
substring( Returns a string containing the characters from index start up to but not
start, end ) including index end in the source string.
toLowerCase() Returns a string in which all uppercase letters are converted to lowercase
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.
valueOf() Returns the same string as the source string.
getFullYear() Returns the year as a four-digit number in local time or UTC, respectively.
getUTCFullYear()
getHours() Returns a number from 0 to 23 representing hours since midnight in local time or UTC, respectively.
getUTCHours()
getMilliseconds() Returns a number from 0 to 999 representing the number of milliseconds in local time or UTC, respectively.
getUTCMilliSeconds() The time is stored in hours, minutes, seconds and milliseconds.
getMinutes() Returns a number from 0 to 59 representing the minutes for the time in local time or UTC, respectively.
getUTCMinutes()
getMonth() Returns a number from 0 (January) to 11 (December) representing the month in local time or UTC,
getUTCMonth() respectively.
getSeconds() Returns a number from 0 to 59 representing the seconds for the time in local time or UTC, respectively.
getUTCSeconds()
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, respectively.
setUTCDate( val )
Fig. 12.8 Methods of the Date object.
setHours( h, m, s, ms ) Sets the hour in local time or UTC, respectively. The second, third and fourth
arguments representing the minutes, seconds and milliseconds are optional. If
setUTCHours( h, m, s, ms ) 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, respectively. The second argument
representing the date is optional. If the optional argument is not specified, the
setUTCMonth( m, d ) current date value in the Date object is used.
setSeconds( s, ms ) Sets the second in local time or UTC, respectively. The second argument
representing the milliseconds is optional. If this argument is not specified, the
setUTCSeconds( s, ms ) current millisecond value in the Date object is used.
toUTCString() Returns a string representation of the date and time in the form: 19 Sep
2001 15:47:22 UTC
toString() Returns a string representation of the date and time in a form specific to the
locale of the computer (Mon Sep 19 15:47:22 EDT 2001 in the United
States).
valueOf() The time in number of milliseconds since midnight, January 1, 1970.
UNIT – 2 NOTES
<html>
<head>
<title>Object Model</title>
<script>
function start()
{
alert(ptext.innerText);
ptext.innerText = "Thanks for coming";
} </script>
</head>
<body onload="start()">
<p id="ptext"> Welcome to our web page</p>
</body> </html> P.Kumar, Rajalakshmi Engineering COllege 305
P.Kumar, Rajalakshmi Engineering COllege 306
Collections all and children
• Collections
– Arrays of related objects on a page
– all
• all the HTML elements in a document
– children
• Specific element contains that element’s child elements
<HTML>
<HEAD> <TITLE>Object Model</TITLE> <SCRIPT >
function start()
{ var a = prompt( "Enter a color name for the " +
"background of this page", "" );
document.body.style.backgroundColor = a;
}
</SCRIPT> </HEAD>
<BODY ONLOAD =" start()"> <P>Welcome to our
Web site!</P> </BODY>
</HTML>
P.Kumar, Rajalakshmi Engineering COllege 309
P.Kumar, Rajalakshmi Engineering COllege 310
dynamicstyle2
document all
navigator body
plugins
location embeds
event filters
screen forms
images
Key links
object plugins
collection scripts
styleSheets
styleSheets Contains styleSheet objects that represent each style element in the XHTML
document and each style sheet included in the XHTML document via link.
Fig. 13.11 Objects in the Internet Explorer 6 Object Model.
• onload event
– Fires when an element finishes loading
– Used in the body element
– Initiates a script after the page loads into the client
<html>
<head>
<script >
function mymessage()
{
alert("This message was triggered from the onload event");
}
</script>
</head>
<body onload="mymessage()">
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 334
Error Handling with onerror
• onerror event
– Execute specialized error-handling code
<body>
<img id="myimage" onmousedown="lighton()" onmouseup="lightoff()"
src="bulboff.gif" width="100" height="180">
<p>Click to turn on the light</p>
</body>
</html> P.Kumar, Rajalakshmi Engineering COllege 343
onmousemove
<html>
<head>
<script >
var i=1;
function moveright()
{
document.getElementById('header').style.position="relative";
document.getElementById('header').style.left=i;
i++;
}
</script>
</head>
<body onmousemove="moveright()">
<h1 id="header"> Move the mouse over this page </h1>
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 344
Form Processing with onfocus and
onblur
• onfocus event fires when element gains focus
• onblur event fires when element loses focus
<html>
<head>
<script >
function message()
{
alert("This alert box was triggered by the onfocus event handler");
}
</script>
</head>
<body>
<form>
Enter your name: <input type="text" onfocus="message()" size="20">
</form>
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 346
Form Processing with onblur
<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was triggered by the onblur event handler");
}
</script>
</head>
<body>
<p>The onblur event occurs when an element loses focus. Try to click or write in
the input field below, then click elsewhere in the document so the input field
loses focus.</p>
<form>
Enter your name: <input type="text" onblur="message()" size="20">
</form>
</body>
</html>
<html>
<head>
<script>
function message()
{
alert("This alert box was triggered by the onreset event handler");
}
</script>
</head>
<body>
<form onreset="message()">
Enter your name: <input type="text" size="20">
<input type="reset">
</select>
</form>
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 349
Event Bubbling
Outline
Introduction
Flip Filters: flipv and fliph
Transparency with the chroma Filter
Creating Image masks
Miscellaneous Image Filters: invert, gray and xray
Adding shadows to Text
Creating Gradients with alpha
Making Text glow
Creating Motion with blur
Using the wave Filter
Advanced Filters: dropShadow and light
blendTrans Transition
revealTrans Transition
• Filters
– Cause changes that are persistent
• Transitions
– Temporary
– Allow transfer from one page to another with pleasant visual
effect
• For example, random dissolve
<BODY>
<TABLE>
<TR>
<!-- Filters are applied in style declarations -->
<TD STYLE = "filter: fliph">Text</TD>
<TD>Text</TD>
</TR>
<TR>
<!-- More than one filter can be applied at once -->
<TD STYLE = "filter:. flipv fliph">Text</TD>
<TD STYLE = "filter: flipv">Text</TD>
</TR>
</TABLE>
</BODY>
</HTML>
<H1>Mask Filter</H1>
• invert filter
– Negative image effect
• Dark areas become light and light areas become dark
• gray filter
– Grayscale image effect
• All color is stripped from the image, only brightness data
remains
• xray filter
– X-ray effect
• Inversion of the grayscale effect
<body>
<h2 style="filter:glow()">Glow</h2>
<h2 style="filter:blur()">Blur</h2>
<h2 style="filter:fliph()">Flip H</h2>
<h2 style="filter:flipv()">Flip V</h2>
<h2 style="filter:shadow()">Shadow</h2>
<h2 style="filter:dropshadow()">Drop Shadow</h2>
<h2 style="filter:wave(Strength=2)">Wave</h2>
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 370
blendTrans Transition
function Blend()
{
if (document.getElementById("Macaws").style.visibility == "visible") {
document.getElementById("Macaws").style.filter="blendTrans(duration=3)";
document.getElementById("Macaws").filters.blendTrans.apply();
document.getElementById("Macaws").style.visibility="hidden";
document.getElementById("Macaws").filters.blendTrans.play();
document.getElementById("Lion").style.filter="blendTrans(duration=3)";
document.getElementById("Lion").filters.blendTrans.apply();
document.getElementById("Lion").style.visibility="visible";
document.getElementById("Lion").filters.blendTrans.play();
} else {
document.getElementById("Lion").style.filter="blendTrans(duration=3)";
document.getElementById("Lion").filters.blendTrans.apply();
document.getElementById("Lion").style.visibility="hidden";
document.getElementById("Lion").filters.blendTrans.play();
document.getElementById("Macaws").style.filter="blendTrans(duration=3)";
document.getElementById("Macaws").filters.blendTrans.apply();
document.getElementById("Macaws").style.visibility="visible";
document.getElementById("Macaws").filters.blendTrans.play();
}
}
</script>
<body>
<input type = button value = clickme onclick = Blend()>
<img id="Macaws" src="Macaws.jpg"
style= "position:absolute;visibility:visible"/>
<img id="Lion" src="Lion.jpg"
style="position:absolute;visibility:hidden"/>
P.Kumar, Rajalakshmi Engineering COllege 374
revealTrans Transition
• revealTrans filter
– Create professional-style transitions
– From box out to random dissolve
• object.style.filter="revealTrans(duration=second
s, transition=n)"
• Data binding
– Data no longer reside exclusively on the server
– Data can be maintained on the client
– Eliminate server activity and network delays
• Data Source Objects (DSOs)
– Tabular Data Control (TDC)
• Data file
– Header row
• Specifies the names of the columns below
– Text qualifiers ( @ )
• Enclose data in each field
– Field delimiter ( | )
• Separate each field
– Recordset
– Eg: @ColorName@|@ColorHexRGBValue@
@green@|@#008000@
<HTML>
<HEAD>
<TITLE>Intro to Data Binding</TITLE>
function reNumber()
{
if( !recordSet.EOF )
recordNumber.innerText = recordSet.absolutePosition;
else
recordNumber.innerText = " ";
}
function forward()
{
if( !recordSet.EOF )
recordSet.MoveNext();
else
recordSet.MoveFirst();
colorSample.style.backgroundColor = colorRGB.innerText;
reNumber();
}
</SCRIPT>
</HEAD> P.Kumar, Rajalakshmi Engineering COllege 385
<BODY ONLOAD = "reNumber()" ONCLICK = "forward()">
</BODY>
P.Kumar, Rajalakshmi Engineering COllege 386
</HTML>
75 </body>
76 </html>
Outline
introdatabind.html
(4 of 4)
<HEAD>
<TITLE>Binding to a IMG</TITLE>
<OBJECT ID = "Images"
CLASSID = "CLSID:333C7BC4-460F-11D0-BC04-
0080C7055A83">
<PARAM NAME = "DataURL" VALUE = "images.txt">
<PARAM NAME = "UseHeader" VALUE = "True">
</OBJECT>
break; </SCRIPT>
• </HEAD>
P.Kumar, Rajalakshmi Engineering COllege 391
P.Kumar, Rajalakshmi Engineering COllege 392
Binding to a table
<HTML>
<HEAD>
<TITLE>Data Binding and Tables</TITLE>
<OBJECT ID = "Colors"
CLASSID = "CLSID:333C7BC4-460F-11D0-BC04-
0080C7055A83">
<PARAM NAME = "DataURL" VALUE =
"HTMLStandardColors.txt">
<PARAM NAME = "UseHeader" VALUE = "TRUE">
<PARAM NAME = "TextQualifier" VALUE = "@">
<PARAM NAME = "FieldDelim" VALUE = "|">
</OBJECT>
</HEAD>
P.Kumar, Rajalakshmi Engineering COllege 394
<BODY STYLE = "background-color: darkseagreen">
<THEAD>
<TR STYLE = "background-color: mediumslateblue">
<TH>Color Name</TH>
<TH>Color RGB Value</TH>
</TR>
</THEAD>
<TBODY>
<TR STYLE = "background-color: lightsteelblue">
<TD><SPAN DATAFLD = "ColorName"></SPAN></TD>
<TD><SPAN DATAFLD = "ColorHexRGBValue"
STYLE = "font-family: monospace"></SPAN></TD>
</TR>
</TBODY>
</TABLE>
</BODY>
</HTML>
<HEAD>
<TITLE>Data Binding and Tables</TITLE>
<OBJECT ID = "Colors"
CLASSID = "CLSID:333C7BC4-460F-11D0-BC04-
0080C7055A83">
<PARAM NAME = "DataURL" VALUE =
"HTMLStandardColors.txt">
<PARAM NAME = "UseHeader" VALUE = "TRUE">
<PARAM NAME = "TextQualifier" VALUE = "@">
<PARAM NAME = "FieldDelim" VALUE = "|">
</OBJECT>
</HEAD>
P.Kumar, Rajalakshmi Engineering COllege 398
<BODY STYLE = "background-color: darkseagreen">
<H1>Sorting Data</H1>
<THEAD>
<TR STYLE = "background-color: mediumslateblue">
<TH>Color Name</TH>
<TH>Color RGB Value</TH>
</TR>
</THEAD>
<TBODY>
<TR STYLE = "background-color: lightsteelblue">
<TD><SPAN DATAFLD = "ColorName"></SPAN></TD>
<TD><SPAN DATAFLD = "ColorHexRGBValue"
STYLE = "font-family: monospace"></SPAN></TD>
</TR>
</TBODY>
</TABLE>
</BODY>
</HTML>
UNIT – 3 NOTES
• Multimedia
– Use of sound, images, graphics and video
– Add sound, video, and animated characters to Web-based
applications
– Streaming technologies
<HTML>
<HEAD><TITLE>The BGSOUND Element</TITLE>
<BGSOUND ID = "audio" SRC = "jazzgos.mid" LOOP = 1"></BGSOUND>
</HTML>
<HTML>
<HEAD>
<TITLE>An Embedded Image Using the DYNSRC Property</TITLE>
<BGSOUND SRC="newage.mid" LOOP="-1">
</HEAD>
<BODY>
<H1>An Embedded Video Using the IMG Element's DYNSRC
Property</H1>
<H2>Spinning Globe and New Age Music</H2>
This video is from the
<a href="http://www.nasa.gov/gallery/">
NASA Multimedia Gallery</a><BR>
This sound is from the free sound downloads at the
<a href="http://msdn.microsoft.com/downloads/default.asp">
Microsoft Developer Network</a> downloads site.
<HR>
P.Kumar, Rajalakshmi Engineering COllege 413
<TABLE><TR>
<TD>
<IMG DYNSRC="pathfinder.mpeg" START="mouseover"
WIDTH="180" HEIGHT="135" LOOP="-1"
ALT="A spinning image of the Earth"></TD>
<TD>This page will play the audio clip and video in a
loop.<BR>The video will not begin playing until you move
the mouse over the video.<BR>Press <B>Stop</B> to stop
playing the sound and the video.</TD></TR></TABLE>
</BODY>
</HTML>
• Element embed
– Embed RealOne Player plug-ins for video and audio
– Attribute type
• Specifies MIME type of embedded file
– Attributes width and height
• Specify dimensions of space the control occupies
– Attribute autostart
• Determines whether media start playing when page loads
– Attribute controls
• Specifies which controls users can access
– Attribute src
• Set to location of streaming media
Security
Public-Key Cryptography
Cryptanalysis
Key Agreement Protocols
Key Management
Secure Sockets Layer (SSL)
WTLS
IPSec and Virtual Private Networks (VPN)
Security Attacks
Network Security
Legal Issues
Privacy
Defamation
Sexually Explicit Speech
SPAM
Copyright and Patents
– E-business
• All aspects of e-commerce, plus internal operations of doing business
e-business not included under the category of e-commerce
• For example, production, development, corporate infrastructure and
product management are aspects of e-business not included under the
category of e-commerce
• e-business
– Expansion of old technologies and techniques
• Electronic Funds Transfers
– Requires new business models and categories
– Pioneered by early e-businesses
• Amazon.com, eBay, Yahoo among others
• Shopping-cart metaphor
– Holds items a user has selected to buy
– Merchant server contains database of available items
– User puts all desired items in the cart
– When finished, user “checks out”
• Prices totaled
• Shipping, tax and other charges applied
• Shipping and payment details gathered
• Order confirmed
• Ex: www.amazon.com
• Online auctions
– Buyers bid on items made available by various sellers
• No fixed price
– Very attractive to customers
• Often able to get lower prices on goods than traditional stores
– Site is searchable to allow easy location of desired items
– Site receives a commission on each sale
– Model also employed in business-to-business transactions
– www.eBay.com is the leading auction site
• Multiple approaches
– Turnkey solutions (a prepackaged e-business)
• Ready-made e-Business sites [store.yahoo.com]
– e-Business templates
• Outline business’ structure
• Design details left open to owner
– Outsource control entirely to a specialized firm
• Expensive
• Little hassle, lets experts control it while you control your
business
– Build original, custom solution
• Allows maximum control, makes your site unique
• Most expensive, involves “reinventing the wheel”
P.Kumar, Rajalakshmi Engineering COllege 434
e-Marketing
• Marketing campaign
– Marketing your site through multiple means
• Market research
• Advertising
• Promotions
• Branding
• Public Relations (PR)
• Search engines
• Brand
– Name, logo or symbol that defines company’s products or
services
• Unique
• Recognizable
• Easy to remember
– Brand equity
• “Value” of the brand
• Customer perception and loyalty
– Companies with existing brand may more easily establish
their brand on the Internet
• New companies must work to establish trust in their brand
• Marketing research
– Marketing mix
• Product or service details
• Pricing
• Promotion
• Distribution
– Focus groups
– Interviews
– Surveys and questionnaires
– Secondary research
• Reviewing pre-existing data
• e-Mail marketing
– Part of the reach of the campaign
• Span of people who marketing should target
– Direct mail vs. indirect mail
• Direct mail is personalized to the individual recipient
• Direct is often more effective
• Offers right product at right time
• Tailor mailing to customer’s interests
– Opt-in e-Mail lists
• Customer chooses to subscribe
• Send newsletters with information on offers and promotions
• Promotions
– Attract visitors
– Encourage purchasing
– Increase brand loyalty
– Should not be only reason people purchase from your
company
• Sign of weak product or brand
– Be sure cost of promotion is not so great that no profit is
ever seen
• Consumer tracking
– Keep user profiles
– Record visits
– Analyze results of advertising and promotion
– Helps define target market
• Group toward whom it is most profitable to target marketing
resources
– Log files contain many useful details
• IP address
• Time and frequency of visits
• Advertising
– Establish and strengthen branding
– Publish URL in all advertising
• Internet advertising becoming important
– Links and banners on sites viewed often by target market
• Can be interactive or animated
– Allow advertising on your site in return for payment
– Pop-up ads
• Appear in a separate window when page loads
• Often extremely irritating to customers
• Actually decrease interest in advertised product due to negative
association with pop-up ad
• Search engines
– Scan websites for desired content
– Being highly ranked in search results important
• People tend not to browse results too deeply
– Some sites base your ranking on meta tags
• Hidden XHTML tags that contain information about site
• Keywords, title, summary
– Others simply “spider” the site
• Program reads content and decides what is important
• Affiliate programs
– Company pays other sites to be affiliates
• Advertise the company’s products
• When their ad leads to purchases from the company, affiliate
site receives a commission
– Increases exposure and number of site visits
– Amazon.com has large, successful affiliate program
• Public relations
– Provide customers with latest information
• Products and services
• Sales
• Promotions
– Press releases
– Presentations and speeches
– e-Mail
– Crisis management
• Issue statements regarding company problems
• Minimize damage to company, brand and reputation
• Aspects of CRM
– Call handling
• Management of calls between customers and service
representatives
– Sales tracking
– Transaction support
• Support for people and technology involved in keeping
transactions running smoothly
– Personalization of customer experience
• Digital cash
– Stored electronically
– Analogous to traditional bank account
• Customers deposit money
– Overcomes drawbacks of credit cards
• Digital cash accounts often allow deposits in form of checks or
bank transfers
• Allows merchants to accept customers without credit cards
• e-Wallets
– Store billing and shipping information
– Fill out forms at compatible sites in one click
• Micropayments
– Merchants often charged fee for credit card transactions
• For small items, fee can exceed cost of item
– Micropayments allow merchants to avoid this problem
• Add together all small transactions and pay percentage of that
– Similar to concept of phone bill
• Pay one large sum monthly rather than tiny sum per each use
• Smart cards
– Memory cards
• Only allow for storage of information
– Microprocessor cards
• Like tiny computers
• Can do processing in addition to storing data
– Contact interface
• Card inserted into reading device for use
– Contactless interface
• Data transmitted via wireless device inside card
– Data and money protected by personal identification number
(PIN)
• Cryptography
– Transforms data using cipher or cryptostream
– Key acts as password that combined with cipher will decrypt
encoded message into original message
– Early cryptography relied on symmetric cryptography
• Same key used to encrypt and decrypt
• Problem of how to securely transmit key itself arose
– Solution was public-key cryptography
• Two related but different keys used
• Sender uses receiver’s public key to encode
• Receiver decodes with private key
• Keys long enough that guessing or cracking them takes so
much time it is not worth the effort
P.Kumar, Rajalakshmi Engineering COllege 457
Public-Key Cryptography
• Digital signatures
– Same concept as physical written signatures
• Authenticate signer
• Difficult to forge
– Part of public-key cryptography
– Generated by running phrase through hash function
• Returns hash value
– Hash value for a phrase is over 99% guaranteed unique
• ie., two different phrases very unlikely to generate same value
• PKI implementations
– More secure than standard point-of-sale (POS) transactions
• Strong encryption can take decades to crack using current
technology
– RSA encryption popular choice for PKI
• Developed at MIT in 1977
– Pretty Good Privacy (PGP)
• Implementation of PKI
• Very popular way to encrypt e-mail
• Operates using web of trust
• Preventative measures
– Key expiration dates
• If attacker breaks or steals key, only useful for limited time
– Exchange secret keys securely with public-key cryptography
• SSL
– Layer on top of TCP/IP
– Implements public-key encryption using RSA algorithm
– Generates secret key referred to as session key
• Rest of transaction encrypted using this key
– Messages still sent through TCP/IP after encryption step
– Generally used for point-to-point connections
• One computer communicating with another directly
– Transport Layer Security (TLS) another similar technology
• SSL, cont.
– SSL does not protect data stored on server
• Only data that is currently traveling across network
– Stored data should be encrypted by another means
– Always take standard precautions against cracker attacks
• Making SSL more efficient
– Encryption taxing on server resources
– Dedicated SSL encoding/decoding hardware exists
• Peripheral component interface (PCI) cards
• Offload these tasks from CPU
• Types of networks
– Local Area Network (LAN)
• Connects physically close computers
– Wide Area Network (WAN)
• Connect computers in multiple locations
• Employ private phone lines, radio waves or other techniques
– Virtual Private Network (VPN)
• Leverage Internet to simulate LAN for multiple remote
networks and wireless users
• Secure tunnel over Internet
• Data protected by encryption
• Network security
– Allow authorized users access they need
– Prevent unauthorized users from accessing and damaging
network
– Firewall a vital tool for network security
• Protects LANs from unauthorized traffic
• Placed between external Internet connection and computers on
local network
• Blocks or allows traffic based on rules set by administrator
• Administrator must balance users’ needs for functionality
against need for network security
• Defamation
– Consists of slander and libel
• Slander is spoken
• Libel is written or spoken in a broader context than slander
• Proving defamation
– Plaintiff must:
• Show that statement was written, spoken or broadcast
• Reasonably identify individual responsible
• Show that the statement is indeed defamatory
• Show that the statement was intended to cause harm and
known to be false
• Show evidence of injury or actual loss
• E-mail marketing
– Can be useful or harmful
– Unsolicited mass-mailings, or Spam, strongly frowned on
• Many Internet users received hundreds per day
• Content often at best irrelevant and at worst highly offensive
• Possible for children to receive pornography, for example
– Legislation being created to deal with Spam epidemic
– Software to combat spam also exists
– Spammers constantly evolve to circumvent new measures
– One of the toughest usability and privacy issues with
Internet today
• Copyright
– Protection given to author of original piece
• Protects an expression of idea, not idea itself
– Incentive to create by guaranteeing credit for work
• Life of author plus 70 years
– Digital technology has made copyright gray area
• Fair use vs. piracy
• Copies can be perfect, not cheap imitations
– Movies and MP3-encoded music files hottest area of debate
• File-sharing programs lets users download copyrighted works
freely
• Costs distributors and artists money
• Users want to sample music, enjoy lower prices
P.Kumar, Rajalakshmi Engineering COllege 486
Copyrights and Patents
• Patents
– Grant creator sole rights to a discovery
– Designed to foster invention and innovation
• Guarantees new idea cannot be stolen from inventor
– Possible to patent method of doing business
• Must be non-obvious to person skilled in relevant field
– Also contentious area
• Some feel patents stifle rather than foster innovation
• 20-year duration may be too long in fast-paced software world
• Some companies file patents solely to profit from infringement
lawsuits later on
• Mobile business
– E-business enabled by wireless technology
– Relatively new, but rapidly growing
– Access critical business information anytime, anywhere
• Employees can conduct their duties more easily
• Customers can interact with online businesses in new ways and
locations
• Location-identification technologies
– Determine users’ physical location to within yards
– Useful in wireless marketing
• Send promotion data when user is near relevant location
– Great benefits to emergency services
• Quickly and accurately locate victims
– Made possible by relationships between wireless providers,
networks and users
– Multipath errors can cause problems
• Signals reflecting off nearby objects
• CITA
– Cellular Telecommunications and Internet Association
– Group that has created guidelines for consumer privacy
– Outlined four guidelines
• Alert consumers when location being identified
• Always use opt-in marketing
• Consumers able to access their own information
• Same protections offered by all devices and carriers
• Web server
– Responds to client requests by providing resources
• URI (Uniform Resource Identifier)
• Web server and client communicate with
platform-independent Hypertext Transfer Protocol
(HTTP)
• Request methods
– get
– post
– Retrieve and send client form data to Web server
– Post data to a server-side form handler
• Client-side scripts
– Validate user input
• Reduce requests needed to be passed to server
• Access browser
• Enhance Web pages with DHTML, ActiveX controls, and
applets
• Server-side scripts
– Executed on server
– Generate custom response for clients
– Wide range of programmatic capabilities
– Access to server-side software that extends server
functionality
Web Site Content Directory dialog of the Virtual Directory Creation Wizard.
Web Site Content Directory dialog of the Virtual Directory Creation Wizard.
• www.microsoft.com/msdownload/ntoptionpack/askwiz.asp
• www.w3.org/Protocols
• www.apache.org
• httpd.apache.org
• httpd.apache.org/docs-2.0
• www.apacheweek.com
• linuxtoday.com/stories/18780.html
• www.iisanswers.com
• www.iisadministrator.com
• Web server
– Responds to client requests by providing resources
• URI (Uniform Resource Identifier)
• Web server and client communicate with
platform-independent Hypertext Transfer Protocol
(HTTP)
• Request methods
– get
– post
– Retrieve and send client form data to Web server
– Post data to a server-side form handler
• URL http://www.abc.org/iis/review1.htm
• URN www.abc.org/iis/review1.htm#one
• URI http://www.abc.org/iis/review1.htm.html#one
Client-side scripts
• VBScript , JavaScript and Ajax
(Asynchronous JavaScript and XML )
Server-side scripts
• ASP, JSP, PHP (Hypertext Preprocessor-
OSS), Cold fusion etc
JavaScript VBScript
• Scripting language Scripting language
• Object-based Not object-based
• Supports functions Supports functions
• Secure Secure
• C/C++ based Subset of Visual Basic
• Supported by all browsers Presently supported by
only Internet Explorer
• Easy to learn Based on BASIC
• FTP Site
– Used for transferring large files across the Internet
• HTTP Site
– Used most frequently to request documents from Web
servers
• SMTP Virtual Server
– Sends and receives electronic mail
• Web Site Content Directory
– Directory containing the documents that clients will view
UNIT – 4 NOTES
Outline
Introduction
Relational Database Model
Relational Database Overview: Books.mdb Database
SQL (Structured Query Language)
Basic SELECT Query
WHERE Clause
ORDER BY Clause
Merging Data from Multiple Tables: INNER JOIN
Joining Data from Tables Authors, AuthorISBN,
Titles and Publishers
INSERT Statement
UPDATE Statement
DELETE Statement
• Database
– Integrated collection of data
– Database management system (DBMS)
• Store and organize data consistent with database’s format
• Relational database
– SQL (Structured Query Language)
• Queries
• Manipulate data
• Composed of tables
• Row
– Number column
– Primary key
• Reference data in the table
• A column or set of columns in table contains unique data
department location
413 New Jersey
611 Orlando
642 Los Angeles
Fig. 22.2 Table formed by selecting department and location data from the Employee table.
Field Description
authorID Author’s ID number in the database. In the Books.mdb
database, this Integer column is defined as auto-
increment. For each new row inserted in this table, the
database increments the authorID value, ensuring that
each row has a unique authorID. This column represents
the table’s primary key.
firstName Author’s first name (a String).
lastName Author’s last name (a String).
Fig. 22.3 Authors table from Books.mdb.
publisherID publisherName
1 Prentice Hall
2 Prentice Hall PTG
Fig. 22.6 Data from the Publishers table of Books.mdb.
Field Description
authorID The author’s ID number, which allows the database
to associate each book with a specific author. The
integer ID number in this column must also appear
in the Authors table.
isbn The ISBN number for a book (a String).
Fig. 22.7 AuthorISBN table from Books.mdb.
<html> <body>
<% response.write("Hello World!") %>
</body> </html>
An ASP file can also contain server
scripts, surrounded by the delimiters <%
and %>.
Server scripts are executed on the
server, and can contain any expressions,
statements, procedures, or operators valid
for the scripting language you prefer to
use.
P.Kumar, Rajalakshmi Engineering COllege 575
ASP Variables
<html>
<body>
<%
dim name
name=“Gold"
response.write("My name is: " & name)
%>
</body>
</html>
<%
dim i
for i=1 to 6
response.write("<h" & i & ">Header " & i & "</h" & i
& ">")
next
%>
</body>
</html>
ASP Response
ASP Request
ASP Application
ASP Session
ASP Server
ASP Error
ASP FileSystem
ASP TextStream
ASP Drive
ASP File
ASP Folder
ASP Dictionary
ASP ADO
P.Kumar, Rajalakshmi Engineering COllege 584
Response Object
used to send output to the user from the
server
<html>
<body>
<%
response.write("Hello World!")
%>
</body>
</html>
Output:
Default Timeout is: 20 minutes. (Server time out)
Timeout is now: 30 minutes. (Now client can change to 30 min as session
out)
P.Kumar, Rajalakshmi Engineering COllege 588
FileSystemObject
The FileSystemObject is used to
access the file system on the server.
This object can manipulate files,
folders, and directory paths.
<html>
<body>
<%
set
conn=Server.CreateObject("ADODB.Connection
")
conn.Provider="Microsoft.Jet.OLEDB.4.0"
conn.Open(Server.Mappath("/db/test.mdb"))
Request.Form
Request.QueryString
Request.QueryString
Request.Form
True
False
True
False
1. data elements
2. markup declarations (instructions for the XML
parser)
3. processing instructions (for the application
program that is processing the data in the
document)
- XML names:
- Entity names:
- No length limitation
- Must begin with a letter, a dash, or a colon
- Can include letters, digits, periods, dashes,
underscores, or colons
&entity_name;
< <
> >
& &
" "
' '
e.g., instead of
use
<!keyword … >
- General form:
e.g.,
memo
e.g.,
<!ELEMENT person
(parent+, age, spouse?, sibling*)>
- Declaring Attributes
- General form:
- Default values:
a value
#FIXED value (every element will have
this value),
#REQUIRED (every instance of the element must
have a value specified), or
#IMPLIED (no default value and need not specify
a value)
- Two kinds:
- A reference: &jfk;
SHOW planes.dtd
http://xml.apache.org/xerces-j/index.html
- Internal DTDs
<!DOCTYPE root_name [
…
]>
- External DTDs
- Two purposes:
http://www.w3.org/2001/XMLSchema
targetNamespace =
"http://cs.uccs.edu/planeSchema"
xmlns = "http://cs.uccs.edu/planeSchema"
<xsd:schema
xmlns:xsd =
"http://www.w3.org/2001/XMLSchema"
targetNamespace =
"http://cs.uccs.edu/planeSchema"
xmlns = "http://cs.uccs.edu/planeSchema"
elementFormDefault = "qualified">
<planes
xmlns = "http://cs.uccs.edu/planeSchema"
xmlns:xsi =
http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation =
"http://cs.uccs.edu/planeSchema
planes.xsd" >
- Use the element tag and set the name and type
attributes
fixed = "three-toed"
- User-Defined Types
http://www.ltg.ed.ac.uk/~ht/xsv-status.html
SHOW planes.xml
- XSLT – Transformations
- XPATH - XML Path Language
- XSL-FO - Formatting objects
- An example:
<xsl:stylesheet xmlns:xsl =
"http://www.w3.org/1999/XSL/Format"
xmlns =
"http://www.w3.org/1999/xhtml">
- Has no content
1. Service providers
2. Service requestors
3. A service registry
UNIT – 5 NOTES
• Interface Servlet
– All servlets must implement this interface
– All methods of interface Servlet are invoked by servlet
container
• Servlet life cycle
– Servlet container invokes the servlet’s init method
– Servlet’s service method handles requests
– Servlet’s destroy method releases servlet resources when
the servlet container terminates the servlet
• Servlet implementation
– GenericServlet
– HttpServlet
P.Kumar, Rajalakshmi Engineering COllege 654
Interface Servlet and the Servlet Life Cycle
(Cont.)
• Init - This method is automatically called once
during a servlet’s execution cycle to initialize the
servlet.
• service method - which receives the request,
processes the request and sends a response to the
client.
• Destroy - This “cleanup” method is called when a
servlet is terminated by its servlet container.
Resources used by the servlet, such as an open file
or an open database connection, should be
deallocated here.
P.Kumar, Rajalakshmi Engineering COllege 655
HttpServlet Class
• Web server
– creates an HttpServletRequest object
– passes it to the servlet’s service method
• HttpServletRequest object contains the request from the
client
• Methods: getParameter, Enumeration, getCookies, getSession
HttpServletResponse Interface
• Web server
– creates an HttpServletResponse object
– passes it to the servlet’s service method
• Methods: addCookie, PrintWriter, setContentType
<HTML>
<HEAD>
<TITLE>Servlet HTTP GET Example</TITLE>
</HEAD>
<BODY>
<FORM ACTION="http://localhost:8080/servlet/HTTPGetServlet"
METHOD="GET">
<P>Click the button to have the servlet send an HTML document</P>
<INPUT TYPE="submit" VALUE="Get HTML Document">
</FORM>
</BODY>
</HTML>
• Web applications
– JSPs, servlets and their supporting files
• Deploying a Web application
– Directory structure
• Context root
– Web application archive file (WAR file)
– Deployment descriptor
• web.xml
Directory Description
context root This is the root directory for the Web application. All the
JSPs, HTML documents, servlets and supporting files such
as images and class files reside in this directory or its
subdirectories. The name of this directory is specified by the
Web application creator. To provide structure in a Web
application, subdirectories can be placed in the context root.
For example, if your application uses many images, you
might place an images subdirectory in this directory. The
examples of this chapter use jhtp5 as the context root.
WEB-INF This directory contains the Web application deployment
descriptor (web.xml).
WEB-INF/classes This directory contains the servlet class files and other
supporting class files used in a Web application. If the
classes are part of a package, the complete package directory
structure would begin here.
WEB-INF/lib This directory contains Java archive (JAR) files. The JAR
files can contain servlet class files and other supporting class
files used in a Web application.
Fig. 36.8 Web application standard directories.
<description>
This is the Web application in which we demonstrate our JSP and Servlet examples.
</description>
// Using cookies.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
response.setContentType( "text/html" );
output = response.getWriter();
P.Kumar, Rajalakshmi Engineering COllege 668
// send HTML page to client
output.println( "<HTML><HEAD><TITLE>" );
output.println( "Cookies" );
output.println( "</TITLE></HEAD><BODY>" );
output.println( "<P>Welcome to Cookies!<BR>" );
output.println( "<P>" );
output.println( language );
output.println( " is a great language." );
output.println( "</BODY></HTML>" );
response.setContentType( "text/html" );
output = response.getWriter();
output.println( "<HTML><HEAD><TITLE>" );
output.println( "Cookies II" );
output.println( "</TITLE></HEAD><BODY>" );
output.println( "</BODY></HTML>" );
output.close(); // close stream
}
<BODY>
<FORM ACTION=http://localhost:8080/servlet/CookieExample METHOD="POST">
<STRONG>Select a programming language:</STRONG><BR>
<INPUT TYPE="radio" NAME="lang" VALUE="C">C<BR>
<INPUT TYPE="radio" NAME="lang" VALUE="C++">C++<BR>
<INPUT TYPE="radio" NAME="lang" VALUE="Java" CHECKED>
Java<BR>
<INPUT TYPE="radio" NAME="lang" VALUE="Visual Basic 6">
Visual Basic 6
<P><INPUT TYPE="submit" VALUE="Submit">
<INPUT TYPE="reset"> </P>
</FORM>
</BODY>
</HTML>
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
response.setContentType( "text/html" );
output = response.getWriter();
if ( session != null )
valueNames = session.getValueNames();
else
valueNames = null;
response.setContentType( "text/html" );
output = response.getWriter();
output.println( "<HTML><HEAD><TITLE>" );
output.println( "Sessions II" );
output.println( "</TITLE></HEAD><BODY>" );
output.println( "</BODY></HTML>" );
output.close(); // close stream
}
<BODY>
<FORM ACTION=http://localhost:8080/servlet/SessionExample METHOD="POST">
<STRONG>Select a programming language:</STRONG><BR>
<INPUT TYPE="radio" NAME="lang" VALUE="C">C<BR>
<INPUT TYPE="radio" NAME="lang" VALUE="C++">C++<BR>
<INPUT TYPE="radio" NAME="lang" VALUE="Java" CHECKED> Java<BR>
<INPUT TYPE="radio" NAME="lang" VALUE="Visual Basic 6"> Visual Basic 6
<P><INPUT TYPE="submit" VALUE="Submit">
<INPUT TYPE="reset"> </P>
</FORM>
</BODY>
</HTML>
{ System.out.println(e);}
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String mrollno = req.getParameter("rollno") ;
try {
PreparedStatement ps = dbConn.prepareStatement("select * from stud
where rollno = ?") ;
ps.setString(1, mrollno) ;
ResultSet rs = ps.executeQuery() ;
out.println("<html>");
out.println("<body>");
out.println("<head>");
out.println("<title>Hello World!</title>");
out.println("</head>");
out.println("<body>");
out.println("<table border = 1>");
P.Kumar, Rajalakshmi Engineering COllege 683
while(rs.next())
{
out.println("<tr><td>Roll No. : </td>");
out.println("<td>" + rs.getString(1) + "</td></tr>");
out.println("<tr><td>Name : </td>");
out.println("<td>" + rs.getString(2) +"</td></tr>");
out.println("<tr><td>Branch : </td>");
out.println("<td>" + rs.getString(3) + "</td></tr>");
out.println("<tr><td>10th Mark : </td>");
out.println("<td>" + rs.getString(4) + "</td></tr>");
out.println("<tr><td>12th Mark : </td>");
out.println("<td>" + rs.getString(5) + "</td></tr>");
}
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
catch (Exception e)
{ System.out.println(e); }
}
} P.Kumar, Rajalakshmi Engineering COllege 684
• Database Structure – Student.mdb
• JavaServer Pages
– Extension of Servlet technology
• Web content delivery
• Reuse existing Java components
– Without programming Java
• Create custom tags
– Encapsulate complex functionality
• Classes and interfaces specific to JSP
– Package javax.servlet.jsp
– Package javax.servlet.jsp.tagext
• Key components
– Directives
– Actions
– Scriptlets
– Tag libraries
• Directive
– Message to JSP container
• i.e., program that compiles/executes JSPs
• They are used to set global values such as class declaration,
methods to be implemented, output content type, etc.
• They do not produce any output to the client.
• The three directives
– are page - specify page settings,
– to include content from other resources and
– to specify custom tag libraries for use in a JSP.
• Actions
– Predefined JSP tags that encapsulate functionality
– Often performed based on information from client request
– Can be used to create Java objects for use in scriptlets
• Scriptlet
– Also called “Scripting Elements”
• A scriptlet consists of one or more valid Java statements.
• vs. Active Server Pages (ASP). ASP is a similar technology from Microsoft. The
advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual
Basic or other MS-specific language, so it is more powerful and easier to use. Second, it
is portable to other operating systems and non-Microsoft Web servers.
• vs. Pure Servlets. JSP doesn't give you anything that you couldn't in principle do with a
servlet. But it is more convenient to write (and to modify!) regular HTML than to have a
zillion println statements that generate the HTML. Plus, by separating the look from the
content you can put different people on different tasks: your Web page design experts
can build the HTML, leaving places for your servlet programmers to insert the dynamic
content.
• vs. Server-Side Includes (SSI). SSI is a widely-supported technology for including
externally-defined pieces into a static Web page. JSP is better because it lets you use
servlets instead of a separate program to generate that dynamic part. Besides, SSI is
really only intended for simple inclusions, not for "real" programs that use form data,
make database connections, and the like.
• vs. JavaScript. JavaScript can generate HTML dynamically on the client. This is a
useful capability, but only handles situations where the dynamic information is based on
the client's environment. With the exception of cookies, HTTP and form submission
data is not available to JavaScript. And, since it runs on the client, JavaScript can't
access server-side resources like databases, catalogs, pricing information, and the like.
<html>
<head>
<meta http-equiv = "refresh" content = "60" />
</head>
<body>
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 697
Outline
Clock.jsp
• Implicit Objects
– Provide access to many servlet capabilities within a JSP
– Four scopes
• Application scope
– Objects owned by the container application
– Any servlet or JSP can manipulate these objects
• Page scope
– Objects that exist only in page in which they are defined
– Each page has its own instance of these objects
• Request scope
– Objects exist for duration of client request
– Objects go out of scope when response sent to client
• Session scope
– Objects exist for duration of client’s browsing session
– Objects go out of scope when client terminates session or when
session timeout occurs
P.Kumar, Rajalakshmi Engineering COllege 699
Implicit object Description
Application Scope
application This javax.servlet.ServletContext object represents the container in which the JSP
executes.
Page Scope
config This javax.servlet.ServletConfig object represents the JSP configuration options. As
with servlets, configuration options can be specified in a Web application descriptor.
exception This java.lang.Throwable object represents the exception that is passed to the JSP error
page. This object is available only in a JSP error page.
out This javax.servlet.jsp.JspWriter object writes text as part of the response to a
request. This object is used implicitly with JSP expressions and actions that insert string content
in a response.
page This java.lang.Object object represents the this reference for the current JSP instance.
• Scripting
– Dynamically generated content
– Insert Java code and logic in JSP using scripting
– Escape sequences
<html ><head>
<title>Processing "get" requests with data</title>
</head>
<body>
<% String name = request.getParameter( "firstName" );
welcome.jsp
Action Description
<jsp:include> Dynamically includes another resource in a JSP. As the JSP executes, the
referenced resource is included and processed.
<jsp:forward> Forwards request processing to another JSP, servlet or static page. This
action terminates the current JSP’s execution.
<jsp:plugin> Allows a plug-in component to be added to a page in the form of a
browser-specific object or embed HTML element. In the case of a
Java applet, this action enables the downloading and installation of the
Java Plug-in, if it is not already installed on the client computer.
<jsp:param> Used with the include, forward and plugin actions to specify
additional name/value pairs of information for use by these actions.
JavaBean Manipulation
<jsp:useBean> Specifies that the JSP uses a JavaBean instance. This action specifies the
scope of the bean and assigns it an ID that scripting components can use
to manipulate the bean.
<jsp:setProperty> Sets a property in the specified JavaBean instance. A special feature of
this action is automatic matching of request parameters to bean properties
of the same name.
<jsp:getProperty> Gets a property in the specified JavaBean instance and converts the result
to a string for output in the response.
Fig. 37.5 JSP standard actions.
• <jsp:include> action
– Enables dynamic content to be included in a JSP
– More flexible than include directive
• Requires more overhead when page contents change frequently
• banner.html, toc.html, clock.jsp, include.jsp and the images
directory into the jsp directory
• Open your Web browser and enter the following URL to test
• http://localhost:8080/jsp/include.jsp
<html >
<head>
<meta http-equiv = "refresh" content = "60" />
</head>
<body>
<td>
<%-- include clock2.jsp in this JSP --%>
<jsp:include page = "clock.jsp" flush = "true" /> </td>
</tr>
</table>
</body> </html>
P.Kumar, Rajalakshmi Engineering COllege 713
Outline
• <jsp:forward> action
– Enables JSP to forward request to different resources
• Can forwarded requests only resources in same context
• <jsp:param> action
– Specifies name/value pairs of information
• Name/Value pairs are passed to other actions
<html>
<head> <title>Forward request to another JSP</title></head>
<body>
<% // begin scriptlet
} // end if
else {
• <jsp:useBean> action
– Enables JSP to manipulate Java object
• Creates Java object or locates an existing object for use in JSP
Attribute Description
id The name used to manipulate the Java object with actions
<jsp:setProperty> and <jsp:getProperty>. A variable of
this name is also declared for use in JSP scripting elements. The name
specified here is case sensitive.
scope The scope in which the Java object is accessible—page, request,
session or application. The default scope is page.
class The fully qualified class name of the Java object.
beanName The name of a bean that can be used with method instantiate of
class java.beans.Beans to load a JavaBean into memory.
type The type of the JavaBean. This can be the same type as the class
attribute, a superclass of that type or an interface implemented by that
type. The default value is the same as for attribute class. A
ClassCastException occurs if the Java object is not of the type
specified with attribute type.
Fig. 37.13 Attributes of the <jsp:useBean> action.
<body>
<p >AdRotator Example</p>
<p>
<% = getImage()%>
<% = getLink()%>
</p>
</body>
</html>
P.Kumar, Rajalakshmi Engineering COllege 723
Outline
Attribute Description
name The ID of the JavaBean for which a property (or properties) will be
set.
property The name of the property to set. Specifying "*" for this attribute
causes the JSP to match the request parameters to the properties of the
bean. For each request parameter that matches (i.e., the name of the
request parameter is identical to the bean’s property name), the
corresponding property in the bean is set to the value of the parameter.
If the value of the request parameter is "", the property value in the
bean remains unchanged.
param If request parameter names do not match bean property names, this
attribute can be used to specify which request parameter should be
used to obtain the value for a specific bean property. This attribute is
optional. If this attribute is omitted, the request parameter names must
match bean property names.
value The value to assign to a bean property. The value typically is the result
of a JSP expression. This attribute is particularly useful for setting
bean properties that cannot be set using request parameters. This
attribute is optional. If this attribute is omitted, the JavaBean property
must be of a type that can be set using request parameters.
Fig. 37.16 Attributes of the <jsp:setProperty> action.
• JSP directives
– Messages to JSP container
– Enable programmer to:
• Specify page settings
• Include content from other resources
• Specify custom-tag libraries
– Delimited by <%@ and %>
Attribute Description
language The scripting language used in the JSP. Currently, the only valid value
for this attribute is java.
extends Specifies the class from which the translated JSP will be inherited. This
attribute must be a fully qualified class name.
import Specifies a comma-separated list of fully qualified type names and/or
packages that will be used in the current JSP. When the scripting
language is java, the default import list is java.lang.*,
javax.servlet.*, javax.servlet.jsp.* and
javax.servlet.http.*. If multiple import properties are
specified, the package names are placed in a list by the container.
session Specifies whether the page participates in a session. The values for this
attribute are true (participates in a session—the default) or false
(does not participate in a session). When the page is part of a session,
implicit object session is available for use in the page. Otherwise,
session is not available, and using session in the scripting code
results in a translation-time error.
Fig. 37.18 Attributes of the page directive.
P.Kumar, Rajalakshmi Engineering COllege 728
page Directive (cont.)
Attribute Description
buffer Specifies the size of the output buffer used with the implicit object out. The
value of this attribute can be none for no buffering, or a value such as 8kb
(the default buffer size). The JSP specification indicates that the buffer used
must be at least the size specified.
autoFlush When set to true (the default), this attribute indicates that the output buffer
used with implicit object out should be flushed automatically when the
buffer fills. If set to false, an exception occurs if the buffer overflows.
This attribute’s value must be true if the buffer attribute is set to none.
isThreadSafe Specifies if the page is thread safe. If true (the default), the page is
considered to be thread safe, and it can process multiple requests at the same
time. If false, the servlet that represents the page implements interface
java.lang.SingleThreadModel and only one request can be
processed by that JSP at a time. The JSP standard allows multiple instances
of a JSP to exists for JSPs that are not thread safe. This enables the container
to handle requests more efficiently. However, this does not guarantee that
resources shared across JSP instances are accessed in a thread-safe manner.
info Specifies an information string that describes the page. This string is returned
by the getServletInfo method of the servlet that represents the
translated JSP. This method can be invoked through the JSP’s implicit page
object.
Fig. 37.18 Attributes of the page directive.
P.Kumar, Rajalakshmi Engineering COllege 729
page Directive (cont.)
Attribute Description
errorPage Any exceptions in the current page that are not caught
are sent to the error page for processing. The error page
implicit object exception references the original
exception.
isErrorPage Specifies if the current page is an error page that will be
invoked in response to an error on another page. If the
attribute value is true, the implicit object exception
is created and references the original exception that
occurred. If false (the default), any use of the
exception object in the page results in a translation-
time error.
contentType Specifies the MIME type of the data in the response to
the client. The default type is text/html.
Fig. 37.18 Attributes of the page directive.
<html >
<head> <title>Using the include directive</title></head>
<body>
<table> <tr>
<td > <img src = "images/logo.jpg" width = "140" height = "93" alt = “rec " /> </td>
<td>
<%-- include banner.html in this JSP --%>
<%@ include file = "banner.html" %> </td> </tr>
<td >
<%-- include clock2.jsp in this JSP --%>
<%@ include file = "clock2.jsp" %>
</td> </tr> </table>
</body>
</html> P.Kumar, Rajalakshmi Engineering COllege 732
Tag Libraries
// output content
out.print( "Welcome to JSP Tag Libraries!" );
}
Demonstrate
• Enables users to place their first name, last name
and e-mail address into a guest book database.
• After submitting their information, users see a
Web page containing all the users in the guest
book. Each person’s e-mail address is displayed
as a hyperlink that allows the user to send an e-
mail message to the person.
public void setFirstName( String name ) // set the guest's first name
{
firstName = name;
}
public String getFirstName() // get the guest's first name
{
return firstName;
}
public void setLastName( String name ) // set the guest's last name
{
lastName = name;
}
public String getLastName() // get the guest's last name
{
return lastName;
}
public void setEmail( String address ) // set the guest's email address
{
email = address;
}
public String getEmail() // get the guest's email address
{
return email; P.Kumar, Rajalakshmi Engineering COllege 738
}
}
GuestDataBean.java
Class GuestDataBean makes a database connection and
supports
inserting and retrieving data from the database.
// package com.jsp.beans;
import java.io.*;
import java.sql.*;
import java.util.*;
guest.setFirstName( results.getString( 1 ) );
guest.setLastName( results.getString( 2 ) );
guest.setEmail( results.getString( 3 ) );
guestList.add( guest );
}
return guestList;
}
P.Kumar, Rajalakshmi Engineering COllege 740
GuestDataBean.java
<html >
<head>
<title>Guest Book Login</title>
</head>
P.Kumar, Rajalakshmi Engineering COllege 742
guestBookLogin.jsp
<body>
<jsp:setProperty name = "guest" property = "*" />
<p>Enter your first name, last name and email address to register in our guest book.</p>
<table>
<tr>
<td>First name</td>
<td>
<input type = "text" name = "firstName" />
</td>
</tr>
<tr> <td>Email</td>
<td> <input type = "text" name = "email" /> </td> </tr>
</html>
P.Kumar, Rajalakshmi Engineering COllege 744
guestBookView.jsp
<table>
<thead> <tr>
<th>Last name</th>
<th>First name</th>
<th>Email</th>
</tr> </thead> <tbody>
while ( guestListIterator.hasNext() ) {
guest = ( GuestBean ) guestListIterator.next();
<td>
<a href = "mailto:<%= guest.getEmail() %>">
<%= guest.getEmail() %></a>
</td> </tr>
} // end while
</tbody> </table>
</body>
</html> P.Kumar, Rajalakshmi Engineering COllege 747
Case Study: Guest Book (Cont.)
9. Make check for Run Apache Tomcat and Show and uncheck Show Readme.
15. Create a folder named CLASSES under Web-INF folder and copy all your .class files.
16. Copy the WEB.XML file from d:\tomcat\webapps\ROOT\WEB-INF folder to your WEB-
INF folder. Edit the servlet-name, servlet-class in servlet tag and also servlet-name, url-
pattern in servlet-mapping.
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<servlet-name>Banking</servlet-name>
<servlet-class>Banking</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Banking</servlet-name>
<url-pattern>/Banking</url-pattern>
</servlet-mapping>
</web-app>
23. After successful deployment you will get a screen like as below: