You are on page 1of 342

WEB TECHNOLOGIES

B.Tech IT III YEAR II SEMESTER

UNIT I

OVERVIEW:

This unit provides information about web technologies that relate to the interface
between web servers and their clients. This information includes markup languages,
programming interfaces and languages, and standards for document identification
and display. The term "Web 2.0" (2004present) is commonly associated with web
applications that facilitate interactive information sharing, interoperability, usercentered design and collaboration on the World Wide Web. Examples of Web 2.0
include web-based communities, hosted services, web applications, socialnetworking sites, video-sharing sites, wikis, blogs and folksonomies. A Web 2.0 site
allows its users to interact with other users or to change website content, in contrast
to non-interactive websites where users are limited to the passive viewing of
information that is provided to them.

OBJECTIVES

Introduction to Web Technologies

Explain how does client sever model work

HTML & HTTP Protocol, Basic structure

Lists & Tables

Images & Hyper Links

Forms & Frames

Cascading Style Sheets(CSS)

Introduction to Web Technologies


WWW (World Wide Web ) simply called as WEB is the collection of millions of web pages
across thousands of computers.

A web page refers to any document on the web. Every web page is identified by a unique URL in
the internet and it contains hyper text i.e different types of text such as plain text ,graphics,
animation, Audio, video etc.
Web technology relates to the interface between web servers and their clients. It includes markup
languages, programming interfaces and languages, and standards for document identification and
display.
A web application is any application that is specifically used through a web browser. Some
examples of web applications include , ON Line Book Store , Shopping , Citrix Meta frame
applications and any number of tools such as package tracking that are found on the Internet.

Accessing information on the Web

Accessing information on the Web


Information on the Web is stored in documents, using a language called HTML (HyperText
Markup Language). Web clients must interpret HTML to be able to display the documents to a
user. The protocol that governs the exchange of information between the Web server and Web
client is named HTTP (HyperText Transfer Protocol).

External data in HTML documents


HTML documents can include graphics or other types of data by referencing an external file (for
example, a GIF or JPEG file for a graphic). Not all these external formats are supported by all Web
clients. When the document contains such data, the Web client can send a request to the Web server
to provide the relevant graphic. If the Web client does not support the format, it does not request the
information from the server.
Any Web Application we consider It follows Client Server Technology

CLIENT / SERVER MODEL


Client server

Client/server describes the relationship between two computer programs in which one program,
the client, makes a service request from another program, the server, which fulfils the request.
Although programs within a single computer can use the client/server idea, it is a more important
idea in a network. In a network, the client/server model provides a convenient way to
interconnect programs that are distributed efficiently across different locations. Computer
transactions using the client/server model are very common. For example, to check your bank
account from your computer, a client program in your computer forwards your request to a
server program at the bank. That program might in turn forward the request to its own client
program that sends a request to a database server at another bank computer to retrieve your
account balance. The balance is returned back to the bank data client, which in turn serves it
back to the client in your personal computer, which displays the information for you.

Client server model diagram

HTML
HTML, Hypertext Mark-up Language, is the predominant markup language for developing
web pages. It provides a means to describe the structure of text-based information in a
documentby denoting certain text as links, headings, paragraphs, lists, etc.and to supplement
that text with interactive forms, embedded images, and other objects. HTML is written in the
form of "tags" consisting minimally of "elements" surrounded by angle brackets. HTML can also
describe, to some degree, the appearance and semantics of a document, and can include
embedded scripting language code (such as JavaScript) that can affect the behavior of Web
browsers and other HTML processors.
HTML is a language for describing web pages.
HTML is a markup language
A markup language is a set of markup tags
The tags describe document content
HTML documents contain HTML tags and plain text
HTML documents are also called web pages

HTML markup tags are usually called HTML tags


HTML tags are keywords (tag names) surrounded by angle brackets like <html>
HTML tags normally come in pairs like <b> and </b>
The first tag in a pair is the start tag, the second tag is the end tag
The end tag is written like the start tag, with a forward slash before the tag name
Start and end tags are also called opening tags and closing tags

<tagname>content</tagname>

HTML Versions
Since the early days of the web, there have been many versions of HTML:
Version

Year

HTML

1991

HTML+

1993

HTML 2.0

1995

HTML 3.2

1997

HTML 4.01

1999

XHTML 1.0

2000

HTML5

2012

XHTML5

2013

Web Browsers
The purpose of a web browser (such as Google Chrome, Internet Explorer, Firefox, Safari) is to
read HTML documents and display them as web pages.

HTML Page Structure


Below is a visualization of an HTML page structure:
<html>

<head>
<title>Welcome To WWW </title>
</head>
<body>
<h1>This a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>

Basic HTML Elements :


<HTML>, <HEAD>, <BODY> Tags
Each HTML document is contained within the starting <HTML> & ending </HTML>
tags.
Each HTML document also includes a header section indicated by the <HEAD> tag
which in turn contains elements like <TITLE> , <META> <SCRIPT> etc.
What ever the data we want to present must be written with in <BODY> </BODY>tags
By applying different styles
<META>
This tag is mainly used to pass information about the web page to the external world , or
to pass messages to the client such as the language of the document, last modified date
etc using the HTTP-EQUIV and CONTENT attribute pairs:
Example

<META HTTP-EQUIV="keywords" CONTENT="Biology, Chemistry">


<META HTTP-EQUIV="Last-Modified" CONTENT="Sep 06, 1996">

HTML Paragraphs <p> tag


HTML paragraphs are defined with the <p> tag.
Example
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<pre> Tag
It is a pre-formatted tag : Displays as it is..
The data in html is displayed from left right and top to bottom irrespective of what ever format
we write in program Therefore to display as it is how we write in program we can use <pre> tag

HTML Headings
HTML defines different types of headers using six header tags i,e <h1> to <h6> tags.
The order of Font size is in decreasing order from h1 to h6
Example
<h1>HELLO</h1>
<h2>HELLO</h2>
<h3>HELLO</h3>
<h4>HELLO</h4>
<h5>HELLO</h5>
<h6>HELLO</h6>

<font> tag
Specify the font size, font face and color of text:
<font size="3" color="red">This is some text!</font>
<font size="2" color="blue">This is some text!</font>
<font face="verdana" color="green">This is some text!</font>

HTML Text Formatting Tags


Tag

Description

<b>

Defines bold text

<em>

Defines emphasized text

<i>

Defines italic text

<small> Defines smaller text


<strong> Defines important text
<sub>

Defines subscripted text

<sup>

Defines superscripted text

<strike> Defines striking text


<del>

Defines deleted text

<u>

Defines underline

HTML "Computer Output" Tags


Tag

Description

<code> Defines computer code text


<kbd> Defines keyboard text
<samp> Defines sample computer code
<var>

Defines a variable

<pre>

Defines preformatted text

HTML Citations, Quotations, and Definition Tags

Tag

Description

<abbr>

Defines an abbreviation or acronym

<address>

Defines contact information for the author/owner of a document

<bdo>

Defines the text direction

<blockquote>

Defines a section that is quoted from another source

<q>

Defines an inline (short) quotation

<cite>

Defines the title of a work

<dfn>

Defines a definition term

Attributes
Every Tag is associated with set of Attributes an attribute defines the characteristic of a
particular tag.
An Attribute is represented as a name value pair with in a tag
A tag can contain any no of attributes separated by space
Example
The attributes of body tag are
<body bgcolor=red text= green>
bgcolor represent the background color of the document and text represent the foreground color
of the document.

HTML Lists
Lists are used to display the list of elements in an order
Basically HTML supports Three types of lists Ordered List , Un Ordered List Definition List

HTML Unordered Lists


An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.

The list items are marked with bullets (typically small black circles).
Example
<ul>
<li>Coffee</li>
<li>Milk</li>
</ul>
How the HTML code above looks in a browser:
Coffee
Milk

HTML Ordered Lists


An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.
The list items are marked with numbers.
Example
<ol>
<li>Coffee</li>
<li>Milk</li>
</ol>
How the HTML code above looks in a browser:
1. Coffee
2. Milk

HTML Description Lists


A description list is a list of terms/names, with a description of each term/name.
The <dl> tag defines a description list.
The <dl> tag is used in conjunction with <dt> (defines terms/names) and <dd> (describes each
term/name):

Example
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
How the HTML code above looks in a browser:
Coffee
- black hot drink
Milk
- white cold drink

HTML Links
Linking or Navigating from one page to another
Html supports three types of Hyper Links
Text Hyper Link ( Text a Link)
Graphical HyperLink ( Image as a link)
Link with in single document or Internal Link
HTML links are defined with the <a> tag.
Example
Text Hyper Link
<a href="http://www.w3schools.com">Click</a>
Graphical Hyper Link
<a href="Pictures.html"> <img src =flower.gif ></a>
Internal Link
<h1><a name="seealso">See also</a></h1>
Or:
<h1 id="seealso">See also</h1>
then link to it:

<a href="#seealso">Go to the see also section</a>


The compulsory attribute for <a> tag is HREF to specify linking page

HTML Images
HTML images are defined with the <img> tag.
Example

<img src="flower.jpg" alt="W3Schools.com" width="104" height="142">


The compulsory attribute for <a> tag is src to specify URL of the image
alt stands for Alternate Text If the browser is not supporting Images it display the value of
ALT .
height and width specify the height and width of the image.

HTML Tables
Tables are defined with the <table> tag.
A table is divided into rows using <tr> , and each row is divided into data cells using<td> tag).
td stands for "table data," and holds the content of a data cell. A <td> tag can contain text, links,
images, lists, forms, other tables, etc.
Example
<caption> Time Table </caption>
<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>

<td>row 2, cell 2</td>


</tr> </table>
<Caption> tag is used to display Heading of the table .

Important attributes of Table are


Height

- To specify height of the table

Width

- To specify width of the table

Border

- To specify border of the table

Bgcolor

- To specify background color to the table or to the row or to the coloumn

Colspan

- To combine two coloumns

Row span

- To combine two rows

Cell spacing

- To give space between the cells

Cell Padding

- space between the data and the border

HTML FORMS
HTML forms are used to pass data to a server.
An HTML form can contain input elements like text fields, checkboxes, radio-buttons, submit
buttons and more. A form can also contain select lists, textarea, fieldset, legend, and label
elements.
The <form> tag is used to create an HTML form:
The most important form element is the <input> element.
The <input> element is used to select user information.
An <input> element can vary in many ways, depending on the type attribute. An <input>
element can be of type text field, checkbox, password, radio button, submit button, and more.

Text Fields
<input type="text"> defines a one-line input field that a user can enter text into:
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
How the HTML code above looks in a browser:
First name:
Last name:

ROSE
LILLY

<input type="password"> defines a password field:


<form>
Password: <input type="password" name="pwd">
</form>
How the HTML code above looks in a browser:
Password:

********

The characters in a password field are masked (shown as asterisks or circles).


Radio Buttons
<input type="radio"> defines a radio button. Radio buttons let a user select ONLY ONE of a
limited number of choices:
<form>
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female
</form>
How the HTML code above looks in a browser:

Male
Female
Check Box
<input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO or MORE
options of a limited number of choices.
<form>
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
How the HTML code above looks in a browser:
I have a bike
I have a car
Submit Button
<input type="submit"> defines a submit button.
A submit button is used to send form data to a server. The data is sent to the page specified in the
form's action attribute. The file defined in the action attribute usually does something with the
received input:
<form name="input" action="html_form_action.asp" method="get">
Username: <input type="text" name="user">
<input type="submit" value="Submit">
</form>
How the HTML code above looks in a browser:

Username:

Submit

If you type some characters in the text field above, and click the "Submit" button, the browser
will send your input to a page called "html_form_action.asp". The page will show you the
received input.

HTML FRAMES
Frames in HTML
To divide a web page into different partitions we use Frames
Two tags called <frameset> </frameset> and <frame > are used for creating frames and loading
pages into those frames.
Ex:
<frameset rows="60%,*">
<frame src="first.html"/>
<frame src="second.html"/>
</frameset>

<frameset> tag is a

A container tag, requires a closing </frameset> tag


Determines the frame types and sizes on the page
Two frame types:
Columns
Rows
rows and cols are the attributes of the <frameset>
rows is used to divide the frame horizontally based on value given.
cols is used to divide the frame vertically based on value given.
In the frameset document, the <frameset> element takes the place of the <body> element

<frame> tag is used to

Load a web page into a frame using src attribute


Use the name attribute to name a frame, then target the frame name with hyperlinks
The syntax for naming a frame is as follows:
<frame src="url" name="framename"/>

The following code names a frame:


<frame src="james.html" name="authors"/>

The following code targets this frame:

<a href="james.html" target= "authors"> Visit James </a>

If a user clicks the Visit James link, the James page will open in the Authors frame

Ex1:
<frameset rows="40%,60%">
<frame src="top.htm" name="top">
<frame src="bottom.htm" name="bottom">
</frameset>

Ex2 :
<frameset rows="16%,84%">
<frame src="top.htm" name="top">
<frameset cols="50%,50%">
<frame src="left.htm" name="left">
<frame src="right.htm" name="right">
</frameset></frameset>

Cascading Style Sheets


Cascading Style Sheets (CSS) is a style sheet language used for describing the look and
formatting of a document written in a markup language.
CSS stands for cascading style sheets. Cascading style sheets provide the ability to change the
appearance of text (such as fonts, colors, spacing) on Web pages. Using CSS, you can also
position elements on the page, make certain elements hidden, or change the appearance of the
browser, such as changing the color of scroll bars in Microsoft Internet Explorer.

For Applying styles to different html elements we use CSS


Basic Structure of a Styles

Each definition contains:


A property
A colon
A value
A semicolon to separate two or more style properties
Can include one or more values
Example:
h1 {font-size:12pt; color:red}

body
{
background-color:#d0e4fe;
}
h1
{
color:orange;
text-align:center;
}
p
{
font-family:"Times New Roman";
font-size:20px;
}

HTML supports three types of Style Sheets

External style sheet


Internal or Embedded styles
Inline styles

External or Embeded Style Sheet


An external style sheet is ideal when the style is applied to many pages. With an external style
sheet, you can apply unique style properties to different pages a site.
Each page must link to the style sheet using the <link> tag. The <link> tag goes inside the head
section:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
An external style sheet can be written in any text editor. The file should not contain any html
tags. Your style sheet should be saved with a .css extension. An example of a style sheet file is
shown below:
Ex: mystyle.css
hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}
Internal or Embeded Style Sheet
An internal style sheet should be used when a single document has a unique style. You define
internal styles in the head section of an HTML page, by using the <style> tag, like this:
<head>
<style>
hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}
</style>
</head>

Inline Styles
To use inline styles you use the style attribute in the relevant tag. The style attribute can contain
any CSS property. The example shows how to change the color and the left margin of a
paragraph:
<p style="color:sienna;margin-left:20px;">This is a paragraph.</p>

Note:
If we represent style as an attribute it is called Inline Style Sheeet
If we represent style as a tag it is called Embeded style Sheeet
If we represent styles in a seperate file and link that to a web page it is called External
style sheet

Important Questions :
1. a) Explain the purpose of cascading style sheets.
b) Design and create the page(s) for accepting the values of name and marks in a table then
displays them in the descending order of the marks.
2. Explain the following input components in HTML forms with proper syntax of the
corresponding HTML tags.
a) Text Input
b) Selectable list with multiple selection option
c) Radio Buttons.
3. Write HTML code to create a frame with a table contents on the left side of the window, and
have each entry in the table of contents. Use internal linking to scroll down the document
frame to the appropriate subsection.

Web Technologies
B.Tech III Year II Semester
IT DEPT

Java Script
Unit II

JavaScript
Introduction
data types & expressions
Arrays in Java Scripts
control statements
functions & libraries
Java Script Objects
Event Handling
Dynamic HTML Introduction
Dynamic HTML with Java Sripts

Introduction
HTML is good for developing static Web pages
can specify text/image layout, presentation, links,
Web page looks the same each time it is accessed
in order to develop interactive/reactive pages, must integrate programming in some form or
another

client-side programming
Client side validations of a Web application can be Performed using a scripting language
e.g., JavaScript, JScript, VBScript
Scripting elements are embedded in the HTML of a Web page, with (HTML) tags to identify
the program component
e.g., <script

type="text/javascript"> </script>

the browser executes the program as it loads the page, integrating the dynamic output of
the program with the static content of HTML
could also allow the user (client) to input information and process it, might be used to
validate input before its submitted to a remote server

Scripts vs. Programs


a scripting language is a simple, interpreted programming language
scripts are embedded as plain text, interpreted by application

simpler execution model: don't need compiler or development environment


saves bandwidth: source code is downloaded, not compiled executable
platform-independence: code interpreted by any script-enabled browser
but: slower than compiled code, not as powerful/full-featured
JavaScript: the first Web scripting language, developed by Netscape in 1995
syntactic similarities to Java/C++, but simpler, more flexible in some respects,
limited in others (loose typing, dynamic variables, simple objects)
JScript: Microsoft version of JavaScript, introduced in 1996
same core language, but some browser-specific differences
fortunately, IE, Netscape, Firefox, etc. can (mostly) handle both
JavaScript & JScript

Common Scripting Tasks


adding dynamic features to Web pages

validation of form data (probably the most commonly used application)


image rollovers
time-sensitive or random page elements
handling cookies

defining programs with Web interfaces


utilize buttons, text boxes, clickable images, prompts, etc

limitations of client-side scripting


since script code is embedded in the page, it is viewable to the world
for security reasons, scripts are limited in what they can do
e.g., can't access the client's hard drive
since they are designed to run on any machine platform, scripts do not contain platform
specific commands
script languages are not full-featured
e.g., JavaScript objects are very crude, not good for large project development

JavaScript
JavaScript code can be embedded in a Web page using <script> tags
the output of JavaScript code is displayed as if directly entered in HTML
<html>
<head>
<title>JavaScript Page</title>
<script type="text/javascript">
// silly code to demonstrate output
document.write("<p>Hello world!</p>");

document.write displays text in the page

text to be displayed can include HTML


tags
the tags are interpreted by the browser
when the text is displayed

document.write(" <p>How are <br/> " +


" <i>you</i>?</p> ");
</script>
</head>
<body>
<p>Here is some static text as well.</p>

as in C++/Java, statements end with ;


but a line break might also be interpreted as
the end of a statement (depends upon
browser)

</body>
</html>

JavaScript comments similar to C++/Java


//

starts a single line comment

/**/ enclose multi-line comments

JavaScript Data Types & Variables

JavaScript has only three primitive data types


String : "foo"
Number : 12
Boolean : true

'how do you do?'


"I said 'hi'."
""
3.14159
1.5E6
false
Null : the only value of Null is the reserve word null indicates no value
Undefined : If a variable is explicitly declared but not assigned a value it
has the value undefined
<html>
<head>
<title>Data Types and Variables</title>
</head>
<body>
<script type="text/javascript">
var x, y;
x= 1024;
y=x; x = "foobar";
document.write("<p>x = " + y + "</p>");
document.write("<p>x = " + x + "</p>");
</script>
</body>
</html>

assignments are as in C++/Java


message = "howdy";
pi = 3.14159;

variable names are sequences of letters,


digits, and underscores that start with a letter
or an underscore
variables names are case-sensitive
you don't have to declare variables, will be
created the first time used, but its better if
you use var statements
var message, pi=3.14159;

variables are loosely typed, can be assigned


different types of values (Danger!)

JavaScript Arrays
arrays store a sequence of items, accessible via an index

since JavaScript is loosely typed, elements do not have to be the same type
to create an array, allocate space using new

(or can assign directly)

items = new Array(10);

// allocates space for 10 items

items = new Array();

// if no size given, will adjust dynamically

items = [0,0,0,0,0,0,0,0,0,0]; // can assign size & values []

to access an array element, use [] (as in C++/Java)


for (i = 0; i < 10; i++) {
items[i] = 0;

// stores 0 at each index

the length property stores the number of items in the array


for (i = 0; i < items.length; i++) {
document.write(items[i] + "<br>");
}

// displays elements

Array Example
<html>
<head>
<title>Die Statistics</title>
<script type="text/javascript"
src="http://www.csc.liv.ac.uk/~martin/teaching/comp519/JS/r
andom.js">
</script>
</head>
<body>
<script type="text/javascript">
numRolls = 60000;
dieSides = 6;
rolls = new Array(dieSides+1);
for (i = 1; i < rolls.length; i++) {
rolls[i] = 0;
}
for(i = 1; i <= numRolls; i++) {
rolls[randomInt(1, dieSides)]++;
}

for (i = 1; i < rolls.length; i++) {


document.write("Number of " + i + "'s = " +
rolls[i] + "<br />");
}
</script>
</body>
</html>

suppose we want to
simulate die rolls and
verify even distribution
keep an array of counters:
initialize each count to 0
each time you roll X,
increment rolls[X]
display each counter

Arrays (cont.)
Arrays have predefined methods that allow them to be used as stacks,
queues, or other common programming data structures.
var stack = new Array();
stack.push("blue");
stack.push(12);
stack.push("green");
var item = stack.pop();

//
//

stack is now the array ["blue", 12]


stack = ["blue", 12, "green"]
// item is now equal to "green"

var q = [1,2,3,4,5,6,7,8,9,10];
item = q.shift();
// item is now equal to 1, remaining
// elements of q move down one position
// in the array, e.g. q[0] equals 2
q.unshift(125); // q is now the array [125,2,3,4,5,6,7,8,9,10]
q.push(244);
// q = [125,2,3,4,5,6,7,8,9,10,244]

JavaScript Operators & Control Statements


<html>
<head>
<title>Folding Puzzle</title>
</head>
<body>
<script type="text/javascript">
var distanceToSun = 93.3e6*5280*12;
var thickness = .002;
var foldCount = 0;
while (thickness < distanceToSun) {
thickness *= 2;
foldCount++;
}
document.write("Number of folds = " +
foldCount);
</script>
</body>
</html>

standard C++/Java operators &


control statements are provided
in JavaScript
+, -, *, /, %, ++, --,
==, !=, <, >, <=, >=
&&, ||, !,===,!==

if , if-else, switch
while, for, do-while,
PUZZLE: Suppose you took a piece
of paper and folded it in half, then in
half again, and so on.

How many folds before the thickness


of the paper reaches from the earth to
the sun?

JavaScript Math Routines


<html>
<head>
<title>Random Dice Rolls</title>
</head>
<body>
<div style="text-align:center">
<script type="text/javascript">
var roll1 = Math.floor(Math.random()*6) + 1;
var roll2 = Math.floor(Math.random()*6) + 1;
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/comp519/Images/die" +
roll1 + ".gif alt=dice showing + roll1 />");
document.write("&nbsp;&nbsp;");
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/comp519/Images/die" +
roll2 + ".gif alt=dice showing + roll2 />");
</script>
</div>
</body>
</html>

the built-in Math


object contains
functions and
constants
Math.sqrt
Math.pow
Math.abs
Math.max
Math.min
Math.floor
Math.ceil
Math.round
Math.PI
Math.E
Math.random

function returns a real


number in [0..1)

Interactive Pages Using Prompt


<html>
<head>
<title>Interactive page</title>
</head>

<body>
<script type="text/javascript">
var userName = prompt("What is your name?", "");
var userAge = prompt("Your age?", "");
var userAge = parseFloat(userAge);
document.write("Hello " + userName + ".")
if (userAge < 18) {
document.write(" Do your parents know " +
"you are online?");
}
else {
document.write(" Welcome friend!");
}
</script>
<p>The rest of the page...</p>
</body>
</html>

crude user interaction can


take place using prompt
1st argument: the prompt
message that appears in the
dialog box
2nd argument: a default value
that will appear in the box (in
case the user enters nothing)

the function returns the value


entered by the user in the
dialog box (a string)
if value is a number, must use
parseFloat (or parseInt) to
convert

forms will provide a better


interface for interaction
(later)

User-Defined Functions
function definitions are similar to C++/Java, except:
no return type for the function (since variables are loosely typed)
no variable typing for parameters (since variables are loosely typed)
by-value parameter passing only (parameter gets copy of argument)
function isPrime(n)
// Assumes: n > 0
// Returns: true if n is prime, else false
{
if (n < 2) {
return false;
}
else if (n == 2) {
return true;
}
else {
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}

Can limit variable scope to the


function.
if the first use of a variable is preceded
with var, then that variable is local to
the function
for modularity, should make all
variables in a function local

Function Example
<html>
<head>
<title>Prime Tester</title>
<script type="text/javascript">
function isPrime(n)
// Assumes: n > 0
// Returns: true if n is prime
{
// CODE AS SHOWN ON PREVIOUS SLIDE
}
</script>
</head>

<body>
<script type="text/javascript">
testNum = parseFloat(prompt("Enter a positive integer", "7"));
if (isPrime(testNum)) {
document.write(testNum + " <b>is</b> a prime number.");
}
else {
document.write(testNum + " <b>is not</b> a prime number.");
}
</script>
</body>
</html>

Function definitions
(usually) go in the
<head> section
<head> section is
loaded first, so then
the function is
defined before code
in the <body> is
executed (and,
therefore, the
function can be
used later in the
body of the HTML
document)

<html>

<head>
<title> Random Dice Rolls Revisited</title>
<script type="text/javascript">
function randomInt(low, high)
// Assumes: low <= high
// Returns: random integer in range [low..high]
{
return Math.floor(Math.random()*(high-low+1)) + low;
}
</script>
</head>

Another
Example
recall the dynamic dice
page

<body>
<div style="text-align: center">
<script type="text/javascript">
roll1 = randomInt(1, 6);
roll2 = randomInt(1, 6);

could define a function for


generating random
numbers in a range, then
use whenever needed

document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/comp519/Images/die" +
roll1 + ".gif'/>");
document.write("&nbsp;&nbsp;");
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/comp519/Images/die" +
roll2 + ".gif'/>");
</script>
</div>
</body>
</html>

easier to remember,
promotes reuse

JavaScript Libraries
better still: if you define functions that may be useful to many pages, store in a
separate library file and load the library when needed

the file at http://www.csc.liv.ac.uk/~martin/teaching/comp519/JS/random.js


contains definitions of the following functions:
randomNum(low, high)
randomInt(low, high)
randomChar(string)
randomOneOf([item1,,itemN])

returns random real in range [low..high)


returns random integer in range [low..high)
returns random character from the string
returns random item from list/array

Note: as with external style sheets, do not put <script> tags in the external JavaScript library file
load a library using the SRC attribute in the SCRIPT tag (put nothing between the beginning
and ending tags)
<script type="text/javascript"
src="http://www.csc.liv.ac.uk/~martin/teaching/comp519/JS/random.js">
</script>

Library Example
<html>
<head>
<title> Random Dice Rolls Revisited</title>
<script type="text/javascript"
src="http://www.csc.liv.ac.uk/~martin/teaching/comp519/JS/random.js">
</script>
</head>
<body>
<div style="text-align: center">
<script type="text/javascript">
roll1 = randomInt(1, 6);
roll2 = randomInt(1, 6);
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/comp519/Images/die" +
roll1 + ".gif'/>");
document.write("&nbsp;&nbsp;");
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/comp519/Images/die" +
roll2 + ".gif'/>");
</script>
</div>
</body>
</html>

JavaScript Objects
an object defines a new type (formally, Abstract Data Type)

encapsulates data (properties) and operations on that data (methods)


Java Script supports many implicit objects for various operations they are
String Object
Number Object
Date Object
Document Object
Navigator Object
Window Object
History Object etc..

String Object
a String object encapsulates a sequence of characters, enclosed in quotes
properties include
length

methods include
charAt(index)
substring(start, end)
toUpperCase()
toLowerCase()

: stores the number of characters in the string


: returns the character stored at the given index
(as in C++/Java, indices start at 0)
: returns the part of the string between the start
(inclusive) and end (exclusive) indices
: returns copy of string with letters uppercase
: returns copy of string with letters lowercase

to create a string, assign using new or (in this case) just make a direct assignment (new is implicit)
word = new String("foo");

word = "foo";

properties/methods are called exactly as in C++/Java


word.length

word.charAt(0)

String example: Palindromes


function strip(str)
// Assumes: str is a string
// Returns: str with all but letters removed
{
var copy = "";
for (var i = 0; i < str.length; i++) {
if ((str.charAt(i) >= "A" && str.charAt(i) <= "Z") ||
(str.charAt(i) >= "a" && str.charAt(i) <= "z")) {
copy += str.charAt(i);
}
}
return copy;
}
function isPalindrome(str)
// Assumes: str is a string
// Returns: true if str is a palindrome, else false
{
str = strip(str.toUpperCase());
for(var i = 0; i < Math.floor(str.length/2); i++) {
if (str.charAt(i) != str.charAt(str.length-i-1)) {
return false;
}
}
return true;
}

suppose we want to
test whether a word
or phrase is a
palindrome
noon
Radar
Madam, I'm Adam.
A man, a plan, a canal:
Panama!
must strip non-letters out of the
word or phrase

make all chars uppercase in


order to be case-insensitive
finally, traverse and compare
chars from each end

<html>

<head>
<title>Palindrome Checker</title>
<script type="text/javascript">
function strip(str)
{
// CODE AS SHOWN ON PREVIOUS SLIDE
}
function isPalindrome(str)
{
// CODE AS SHOWN ON PREVIOUS SLIDE
}
</script>
</head>
<body>
<script type="text/javascript">
text = prompt("Enter a word or phrase", "Madam, I'm Adam");
if (isPalindrome(text)) {
document.write("'" + text + "' <b>is</b> a palindrome.");
}
else {
document.write("'" + text + "' <b>is not</b> a palindrome.");
}
</script>
</body>
</html>

Date Object
String & Array are the most commonly used objects in JavaScript
other, special purpose objects also exist

the Date object can be used to access the date and time
to create a Date object, use new & supply year/month/day/ as desired
today = new Date();

// sets to current date & time

newYear = new Date(2002,0,1); //sets to Jan 1, 2002

12:00AM

methods include:
newYear.getYear()
newYear.getMonth()
newYear.getDay()
newYear.getHours()
newYear.getMinutes()
newYear.getSeconds()
newYear.getMilliseconds()

can access individual components of a date

<html>

Date Example

<head>
<title>Time page</title>
</head>
<body>
Time when page was loaded:
<script type="text/javascript">
now = new Date();
document.write("<p>" + now + "</p>");
time = "AM";
hours = now.getHours();
if (hours > 12) {
hours -= 12;
time = "PM"
}
else if (hours == 0) {
hours = 12;
}
document.write("<p>" + hours + ":" +
now.getMinutes() + ":" +
now.getSeconds() + " " +
time + "</p>");
</script>
</body>
</html>

by default, a date will be displayed in


full, e.g.,
Sun Feb 03 22:55:20 GMT-0600
(Central Standard Time) 2002

can pull out portions of the date using


the methods and display as desired
here, determine if "AM" or "PM" and
adjust so hour between 1-12
10:55:20 PM

Another Example
<html>
<head>
<title>Time page</title>
</head>
<body>
<p>Elapsed time in this year:
<script type="text/javascript">
now = new Date();
newYear = new Date(2012,0,1);
secs = Math.round((now-newYear)/1000);
days = Math.floor(secs / 86400);
secs -= days*86400;
hours = Math.floor(secs / 3600);
secs -= hours*3600;
minutes = Math.floor(secs / 60);
secs -= minutes*60
document.write(days + " days, " +
hours + " hours, " +
minutes + " minutes, and " +
secs + " seconds.");
</script>
</p>
</body>
</html>

you can add and subtract Dates:


the result is a number of
milliseconds
here, determine the number of
seconds since New Year's day
(note: January is month 0)
divide into number of days, hours,
minutes and seconds

document Object
Internet Explorer, Firefox, Opera, etc. allow you to access information about an
HTML document using the document object
<html>

<head>
<title>Documentation page</title>
</head>
<body>
<table width="100%">
<tr>
<td><i>
<script type="text/javascript">
document.write(document.URL);
</script>
</i></td>
<td style="text-align: right;"><i>
<script type="text/javascript">
document.write(document.lastModified);
</script>
</i></td>
</tr>
</table>
</body>
</html>

document.write()

method that displays text in


the page
document.URL

property that gives the


location of the HTML
document

document.lastModified

property that gives the date &


time the HTML document was
last changed

navigator Object
navigator.appName

<html>
<!- COMP519

property that gives the browser


name

<head>
<title>Dynamic Style Page</title>

navigator.appVersion

property that gives the browser


version
<!-- MSIE.css

-->

a {text-decoration:none;
font-size:larger;
color:red;
font-family:Arial}
a:hover {color:blue}

<!-- Netscape.css

-->

a {font-family:Arial;
color:white;
background-color:red}

js14.html

16.08.2006 -->

<script type="text/javascript">
if (navigator.appName == "Netscape") {
document.write('<link rel=stylesheet '+
'type="text/css" href="Netscape.css">');
}
else {
document.write('<link rel=stylesheet ' +
'type="text/css" href="MSIE.css">');
}
</script>
</head>
<body>
Here is some text with a
<a href="javascript:alert('GO AWAY')">link</a>.
</body>
</html>

User-Defined Objects
can define new objects, but the notation can be somewhat awkward
simply define a function that serves as a constructor
specify data fields & methods using this

no data hiding: can't protect data or methods


// Die class definition
function Die(sides)
{
this.numSides = sides;
this.numRolls = 0;
this.roll = roll;
// define a pointer to a function
}
function roll()
{
this.numRolls++;
return Math.floor(Math.random()*this.numSides) + 1;
}

define Die function (i.e.,


the object's constructor)
initialize data fields in the
function, preceded with
"this"
similarly, assign method to
separately defined function
(which uses this to access
data)

Object Example

<html>

<head>
<title>Dice page</title>
<script type="text/javascript"
src="Die.js">
</script>
</head>
<body>
<script type="text/javascript">
die6 = new Die(6);
die8 = new Die(8);
roll6 = -1;
// dummy value to start loop
roll8 = -2;
// dummy value to start loop
while (roll6 != roll8) {
roll6 = die6.roll();
roll8 = die8.roll();
document.write("6-sided: " + roll6 +
"&nbsp;&nbsp;&nbsp;&nbsp;" +
"8-sided: " + roll8 + "<br />");

}
document.write("<br />Number of rolls: " +
die6.numRolls);
</script>
</body>
</html>

create a Die object using new


(similar to String and Array)

here, the argument to Die


initializes numSides for that
particular object
each Die object has its own
properties (numSides &
numRolls)
Roll(), when called on a
particular Die, accesses its
numSides property and
updates its NumRolls

Event Handling in Java Script


Event:

An event is something that happens, e.g. a mouse click on a button, an image that has loaded.
Events usually occur as a result of human interaction with the browser, e.g. selecting a document to
load, entering form information.
Event Handlers
Event handlers are JavaScript methods, i.e. functions of objects, that allow us as JavaScript
programmers to control what happens when events occur.
For example, the following form has an onSubmit event handler that displays an alert message:
<FORM NAME="formName" onSubmit="alert('Form submitted') >
<INPUT TYPE="SUBMIT"> </FORM>

List of Event objects and Event Handlers


Object

Event Handlers

Area

onClick(), onMouseOut(), onMouseOver()

button

onBlur(), onClick(), onFocus()

checkbox

onBlur(), onClick(), onFocus()

form

onReset(), onSubmit()

frame

onLoad(), onUnload()

image

onAbort(), onError(), onLoad()

link

onClick(), onMouseOut(), onMouseOver()

password

onBlur(), onChange(), onFocus()

radio

onBlur(), onClick(), onFocus()

reset

onBlur(), onClick(), onFocus()

select

onBlur(), onChange(), onFocus()

submit

onBlur(), onClick(), onFocus()

text

onBlur(), onChange(), onFocus()

textarea

onBlur(), onChange(), onFocus()

window

onBlur(), onError(), onFocus(), onLoad(),


onUnload()

What is DHTML

Generally, DHTML refers to applications that allow a Web page to change dynamically without
requiring the request is to be passed to/from a web server.

More specifically, DHTML refers to the interaction of HTML, CSS and Scripting language
(JavaScript).

Crucial component of DHTML is DOM (Document Object Model)

DHTML = HTML + CSS + JavaScript + DOM

Why comes DHTML

To make Web pages interactive.


HTML pages have static nature.
DHTML provides us with enhanced creative control so we can manipulate any page element at any
time.
It is the easiest way to make Web pages interactive.
It doesnt increase server workload and require special software to support.

JavaScript and DHTML


Example 1 :
Changing background and text colors Dynamically :
<html>
<head>
<script type=text / javascript >
function change()
{
document.body.style.backgroundColor=blue ;
document.body.style.color=yellow ;
}
</script></head>
<body bgcolor=red>
<form type=button value=CHANGE COLOR onclick= change() >
</form> </body></html>
OUT PUT :
Changes background color to blue and text color to yellow when u click the button

Example 2 :
Changing Font Dynamically using Mouse Events:
<html>
<head> <title> dynamic font styles and colors for links</title>
</head>
<body bgcolor=red>
<a style= color : blue;
onmouseover =this.style.color=red; this.style.font =italic 16pt Times ;
onmouseout =this.style.color=blue; this.style.font =normal 16pt Times ; >
Click Here </a>
</body>
</html>
OUT PUT :
When the mouse is placed on Hyper link text it will be changed from blue to red color.
When the mouse is out of the Hyper link it will be change back to blue color.

Important questions
1.

Explain the features advantages and limitations of java script

2.

With an example explain how parameters are passed to functions in


JavaScript

3.

Write a JavaScript program to convert distance in kilometers, miles to


meters or inches

4.

Explain the characteristics of DHTML

5.

Compare and contrast HTML and DHTML with suitable examples.

6.

Write a java script to verify a phone number, email-id and date formats.

7.

Explain Event Handling in Java script with an example

8.

Explain all the Implicit java script objects their properties and methods

Web Technologies
B.Tech. IT III Year II Semester
UNIT III

XML

eXtensible

Markup Language
(XML)

By:
G Indira Priyadarshini
IT DEPT, VJIT

Outline of Presentation

Introduction
Comparison between XML and HTML
XML Syntax
Document Type Definition (DTD)
Name Spaces
XML Schema
XSLT
XML Parsers

XML.
Based on Standard Generalized Markup Language
(SGML)
Version 1.0 introduced by World Wide Web
Consortium (W3C) in 1998
Bridge for data exchange on
the Web

XML Standards an Overview


XML Core Working Group:
XML 1.0 (Feb 1998), 1.1 (candidate for recommendation)
XML Namespaces (Jan 1999)
XML Inclusion (candidate for recommendation)

XSLT Working Group:


XSL Transformations 1.0 (Nov 1999), 2.0 planned
XPath 1.0 (Nov 1999), 2.0 planned
eXtensible Stylesheet Language XSL(-FO) 1.0 (Oct 2001)

XML Linking Working Group:


XLink 1.0 (Jun 2001)
XPointer 1.0 (March 2003, 3 substandards)

XQuery 1.0 (Nov 2002) plus many substandards


XMLSchema 1.0 (May 2001)

Comparisons

XML
Extensible set of tags
Content orientated
Standard Data
infrastructure
Allows multiple output
forms

HTML
Fixed set of tags
Presentation oriented
No data validation
capabilities
Single presentation

XML Syntax by Example


<article>
<author>Gerhard Weikum</author>
<title>The Web in 10 Years</title>
</article>

Easy to understand for human users


An XML element is made up of a start tag, an end tag,
and data in between.
Very expressive (semantics along with the data)
Well structured, easy to read and write from programs

Possible Advantages of Using XML

Truly Portable Data


Easily readable by human users
Very flexible and customizable (no finite tag set)
Easy to use from programs (libs available)
Easy to convert into other representations
(XML transformation languages)
Widely used and supported

XML Documents
Whats in an XML document?
Elements
Attributes
plus some other details

A Simple XML Document


<article>
<author>Gerhard Weikum</author>
<title>The Web in Ten Years</title>
<text>
<abstract>In order to evolve...</abstract>
<section number=1 title=Introduction>
The <index>Web</index> provides the universal...
</section>
</text>
</article>

A Simple XML Document


<article>
Freely definable tags
<author>Gerhard Weikum</author>
<title>The Web in Ten Years</title>
<text>
<abstract>In order to evolve...</abstract>
<section number=1 title=Introduction>
The <index>Web</index> provides the universal...
</section>
</text>
</article>

A Simple XML Document


Start Tag
<article>
<author>Gerhard Weikum</author>
<title>The Web in Ten Years</title>
<text>
<abstract>In order to evolve...</abstract>
<section number=1 title=Introduction>
The <index>Web</index> provides the universal...
</section>
</text>
</article>

End Tag

Element

Content of
the Element
(Subelements
and/or Text)

A Simple XML Document


<article>
<author>Gerhard Weikum</author>
<title>The Web in Ten Years</title>
<text>
<abstract>In order to evolve...</abstract>
<section number=1 title=Introduction>
The <index>Web</index> provides the universal...
</section>
</text>
</article>

Attributes with
name and value

Elements in XML Documents


(Freely definable) tags: article, title, author
with start tag: <article> etc.
and end tag: </article> etc.

Elements: <article> ... </article>


Elements have a name (article) and a content (...)
Elements may be nested.
Elements may be empty: <this_is_empty/>
Element content is typically parsed character data (PCDATA),
i.e., strings with special characters, and/or nested elements (mixed
content if both).
Each XML document has exactly one root element and forms a
tree.
Elements with a common parent are ordered.

Elements vs. Attributes


Elements may have attributes (in the start tag) that have a name and
a value, e.g. <section number=1>.
What is the difference between elements and attributes?
Only one attribute with a given name per element (but an arbitrary
number of subelements)
Attributes have no structure, simply strings (while elements can
have subelements)
As a rule of thumb:
Content into elements
Metadata into attributes
Example:
<person born=1912-06-23 died=1954-06-07>
Alan Turing</person> proved that

XML Documents as Ordered Trees


article

author

title

text
number=1

Gerhard
Weikum

abstract

title=

In order
The Web
in 10 years

section

The

index
Web

provides

More on XML Syntax


Some special characters must be escaped using entities:
< &lt;
& &amp;
(will be converted back when reading the XML doc)
Some other characters may be escaped, too:
> &gt;
&quot;
&apos;

Well-Formed XML Documents


A well-formed document must adher to, among others, the
following rules:
Every start tag has a matching end tag.
Elements may nest, but must not overlap.
There must be exactly one root element.
Attribute values must be quoted.
An element may not have two attributes with the same
name.
Comments and processing instructions may not appear
inside tags.
No unescaped < or & signs may occur inside character
data.

Well-Formed XML Documents


A well-formed document must adher to, among others, the
following rules:
Every start tag has a matching end tag.
Elements may nest, but must not overlap.
There must be exactly one root element.
Only well-formed documents
Attribute values must be quoted.
canmay
benot
processed
by XML
An element
have to attributes
with the same
name.
parsers.
Comments and processing instructions may not appear
inside tags.
No unescaped < or & signs may occur inside character
data.

Document Type Definitions


Sometimes XML is too flexible:
Most Programs can only process a subset of all possible
XML applications
For exchanging data, the format (i.e., elements,
attributes and their semantics) must be fixed
Document Type Definitions (DTD) for establishing the
vocabulary for one XML application (in some sense
comparable to schemas in databases)
A document is valid with respect to a DTD if it conforms
to the rules specified in that DTD.
Most XML parsers can be configured to validate.

DTD Example: Elements


<!ELEMENT
<!ELEMENT
<!ELEMENT
<!ELEMENT
<!ELEMENT
<!ELEMENT
<!ELEMENT
<!ELEMENT

article
title
author
text
abstract
section
literature
index

(title,author+,text)>
(#PCDATA)>
(#PCDATA)>
(abstract,section*,literature?)>
(#PCDATA)>
(#PCDATA|index)+>
(#PCDATA)>
(#PCDATA)>

Content of the title element


is parsed character data

Content of the text element may


contain zero or more section
elements in this position

Content of the article element is a title element,


followed by one or more author elements,
followed by a text element

Element Declarations in DTDs


One element declaration for each element type:
<!ELEMENT element_name content_specification>

where content_specification can be


(#PCDATA) parsed character data
(child)
one child element
(c1,,cn) a sequence of child elements c1cn
(c1||cn) one of the elements c1cn
For each component c, possible counts can be specified:

c
c+
c*
c?

exactly one such element


one or more
zero or more
zero or one

Plus arbitrary combinations using parenthesis:


<!ELEMENT f ((a|b)*,c+,(d|e))*>

More on Element Declarations


Elements with mixed content:
<!ELEMENT text (#PCDATA|index|cite|glossary)*>

Elements with empty content:


<!ELEMENT image EMPTY>

Elements with arbitrary content (this is nothing for


production-level DTDs):
<!ELEMENT thesis ANY>

Attribute Declarations in DTDs


Attributes are declared per element:
<!ATTLIST section number CDATA #REQUIRED
title CDATA #REQUIRED>

declares two required attributes for element section.


element name
attribute name
attribute type
attribute default

Attribute Declarations in DTDs


Attributes are declared per element:
<!ATTLIST section number CDATA #REQUIRED
title CDATA #REQUIRED>

declares two required attributes for element section.


Possible attribute defaults:
#REQUIRED
is required in each element instance
#IMPLIED
is optional
#FIXED default always has this default value
default
has this default value if the attribute is
omitted from the element instance

Attribute Types in DTDs


string data
(A1||An) enumeration of all possible values of the
attribute (each is XML name)
ID
unique XML name to identify the element
IDREF
refers to ID attribute of some other element
(intra-document link)
IDREFS
list of IDREF, separated by white space
plus some more
CDATA

Attribute Examples
<ATTLIST publication type
pubid
<ATTLIST cite
cid
<ATTLIST citation
ref
cid

(journal|inproceedings) #REQUIRED
ID #REQUIRED>
IDREF #REQUIRED>
IDREF #IMPLIED
ID #REQUIRED>

<publications>
<publication type=journal pubid=Weikum01>
<author>Gerhard Weikum</author>
<text>In the Web of 2010, XML <cite cid=12/>...</text>
<citation cid=12 ref=XML98/>
<citation cid=15>...</citation>
</publication>
<publication type=inproceedings pubid=XML98>
<text>XML, the extended Markup Language, ...</text>
</publication>
</publications>

Attribute Examples
<ATTLIST publication type
pubid
<ATTLIST cite
cid
<ATTLIST citation
ref
cid

(journal|inproceedings) #REQUIRED
ID #REQUIRED>
IDREF #REQUIRED>
IDREF #IMPLIED
ID #REQUIRED>

<publications>
<publication type=journal pubid=Weikum01>
<author>Gerhard Weikum</author>
<text>In the Web of 2010, XML <cite cid=12/>...</text>
<citation cid=12 ref=XML98/>
<citation cid=15>...</citation>
</publication>
<publication type=inproceedings pubid=XML98>
<text>XML, the extended Markup Language, ...</text>
</publication>
</publications>

Linking DTD and XML Docs


Document Type Declaration in the XML document:
<!DOCTYPE article SYSTEM http://www-dbs/article.dtd>

keywords

Root element

URI for the DTD

Linking DTD and XML Docs


Internal DTD:
<?xml version=1.0?>
<!DOCTYPE article [
<!ELEMENT article (title,author+,text)>
...
<!ELEMENT index (#PCDATA)>
]>
<article>
...
</article>

Both ways can be mixed, internal DTD overwrites


external entity information:
<!DOCTYPE article SYSTEM article.dtd [
<!ENTITY % pub_content (title+,author*,text)
]>

Flaws of DTDs
No support for basic data types like integers, doubles,
dates, times,
No structured, self-definable data types
No type derivation
id/idref links are quite loose (target is not specified)
XML Schema

Namespaces
<library>
<description>Library of the CS Department</description>
<book bid=HandMS2000>
<title>Principles of Data Mining</title>
<description>
Short introduction to <em>data mining</em>, useful
for the IRDM course
</description>
</book>
</library>

Semantics of the description element is ambigous


Content may be defined differently
Renaming may be impossible (standards!)
Disambiguation of separate XML applications using
unique prefixes

Namespace Syntax
<dbs:book xmlns:dbs=http://www-dbs/dbs>

Prefix as abbrevation
of URI

Unique URI to identify


the namespace

Signal that namespace


definition happens

Namespace Example
<dbs:book xmlns:dbs=http://www-dbs/dbs>
<dbs:description> ... </dbs:description>
<dbs:text>
<dbs:formula>
<mathml:math
xmlns:mathml=http://www.w3.org/1998/Math/MathML>
...
</mathml:math>
</dbs:formula>
</dbs:text>
</dbs:book>

Default Namespace
Default namespace may be set for an element and its
content (but not its attributes):
<book xmlns=http://www-dbs/dbs>
<description>...</description>
<book>

Can be overridden in the elements by specifying the


namespace there (using prefix or default namespace)

XML Schema Basics


XML Schema is an XML application
They have a number of data types including string,
decimal, integer, boolean, date, and time.)
Allows defining possible values for elements
They divide elements into simple and complex types.
Allows defining types derived from existing types
Allows posing constraints on the occurrence of elements
They also determine the tree structure and how many
children a node may have.
Allows forcing uniqueness and foreign keys

Schema for First address


Example
<?xml version="1.0" encoding="ISO-8859-1" ?>
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="address">
<xs:complexType>
<xs:sequence>
<xs:element name="name"
type="xs:string"/>
<xs:element name="email"
type="xs:string"/>
<xs:element name="phone"
type="xs:string"/>
<xs:element name="birthday"
type="xs:date"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

<?xml version=1.0/>
<address>
<name>Alice Lee</name>
<email>alee@aol.com</email>
<phone>212-346-234</phone>
<birthday>1985-03-02 </birthday>
</address>

Explanation of Example Schema


<?xml version="1.0" encoding="ISO-8859-1" ?>
ISO-8859-1, Latin-1, is the same as UTF-8 in the first 128 characters.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
www.w3.org/2001/XMLSchema contains the schema standards.
<xs:element name="address">
<xs:complexType>
This states that address is a complex type element.
<xs:sequence>
This states that the following elements form a sequence and must come in the
order shown.
<xs:element name="name" type="xs:string"/>
This says that the element, name, must be a string.
<xs:element name="birthday" type="xs:date"/>
This states that the element, birthday, is a date. Dates are always of the form
yyyy-mm-dd.

Simplified XML Schema for


article XML document
<xs:schema>
<xs:element name=article>
<xs:complexType>
<xs:sequence>
<xs:element name=author type=xs:string/>
<xs:element name=title type=xs:string/>
<xs:element name=text>
<xs:complexType>
<xs:sequence>
<xs:element name=abstract type=xs:string/>
<xs:element name=section type=xs:string
minOccurs=0 maxOccurs=unbounded/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

XSLT
Extensible Stylesheet Language Transformations
To Present an XML document there are two approaches
1) Using Cascading Style Sheets or
2) Using XSLT

XSLT is used to transform one xml document into another, often


an html document.
The Transform classes are now part of Java 1.4.
A program is used that takes as input one xml document and
produces as output another.
If the resulting document is in html, it can be viewed by a web
browser.
This is a good way to display xml data.

A Style Sheet to Transform address.xml


<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="address">
<html><head><title>Address Book</title></head>
<body>
<xsl:value-of select="name"/>
<br/><xsl:value-of select="email"/>
<br/><xsl:value-of select="phone"/>
<br/><xsl:value-of select="birthday"/>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

The Result of the Transformation

OUTPUT
Alice Lee
alee@aol.com
123-45-6789
1983-7-15

XML Parsers
All modern browsers have a built-in XML parser.
An XML parser converts an XML document into an XML DOM object - which
can then be manipulated with JavaScript.
XML supports two parsers
SAX Simple API for XML
Uses a call-back method
Similar to javax listeners
SAX approach to processing an XML document is called event processing.
The Processor scans the XML document from beginning to end.
DOM Document Object Model
Creates a parse tree
Requires a tree traversal
DOM approach build a hierarchical syntactical structure of XML
document which creates dynamic document s

References
Programming The World Wide Web Fourth Edition
by Robert W Sebesta
Elliotte Rusty Harold, Processing XML with Java,
Addison Wesley, 2002.
Elliotte Rusty Harold and Scott Means, XML
Programming, OReilly & Associates, Inc., 2002.
W3Schools Online Web Tutorials,

Important Questions
1. What is XML? How is XML useful? How is XML compatible with others
2. a) What is a document type definition (DTD)? How do you create DTD?
b) Explain DTD sequences
3. What is an XML schema? With an example explain the working of XML
schema.
4. Explain the working of XSL. ..
5. a)What is Document Object Model (DOM)? Explain the DOM levels
b) Differentiate SAX and DOM Parsers

Web Technologies
B.Tech. IT III Year II Semester
UNIT IV

Java Beans
By:

G Indira Priyadarshini
IT DEPT, VJIT

2000 Prentice Hall, Inc. All rights reserved.

Outline of Presentation

Introduction
Java Bean API
Properties
Introspection Using Design Patterns
BDK
Example (Animation Bean)
Introspection using BeanInfo Interface

2000 Prentice Hall, Inc. All rights reserved.

Definition
Java Bean is a reusable software component that
can be manipulated visually in a builder tool.
(from Java Bean Specification)
The JavaBeans API provides a framework for
defining reusable, embeddable, modular software
components.

2000 Prentice Hall, Inc. All rights reserved.

Introduction
JavaBeans (beans)
Reusable software component model
Assemble predefined components
Create powerful applications and applets

Graphical programming and design environments


Builder tools
Support beans, reuse and integrate components

Component assembler
Programmer who use defined components
Work on design of GUI and functionality
Do not need to know implementation
Just need to know services

The JavaBeans API


Features implemented as extensions to standard
Java Class Library
Main Component Services

GUI merging
Persistence
Event Handling
Introspection
Application Builder Support
Security issues

2000 Prentice Hall, Inc. All rights reserved.

User Interface Merging


Containers usually have Menus and/or toolbars
Allows components to add features to the menus
and/or toolbars
Define mechanism for interface layout between
components and containers

2000 Prentice Hall, Inc. All rights reserved.

Persistence
Components can be stored and retrieved
Default inherit serialization
Can define more complex solutions based on
needs of the components

2000 Prentice Hall, Inc. All rights reserved.

Event Handling
Defines how components interact
Java AWT event model serves as basis for the
event handling APIs
Provides a consistent way for components to
interact with each other

2000 Prentice Hall, Inc. All rights reserved.

Introspection
Defines techniques so components can expose
internal structure at design time
Allows development tools to query a component
to determine member variables, methods, and
interfaces
Two Approaches of Introspection are
1. Standard naming patterns (Design Patterns)
2. Using BeanInfo Interface

2000 Prentice Hall, Inc. All rights reserved.

Application Builder Support


Provides support for manipulating and editing
components at design time
Used by tools to provide layout and customizing
during design
Should be separate from component
Not needed at run time

2000 Prentice Hall, Inc. All rights reserved.

Security Issues
JavaBeans are sbject to the standard Java security
model
The security model has neither extended nor
relaxed.
If a bean runs as an untrusted applet then it will be
subject to applet security
If a bean runs as a stand-alone application then it
will be treated as a normal Java application.

2000 Prentice Hall, Inc. All rights reserved.

Properties
A builder tool can:

discover a beans properties


determine the properties read/write attribute
locate an appropriate property editor for each type
display the properties (in a sheet)
alter the properties at design-time

2000 Prentice Hall, Inc. All rights reserved.

Types of Properties

Simple : single value property


Index: multiple-value properties
Bound: provide event notification when value
changes
Constrained: how proposed changes can be
okayed or vetoed by other object

2000 Prentice Hall, Inc. All rights reserved.

Properties Introspection using design patterns


When a builder tool introspect your bean it
discovers two methods: getter and setter methods.
Design Patterns for Properties are
public T getN() or public T[ ] getN()
Public T getN(int index)
public void setN(T value) or public void setN(T value[ ])
public void setN(int index,T value)
T Type N- name of the property
Eg : public Color getColor()
public void setColor(Color c)

2000 Prentice Hall, Inc. All rights reserved.

Simple Properties.
Adding a Color property
Create and initialize a private instance variable
private Color color = Color.blue;

Write public getter & setter methods


public Color getColor() {
return color;
}
public void setColor(Color c) {
color = c;
repaint();
}

2000 Prentice Hall, Inc. All rights reserved.

Events Introspection using design patterns


Source Bean fires events at the listeners using
method of those interfaces.
Example: if a source Bean register ActionListsener
objects, it will fire events at those objects by
calling the actionPerformed method on those
listeners
Design patterns for Events :
Events can be identified by the following patterns
public void addTListener(Tlistener eventListener);
public void addTListener(Tlistener eventListener) throws
TooManyListeners;
public void removeTListener(Tlistener eventListener); T -Type
2000 Prentice Hall, Inc. All rights reserved.

Methods Introspection using design patterns

Design Patterns are not used for naming nonproperty methods.


The Introspection Mechanism finds all of the
public methods of a bean

2000 Prentice Hall, Inc. All rights reserved.

BeanInfo interface
Question: how does a Bean exposes its features in
a property sheet?
Answer: using java.beans.Introspector class
(which uses Core Reflection API)
The discovery process is named introspection
OR you can associate a class that implements the
BeanInfo with your bean

2000 Prentice Hall, Inc. All rights reserved.

BeanInfo interface.
Why use BeanInfo then?
Using BeanInfo you can:
Expose features that you want to expose

2000 Prentice Hall, Inc. All rights reserved.

Bean Customization
The appearance and behavior of a bean can be
customized at design time.
Two ways to customize a bean:
using a property editor
each bean property has its own editor
a beans property is displayed in a property sheet

using customizers
gives you complete GUI control over bean customization
used when property editors are not practical

2000 Prentice Hall, Inc. All rights reserved.

Property Editors
If you provide a custom property editor class, then
you must refer to this class by calling
PropertyDescriptor.setPropertyEditorClass in a
BeanInfo class.
Each bean may have a BeanInfo class which
customizes how the bean is to appear.
SimpleBeanInfo implements that interface

2000 Prentice Hall, Inc. All rights reserved.

Beans Development Kit (BDK)


To start the BeanBox:
run.bat (Windows)
run.sh (Unix)

2000 Prentice Hall, Inc. All rights reserved.

BDK
ToolBox contains the beans available
BeanBox window is the form where you visually
wire beans together.
Properties sheet: displays the properties for the
Bean currently selected within the BeanBox
window.

2000 Prentice Hall, Inc. All rights reserved.

24

Developing a Simple Bean Using the BDK


1.
2.
3.
4.
5.
6.
7.

Create a directory for the new Bean


Create java source file(s)
Compile the source file(s)
Create manifest file
Create the jar file
Start the BDK
test

2000 Prentice Hall, Inc. All rights reserved.

MyFirstBean
import java.awt.*;
import java.io.Serializable;
public class FirstBean extends Canvas implements
Serializable {

public FirstBean() {

setSize(50,30);

setBackground(Color.blue);

}
}

2000 Prentice Hall, Inc. All rights reserved.

First Bean
Compile: javac FirstBean.java
Create a manifest file:
manifest.txt
Name: FirstBean.class
Java-Bean: True

Create a jar file:


jar cfm FirstBean.jar mani.txt FirstBean.class

2000 Prentice Hall, Inc. All rights reserved.

Example (Animation bean)


Example of bean concept
Have animation bean
Want two buttons, start and stop

With beans, can "hook up" buttons to startAnimation


and stopAnimation methods
When pressed, method called
Builder tool does work

Use previously defined, reusable components


Little or no code must be written
Component assembler can "connect the dots

2000 Prentice Hall, Inc. All rights reserved.

Example (Animation bean)


BeanBox installation
Free utility from JavaBeans Development Kit (BDK)
http://java.sun.com/beans/software/index.html
Windows, Solaris, and platform independent versions
In Windows version, minor bug
Do not install in directory with spaces in name
To run, go to install directory, beanbox subdirectory, load
run.bat (or run.sh)

BeanBox test container for JavaBeans


Preview how bean will be displayed
Not meant to be robust development tool

Example (Animation bean)


Use screen captures from Windows
Start application, following appears:

ToolBox has 16 sample


JavaBeans

Properties
customizes selected
bean.

Method Tracer displays


debugging messages (not
discussed)
BeanBox window tests beans.
Background currently selected
(dashed box).

Example (Animation bean)


Initially, background selected
Customize in Properties box

Example (Animation bean)


Now, add JavaBean in BeanBox window
Click ExplicitButton bean in ToolBox window
Functions as a JButton
Click crosshair where center of button should appear
Change label to "Start the Animation"

Example (Animation bean)


Select button (if not selected) and move to corner
Position mouse on edges, move cursor appears
Drag to new location

Resize button
Put mouse in corner, resize cursor
Drag mouse to change size

Example (Animation bean)


Add another button (same steps)
"Stop the Animation"

Add animation bean


In ToolBox, select Juggler and add to BeanBox
Animation begins immediately

Properties for juggler.

Example (Animation bean)


Now, "hook up" events from buttons
Start and stop animation

Edit menu
Access to events from beans that are an event source (bean can
notify listener)
Swing GUI components are beans
Select "Stop the Animation"
Edit->Events->button push -> actionPerformed

Example (Animation bean)


Line appears from button to mouse
Target selector - target of event
Object with method we intend to call
Connect the dots programming
Click on Juggler, brings up EventTargetDialog
Shows public methods
Select stopJuggling

Example (Animation bean)


Event hookup complete
Writes new hookup/event adapter class
Object of class registered as actionListener fro button
Can click button to stop animation

Repeat for "Start the Animation" button


Method startAnimation

Example (Animation bean)


Save as design
Can reloaded into BeanBox later
Can have any file extension

Opening
Applet beans (like Juggler) begin executing immediately

Example (Animation bean)


Save as Java Applet
File->Make Applet
Stores .class file in .jar (Java Archive File)
Can rename and change directory

Example (Animation bean)


To run applet
Go to command line, go to directory where applet saved
Should be .html file, load into appletviewer
Background not yellow
BeanBox container not saved as part of applet
Applet is a container, can hold beans

Archive property of <applet> tag


Comma separated list of .jar files used
.jar files for beans listed
Source code in AppletName_files directory

<html>

<head>

<title>Test page for OurJuggler as an APPLET</Title>

</head>

<body>

<h1>Test for OurJuggler as an APPLET</h1>

This is an example of the use of the generated

OurJuggler applet.

archives, one per JAR used in building the Applet

HTML file

Notice the Applet tag requires several

10 <p>
11 <applet
12

archive="./OurJuggler.jar,./support.jar

13

,./juggler.jar

14

,./buttons.jar

15

"

16

code="OurJuggler"

17

width=382

18

height=150

19 >
20 Trouble instantiating applet OurJuggler!!
21 </applet>

1. archive

Program Output

Specifying the BeanInfo Class for a


JavaBean
11
12
14
15

public PropertyDescriptor[] getPropertyDescriptors()


{
PropertyDescriptor fieldWidth =
new PropertyDescriptor( "fieldWidth", beanClass );

getPropertyDescriptors (overridden)
Returns array of PropertyDescriptor objects
Each describes property
new PropertyDescriptor( "propertyName", beanClass )
Property must have named set and get methods
26

currentValue.setBound( true );

setBound( true )
Specifies property is bound

Specifying the BeanInfo Class for a


JavaBean
39

public int getDefaultPropertyIndex()

40

41
42

return 1;
}

getDefaultPropertyIndex (overridden)
Returns array index of default property
In this case, currentValue
44

public EventSetDescriptor[] getEventSetDescriptors() {

getEventSetDescriptors
Returns array of EventSetDescriptor objects
Describes events supported by bean

Specifying the BeanInfo Class for a


JavaBean
46
47
48
49
50

EventSetDescriptor changed =
new EventSetDescriptor( beanClass,
"propertyChange",
java.beans.PropertyChangeListener.class,
"propertyChange");

Constructor arguments
1: Class object, represents event source
2: String, event set name
mouse includes mousePressed, mouseClicked...
We use propertyChange
3: Class object, implemented event listener interface
Creates anonymous object of class
4: String, name of listener method called when event occurs

Specifying the BeanInfo Class for a


JavaBean
52
53

changed.setDisplayName(
"SliderFieldPanel value changed" );

Class EventSetDescriptor
Method setDisplayName( stringName )
Specifies name for event set in builder tool

// Fig. 25.38: SliderFieldPanelBeanInfo.java

Same package as
// The BeanInfo class for SliderFieldPanel

package jhtp3beans;

4
5

import java.beans.*;

bean.
Extend SimpleBeanInfo class, with
default implementation of BeanInfo
interface.
1. package

6
7

public class SliderFieldPanelBeanInfo extends SimpleBeanInfo {

11

1.1 import
public final static Class beanClass =
Create Class object, provides
SliderFieldPanel.class;
access to class
1.2 definition.
extends
Specify properties that can be
SimpleBeanInfo
by builder.
public PropertyDescriptor[]exposed
getPropertyDescriptors()

12

8
9
10

13
14
15
16
17
18
19
20
21
22
23
);
24

1.3 Class

try {
PropertyDescriptor fieldWidth =
new PropertyDescriptor( "fieldWidth", beanClass );
PropertyDescriptor currentValue =
new PropertyDescriptor(
"currentValue", beanClass );
PropertyDescriptor maximumValue =

2.1 setBound

new PropertyDescriptor(
"maximumValue", beanClass );
PropertyDescriptor minimumValue =
new PropertyDescriptor( "minimumValue", beanClass
Specify bound

25

// ensure PropertyChangeEvent occurs for this property

26

currentValue.setBound( true );

27

2. getProperty
Descriptors

property.

28
29
30
31
32
33
34

}
catch ( IntrospectionException ie ) {
throw new RuntimeException( ie.toString() );

35

36

PropertyDescriptor descriptors[] = { fieldWidth,


currentValue, maximumValue, minimumValue };
return descriptors;

3.
getDefaultProperty
Index
Get array index of default
property
(currentValue).

37
38

// the index for the currentValue property

39

public int getDefaultPropertyIndex()

40

41
42

return 1;

45
46

4.2 setDisplayName
public EventSetDescriptor[] getEventSetDescriptors() {
try {
EventSetDescriptor changed =

47

new EventSetDescriptor( beanClass,

48

"propertyChange",

49

java.beans.PropertyChangeListener.class,

50

"propertyChange");

51
52
53

changed.setDisplayName(
"SliderFieldPanel value changed" );

54
55

4.1 Constructor

43
44

4. getEventSet
Descriptors

EventSetDescriptor[] descriptors = { changed };

Describes events supported


by bean.

Set title of event in


builder.

56
57
58
59
60
61
62
63 }

return descriptors;
}
catch (IntrospectionException e) {
throw new RuntimeException(e.toString());
}
}

Program Output

Only the specified properties are listed.

JavaBeans World Wide Web Resources


Web resources
http://java.sun.com/beans/
Download Beans Development Kit, docs
http://java.sun.com/beans/spec.html
Specifications
http://java.sun.com/beans/tools.html
Beans-enabled development tools
http://java.sun.com/beans/directory/
Searchable directory of beans
http://java.sun.com/products/hotjava/bean/
index.html
Evaluation version of bean with HTML rendering

Important Questions
1.

a) Explain the featues of java beans


b) Explain the advantages and disadvantages of
Java Beans.

2. Describe the different types of properties used in Java Beans with an


example.
3.

Explain about Introspection

4. Describe the bean info interface.

2000 Prentice Hall, Inc. All rights reserved.

Web Technologies
B.Tech. IT III Year II Semester
UNIT V

WEB SERVERS &SERVLETS

Outline of Presentation

Tomcat Webserver
Introduction To Servlets
Life Cycle of Servlet
Servlet API
Reading Servlet Parameters
Steps to Run a Servlet
Example to handle Http Request and Response
Using Cookies and Session Tracking
Security Issues

Tomcat WebServer
A servlet container is like a mini server, but only
for serving html, jsp and servlets.
Many servlet containers could be used for this course.
Some may even be easier to configure than tomcat,
but tomcat provides an easy-to-use
development/deployment tool and also complies with
the servlet specification best of all containers.
Tomcat is from Apache and is open-source.
Tomcat can be used as a stand-alone servlet container.
You can install the Apache server with Tomcat, and
then proceed to configure each for their individual
purposes. (The server would relay servlet requests to
Tomcat.)

Introduction to Servlets
What can you build with Servlets?

Search Engines
E-Commerce Applications
Shopping Carts
Product Catalogs
Intranet Applications
Groupware Applications:
bulletin boards
file sharing

Servlets vs. CGI

Perl 1
Browser 1
Browser 2

Web
Server

Perl 2

Browser N
Perl N

Browser 1
Browser 2
Browser N

Web
Server

Servlet

A Servlet does not run in


a separate process.
A Servlet stays in
memory between
requests.
A CGI program needs to
be loaded and started for
each CGI request.
There is only a single
instance of a servlet
which answers all
requests concurrently.

Benefits of Java Servlets


Performance
The performance of servlets is superior to CGI because there is no
process creation for each client request.
Each request is handled by the servlet container process.
After a servlet has completed processing a request, it stays resident in
memory, waiting for another request.

Portability
Like other Java technologies, servlet applications are portable.

Rapid development cycle


As a Java technology, servlets have access to the rich Java library that
will help speed up the development process.

Robustness
Servlets are managed by the Java Virtual Machine.
Don't need to worry about memory leak or garbage collection, which
helps you write robust applications.

Widespread acceptance
Java is a widely accepted technology.

Definitions
A servlet is a Java class that can be loaded
dynamically into and run by a special web server.
This servlet-aware web server, is known as servlet
container.
Servlets interact with clients via a request-response
model based on HTTP.
Therefore, a servlet container must support HTTP as
the protocol for client requests and server responses.
A servlet container also can support similar protocols
such as HTTPS (HTTP over SSL) for secure
transactions.

Servlet Container Architecture

HTTP Request
Browser

HTTP Response

HTTP
Server

Servlet
Container
Static
Content

Servlet

How Servlets Work

Receive
Request

is servlet
loaded?

No

Yes
is servlet
current?

No
Load Servlet

Yes

Send
Response

Process Request

Servlet Life Cycle

Initialization
init()

Service
service()
doGet()
doPost()
doDelete()
doHead()
doTrace()
doOptions()

Destruction
destroy()

Concurrent
Threads
of Execution

Servlet Life Cycle


When a servlet is FIRST requested, it is loaded into the
servlet engine. The init() method of the servlet is invoked
so that the servlet may initialize itself.
Once initialization is complete, the request is then
forwarded to the appropriate method (ie. doGet or doPost)
The servlet is then held in memory. Subsequent requests
are simply forwarded to the servlet object.
When the engine wishes to remove the servlet, its destroy()
method is invoked.
NOTE: Servlets can receive multiple requests for multiple
clients at any given time. Therefore, servlets must be

thread safe

Servlet APIs

Every servlet must implement javax.servlet.Servlet


interface
Most servlets implement the interface by extending
one of these classes
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet

Generic Servlet & HTTP Servlet


GenericServlet

Client
request
Server

service ( )

response

HTTPServlet

Browser

doGet( )

request
HTTP
Server

response

service ( )

doPost( )

Interface javax.servlet.Servlet
The Servlet interface defines methods

to initialize a servlet
Life
Cycle
to receive and respond to client requests
Methods
to destroy a servlet and its resources
to get any startup information
to return basic information about itself, such as its author,
version and copyright.

Developers need to directly implement this interface


only if their servlets cannot (or choose not to) inherit
from GenericServlet or HttpServlet.

GenericServlet - Methods
void init(ServletConfig config)
Initializes the servlet.

void service(ServletRequest req, ServletResponse res)


Carries out a single request from the client.

void destroy()
Cleans up whatever resources are being held (e.g., memory, file
handles, threads) and makes sure that any persistent state is
synchronized with the servlet's current in-memory state.

ServletConfig getServletConfig()
Returns a servlet config object, which contains any initialization
parameters and startup configuration for this servlet.

String getServletInfo()
Returns a string containing information about the servlet, such as its
author, version, and copyright.

HttpServlet - Methods
void doGet (HttpServletRequest request,
HttpServletResponse response)
handles GET requests
void doPost (HttpServletRequest request,
HttpServletResponse response)
handles POST requests
void doPut (HttpServletRequest request,
HttpServletResponse response)
handles PUT requests
void doDelete (HttpServletRequest request,
HttpServletResponse response)
handles DELETE requests

Servlet Request Objects


provides client request information to a servlet.
the servlet container creates a servlet request object and passes
it as an argument to the servlet's service method.
the ServletRequest interface define methods to retrieve data
sent as client request:
parameter name and values
attributes
input stream
HTTPServletRequest extends the ServletRequest interface to
provide request information for HTTP servlets

HttpServletRequest - Methods
Enumeration getParameterNames()
an Enumeration of String objects, each String
containing the name of a request parameter; or
an empty Enumeration if the request has no
parameters
java.lang.String[] getParameterValues (java.lang.String name)
Returns an array of String objects containing
all of the values the given request parameter
has, or null if the parameter does not exist.
java.lang.String getParameter (java.lang.String name)
Returns the value of a request parameter as a
String, or null if the parameter does not exist.

HttpServletRequest - Methods
Cookie[] getCookies()
Returns an array containing all of the Cookie objects the
client sent with this request.
java.lang.String getMethod()
Returns the name of the HTTP method with which\thi
request was made, for example, GET, POST, or PUT.
java.lang.String getQueryString()
Returns the query string that is contained in the request
URL after the path.
HttpSession getSession()
Returns the current session associated with this request, or
if the request does not have a session, creates one.

Servlet Response Objects


Defines an object to assist a servlet in sending a
response to the client.
The servlet container creates a ServletResponse
object and passes it as an argument to the servlet's
service method.

HttpServletResponse - Methods
java.io.PrintWriter getWriter()
Returns a PrintWriter object that can send
character text to the client
void setContentType (java.lang.String type)
Sets the content type of the response being
sent to the client. The content type may
include the type of character encoding used,
for example, text/html; charset=ISO-8859-4
int getBufferSize()
Returns the actual buffer size used for the
response

Reading Servlet Parameters


The request object (which implements
HttpServletRequest) provides information from the
HTTP request to the servlet
One type of information is parameter data, which is
information from the query string portion of the
HTTP request

Query string with


one parameter

Steps to Running a Servlet

Create a directory structure under Tomcat for your


application.
Write the servlet source code.
Compile your source code.
deploy the servlet
Run Tomcat
Call your servlet from a web browser

Create a Directory Structure


The webapps directory is the Tomcat installation dir
(CATALINA_HOME) is where you store your web applications.

A web application is a collection of servlets and other contents installed


under a specific subset of the server's URL namespace.

A separate directory is dedicated for each servlet application.


Create a directory called myApp under the webapps directory.
Create the src and WEB-INF directories under myApp, and create a
directory named classes under WEB-INF.
The src directory is for your source files, and the classes directory
under WEB-INF is for your Java classes.
If you have html files, you put them directly in the myApp directory.
The admin, ROOT, and examples directories are for applications created
automatically when you install Tomcat

Write the Servlet Code


Servlets implement the javax.servlet.Servlet interface.
Because most servlets extend web servers that use the
HTTP protocol to interact with clients, the most
common way to develop servlets is by specializing
the javax.servlet.http.HttpServlet class.
The HttpServlet class implements the Servlet
interface by extending the GenericServlet base class,
and provides a framework for handling the HTTP
protocol.
Its service() method supports standard HTTP requests
by dispatching each request to a method designed to
handle it.
In myApp/src, create a file called TestingServlet.java

Servlet Example
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
14:
16:
17:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req,
HttpServletResponse res)
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println( "<HTML><HEAD><TITLE> Hello You! +
</Title></HEAD> +
<Body> HelloYou!!!</BODY></HTML> );
out.close();
}
}

An Example of Servlet (I)


Lines 1 to 3 import some packages which
contain many classes which are used by
the Servlet (almost every Servlet needs
classes from these packages).

The Servlet class is declared in line 5. Our


Servlet extends javax.servlet.http.HttpServlet,
the standard base class for HTTP Servlets.

In lines 7 through 16 HttpServlet's doGet


method is getting overridden

An Example of Servlet (II)


In line 11 we use a method of the
HttpServletResponse object to set the content
type of the response that we are going to
send. All response headers must be set
before a PrintWriter or ServletOutputStream is
requested to write body data to the
response.

In line 12 we request a PrintWriter object to


write text to the response message.

In lines 13 and 14 we use the PrintWriter to


write the text of type text/html (as specified
through the content type).

An Example of Servlet (III)


The PrintWriter gets closed in line 15 when
we are finished writing to it.

In lines 18 through 21 we override the


getServletInfo() method which is supposed to
return information about the Servlet, e.g.
the Servlet name, version, author and
copyright notice. This is not required for
the function of the HelloClientServlet but can
provide valuable information to the user of
a Servlet who sees the returned text in the
administration tool of the Web Server.

Compile the Servlet


Compile the Servlet class
The resulting TestingServlet.class file should
go under myApp/WEB-INF/classes

Deploy the Servlet


In the Servlet container each application is
represented by a servlet context
each servlet context is identified by a unique path
prefix called context path
For example our application is identified by
/myApp which is a directory under webapps.
The remaining path is used in the selected context to
find the specific Servlet to run, following the rules
specified in the deployment descriptor.

Deployment Descriptor

The deployment descriptor is a XML file called web.xml that resides in the WEBINF directory whitin an application.

<web-app xmlns=http://java.sun.com/xml/ns/j2ee>
<display-name>test</display-name>
<description>test example</description>
<servlet>
<servlet-name>Testing</servlet-name>
<servlet-class>TestingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Testing</servlet-name>
<url-pattern>/servlet/TestingServlet</url-pattern>
</servlet-mapping>
</web-app>

Run the Servlet


To execute your Servlet, type the following
URL in the Browsers address field:
http://localhost/myApp/servlet/myServlet

Web Client Session Tracking


HTTP is a stateless protocol that takes requests from
web clients and responds with a file. It does not
memorize what has happened in the past.
FTP and Telnet protocols know the client states, such
as users, connections, and disconnections but HTTP
does not.
A client session consists of a series of conversations
between the client and web applications on the web
server.

Web Client Session Tracking


contd..
Using the HttpSession API in session management is
quite straightforward, and it may be the best option
for session tracking in most cases.
The HttpSession object can hold a session id that can
be used to identify whether the requests are within the
same session so that they can share the same data.
Each HttpSession object represents a single user
HTTP session.

Web Client Session Tracking


contd..
Mechanisms for session maintenance:
Cookies
URL Rewriting

Hidden Form fields

Servlet Cookies
Cookies are text files that store sets of param/value
pairs. The Servlet at the server side generates the
cookie based on the clients HTTP request.
The cookie is created on the server side and sent back
to the client along with the HttpServletResponse
object.
The cookie is stored in the clients browser.

Servlet Cookies contd..

URL Rewriting

Rewrite the URLs of the links of a web page to


contain extra information in the form of query string
or extra path information.
Example : a user named John Doe log in with
session ID=1234 and enter page1.cgi , page1.cgi
contains a link to page2.cgi
When user click link to page2.cgi, the URL is:
http://sample.com/page2.cgi?fname=John&lname=Doe&sess
ionid=1234

Hidden Form Fields


<input type=HIDDEN name=id value=1234>

Typically contained in forms that are placed in a


common frame of a frameset
Accessed using client-side javascript
When javascript executes in one page of an
application, it stored values(session ID) in hidden
form fields.

Security Issues
Server-side Security Issues

Interception of Session State Information


Forgery of Session State Information
Session Timeout
Buffer Overflow
Data Validation

Security Issues contd..


Page Sequencing
Information Reporting
Browser Residue

User Authentication
Logging of Sensitive Information

Importanat questions
1. Briefly explain about Tomcat web server.
2 a) What are the limitations of Servlets?
b) Explain Servlet Vs CGI
3. Explain the life cycle of a servlet.
4. Write a session tracker that tracks the number of accesses and last access
data of a particular web page.
5.a) Discuss about javax.servelet package.
b) What are the security issues related to servlets.

Web Technologies
B.Tech. IT III Year II Semester
UNIT VI

JSP
Java Server Pages

Outline of Presentation

Introduction to JSP
Servlets Vs JSP
Lifecycle of JSP
JSP Elements
Anatomy of a JSP page
JSP Processing
JSP Application Design with MVC setting
Installing JSDK
Installing Tomcat Server

Introduction
JavaServer Pages (JSP) is a technology that
helps software developers create dynamically
generated web pages based on HTML XML or other document
types.
JSP separates content generation from content presentation
Released in 1999 by Sun Microsystems JSP is similar to the
Java Programming language.
To deploy and run JavaServer Pages, a compatible web server
with a servlet container, such as Apache Tomcat or Jetty, is
required.

Servlets
Server side Java programs
Solve scalability issue
serlvets are run on threads of execution not separate
processes

Solve portability issue


runs on every platform that supports Java
supported by all most popular web servers

Issue
html tags are embedded in java programs within out.print()
statements which reduces flexibilty of programming

JSP
server-side technology
separate dynamic content from static content
of a page
Java scriptlets embedded into html-like page

Separate the work of


java programmers
page designers

JSP relationship to Servlets

A JSP is converted into a Servlet

JSP Life Cycle


JSP Life Cycle
JSP is a Web server side programming technology based on
Servlet technology. The JSP specification is built on the top of
the Servlet API.
Any JSP page is translated into a Java Servlet by a JSP engine
at runtime so that the JSP life cycle is determined by Servlet
technology.
The JSP engine is a JSP specification implementation which
comes with web servers that implement JSP. Tomcat is one
example.
When a request comes to a JSP page, it may come from client
browser or come from another Web component such as a
Servlet or JSP.

JSP Life Cycle (cont.)


The Web server asks the JSP engine to check whether
the JSP page has never been accessed before, or it has
been modified since its last access. If this is the case
the JSP engine will
1. Parse the JSP document to translate into a Servlet Java file
2. Compile the Servlet Java file into a class file

Then the Servlet container loads the Servlet class for


execution and sends the results back to the client.

JSP Life Cycle (cont.)

JSP file

(when JSP get


first access or get
changed)
translate

Servlet
Java file

JSP engine
Servlet Container
Process of a JSP page

compile

Servlet
Class

JSP Life Cycle (cont.)


The jspInit()
This method is executed first after the JSP is loaded.
The jspInit() is only called once during any JSP component
life time.
<%! public void jspInit(){ . . . } %>
_jspService()
This method is executed for processing client request and
send the response back to client.
_jspDestroy()
This method is executed to destroy the JSP object.

JSP Elements
Besides HTML tag elements, JSP provides four basic
categories of constructors (markup tags): directives, scripting
elements, standard actions, and comments.

JSP Directives
JSP Actions
JSP Scripting Elements
JSP comments
Expression Language

JSP Syntax
Elements

JSP Standard Syntax

JSP XML Syntax

<%! ..%>

<jsp:declaration> .. </jsp:declaration>

<%@ include .. %>

<jsp:directive.include .. />

<%@ page attributes %>

<jsp:directive.page attributes />

<%@ taglib .. %>

<html xmlns:prefix="tag library URL" >

Expressions

<%= ..%>

<jsp:expression> .. </jsp:expression>

Scriptlets

<% ..%>

<jsp:scriptlet> .. </jsp:scriptlet>

Comments

<%--.. --%>

<!-- .. -->

Declarations

Directives

JSP Directives
JSP directives provide directions and instructions to the container,
telling it how to handle certain aspects of JSP processing.
A JSP directive affects the overall structure of the servlet class.
Syntax:
<%@ directive attribute="value" %>

There are three types of directive tag:


Directive

Description

<%@ page ... %>

Defines page-dependent attributes, such as scripting


language, error page, and buffering requirements.

<%@ include ... %>

Includes a file during the translation phase.

<%@ taglib ... %>

Declares a tag library, containing custom actions, used in


the page

The page Directive


The page directive is used to provide instructions to the container that pertain to
the current JSP page. You may code page directives anywhere in your JSP page. By
convention, page directives are coded at the top of the JSP page.
Following is the basic syntax of page directive:
<%@ page attribute="value" %>
You can write XML equivalent of the above syntax as follows:
<jsp:directive.page attribute="value" />

The page Directive


Following is the list of attributes associated with page directive:
Attribute

Purpose

buffer

Specifies a buffering model for the output stream.

autoFlush

Controls the behavior of the servlet output buffer.

contentType

Defines the character encoding scheme.

errorPage

Defines the URL of another JSP that reports on Java unchecked


runtime exceptions.

isErrorPage

Indicates if this JSP page is a URL specified by another JSP page's


errorPage attribute.

extends

Specifies a superclass that the generated servlet must extend

import

Specifies a list of packages or classes for use in the JSP as the


Java import statement does for Java classes.

info

Defines a string that can be accessed with the servlet's


getServletInfo() method.

isThreadSafe

Defines the threading model for the generated servlet.

language

Defines the programming language used in the JSP page.

session

Specifies whether or not the JSP page participates in HTTP


sessions

isELIgnored

Specifies whether or not EL expression within the JSP page will be


ignored.

isScriptingEnabled

Determines if scripting elements are allowed for use.

Page Directive
Example:
<%@ page import="package.class" %>
<%@ page import="java.util.*" %>
<%@ page contentType="text/html" %>
<% response.setContentType("text/html"); %>

The include Directive:


The include directive is used to include a file during the translation phase. This
directive tells the container to merge the content of other external files with the
current JSP during the translation phase. You may code include directives
anywhere in your JSP page.
The general usage form of this directive is as follows:
<%@ include file="relative url" >
The filename in the include directive is actually a relative URL. If you just specify a
filename with no associated path, the JSP compiler assumes that the file is in the
same directory as your JSP.
You can write XML equivalent of the above syntax as follows:
<jsp:directive.include file="relative url" />

Include Directive
<%@ include file="Relative URL">
Included at Translation time
May contain JSP code such as response header
settings, field definitions, etc... that affect the
main page

The taglib Directive


The taglib directive declares that your JSP page uses a set of custom tags,
identifies the location of the library, and provides a means for identifying the
custom tags in your JSP page.

The taglib directive follows the following syntax:


<%@ taglib uri="uri" prefix="prefixOfTag" >
Where the uri attribute value resolves to a location the container understands and
the prefix attribute informs a container what bits of markup are custom actions.
You can write XML equivalent of the above syntax as follows:
<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />
When you use a custom tag, it is typically of the form <prefix:tagname>. The
prefix is the same as the prefix you specify in the taglib directive, and the tagname
is the name of a tag implemented in the tag library

Scripting Elements
There are three types of Scripting Elements
Declaration
Expression
Scriptlets

Declaration Element
The JSP declaration element defines page-scope
variables to store information or defines supporting
methods that the rest of a JSP page may need.
Declaration elements do not produce outputs.
Its syntax is
<%! Java Code %>
Example:
<%! int i=0; Double d; %>

Declaration Element (cont.)


You can also declare methods by declaration scripting elements. For example,
you can declare the JSP life cycle methods jspInit() and jspDestroy() as follows :
<%! Connection conn %>
...
<%! public void jspInit() {
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = java.sql.DriverManager.getConnection(
"jdbc:oracle:oci9:myDB","scott","tiger");
}
catch (Exception e)
{
. . .}
}
}
%>

Expression Element
Typically, expressions are used to display simple values of
variables or return values of shared data by invoking a bean's
getter methods.
In JSP, the results of an expression evaluation are always
converted to a string and directly included in the output page.
The predefined JSP objects such as request, response, and
session can also be used within the expression element to
make the expression as simple as possible.
Syntax : <%= expr %>
// No semicolon
<%= i * j + k %>
<%= myBean.getSalary() %>
<%= request.getRemoteHost() %>
<%= new java.util.Date() %> // To display Date & Time

Scriptlet Element
JSP scriptlets are embedded within <% ... %> tags. They are
executed at the runtime.
<% Java code
%>
The scriptlets are inserted into the _jspService() method of the
translated Servlet code which is invoked by the Servlet
service() method. This java code is executed when the request
is serviced by the JSP page. You can put any valid Java code
within a scriptlet element, and it is not limited to one line of
source code. For example, the following displays the counter
during execution of a loop, combining the use of the
expressions element and the scriptlets element:
<% for (int i=1; i<=4; i++) { %>

The counter is now <% = i %>


<% } %>

JSP Standard Actions


The JSP specification defines a few standard
action elements (built-in in JSP)
The syntax:
<jsp:action-name attr1=value1 attr2=value2>
action_body
</jsp:action-name>

or (with no body)

<jsp: action-name attr1=value1

attr2=value2 />

JSP forward Action


<jsp:forward page="another page" />
This action forwards the request to another
page, i.e. an internal redirect.
For example, it forwards the control from
current page to second.jsp.
...
<jsp:forward page=second.jsp/>
...

JSP include Action


Addition to the JSP page include directive that includes a
page at the JSP translation time, JSP also supports an
action that can dynamically include a page at run-time.
<jsp:include page = <jsp or html page> flush=true |
false />
If the flush attribute is set to true, the included page will
update when the JSP is updated. Remember that the
include directive only copies the contents once and never
changes afterwards since it is static. The purpose of
include action is to include the other page to be part of
current page. It is used for conditionally including other
pages at run time.

jsp:useBean Action Element


The jsp:useBean action instantiates an instance of the bean
class if there is not an existing one or creates a reference to
an existing one. It also specifies the visibility and
accessibility scope of this bean. The other Web
components in JSP can reference this bean object by its id.
Its syntax is given as:
<jsp:useBean id="name" class=<package>.<Java bean
class> scope=. . .>
The id is the access name of this bean. The scope attribute
defines the visibility of this bean.

page
Only active in the page , default scope
request Active for the current request
session Active for the current session
application
Active for the current application

jsp:useBean Action Element (cont.)


After you get a reference to a bean you can use
jsp:setProperty action and jsp:getProperty action to modify
and retrieve the bean properties.

Once you have a bean reference, you can also modify its
properties by calling the beans getXXX() or setXXX()
methods explicitly in a scriptlets element.
Note that the class specified for the bean must be in the
server's regular class path. For example, in Tomcat, this class
and all the classes it uses should go in the classes directory or
be in a jar file in the lib directory.

jsp:useBean Action Element (cont.)


You can also incorporate Java code into the body of a
jsp:useBean tag so that the incorporated code will be
executed when the bean is instantiated for the first
time. If the instance exists already the code will be
ignored.
<jsp:useBean ...>
Java code
</jsp:useBean>

jsp:setProperty Action
You use jsp:setProperty to assign values to properties of a
bean. You can either use jsp:setProperty after, but outside of, a
jsp:useBean element or within the body of jsp:useBean action
element.
Option 1:
<jsp:useBean id="myBook" ... />
...
<jsp:setProperty name="myBook" property="price" ... />
In this case, the jsp:setProperty is executed regardless of
whether a new bean was instantiated or an existing bean was
found.

jsp:setProperty Action (cont.)


Option 2:
<jsp:useBean id="myBook" ... >
...
<jsp:setProperty name="myBook" property="price" ... />
</jsp:useBean>
In this case, the jsp:setProperty is executed only if a new object is
instantiated, i.e., no existing bean object exists yet.
The following action sets myBooks price property to 31.99.
<jsp:setProperty name="myBook" property="price" value =
31.99 />

jsp:setProperty Action (cont.)


The required name attribute is the id of the bean
specified in <jsp:useBean> action tag.
The required property attribute specifies the
property you want to set. You can also assign a "*" to
the property if all request parameter names match
bean property names. It will set all corresponding
properties of the bean with the values of request
parameters either from request form or request string.
The valueattribute specifies the value for the
property. The String type value will be converted to
the correct type for the property.

jsp:setProperty Action (cont.)


You can also associate the bean properties with the input
parameters. The next example shows that the bookPrice input
parameter in the request form or query string is associated with
the price property of myBook bean.
<jsp:setProperty name="myBook" property="price"
param="bookPrice" />
Or you can associate all properties with input request
parameters with the * wildcard character. Assume that there
are four input request parameters whose names match four
property names: title, isbn, price, and quantity. Whatever data
you input to the parameters will be assigned to the properties
with same names. This is one of the most useful javaBean
features.
<jsp:setProperty name="myBook" property="*" />

jsp:setProperty Action (cont.)


You can't use both value and param at same time, but
it is allowed to use neither. If you use neither param
nor value, that indicates that a parameter name
matches the property name. JSP will take the input
from the parameter which has the same name as the
property name.
jsp:setProperty action is much more powerful than
the setXXX() methods in that it can automatically
convert String type data to the required data type of
the bean property and set multiple properties using
only one single command.

jsp:getProperty Action Element


This element retrieves the value of a bean property, converts it to
a string, and inserts it into the JSP outputs. The two required
attributes are name the id of a bean defined via jsp:useBean,
and property the property whose value should be inserted.
<jsp:useBean id='myBook'

class='shopping.Book'

scope='session' >
...
The next action can return the number of copies of myBook,
which may reference a specific book at the time.

<jsp:getProperty name="myBook" property="quantity" />

To return the price of the same book:

<jsp:getProperty name="myBook" property="price" />


</jsp:useBean>

Example
The form.jsp takes user name input on the form request, saves the
input in a JavaBean, and redirects to response.jsp. The
response.jsp JSP page gets the username from the bean, and
finally it responds to the user with a message Hello, <user
name>.
<%@ page import="user.NameBean" %>
<jsp:useBean id="myBean" scope="request" class="user.NameBean" />
<jsp:setProperty name="myBean" property="*" />
<html>
<body>
<form method="get">
<input type="text" name="userName" size="20">
<br>
<input type="submit" value="Submit">
</form>
<% if (request.getParameter("userName") != null) { %>
<%@ include file="response.jsp" %>
<% } %>
</body>
</html>

(cont.)

Here is the NameBean javaBean file.


package user;
public class NameBean {
String userName;
public NameBean(){ userName=null; }
public void setUserName(String name) { userName=name; }
public String getUserName() { return userName; }
}
Here is the response.jsp file
<h1>Hello, <jsp:getProperty name="myBean"
property="userName" /></h1>

jsp:plugin Action Element


The jsp:plugin action can insert an Java Applet client-side
component into a server-side JSP page component. It
downloads Java plug-in software (if necessary) and client-side
component such as Applet and executes the client-side
component.
The syntax is as follows.
<jsp:plugin type=applet code=MyApplet.class
width=400 height=200>
...
<!-- Parameter lists passed on the current JSP -->
<jsp:param name=username value=Smith />

</jsp:plugin>

jsp:plugin Action Element (cont.)


The <jsp:plugin> element can display an Applet object or a
bean object in the client Web browser, using a Java plug-in
which is part of the browser or downloaded from a specified
URL.
When the JSP file sends an HTML response to the client, the
<jsp:plugin> element is replaced by an <object> element in
HTML specification. In general, the attributes to the
<jsp:plugin> element specify whether the object is a bean or
an applet, locate the code that will be run, position the object
in the browser window, specify an URL from which to
download the plug-in software, and pass parameter names
and values to the object.

JSP Comments
JSP Comments: Different from HTML comments
<!-- an HTML comment -->
<%-- a JSP comment --%>
JSP comments are used for documenting JSP code
and are not visible client-side (using browser's View
Source option) where as HTML comments are
visible.

Expression Language (EL)


A new feature of JSP technology version 2.0 is the
Expression Language (EL). The EL is a simple and
very powerful notation which makes it easier for the
JSP page author to write code for accessing
application data such as data stored in JavaBean
components and attribute data of pageContext,
request, session, and application.
EL uses a shorthand notation of ${ expr } instead of
<%= expr %>.
For example, you have a Book JavaBean class in
shopping package

Anatomy of JSP page


Anatomy of a JSP Page
A JSP page is a mixture of standard HTML tags, web page content, and some
dynamic content that is specified using JSP constructs. Everything except the
JSP constructs is called Template Text.

Example:
HTML>
<HEAD>
<TITLE>Hello World</TITLE>
Template data
</HEAD>
<BODY>
<H1>Hello World</H1>
Today is: <%= new java.util.Date().toString() %> // Jsp element
</BODY>
</HTML>

JSP Processing
When a JSP page request is processed, the template text and dynamic
content generated by the JSP elements are merged, and the result is sent as
the response to the browser
Whenever a .jsp is requested for the first time, the server needs a JSP
container to process JSP pages
The JSP container initiates the translation phase for a page
automatically when it receives the first request for the page
1. Translates the .jsp page into a servlet
2. Compiles the servlet into a class file
3. Executes the servlet (response is sent to the client)
As long as the JSP page remains unchanged, any subsequent request goes
straight to the request processing phase
When the JSP page is modified, it goes through the translation phase again
It is loaded once and called repeatedly, until the server is shut down

JSP Processing (cont..)

JSP Application Design with MVC


Modelviewcontroller (MVC)
It is a software pattern for implementing user interfaces.
It divides a given software application into three interconnected parts, so as
to separate internal representations of information from the ways that
information is presented to or accepted from the user.
The central component, the model, consists of application data, business
rules, logic, and functions.
A view can be any output representation of information, such as a chart or a
diagram. Multiple views of the same information are possible, such as a bar
chart for management and a tabular view for accountants.

The third part, the controller, accepts input and converts it to commands for
the model or view.

JSP Application Design with MVC


The Model/View/Controller architecture is a good framework for JSP.

View is a JSP page used for Presentation Layer

The controller object is master Servlet. Every request goes through the controller
who retrieves the necessary model object.

The model may interact with other business entities such as databases or Enterprise
Java Beans (EJB).

The model object sends the output results back to the controller. The controller
takes the results and places it inside the web browser session and forwards a
redirect request to a particular Java Server Page. The JSP, in the case, is the view.
The controller has to bind a model and a view

JSP Application Design with MVC

JSP Application Design with MVC


MVC roles in a pure JSP scenario

Apache Tomcat
Installing Tomcat

Representation and Management of


Data on the Web

What is Tomcat?
Tomcat is a Servlet container (Web server that
interacts with Servlets) developed under the Jakarta
Project of Apache Software Foundation
Tomcat implements the Servlet and the Java Server
Pages (JSP) specifications of Sun Microsystems
Tomcat is an open-source, non commercial project
Licensed under the Apache Software License

Tomcat is written in Java (OS independent)

Basic Setup Steps

Download & Install Java S/W Development Kit


Download a server (Apache Tomcat)
Configure the server
Set up development environment
Test your setup
Establish a deployment method
Create custom Web applications

Install Instructions
Get & install 5.5.15 Core Windows Executable
(apache-tomcat-5.5.15.exe)

Configuration
Port? (8080 or 80)
User: admin
Password: webtech

Installation Configuration
(pswd: webtech)

Set Path to the Installed JVM


(Tomcat 5.5 is designed to run on J2SE 5.0 and later.)

Tomcat Directory Structure


Tomcat-Base

conf

logs

webapps

server

server.xml

ROOT

myApp1

myApp2

work

shared
lib

classes

WEB-INF
web.xml

lib

classes

Tomcat-Home
bin

common
lib

classes

Running & Testing Tomcat

In the Tomcat folder, open the bin


folder.
Click the startup.bat icon.
You should see a black and white Java
command window.

Open your browser and point to


http://localhost:8080.

You should not see any obvious java


error messages.

You should see the Tomcat welcome


page.

Note startup.bat actually calls other


scripts in the same directory
(catalina.bat, particularly).
The .sh files are for running Tomcat on
Linux/Unix

Maybe Mac also.

Testing the Server


Involves two steps:
Verifying that the server can even start
Checking that you can access your own HTML and
JSP pages

use the default Web application.


put HTML and JSP pages in
install_dir/webapps/ROOT or
install_dir/webapps/ROOT/somePath and access
them with http://localhost/filename or
http://localhost/somePath/filename.

The Directory Structure of a Web


Application
An application's directory must contain
the following:
The directory WEB-INF/
A legal web.xml file under WEB-INF/
myApp

<web-app>
</web-app>

WEB-INF

web.xml

Configuring a Web
Application(web.xml)

Application-specific configuration and declarations are


written in the file myApp/WEB-INF/web.xml
This file contains:
Servlet declarations, mappings and parameters
Default files for directory requests

Error pages (sent in cases of HTTP errors)


Security constraints
Session time-out specification
Context (application) parameters
And more

Compiling and Testing Simple Servlets


to verify the environment is all set compile and run
some simple Servlet, i.e. HelloServlet.java
the location for servlets in the default Web
application is:
create a directory name myApp in webapps
install_dir/webapps/myApp/WEB-INF/classes

Once you compile HelloServlet.java, put


HelloServlet.class in:
install_dir/webapps/myApp/WEB-INF/classes

After compiling the code, access the servlet with the


URL:
http://localhost/myApp/HelloServlet

Installing JSDK
1.
2
3
4
5
6
7
8
9

Download the latest version of the *Java JDK from Sun Microsystems
Double-click on the install file and it should open an installer
Click next, then read and accept the license.
On the next screen you will encounter some options. Just leave these alone
and click next
The next page you encounter should install (and in some cases download)
the Java Development Kit.
After the installer is finished, open run by clicking Start > Run.
In the text box, type "cmd" and click "OK
A simple window should be opened with a black background and a text
prompt.
After focusing the window, type "javac" and press enter. If the prompt
returns something along the lines of: "'javac' is not recognized as an
internal or external command, operable program or batch file" then
continue with the next step. If it shows many more options and lines, skip
to step 15.

Installing JSDK(cont..)
9 Open the properties of "My Computer" by either right-clicking the icon on
the desktop or right-clicking Start > My Computer. When the pop up menu
opens, scroll to the bottom and select "Properties".
10 This should open a window named "System Properties". Click on the
"Advanced" tab and then click "Environment Variables".
11 Next, another window opens with a lot of confusing sentences and letters.
Double-click on the "Path" variable on either of the option boxes.
12 Once the variable is opened, a text box in yet another window appears.
Careful not to delete anything in this box. At the end of the text box, add a
semi-colon if there is not one already, and add "C:\Program
Files\Java\jdk1.6.0\bin" to the text box. This is assuming you did not
change the file path of the installation.
13 Click "Apply" and "OK" to all the windows you have just opened. Open
the command prompt again, while following steps 6-9 to see if that "javac"
command works.

Important Questions
1. a) Briefly explain about Tomcat web server
b) How do you Test Tomcat Webserver
2. What are the limitations of Servlets?
3. Explain the Directive and Scripting elements of JSP.
4. Explain JSP Processing with a neat diagram
5. Explain the anatomy of JSP page.
6. Give an overview of java software development kit.
7. Explain various Elements of JSP

Web Technologies
B.Tech. IT III Year II Semester
UNIT VII

JSP
Application Development

Outline of Presentation
JSP scripting elements
Expressions, Scriptlets and declarations
Implicit JSP Objects
Conditional Processing
Displaying Values, Declaring variables & Methods ..
Error handling and Debugging
Sharing Data Between JSP Pages, Requests, and Users
Sharing Session and Application Data
Memory usage Considerations

JSP Scripting Elements


You can insert code into the servlet that will be
generated from the JSP page.
Expressions: <%= expression %>
Evaluated and inserted into the servlets output. i.e.,
results in something like out.println(expression)

Scriptlets: <% code %>


Inserted verbatim into the servlets _jspService method
(called by service)

Declarations: <%! code %>


Inserted verbatim into the body of the servlet class,
outside of any existing methods

JSP Implicit Objects


JSP Implicit objects are created automatically when a web server processes a
JSP page.
request: The HttpServletRequest (1st arg to doGet)
response: The HttpServletResponse (2nd arg to doGet)
session
The HttpSession associated with the request (unless disabled with the
session attribute of the page directive)
out
The stream (of type JspWriter) used to send output to the client
application
The ServletContext (for sharing data) as obtained via
getServletConfig().getContext().
page, pageContext, config, exception

Implicit objects Class files

application: javax.servlet.ServletContext
config: javax.servlet.ServletConfig
exception: java.lang.Throwable
out: javax.servlet.jsp.JspWriter
page: java.lang.Object
pageContext: javax.servlet.jsp.PageContext
request: javax.servlet.ServletRequest
response: javax.servlet.ServletResponse
session: javax.servlet.http.HttpSession

JSP Expressions
Format
<%= Java Expression %>

Result
Expression evaluated, converted to String, and placed into HTML page
at the place it occurred in JSP page
That is, expression placed in _jspService inside out.print

Examples
Current time: <%= new java.util.Date() %>
Your hostname: <%= request.getRemoteHost() %>

XML-compatible syntax
<jsp:expression>Java Expression</jsp:expression>
XML version not supported by Tomcat 3. Until JSP 1.2, servers are not
required to support it.

Example:
<HTML><HEAD>
<TITLE>JSP Expressions</TITLE>
<META NAME="author" CONTENT="Marty Hall">
<META NAME="keywords"
CONTENT="JSP,expressions,JavaServer,Pages,servlets">
<META NAME="description"
CONTENT="A quick example of JSP expressions.">
<LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css">
</HEAD>
<BODY>
<H2>JSP Expressions</H2>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Your hostname: <%= request.getRemoteHost() %>
<LI>Your session ID: <%= session.getId() %>
<LI>The <CODE>testParam</CODE> form parameter:
<%= request.getParameter("testParam") %>
</UL></BODY></HTML>

Example

Example Result
With default setup, if location was
C:\<tomcatHome>\webapps\ROOT\Expressions.jsp

URL would be
http://localhost/Expressions.jsp

All copyrights reserved by C.C. Cheung


2003.

JSP Scriptlets
Format: <% Java Code %>
Result
Code is inserted verbatim into servlet's _jspService

Example
<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
<% response.setContentType("text/plain"); %>

XML-compatible syntax
<jsp:scriptlet>Java Code</jsp:scriptlet>

<%
for (int i=100; i>=0; i--)
{
%>
<%= i %> bottles of beer on the
wall.<br>
<%
}
%>

JSP Scriptlets
Example

Example Using JSP Scriptlets


<HTML>
<HEAD>
<TITLE>Color Testing</TITLE>
</HEAD>
<%
String bgColor =
request.getParameter("bgColor");
boolean hasExplicitColor;
if (bgColor != null) {
hasExplicitColor = true;
} else {
hasExplicitColor = false;
bgColor = "WHITE";
}
%>
<BODY BGCOLOR="<%= bgColor %>">
11

JSP Declarations
Format
<%! Java Code %>

Result
Code is inserted verbatim into servlet's class definition,
outside of any existing methods

Examples
<%! private int someField = 5; %>
<%! private void someMethod(...) {...} %>

XML-compatible syntax
<jsp:declaration>Java Code</jsp:declaration>

Example Using JSP Declarations

<body>
<h1>JSP Declarations</h1>
<%! private int accessCount = 0; %>
<h2>Accesses to page since server reboot:
<%= ++accessCount %></h2>
</body></html>
After

15 total
visits by an
arbitrary number
of different clients
13

Scriptlets vs. Declarations


<%! int count=100; %>
<%= ++count %>

<% int count=100; %>


<%= ++count %>

public final class


_scopeExpermnt1_xjsp
{
int count=100;

public final class


_scopeExpermnt2_xjsp
{
public void _jspService
(HttpServletRequest request,
HttpServletResponse response)
throws java.io.IOException
{
JspWriter out =
pageContext.getOut();

public void _jspService


(HttpServletRequest request,
HttpServletResponse response)
throws java.io.IOException
{
JspWriter out =
pageContext.getOut();

int count=100;

out.print( "\r\n" );
out.print( String.valueOf(
unt ) );
out.print( "\r\n" );
}

out.print( "\r\n" );
++co

out.print( String.valueOf(
unt ) );
out.print( "\r\n" );

}
}

++co

14

JSP Tags + HTML Tags


<h2>Table of Square Roots</h2>
<table border=2>
<tr>
<td><b>Number</b></td>
<td><b>Square Root</b></td>
</tr>
<%
for (int n=0; n<=100; n++)
{
%>
<tr>
<td><%=n%></td>
<td><%=Math.sqrt(n)%></td>
</tr>
<%
}
%>
</table>

15

Error Handling & Debugging


When you are writing JSP code, a programmer may leave a coding errors which can
occur at any part of the code. You can have following type of errors in your JSP
code:
Checked exceptions: Achecked exception is an exception that is typically a user
error or a problem that cannot be foreseen by the programmer. For example, if a file
is to be opened, but the file cannot be found, an exception occurs. These exceptions
cannot simply be ignored at the time of compilation.
Runtime exceptions: A runtime exception is an exception that occurs that probably
could have been avoided by the programmer. As opposed to checked exceptions,
runtime exceptions are ignored at the time of compliation.
Errors: These are not exceptions at all, but problems that arise beyond the control
of the user or the programmer. Errors are typically ignored in your code because
you can rarely do anything about an error. For example, if a stack overflow occurs,
an error will arise. They are also ignored at the time of compilation.
This tutorial will give you few simple and elegant ways to handle run time
exception/error occuring in your JSP code.

Error Handling (cont..)


Using Exception Object:

1
2
3
4

The exception object is an instance of a subclass of Throwable (e.g., java.lang.


NullPointerException) and is only available in error pages. Following is the list of important
medthods available in the Throwable class.
public String getMessage()
Returns a detailed message about the exception that has occurred. This message is initialized
in the Throwable constructor.
public Throwable getCause()
Returns the cause of the exception as represented by a Throwable object.
public String toString()
Returns the name of the class concatenated with the result of getMessage()
public void printStackTrace()
Prints the result of toString() along with the stack trace to System.err, the error output stream.
5 public StackTraceElement [] getStackTrace()
Returns an array containing each element on the stack trace. The element at index 0 represents
the top of the call stack, and the last element in the array represents the method at the bottom
of the call stack.
public Throwable fillInStackTrace()
Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.

Error Handling (cont..)

JSP gives you an option to specify Error Page for each JSP. Whenever the page
throws an exception, the JSP container automatically invokes the error page.

Following is an example to specifiy an error page for a main.jsp. To set up an


error page, use the <%@ page errorPage="xxx" %> directive.

<%@ page errorPage="ShowError.jsp" %>


<html> <head> <title>Error Handling Example</title> </head>
<body>
<% // Throw an exception to invoke the error page
int x = 1;
if (x == 1)
{
throw new RuntimeException("Error condition!!!");
}
%>
</body> </html>

Error Handling (cont..)

Now you would have to write one Error Handling JSP ShowError.jsp, which is given
below.
Notice that the error-handling page includes the directive <%@ page isErrorPage="true"
%>. This directive causes the JSP compiler to generate the exception instance variable.

<%@ page isErrorPage="true" %>


<html> <head> <title>Show Error Page</title> </head>
<body> <h1>Opps...</h1>
<p>Sorry, an error occurred.</p> <p>Here is the exception stack trace: </p> <pre>
<% exception.printStackTrace(response.getWriter()); %>
</pre> </body> </html>

Now try to access main.jsp, it should generate something as follows:


Out Put
java.lang.RuntimeException: Error condition!!! ...... Opps... Sorry, an
error
occurred. Here is the exception stack trace:

Sharing Data Between JSP Pages,


Requests, and Users
Any real application consists of more than a single page, and multiple
pages often need access to the same information and server-side resources.
When multiple pages are used to process the same request, for instance one
page that retrieves the data the user asked for and another that displays it,
there must be a way to pass data from one page to another.
In an application in which the user is asked to provide information in
multiple steps, such as an online shopping application, there must be a way
to collect the information received with each request and get access to the
complete set when the user is ready.
Other information and resources need to be shared among multiple pages,
requests, and all users. Examples are information about currently logged-in
users, database connection pool objects, and cache objects to avoid
frequent database lookups

To share Data

Need to know how to


1) structure a JSP application
2) pass control from one JSP page to another

3) pass data from one JSP to another

Example

A shopping application that accepts a users payment details on a form,


validates the details and displays a confirmation page or error
depending upon user input

Various ways that JSP pages for collection of payment details can be
structured. Can even have everything on a single JSP page (messy for
anything but simplest apps)

Have used 3 JSP pages:


- payment details on a form(userinput.jsp)
- validation of the details (validateinfo.jsp)
- display of a confirmation page (confirmed.jsp) or error
(userinput.jsp) depending upon user input

Structure of JSP pages: example


Userinput.jsp

Userinput.jsp
Displays a form
into which
user enters their
details

Presentation

infovalidate.jsp
infovalidate.jsp
Validates the info
provided in
userinput.jsp
and passes back to
userinput.jsp
if theres an error, or
confirmed.jsp
if info is valid.
Request
processing and
business logic

confirmed.jsp

confirmed.jsp
displays a message
to user to confirm
payment made.

Presentation

Passing control from one page to


another
Separating presentation pages from request
processing/business logic - more than one page used to
process client request
--- need to be able to pass control from one page to another
--- e.g. in the example, infovalidate.jsp need to be
able to forward to either userinput.jsp or confirmed.jsp
depending on validation result
Can use the <jsp:forward> standard action tag

Passing control from one page to


another(cont..)
For example:
A validation page (infovalidate.jsp) forward control to a page, userinput.jsp, in
order to display an error message. Need to include error message in the
the forwarding instruction.

<jsp:forward page = userinput.jsp>


page
<jsp:param name = msg value =Target
invalid
credit card
number/>
</jsp:forward>

Name of parameter to be passed


Value of parameter

Passing control from one page to


another
<jsp:forward page = userinput.jsp>
The target page in this example is assumed to be in
the same directory on the web server as the current
JSP page

<jsp:forward page = /somedir/userinput.jsp>


The target page in this example is assumed to be in
the /somedir/ directory as a subset of the main application
directory (../webapps/myapp/)

Note: the <c:redirect> tag is similar to the


<jsp:forward> tag, but also allows redirection to a different
URL.

Sharing data across pages : Scope


Previous example creates a variable called errorMsg, and sets its value to
Invalid entry. The scope of the variable is request
When a JSP page needs to save data for its processing, it must specify the
scope of the data
The scope of a data object defines how long the data is available for (I.e. how
long it lasts).

userinput.jsp: displays a payment form.


when the user clicks button, infovalidate.jsp is called.
If an entry error is made, the infovalidate.jsp page forwards back to this with
the error.
Note: v. simple example for illustration. Details are not saved to a database
or file.

confirmed.jsp: displays the confirmation.


called by the infovalidate.jsp page if no errors

Sample code user input.jsp


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
Need to know whether this is the
<title>Payment Form</title> first time form is displayed
</head>
<body bgcolor="white">
<form action="userinfovalidate.jsp" method="post">
<table>
<input type="hidden" name="submitted" value="true">
<c:if test="${param.submitted && !empty msg}">
<tr>
<td colspan="2">
<font color="red">
<c:out value = "${msg}"/>
Check if there are any error
</font>
messages to display. Themsg
</td>
variable is set in the validation page
</tr>
</c:if>

Sample code user input.jsp


(continued)

<tr>
<td>Name:</td>
<td>
<input type="text" name="userName" value = "<c:out value =
"${param.userName}"/>">
</td>
<td>Credit card number:</td>
<td>
<input type="text" name="creditCardNumber" value = "<c:out valu
= "${param.creditCardNumber}"/>">
</td>
</tr>
<tr>
<td colspan=2>
<input type="submit" value="Send Data">
</td>
Display any previously enter
<tr>
values of username/credit card
</table>
number
</form>
</body>
html>

Sample code infovalidate.jsp


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%-- tests whether username and credit card have been entered --%>
<%-- if there's an error, set a msg variable --%>
Username request parameter

<c:choose>
<c:when test="${empty param.userName}">
<c:set var = "msg" value = "You must enter your username"
scope = "request"/>
<jsp:forward page="userinfoinput.jsp" />
</c:when>
<c:when test="${empty param.creditCardNumber}">
<c:set var = "msg" value = "You must enter your credit card
number" scope = "request"/>
<jsp:forward page="userinfoinput.jsp" />
</c:when>
<c:otherwise>
<jsp:forward page="confirmed.jsp" />
</c:otherwise>
Must set scope to request.
</c:choose>
Otherwise, the message wont be
available to userinputinfo.jsp

Sample code confirmed.jsp


<%-- displays a confirmation screen to the user --%>

<html>
<head>
<title>User Info Validated</title>
</head>
<body bgcolor="white">
<font color="green" size="+3">
Your payment details are correct - thank you
</font>
</body>
</html>

Note: This page is just template text (apart from comment) so could be created
as a regular HTML file. Making it a JSP page allows dynamic content later
without changing the referring page

Sharing Session & application Data


HTTP is a stateless, request-response protocol. This means that the browser sends
a request for a web resource, and the web server processes the request and returns a
response. The server then forgets this transaction ever happened.
So when the same browser sends a new request, the web server has no idea that this
request is related to the previous one.
This is fine if you're dealing with static files, but it's a problem in an interactive web
application.
In a travel agency application, for instance, it's important to remember the dates and
destination entered to book the flight so the customer doesn't have to enter the same
information again when it's time to make hotel and rental car reservations.
The way to solve this problem is to let the server send a piece of information to the
browser that the browser then includes in all subsequent requests.
This piece of information, called a session ID, is used by the server to recognize a
set of requests from the same browser as related: in other words, as part of the same
session.
A session starts when the browser makes the first request for a JSP page in a
particular application. The session can be ended explicitly by the application, or the
JSP container can end it after a period of user inactivity (the default value is typically
30 minutes after the last request).

Sharing Session..(cont..)

Examples of session tracking information:

Shopping website: Items in a shopping cart:


-> Item1, Gone with the Wind)
->Item2, BeatlesCD)

- Select these on one web page, check-out in a different part of the


website. Web site remembers what you ordered by using session
tracking

Web banking application:

Bank employee selects the branch they are a member of. Session
stores this info in some way:
-> branch, 931012
Application remembers the branch number so that employee does
not have to re-enter. Only customers relevant to the branch are
shown throughout.

Sharing Session..(cont..)

There are a number of different techniques available to web applications


to enable session tracking, including cookies (next course).

In JSP, can be done by simply using the scope attribute of whatever


needs to be tracked.

Set the scope to session, and the relevant attribute will be available
throughout the entire session of the client

Example: a JSP page that displays two counters a hit counter for the
session, and a hit counter for the application

Sharing Session..(cont..)
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<html>
<head> header details etc </html>
<body bgcolor="white">

will last for the users session only

<%-- Increment counters --%>


<c:set var="sessionCounter" scope="session"
value="${sessionCounter + 1}" />
<c:set var="applCounter" scope="application"
value="${applCounter + 1}" />
<h1>Counter page</h1>

will be updated by all users


of the applicaton

This page has been visited <b>


<c:out value="${sessionCounter}" />
</b> times within the current session, and <b>
<c:out value="${applCounter}" />
</b> times by all users since the application was started.
</body>
</html>

Working with Session object


The session object has many useful methods that can
alter or obtain information about the current session.
setMaxInactiveInterval(second)

<html><head>
<title>Session Values</title>
</head><body>
<%
session.setMaxInactiveInterval(10);
String name = (String)
session.getAttribute("username");
out.print("Welcome to my site " + name + "<br>");
%>
INE2720 Web Application
All copyrights reserved by C.C. Cheung
</body></html>
Software Development
2003.

38

Memory Usage Considerations


You should be aware that all objects you save in the application and session
scopes take up memory in the server process. It's easy to calculate how
much memory is used for the application scope because you have full
control over the number of objects you place there. But the total number of
objects in the session scope depends on the number of concurrent sessions,
so in addition to the size of each object, you also need to know how many
concurrent users you have and how long a session lasts.
Example :
Consider a CartBean class , It stores only references to ProductBean
instances, not copies of the beans. An object reference in Java is 8 bytes, so
with three products in the cart we need 24 bytes.
The java.util.Vector object used to hold the references adds some overhead,
say 32 bytes. All in all, we need 56 bytes per shopping cart bean with three
products.

Important Questions
1. Explain Implicit Objects in JSP
2. Explain Error Handling and Debugging in JSP
3. Explain Memory usage considerations in JSP
Application development
4. Explain the dynamic content generation with an example
using JSP
5. Explain Sharing Session and an application with an
example
6. Explain Data sharing between JSP pages with an
example

JDBC
Java Database Connectivity

Outline of Presentation
Introduction to JDBC
JDBC Driver Types
General Architecture
JDBC Components

Database Programming using JDBC


java.sql.* Package
Accessing Database from a JSP Page
Deploying Java Beans in a JSP Page
Introduction To Struts Framework

Introduction to JDBC
JDBC is a front end tool which is used to connect
front end java application to back end database
JDBC is an alternative to ODBC and ADO that
provides database access to programs written in

Java.
JDBC drivers are available for most DBMS
products

A JDBC Driver
Is an interpreter that translates JDBC method calls to

vendor-specific database commands


Database
commands

JDBC calls
Driver

Database

Implements interfaces in java.sql


Can also provide a vendors extensions to the JDBC

standard

JDBC Driver Types

General Architecture

JDBC Components

Database Programming Using JDBC


STEPS:
1.Load the Driver
2.Establish a connection
3.Create JDBC Statements
4.Execute SQL Statements
5.GET ResultSet
6.Close connections

Using JDBC
1. Load the driver:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
//Type1 Driver
2. Establish a connection to the database:
A connection URL string includes the literal jdbc:, followed by the
name of the driver and a URL to the database
String url = "jdbc:odbc:dsn;
Create a Connection object:
Connection con = DriverManager.getConnection(url,
scott,tiger);
3. Create a statement object
Statement stmt = conn.createStatement();
Associate SQL with the statement object
String queryString = select * from emp";

Using JDBC (Continued)


4.Execute the SQL Statements:
Example statements:
ResultSet
rs
=
stmt.executeQuery(querystring);
int
result =
stmt.executeUpdate(updatestring);

Compiled queries can be processed via a PreparedStatement object

Stored procedures can be processed via a CallableStatement object


5. GET Result
while (rs.next()) {
int empno = rs.getInt(1);
String empname = rs.getString(2);
}
6. Close connection
stmt.close();
con.close();

Using a PreparedStatement
// Once you have a connection, you can create a
// "prepared statement" object. A prepared statement is
// precompiled, and can be used repeatedly with new values
// for its parameters.
// Use question marks for parameter place-holders.
PreparedStatement prepStmt = con.prepareStatement(
"INSERT INTO Artist (ArtistID, Name, "
+ "Nationality, BirthDate, DeceasedDate)"
+ "VALUES (ArtistSeq.nextVal, ?, ?, ?, ? )" );
// Now supply values for the parameters
// Parameters are referenced in order starting with 1.
prepStmt.setString( 1, "Galvan" );
prepStmt.setString( 2, "French" );
prepStmt.setInt
( 3, 1910 );
prepStmt.setNull ( 4, Types.INTEGER );
// The PreparedStatement object methods:
// 1) executeUpdate -- statements that modify the database
// 2) executeQuery -- SELECT statements (reads)
prepStmt.executeUpdate();
System.out.println( "Prepared statement executed" );
// Now do it again
prepStmt.setString(
prepStmt.setString(
prepStmt.setInt
(
prepStmt.setInt
(

1,
2,
3,
4,

"Monet" );
"French" );
1840 );
1879 );

prepStmt.executeUpdate();
System.out.println( "Prepared statement executed again" );

Accessing a stored procedure


// Once you have a connection, you can create a
// "callable statement" object to access the stored procedure.
// Inside the curly braces, you call the procedure, and use
// question marks for parameter place-holders.
CallableStatement callStmt = con.prepareCall(
"{call Record_sale( ?, ?, ?, ?, ?, ?)}" );
// Now supply values for the parameters
// Parameters are referenced in order starting with 1.
callStmt.setString( 1, "Barry Goldwater" );
callStmt.setString( 2, "Tobey" );
callStmt.setString( 3, "Mystic Fabric" );
callStmt.setString( 4, "105/135" );
callStmt.setInt
( 5, 24000 );

// And register the OUT variable


// This variable returns information to this program
// from the stored procedure.
callStmt.registerOutParameter( 6, java.sql.Types.VARCHAR );
System.out.println( "Parameters set for CallableStatement" );
// The CallableStatement object has an additional method*
// for use when the stored procedure uses multiple SQL statements.
// 1) executeUpdate -- statements that modify the database
// 2) executeQuery -- SELECT statements (reads)
// *3) execute
-- procedures with multiple SQL statements
callStmt.execute();
System.out.println( "Stored procedure executed" );
// Get the OUT variable contents (parameter 6)
String result = callStmt.getString( 6 );

Java.sql.* package
java.sql.Connection
Statement createStatement (int resultSetType, int resultSetConcurrency)
PreparedStatement prepareStatement (String sql, int resultSetType, int
resultSetConcurrency)
CallableStatement prepareCall (String sql, int resultSetType, int resultSetConcurrency)

resultSetType

resultSetConcurrency

ResultSet.TYPE_FORWARD_ONLY

ResultSet.CONCUR_READ_ONLY

ResultSet.TYPE_SCROLL_INSENSITIVE

ResultSet.CONCUR_UPDATABLE

ResultSet.TYPE_SCROLL_SENSITIVE

Java.sql.* package
java.sql.ResultS
et
void beforeFirst() throws SQLException
void afterLast() throws SQLException
boolean first() throws SQLException

boolean last() throws SQLException


boolean absolute(int row) throws SQLException
boolean relative(int row) throws SQLException

Example : Backward
Statement stmt = conn.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

ResultSet rs = stmt.executeQuery("SELECT empno, sal FROM emp");


rs.afterLast();
while ( rs.previous() )
{

System.out.println(rs.getString("empno") + " " + rs.getFloat("sal"));


}
...

Accessing the Database using JSP


Consider stocks database
There are three tables. Both customer and stocks have a one-to-many
relationship with portfolios. The database stocks.mdb
was registered with the ODBC driver as CoolStocks

customer stocks portfolio


id
lname
fname

symbol id
company symbol
price
num_shares

Register w/ODBC
Create an ODBC data source.
Click on the Start button.
Choose Settings, Control Panel
Double-click on ODBC Data Sources
Choose the System DSN tab
Click Add
Click on the desired driver (Microsoft ODBC for oracle)
Click on the Finish button
Enter a Data Source Name (I called my database CoolStocks
and that name appears in the java code below)

A Simple JSP/JDBC Example


<TITLE>JSP JDBC Example 1</TITLE>
</HEAD>
<BODY>
<! Adapted from James Goodwills Pure JSP
<!-- Set the scripting language to java and -->
<!-- import the java.sql package -->
<%@ page language="java" import="java.sql.*" %>
<%@ page import= "java.io.*" %>

<%
Connection con = null;
try {
// Load the Driver class file
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Make a connection to the ODBC datasource Movie Catalog
con = DriverManager.getConnection("jdbc:odbc:CoolStocks,scott,tiger);
// Create the statement
Statement statement = con.createStatement();
// Use the created statement to SELECT the DATA
// FROM the customer Table.
ResultSet rs = statement.executeQuery("SELECT * " +
"FROM customer");
// Iterate over the ResultSet
%>

<!-- Add an HTML table to format the results -->


<TABLE BORDER="1">
<TR>
<TH> Customer - ID</TH><TH>Last Name</TH>
<TH>First Name</TH>
<%
while ( rs.next() ) {
// get the id, convert to String
out.println("<TR>\n<TD>" + rs.getString("id") + "</TD>");
// get the last name
out.println("<TD>" + rs.getString("lname") + "</TD>");
// get the first name
out.println("<TD>" + rs.getString("fname") + "</TD>\n</TR");
}

// Close the ResultSet


rs.close();
}
catch (IOException ioe) {
out.println(ioe.getMessage());
}
catch (SQLException sqle) {
out.println(sqle.getMessage());
}
catch (ClassNotFoundException cnfe) {
out.println(cnfe.getMessage());
}
catch (Exception e) {
out.println(e.getMessage());
}

finally {
try {
if ( con != null ) {
// Close the connection no matter what
con.close();
}
}
catch (SQLException sqle) {
out.println(sqle.getMessage());
}
}
%>
</BODY>
</HTML>

It Works!(output)

Using JavaBeans in JSP

To use a JavaBean in your JSP page, you need


to:

Include the JavaBean reference in the JSP


page
Set the JavaBean property
Get the JavaBean property

Using JavaBeans in JSP (Contd.)

Including Bean Reference

You can use the JSP action tag, <jsp:useBean> to include a bean
reference in your JSP page.
The <jsp:useBean> action tag creates an instance of the JavaBean and
stores the bean reference in a variable.
The variable can then be used to access the JavaBean throughout the JSP
page.
The following code snippet shows the syntax of the <jsp:useBean> action
tag:
<jsp:useBean
id=Bean Name
scope=ScopeName
class=class name />

Using JavaBeans in JSP (Contd.)

Scope of JavaBean in a JSP page

page: Specifies that the JavaBean object is available only

for the current page. The following code snippet shows


the <jsp:useBean> action tag that includes a bean with a
page scope:
<jsp:useBean id="option_bean" scope =page
class="test.OptionBean"/>

request: Specifies that the JavaBean object is available

for the current request. The following code snippet shows


the <jsp:useBean> action tag that includes a bean with a
request scope:
<jsp:useBean id="option_bean" scope =request
class="test.OptionBean"/>

Using JavaBeans in JSP (Contd.)


session: Specifies that the JavaBean object is available only for
the current session. The following code snippet shows the
<jsp:useBean> action tag that includes a bean with a session
scope:
<jsp:useBean id="option_bean" scope =session
class="test.OptionBean"/>

application: Specifies that the JavaBean object is available for the


entire Web application. The following code snippet shows the
<jsp:useBean> action tag that includes a bean with an
application scope:
<jsp:useBean id="option_bean" scope =application
class="test.OptionBean" />

Using JavaBeans in JSP (Contd.)

Setting Beans Properties

The <jsp:setProperty> tag enables you to set properties for


a JavaBean to specific values.
The <jsp:setProperty> tag can be defined inside
<jsp:useBean> tag or anywhere in the JSP file after the
declaration of <jsp:useBean> tag.
The following syntax shows how to set a property of a
JavaBean using <jsp:setProperty> tag:
<jsp:setProperty name=beanName property=
propertyName>

Using JavaBeans in JSP (Contd.)

The following table describes various attributes of the <jsp:setProperty>


tag:

Attribute

Description

name

Specifies the name of the bean object. The value of this


attribute should be the same as the value of the id attribute
of the <jsp:useBean> tag.

property

Represents the name of JavaBean property to be set.

Using JavaBeans in JSP (Contd.)

Reading Bean Properties

The <jsp:getProperty> action tag is used to read the value of a


JavaBean property in your JSP page.
The value returned by the tag, <jsp:getProperty> is converted into
java.lang.String and is placed into an implicit object, out.
The following syntax shows how to get the JavaBean property using
the <jsp:getProperty> tag:
<jsp:getProperty name=beanName property=propertyName />

Using JavaBeans in JSP (Contd.)

The following table describes various attributes of the <jsp:getProperty>


tag:

Attribute

Description

name

Represents the name of the JavaBean object.

property

Represents the bean property for which you want to retrieve the
value.

Demonstration-Implementing
JavaBeans in JSP

Problem Statement

Create a JSP application that connects to a database and retrieve


the details, such as author id, address, city, state, and zip code
related to authors. The JavaBean component should accept the
author id, driver name, and URL as a parameter. The information is
to be retrieved from authors table.

Demonstration-Implementing
JavaBeans in JSP (Contd.)

Solution

To solve the given problem, perform the following task:


1.
2.
3.
4.

Create a JavaBean that implements the business logic.


Create a JSP page that instantiates a JavaBean.
Create the user interface using HTML.
Access the JSP application.

Struts Frame work


Struts is an open-source framework for building more flexible,

maintainable

and structured front-ends in Java web applications

There are two key components in a web application:


the data and business logic performed on this data
the presentation of data

Struts
helps structuring these components in a Java web app.

controls the flow of the web application, strictly separating

these components
unifies the interaction between them
This separation between presentation, business logic and control is

achieved
by implementing the Model-View-Controller (MVC)
Design Pattern

The Model-View-Controller Pattern - Overview


Splits up responsibilities for handling user interactions in an application into
three layers:
Model, View, Controller

Model
holds application data and business logic

is absolutely independent from the UIs

The Model-View-Controller Pattern - Details


View
presentation of parts of the Model to the user
independent from the internal implementation of the Model
there can be different Views presenting the same Model data

Controller
bridge between Model and View
controls the flow of the application

receives/interprets user input


performs operations on the Model
triggers View update

Benefits:
better maintainability and testability of applications
ability to easily develop different kinds of UIs (e.g. console, GUI, )
separation of different tasks in development
code reusability

Controller ActionServlet
The central component in a Struts application
manages the flow of the application
receives user requests and delegates

them

to the corresponding Action classes


selects the appropriate View to be displayed next
(according to ActionForward returned by an Action class)
represents a Single Point of Entry of the web application

(Front Controller Pattern)


implemented as a simple Java Servlet
listed in the deployment descriptor of the surrounding Web

Container (usually web.xml) for handling *.do requests


can be extended, but in most cases this is not necessary

Controller Actions
perform logic depending on a users request
Actions
are Java classes that extend Struts Action

class org.apache.struts.action.Action
The Action's execute() method is called by
the ActionServlet
Tasks are usually performed by Actions:
depending on the type of action:

perform the action directly (non-complex actions)


call one or more business logic methods in the Model
return an appropriate ActionForward object that tells the
ActionServlet which View component it should forward to
Ex.: failure or success in login application

Controller ActionForms
represent the data stored in HTML forms
hold the state of a form in their properties
provide getter/setter methods to access them
may provide a method to validate form data

ActionForms
are Java classes that extend Struts ActionForm

class org.apache.struts.action.ActionForm
are filled with the form data by the ActionServlet
one ActionForm can be used for more than one HTML form
very useful when building wizards or similar types of forms

Controller ActionForms Validating user input


Validation is done
right in the beginning before the data is used by any business

methods (at this point, validation is limited to the data structure!)


Struts offers two options for server-side validation of user input:
the validate() method in ActionForms
can

be implemented by the ActionForm developer


returns either null (no errors) or an ActionErrors object
a plug-in to use the Jakarta Commons Validator within Struts
based on rules defined in an XML file
there can be one or more rules associated with each property in
a form
rules can define required fields, min./max. length, range, type
error messages and rules can be localized using resource
bundles

View JSPs with Struts tag libraries


The presentation layer in a Struts

application is created using standard JSPs


together with some Struts Tag Libraries
Struts tag libraries
provide access to Model data
enable interaction with ActionForms
provide simple structural logic (such as iteration)
Example:

...

<%@ prefix="html" uri="/WEB-INF/struts-html.tld" %>


<body>
<html:errors/>
<html:form action="login.do">
Username: <html:text property="username"/><br/>
Password: <html:password property="passwd"
redisplay="false"/><br/>
<html:submit>Login</html:submit>
</html:form>
</body>

The Model
Holds the data of an application and provides
business logic methods
Not directly part of the Struts framework!
The Model is usually built of different kinds
of Business Objects:
JavaBeans
simple

Java classes, that follow certain naming conventions


contain attributes and corresponding getters/setters
reside in the Web Container
Enterprise JavaBeans (EJBs)
components containing business logic in a J2EE architecture
reside in an EJB Container
kinds of EJBs: Session Beans, Entity Beans, Message Driven
Beans

Important Questions
1. Explain Different Types of JDBC Drivers
2. Explain the process of Accessing Database from a
JSP Page
3. Explain Struts Framework
4. Explain Deploying of Java Beans in a JSP Page
5. Explain Java.sql.* package
6. Explain Various types of ResultSets with example

You might also like