Você está na página 1de 79

Web Technologies Lab Manual

Hyper Text Markup Language (HTML)


1. Introduction to HTML

What is an HTML File?

HTML stands for Hyper Text Markup Language


An HTML file is a text file containing small markup tags
The markup tags tell the Web browser how to display the page
An HTML file must have an htm or html file extension
An HTML file can be created using a simple text editor

Example

<html>
<head>
<title>Title of
page</title>
</head>
<body>
This is my first homepage. <b>This text is
bold</b> </body>
</html>

HTML Elements

HTML documents are text files made up of HTML elements. HTML elements are defined using
HTML tags.

HTML Tags (Elements)

HTML tags are used to mark-up HTML elements


HTML tags are surrounded by the two characters < and >
The surrounding characters are called angle brackets
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 text between the start and end tags is the element content
HTML tags are not case sensitive, <b> means the same as <B>

Tag Attributes
Tags can have attributes. Attributes can provide additional information about the HTML
elements on your page.

This tag defines the body element of your HTML page: <body>. With an added bgcolor
attribute, you can tell the browser that the background color of your page should be red, like this:
<body bgcolor="red">.

Attributes always come in name/value pairs like this: name="value". Attributes are always added

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 1
Web Technologies Lab Manual

to the start tag of an HTML element.

Basic HTML Tags

The most important tags in HTML are tags that define headings, paragraphs and line breaks.

Headings

Headings are defined with the <h1> to <h6> tags. <h1> defines the largest heading. <h6> defines
the smallest heading.

<h1>This is a
heading</h1>
<h2>This is a
heading</h2>
<h3>This is a
heading</h3>
<h4>This is a
heading</h4>
<h5>This is a
heading</h5>
<h6>This is a
heading</h6>

HTML automatically adds an extra blank line before and after a heading.

Paragraphs

Paragraphs are defined with the <p> tag.

<p>This is a
paragraph</p> <p>This is
another paragraph</p>

HTML automatically adds an extra blank line before and after a paragraph.

Line Breaks

The <br> tag is used when you want to end a line, but don't want to start a new paragraph. The
<br> tag forces a line break wherever you place it.

<p>This <br> is a para<br>graph with line breaks</p>

The <br> tag is an empty tag. It has no closing tag.

Comments in HTML

The comment tag is used to insert a comment in the HTML source code. A comment will be
ignored by the browser. You can use comments to explain your code, which can help you when
you edit the source code at a later date.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 2
Web Technologies Lab Manual

<!-- This is a comment -->

Note that you need an exclamation point after the opening bracket, but not before the closing
bracket.

<b> Defines bold text


<i> Defines italic text
<u> Defines underlined text
<strong> Defines strong text
<sub> Defines subscripted text
<sup> Defines superscripted text
<q> Defines a short quotation

HTML Links

HTML uses a hyperlink to link to another document on the Web.

The Anchor Tag and the href Attribute

HTML uses the <a> (anchor) tag to create a link to another document.

An anchor can point to any resource on the Web: an HTML page, an image, a sound file, a
movie, etc.

The syntax of creating an anchor:

<a href="url">Text to be displayed</a>

The <a> tag is used to create an anchor to link from, the href attribute is used to address the
document to link to, and the words between the open and close of the anchor tag will be
displayed as a hyperlink. This anchor defines a link to W3Schools:

<a href="http://www.google.co.in/">Visit W3Schools!</a>


The Target Attribute

With the target attribute, you can define where the linked document will be opened.

The line below will open the document in a new browser window:

<a
href="http://www.w3schools.c
om/" target="_blank">Visit
W3Schools!</a>

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 3
Web Technologies Lab Manual

The Anchor Tag and the Name Attribute (internal linking)

The name attribute is used to create a named anchor. When using named anchors we can create
links that can jump directly into a specific section on a page, instead of letting the user scroll
around to find what he/she is looking for.

Below is the syntax of a named anchor:

<a name="label">Text to be displayed</a>

The name attribute is used to create a named anchor. The name of the anchor can be any text you
care to use.

The line below defines a named anchor:

<a name="tips">Useful Tips Section</a>


<p>some tips about HTML
…………………..
…………..

…… …………..
…………..
</p>

You should notice that a named anchor is not displayed in a special way.

To link directly to the "tips" section, add a # sign and the name of the anchor to the end of a
URL, like this:

<a href="#tips">
Jump to the Useful Tips Section</a>
When clicked the above section the control goes to the tips section.

HTML Frames

With frames, you can display more than one Web page in the same browser window.

Frames

With frames, you can display more than one HTML document in the same browser window.
Each HTML document is called a frame, and each frame is independent of the others.

The disadvantages of using frames are:

The web developer must keep track of more HTML documents


It is difficult to print the entire page

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 4
Web Technologies Lab Manual

The Frameset Tag

The <frameset> tag defines how to divide the window


into frames Each frameset defines a set of rows or
columns
The values of the rows/columns indicate the amount of screen area each row/column will
occupy
The Frame Tag

The <frame> tag defines what HTML document to put into each frame

In the example below we have a frameset with two columns. The first column is set to 25% of
the width of the browser window. The second column is set to 75% of the width of the browser
window. The HTML document "frame_a.htm" is put into the first column, and the HTML
document "frame_b.htm" is put into the second column:

<frameset
cols="25%,75%">
<frame
src="frame_a.htm">
<frame
src="frame_b.htm">
</frameset>
Frame Tags
Tag Description
<frameset> Defines a set of frames
<frame> Defines a sub window (a frame)
<noframes> Defines a noframe section for browsers that do not handle frames
<iframe> Defines an inline sub window (frame)

With HTML you can create tables.

Table Tags
Tag Description
<table> Defines a table
<th> Defines a table header
<tr> Defines a table row
<td> Defines a table cell

HTML Lists

HTML supports ordered, unordered and definition lists.

Unordered Lists

An unordered list is a list of items. The list items are marked with bullets (typically small black
circles).

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 5
Web Technologies Lab Manual

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

Here is how it looks in a browser:


 Coffee
 Milk

Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.

Ordered Lists

An ordered list is also a list of items. The list items are marked with numbers.

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.

<ol>
<li>Coffee</li>
<li>Milk</li>
</ol>

Here is how it looks in a browser:

1. Coffee
2. Milk

Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.

HTML Forms and Input (creating user interface)

HTML Forms are used to select different kinds of user input.

Forms

A form is an area that can contain form elements.

Form elements are elements that allow the user to enter information (like text fields, text area
fields, drop-down menus, radio buttons, checkboxes, etc.) in a form.

A form is defined with the <form> tag.

<form>
<input>
<input>

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 6
Web Technologies Lab Manual

</form>

Input

The most used form tag is the <input> tag. The type of input is specified with the type attribute.
The most commonly used input types are explained below.

Text Fields

Text fields are used when you want the user to type letters, numbers, etc. in a form.
<form>
First name: <input type="text"
name="firstname"> <br>
Last name: <input type="text"
name="lastname"> </form>

How it looks in a browser:

First name:
Last name:

Note that the form itself is not visible. Also note that in most browsers, the width of the text field
is 20 characters by default.

Radio Buttons

Radio Buttons are used when you want the user to select 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 it looks in a browser:

Male
Female

Note that only one option can be chosen.

Checkboxes
Checkboxes are used when you want the user to select one or more options of a limited number
of choices.

<form>
<input type="checkbox"
name="bike"> I have a bike

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 7
Web Technologies Lab Manual

<br>
<input type="checkbox"
name="car"> I have a car
</form>
How it looks in a browser:

I have a bike
I have a car

The Form's Action Attribute and the Submit Button

When the user clicks on the "Submit" button, the content of the form is sent to another file. The
form's action attribute defines the name of the file to send the content to. 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 it looks in a browser:

Submit
Username:

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

Form Tags

Tag Description
<form> Defines a form for user input
<input> Defines an input field
<textarea> Defines a text-area (a multi-line text input control)
<label> Defines a label to a control

<select> Defines a selectable list (a drop-down box)


<optgroup> Defines an option group
<option> Defines an option in the drop-down box
<button> Defines a push button

HTML Images

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 8
Web Technologies Lab Manual

With HTML you can display images in a document.

The Image Tag and the Src Attribute

In HTML, images are defined with the <img> tag.

The <img> tag is empty, which means that it contains attributes only and it has no closing tag.

To display an image on a page, you need to use the src attribute. Src stands for "source". The
value of the src attribute is the URL of the image you want to display on your page.

The syntax of defining an image:

<img src="url">

The URL points to the location where the image is stored. An image named "boat.gif" located in
the directory "images" on "www.w3schools.com" has the URL:
http://www.w3schools.com/images/boat.gif.

The browser puts the image where the image tag occurs in the document. If you put an image tag
between two paragraphs, the browser shows the first paragraph, then the image, and then the
second paragraph.

The Alt Attribute

The alt attribute is used to define an "alternate text" for an image. The value of the alt attribute is
an author-defined text:

<img src="boat.gif" alt="Big Boat">

The "alt" attribute tells the reader what he or she is missing on a page if the browser can't load
images. The browser will then display the alternate text instead of the image. It is a good practice
to include the "alt" attribute for each image on a page, to improve the display and usefulness of
your document for people who have text-only browsers.

Image Tags
Tag Description

<img> Defines an image


<map> Defines an image map
<area> Defines an area inside an image map

HTML Backgrounds

A good background can make a Web site look really great.

Backgrounds

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 9
Web Technologies Lab Manual

The <body> tag has two attributes where you can specify backgrounds. The background can be a
color or an image.

Bgcolor

The bgcolor attribute sets the background to a color. The value of this attribute can be a
hexadecimal number, an RGB value, or a color name.

<body
bgcolor="#000000">
<body
bgcolor="rgb(0,0,0)"
> <body
bgcolor="black">

The lines above all set the background color to black.

Background

The background attribute sets the background to an image. The value of this attribute is the URL
of the image you want to use. If the image is smaller than the browser window, the image will
repeat itself until it fills the entire browser window.

<body background="clouds.gif">
<body background="http://www.w3schools.com/clouds.gif">

The URL can be relative (as in the first line above) or absolute (as in the second line above).

HTML Fonts

The HTML <font> Tag


By using this tag we can create fonts of various styles, and sizes.
Example:
<p>
<font size="2"
face="Verdana"> This is
a paragraph.
</font
> </p>
<p>
<font size="3"
face="Times"> This is
another paragraph.
</font> </p>
Font Attributes
Attribute Example Purpose
Size="number" size="2" Defines the font size

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 10
Web Technologies Lab Manual

Increases the font


Size="+number" size="+1" size
Decreases the font
Size="-number" size="-1" size
Defines the font-
Face="face-name" face="Times" name
color="color-value" color="#eeff00" Defines the font color
color="color-name" color="red" Defines the font color

Exercise 1:
Design the following static web pages required for an online book
store web site. 1) HOME PAGE:
The static home page must contain two frames.
Top frame : Logo and the college name and links to Home page, Login page, Registration page,
Catalogue page and Cart page (the description of these pages will be given below).
Right frame: The pages to the links in the left frame must be loaded here. Initially this
page contains description of the web site.

Web Site Name


Logo
Hom
e Login Registration Catalogue Cart

Description of the Web Site

2) LOGIN PAGE:
This page looks like below:
Web Site Name
Logo
Logi Registratio
Home n n Catalogue Cart

Login :

Password:

Submit Reset

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 11
Web Technologies Lab Manual

3) CATOLOGUE PAGE:
The catalogue page should contain the details of all the books available in the web
site in a table. The details should contain the following:
6. Snap shot of Cover Page.
7. Author Name.
8. Publisher.
9. Price.
10. Add to cart button
Logo Web Site Name

Catalogu
Home Login Registration e Cart

$ 40.5

Book : XML Bible


Author : Winston
Publication : Wiely

$ 63

Book : AI
Author : S.Russel
Publication : Princeton hall
4) CART PAGE:

The cart page contains the details about the books which are added to the cart.
The cart page should look like this:

Web Site Name


Logo
Car
Home Login Registration Catalogu t
e

Book name Price Quantity Amount


Java 2 $35.5 2 $70
XML bible $40.5 1 $40.5
Total amount
- $130.5

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 12
Web Technologies Lab Manual

5) REGISTRATION PAGE:

Createregistration“ form “with the following fields


1) Name (Text field)
2) Password (password field)
3) E-mail id (text field)
4) Phone number (text field)
5) Sex (radio button)
6) Date of birth (3 select boxes)
7) Languages known (check boxes – English, Telugu, Hindi, Tamil)
8) Address (text area)
6. PAYMENT BY CREDIT CARD PAGE

2. CASCADING STYLE SHEETS (CSS)

What is CSS?

CSS stands for Cascading Style Sheets


Styles define how to display HTML elements
Styles are normally stored in Style Sheets
Styles were added to HTML 4.0 to solve a problem
External Style Sheets can save you a lot of work
External Style Sheets are stored in CSS files
Multiple style definitions will cascade into one

Styles Solve a Common Problem

HTML tags were originally designed to define the content of a document. They were supposed to
say "This is a header", "This is a paragraph", "This is a table", by using tags like <h1>, <p>,
<table>, and so on. The layout of the document was supposed to be taken care of by the browser,
without using any formatting tags.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 13
Web Technologies Lab Manual

As the two major browsers - Netscape and Internet Explorer - continued to add new HTML tags
and attributes (like the <font> tag and the color attribute) to the original HTML specification, it
became more and more

difficult to create Web sites where the content of HTML documents was clearly separated from
the document's presentation layout.

To solve this problem, the World Wide Web Consortium (W3C) - the non-profit, standard setting
consortium responsible for standardizing HTML - created STYLES in addition to HTML 4.0.

Both Netscape 4.0 and Internet Explorer 4.0 support Cascading Style Sheets.

CSS Syntax:

The CSS syntax is made up of three parts: a selector, a property and a value:

selector {property: value}

The selector is normally the HTML element/tag you wish to define, the property is the attribute
you wish to change, and each property can take a value. The property and value are separated by
a colon and surrounded by curly braces:

body {color: black}

If the value is multiple words, put quotes around the value:

p {font-family: "sans serif"}

Note: If you wish to specify more than one property, you should separate each property with
a semi-colon. The example below shows how to define a center aligned paragraph, with a red
text color:

p {text-align:center;color:red}

To make the style definitions more readable, you can describe one property on each line, like
this:

p
{
text-align:
center;
color:
black; font-
family:
arial
}
Grouping

You can group selectors. Separate each selector with a comma. In the example below we have

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 14
Web Technologies Lab Manual

grouped all the header elements. Each header element will be green:

h1,h2,h3,h4,h5,h6
{
color: green
}
The class Selector

With the class selector you can define different styles for the same type of HTML element. Say
that you would like to have two types of paragraphs in your document: one right-aligned
paragraph, and one center-aligned paragraph. Here is how you can do it with styles:

p.right {text-align: right}


p.center {text-align: center}

You have to use the class attribute in your HTML document:

<p class="right">
This paragraph will be right-
aligned. </p>
<p class="center">
This paragraph will be center-
aligned. </p>

Note: Only one class attribute can be specified per HTML element! The example below is
wrong:

<p class="right"
class="center"> This is a
paragraph.
</p>

You can also omit the tag name in the selector to define a style that will be used by all HTML
elements that have a certain class. In the example below, all HTML elements with class="center"
will be center-aligned:

.center {text-align: center}

In the code below both the h1 element and the p element have class="center". This means that
both elements will follow the rules in the ".center" selector:

<h1 class="center">
This heading will be center-
aligned </h1>
<p class="center">
This paragraph will also be center-
aligned. </p>

How to Insert a Style Sheet

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 15
Web Technologies Lab Manual

When a browser reads a style sheet, it will format the document according to it. There are three
ways of inserting a style sheet:

External Style Sheet

An external style sheet is ideal when the style is applied to many pages. With an external style
sheet, you can change the look of an entire Web site by changing one file. 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>

The browser will read the style definitions from the file mystyle.css, and format the document
according to it.

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:
hr {color: sienna}
p {margin-left: 20px} body{background-
image:url("images/back40.gif")}

Internal 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 by using the <style> tag, like this:

<head>
<style
type="text/css">
hr {color:
sienna}
p {margin-left: 20px}
body {background-image:
url("images/back40.gif")} </style>
</head>

The browser will now read the style definitions, and format the document according to it.

Note: A browser normally ignores unknown tags. This means that an old browser that does not
support styles, will ignore the <style> tag, but the content of the <style> tag will be displayed on
the page. It is possible to prevent an old browser from displaying the content by hiding it in the
HTML comment element:

<head>
<style
type="text/css">

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 16
Web Technologies Lab Manual

<!--
hr {color: sienna}
p {margin-left: 20px} body{background-
image:url("images/back40.gif")} -->
</style>
</head>

Inline Styles

An inline style loses many of the advantages of style sheets by mixing content with presentation.
Use this method sparingly, such as when a style is to be applied to a single occurrence of an
element.

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>
Multiple Style Sheets(conflicting style sheets)

If some properties have been set for the same selector in different style sheets, the values will be
inherited from the more specific style sheet.

For example, an external style sheet has these properties for the h3 selector:

h3
{
color:
red; text-
align:
left;
font-
size: 8pt
}

And an internal style sheet has these properties for the h3 selector:

h3
{
text-
align:
right;
font-size:
20pt
}

If the page with the internal style sheet also links to the external style sheet the properties for h3

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 17
Web Technologies Lab Manual

will be:

color:
red; text-
align:
right;
font-size:
20pt

The color is inherited from the external style sheet and the text-alignment and the font-size is
replaced by the internal style sheet.

This is the style sheet file (ex1.css):

body {background-color:
yellow} h1 {font-size:
36pt}
h2 {color: blue}
p {margin-left: 50px}

Exercise

Design a web page using CSS (Cascading Style Sheets) which includes the following:

1) Use different font, styles:


In the style definition you define how each selector should work (font, color
etc.). Then, in the body of your pages, you refer to these selectors to activate
the styles.

2) Set a background image for both the page and single elements on the
page. You can define the background image for the page like this:
BODY {background-image:url(myimage.gif);}
3) Control the repetition of the image with the background-repeat property.
As background-repeat: repeat Tiles the image until the entire page is filled, just like an
ordinary background image in plain HTML.
4) Define styles for
links
as
A:lin
k
A:vis
ited
A:act
ive
A:ho
ver
Example:
<style
type="text/css">
A:link {text-

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 18
Web Technologies Lab Manual

decoration: none}
A:visited {text-
decoration: none}
A:active {text-
decoration: none}
A:hover {text-decoration: underline;
color: red;} </style>
5) Work with
layers:
For
exampl
e:
LAYER 1 ON TOP:
<div style="position: relative; font-size:50px; z-
index:2;">LAYER 1</div> <div style="position: relative;
top:-50; left:5; color: red; font-size:80px; z-
index:1">LAYER 2</div>

LAYER 2 ON TOP:
<div style="position: relative; font-size: 50px; z-index:
3;">LAYER 1</div> <div style="position: relative; top:-50;
left:5; color: red; font-size:80px; z-index:4">LAYER
2</div>

6) Add a customized
cursor: Selector
{cursor:value}
For example:

<html>
<head>
<style type="text/css">
.xlink {cursor:crosshair}
.hlink{cursor:help}
</style>
</head>

<body>
<b>
<a href="mypage.htm" class="xlink">CROSS
LINK</a> <br>
<a href="mypage.htm" class="hlink">HELP
LINK</a> </b>
</body>
</html>

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 19
Web Technologies Lab Manual

3.Java Script

Regular Expressions and Patterns in java script


Regular expressions are very powerful tools for performing pattern matches. Regular
expressions in java script are based on PERL You can perform complex tasks that once required
lengthy procedures with just a few lines of code using regular expressions. Regular expressions
are implemented in JavaScript in two ways:

1) Using literal syntax.


2) When you need to dynamically construct the regular expression, via the RegExp () constructor.

The literal syntax looks something like:

var RegularExpression = /pattern/

While the RegExp() constructor method looks like

var RegularExpression = new RegExp("pattern");

The RegExp () method allows you to dynamically construct the search pattern as a string, and is
useful when the pattern is not known ahead of time.
To use regular expressions to validate a string you need to define a pattern string that
represents the search criteria, then use a relevant string method to denote the action (ie: search,
replace etc). Patterns are defined using string literal characters and meta characters. For
example, the following regular expression determines whether a string contains a valid 5-digit
US postal code (for sake or simplicity, other possibilities are not considered):

<script >
function checkpostal ()
{
var re5digit=/^\d{5}$/ //regular expression defining a 5 digit
number if
(document.myform.myinput.value.search(re5digit)==-1) //if
match failed alert("Please enter a valid 5 digit number inside
form")
}
</script>

<form name="myform">
<input type="text" name="myinput" size=15>
<input type="button" onClick="checkpostal()"
value="check"> </form>
Explanation:
var re5digit=/^\d{5}$/

^ indicates the beginning of the string. Using a ^ metacharacter requires that the
match start at the beginning.
\d indicates a digit character and the {5} following it means that there must be 5
consecutive digit characters.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 20
Web Technologies Lab Manual

$ indicates the end of the string. Using a $ metacharacter requires that the match end
at the end of the string.
Translated to English, this pattern states: "Starting at the beginning of the string there must be
nothing other than 5 digits. There must also be nothing following those 5 digits."
Position Matching

Symbol Description
^ Only matches the beginning of a string.
$ Only matches the end of a string.

Character Classes

Symbo
l Description
Match any one character enclosed in the character set. You may use a hyphen to denote
[xyz] range. For
example. /[a-z]/ matches any letter in the alphabet, /[0-9]/ any single digit.

Match any one character not enclosed in the character set. The caret indicates that none of
[^xyz] the
characters
NOTE: the caret used within a character class is not to be confused with the caret that
denotes the
beginning of a string. Negation is only performed within the square brackets.

. (Dot). Match any character except newline .

\w Match any alphanumeric character including the underscore. Equivalent to [a-zA-Z0-9_].

\W Match any single non-word character. Equivalent to [^a-zA-Z0-9_].

\d Match any single digit. Equivalent to [0-9].

\D Match any non-digit. Equivalent to [^0-9].

Repetition

Symbol Description
{x} Match exactly x occurrences of a regular expression.
{x,} Match x or more occurrences of a regular expression.
{x,y} Matches x to y number of occurrences of a regular expression.

? Match zero or one occurrences. Equivalent to {0,1}.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 21
Web Technologies Lab Manual

* Match zero or more occurrences. Equivalent to {0,}.


+ Match one or more occurrences. Equivalent to {1,}.

Pattern Switches (flags)

In addition to the pattern-matching characters, you can use switches to make the match
global or case-insensitive or both: Switches are added to the very end of a regular
expression.

Propert
y Description Example
i Ignore the case of characters. /The/i matches "the" and "The" and "tHe"
Global search for all occurrences of /ain/g matches both "ain"s in "No pain no gain",
g a instead of
pattern just the first.
gi Global search, ignore case. /it/gi matches all "it"s in "It is our IT department

String and Regular Expression methods

The String object has four methods that take regular expressions as arguments. These are
your workhorse methods that allow you to match, search, and replace a string using the
flexibility of regular expressions:

String Methods Using Regular Expressions

Method Description
match( regular expression ) Executes a search for a match within a string based on a regular
expression. It returns an array of information or null if no match
are found.
replace( regular expression, Searches and replaces the regular expression portion (match)
with the
replacement text ) replaced text instead.
split ( string literal or regular Breaks up a string into an array of substrings based on a regular

expression ) expression or fixed string.

Tests for a match in a string. It returns the index of the match, or -1 if


search( regular expression ) not
found. Does NOT support global searches (ie: "g" flag not
supported).

Here are a few examples:


var string1="Peter has 8 dollars and Jane has
15" parsestring1=string1.match(/\d+/g)
//returns the array [8,15] var
string2="(304)434-5454"

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 22
Web Technologies Lab Manual

parsestring2=string2.replace(/[\(\)-]/g, "") //Returns "3044345454"


(removes "(", ")", and "-") var string3="1,2, 3, 4, 5"
parsestring3=string3.split(/\s*,\s*/) //Returns the array ["1","2","3","4","5"]

RegExp methods

Method Description
Tests a string for pattern matches. This method returns a Boolean that indicates whether or
test(string) not the
specified pattern exists within the searched string. This is the most commonly used method
for
validation.

exec(string) Executes a search for a pattern within a string. If the pattern is not found,
exec () returns a null value. If it finds one or more matches it returns an array
of the match results..

Here is a simple example that uses test() to see if a regular expression matches against a certain
string:

var pattern=/php/i
pattern. test("PHP is your friend") //returns true

Examples:

Valid Number

A valid number value should contain only an optional minus sign, followed by digits,
followed by an optional dot (.) to signal decimals, and if it's present, additional digits. A
regular expression to do that would look like this:

var anum=/(^-*\d+$)|(^-*\d+\.\d+$)/

Valid Date Format

A valid short date should consist of a 2-digit month, date separator, 2-digit day, date
separator, and a 4-digit year (e.g. 02/02/2000). It would be nice to allow the user to use any
valid date separator character that your backend database supported such as slashes, dashes
and periods. You want to be sure the user enters the same date separator character for all
occurrences. The following function returns true or false depending on whether the user
input matches this date format:

function checkdateformat(userinput){
var dateformat = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/
return dateformat.test(userinput) //returns true or false depending on userinput
}
E-mail Addresses

E-mail addresses are of the form xxx@yyy where xxx is the specific mailbox (and can

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 23
Web Technologies Lab Manual

contain underscores and periods) and yyy is the domain which can contain a series of suffixes
such as .com.uk.

/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/

\w+ states one or more alphanumeric must be at the start of the name. ([\.-]?\w+)* allows periods
or dashes to be included in the mailbox name with the trailing \w+ ensuring that those characters
can not finish the name. The @ is the mandatory separator.

The domain name can have several .xx or .xyz suffixes such as .com.uk. Once again \w+
ensures that domain starts with an alphanumeric and ([\.-]?\w+)* allows for the dashes and
periods. Finally (\.\w{2,3})+ ensures that there is at least one suffix of between 2 and 3
characters preceded by a period.

Write JavaScript to validate the following fields of the registration page.

4. Name (Name should contains alphabets and the length should not be less than 6
characters).
5. Password (Password should not be less than 6 characters length).
6. E-mail id (should not contain any invalid and must follow the standard pattern
name@domain.com)
4. Phone number (Phone number should contain 10 digits only).

Validation code for the payment by credit card page

if(document.myform.c.value=="") // you must select card type

window.alert("enter card type")

var num1=/\d{4}/ //card number must have exactly four numbers

if(document.myform.tb1.value.search(num1)==-1)

window.alert("sorry,enter 4 numbers in cardnumber1")

var num2=/\d{4}/

if(document.myform.tb2.value.search(num2)==-1)

window.alert("sorry,enter 4 numbers in cardnumber2")

var num3=/\d{4}/

if(document.myform.tb3.value.search(num3)==-1)

window.alert("sorry,enter 4 numbers in cardnumber3")

var num4=/\d{4}/

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 24
Web Technologies Lab Manual

if(document.myform.tb4.value.search(num4)
==-1) window.alert("sorry,enter 4 numbers in
cardnumber4")
if(document.myform.mon.value=="")
window.alert("enter month")
if(document.myform.b.value=="")

window.alert("ente
r year") var
cv2num=/\d{3}/

if(document.myform.c1.value.search(cv2n
um)==-1) window.alert("sorry,enter 3
digits in cv2 number") var vw=/Jga9uSq/
if(document.myform.v.value.search(vw)=
=-1)

window.alert("sorry,enter correct word")

XML

What is XML?

XML stands for EXtensible Markup Language

XML is a markup language much

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 25
Web Technologies Lab Manual

like HTML XML was designed to


describe data
XML tags are not predefined. You must define your own tags
XML uses a Document Type Definition (DTD) or an XML Schema to
describe the data XML with a DTD or XML Schema is designed to be self-
descriptive
XML is a W3C Recommendation

The Main Difference Between XML and HTML

XML was designed to carry data.

XML is not a replacement for HTML.


XML and HTML were designed with different goals:

XML was designed to describe data and to focus on what data is.
HTML was designed to display data and to focus on how data looks.

HTML is about displaying information, while XML is about describing information.

An Example XML Document

XML documents use a self-describing and simple syntax.

<?xml version="1.0" encoding="ISO-


8859-1"?> <note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this
weekend!</body> </note>

The first line in the document - the XML declaration - defines the XML version and the
character encoding used in the document. In this case the document conforms to the 1.0
specification of XML and uses the ISO-8859-1 (Latin-1/West European) character set.

The next line describes the root element of the document (like it was saying: "this document is a
note"):

<note>

The next 4 lines describe 4 child elements of the root (to, from, heading, and body):

<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>

And finally the last line defines the end of the root element:

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 26
Web Technologies Lab Manual

</note>

DTD - The Document Type Definition


This defines the elements that may be included in your document, what attributes these
elements have, and the ordering and nesting of the elements.
The DTD is declared in a DOCTYPE declaration beneath the XML declaration contained
within an XML document:
Inline Definition:

<?xml version="1.0"?>
<!DOCTYPE documentelement
[definition]> External Definition:
<?xml version="1.0"?>
<!DOCTYPE documentelement SYSTEM "documentelement.dtd">

An example of a book store's inline definition


might be: <?xml version="1.0"?>
<!DOCTYPE bookstore [
<!ELEMENT bookstore
(name,topic+)> <!ELEMENT
topic (name,book*)>
<!ELEMENT name
(#PCDATA)> <!ELEMENT
book (title,author)>
<!ELEMENT title
(#CDATA)> <!ELEMENT
author (#CDATA)>
<!ELEMENT isbn
(#PCDATA)> <!ATTLIST
book isbn CDATA "0">
]>
<bookstore>
<name>Mike's
Store</name> <topic>
<name>XML</name
> <book isbn="123-
456-789">
<title>Mike's Guide To DTD's and XML
Schemas<</title> <author>Mike
Jervis</author>
</book>
</topic>
</bookstore>

Using an inline definition is handy when you only have a few documents and they're offline, as
the definition is always in the file. However, if, for example, your DTD defines the XML
protocol used to talk between two separate systems, re-transmitting the DTD with each
document adds an overhead to the communications. Having an external DTD eliminates the

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 27
Web Technologies Lab Manual

need to re-send each time. We could remove the DTD from the document, and place it in a DTD
file on a Web server that's accessible by the two systems:

<?xml version="1.0"?>
<!DOCTYPE bookstore SYSTEM "bookstore.dtd">
<bookstore>
<name>Mike's Store</name>
<topic>
<name>XML</name>
<book isbn="123-456-789">
<title>Mike's Guide To DTD's and XML Schemas<</title>
<author>Mike Jervis</author>
</book>
</topic>
</bookstore>

The file bookstore.dtd would contain the full definition in a plain text file:
<!ELEMENT bookstore (name,topic+)>
<!ELEMENT topic (name,book*)>
<!ELEMENT name
(#PCDATA)>
<!ELEMENT book
(title,author)>
<!ELEMENT title
(#CDATA)> <!ELEMENT
author (#CDATA)>
<!ELEMENT isbn
(#PCDATA)> <!ATTLIST
book isbn CDATA "0">

The lowest level of definition in a DTD is that something is either CDATA or PCDATA:
Character Data, or Parsed Character Data. We can only define an element as text, and with
this limitation, it is not possible, for example, to force an element to be numeric. Attributes
can be forced to a range of defined values, but they can't be forced to be numeric.
So for example, if you stored your applications settings in an XML file, it could be manually
edited so that the windows start coordinates were strings -- and you'd still need to validate this
in your code, rather than have the parser do it for you.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 28
Web Technologies Lab Manual

4. XML

The purpose of an XML Schema is to define the legal building blocks of an XML document, just
like a DTD.
XML Schemas are extensible to future additions XML Schemas are richer and more powerful
than DTDs XML Schemas are written in XML. XML Schemas support data types XML
Schemas support namespaces
One of the greatest strength of XML Schemas is the support for data types.

A Simple XML Document

Look at this simple XML document called "note.xml":

<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

An XML Schema

The following example is an XML Schema file called "note.xsd" that defines the elements of the
XML
document above ("note.xml"):

<?xml version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"">
<xsd:element name="note">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="to" type="xsd:string"/>
<xsd:element name="from" type="xsd:string"/>
<xsd:element name="heading" type="xsd:string"/>
<xsd:element name="body" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>

The note element is a complex type because it contains other elements. The other
elements (to, from, heading, body) are simple types because they do not contain other
elements.
XSD Simple Elements

A simple element is an XML element that can contain only text. It cannot contain any
other elements or attributes.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 29
Web Technologies Lab Manual

The text can be of many different types. It can be one of the types included in the XML Schema
definition (Boolean, string, date, etc.),You can also add restrictions to a data type in order to
limit its content, or you can require the data to match a specific pattern.

The syntax for defining a simple element is:

<xsd:element name="xxx" type="yyy"/>

where xxx is the name of the element and yyy is the data type of the element.

XML Schema has a lot of built-in data types. The most common types are:

xsd:string
xsd:decimal
xsd:integer
xsd:boolean
xsd:date
xsd:time

Example

Here are some XML elements:

<lastname>Refsnes</lastname>
<age>36</age>
<dateborn>1970-

03-27</dateborn>

And here are the corresponding simple element definitions:

<xsd:element name="lastname"
type="xsd:string"/> <xsd:element
name="age" type="xsd:integer"/>
<xsd:element name="dateborn"
type="xsd:date"/>

XSD Attributes

All attributes are declared as simple types.

Simple elements cannot have attributes. If an element has attributes, it is considered to be of a


complex type. But the attribute itself is always declared as a simple type.

The syntax for defining an attribute is:

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 30
Web Technologies Lab Manual

<xsd:attribute name="xxx" type="yyy"/>

where xxx is the name of the attribute and yyy specifies the data type of the attribute.

Example

Here is an XML element with an attribute:

<lastname lang="EN">Smith</lastname>

And here is the corresponding attribute definition:

<xs:attribute name="lang" type="xs:string"/>

Complex elements

A complex element is an XML element that contains other elements and/or attributes.

There are four kinds of complex elements:

empty elements
elements that contain only other
elements elements that contain
only text
elements that contain both other elements and text

Note: Each of these elements may contain attributes as well!

Examples of Complex Elements

A complex XML element, "product", which is empty:

<product pid="1345"/>

A complex XML element, "employee", which contains only other elements:

<employee>
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>

A complex XML element, "food", which contains only text:

<food type="dessert">Ice cream</food>

A complex XML element, "description", which contains both elements and text:

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 31
Web Technologies Lab Manual

<description>
It happened on <date lang="norwegian">03.03.99</date> ....
</description>

Example:
<employee>
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>

The "employee" element can be declared directly by naming the element, like this:
<xsd:element name="employee"> <xsd:complexType>
<xsd:sequence>
<xsd:element name="firstname"
type="xsd:string"/> <xsd:element
name="lastname" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>

the "employee" element can use the specified complex type. Note that the child elements,
"firstname" and "lastname", are surrounded by the <sequence> indicator. This means that the
child elements must appear in the same order as they are declared.
Exercise

Write an XML file which will display the Book information which includes the following:

1) Title of the book 2) Author Name 3) ISBN number 4) Publisher name 5) Edition
6) Price

Write a Document Type Definition (DTD) to validate the above XML file. Display the
XML file as follows.The contents should be displayed in a table. The header of the table
should be in color GREY. And the Author names column should be displayed in one
color and should be capitalized and in bold. Use your own colors for remaining columns.
Use XML schemas XSL and CSS for the above purpose.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 32
Web Technologies Lab Manual

5. Java beans

Creating java beans using netbeans editor

1. Write the SimpleBean code. Put it in a file named SimpleBean.java, in the d irectory of
your choice. Here's the code:

import java.awt.Color;
import
java.beans.XMLDecoder;
import
javax.swing.JLabel;
import
java.io.Serializable;

public class SimpleBean extends


JLabel implements
Serializable {
public SimpleBean()
{ setText( "Hello
world!" ); setOpaque(
true ); setBackground(
Color.RED );
setForeground(
Color.YELLOW );
setVerticalAlignment(
CENTER );
setHorizontalAlignment( CENTER );
}
}
SimpleBean extends the javax.swing.JLabel graphic component and inherits its
properties, which makes the SimpleBean a visual component. SimpleBean also
implements the java.io.Serializable interface. Your bean may implement either the
Serializable or the Externalizable interface.

2. Create a manifest, the JAR file, and the class file SimpleBean.class. Use the Apache
Ant tool to create these files. Apache Ant is a Java-based build tool that enables you to
generate XML-based configurations files as follows:
<?xml version="1.0" encoding="ISO-8859-1"?>

<project default="build">

<dirname property="basedir" file="${ant.file}"/>

<property name="beanname" value="SimpleBean"/>


<property name="jarfile"
value="${basedir}/${beanname}.jar"/>

<target name="build"

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 33
Web Technologies Lab Manual

depends="compile"> <jar
destfile="${jarfile}"
basedir="${basedir}"
includes="*.
class">
<manifest>
<section name="${beanname}.class">
<attribute name="Java-Bean"
value="true"/> </section>
</manifest>
</jar>
</target>

<target
name="compile">
<javac
destdir="${basedir}"
>
<src
location="${basedir}"/
> </javac>
</target>

<target
name="clean">
<delete
file="${jarfile}"
>
<fileset dir="${basedir}"
includes="*.class"/> </delete>
</target>
</project>
It is recommended to save an XML script in the build.xml file, because Ant recognizes
this file name automatically.

3. Load the JAR file. Use the NetBeans IDE GUI Builder to load the jar file as follows:
1. Start NetBeans.
2. From the File menu select "New Project" to create a new application for your
bean. You can use "Open Project" to add your bean to an existing application.
3. Create a new application using the New Project Wizard.
4. Select a newly created project in the List of Projects, expand the Source Packages
node, and select the Default Package element.
5. Click the right mouse button and select New|JFrameForm from the pop-up menu.
6. Select the newly created Form node in the Project Tree. A blank form
opens in the GUI Builder view of an Editor tab.
7. Open the Palette Manager for Swing/AWT components by selecting Palette
Manager in the Tools menu.
8. In the Palette Manager window select the beans components in the Palette tree
and press the "Add from JAR" button.
9. Specify a location for your SimpleBean JAR file and follow the Add
from JAR Wizard instructions.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 34
Web Technologies Lab Manual

10. Select the Palette and Properties options from the Windows menu.
11. Expand the beans group in the Palette window. The SimpleBean object
appears. Drag the SimpleBean object to the GUI Builder panel.

The following figure represents the SimpleBean object loaded in the GUI Builder panel:

4. Inspect Properties and Events. The SimpleBean properties will appear in the
Properties window. For example, you can change a background property by selecting
another color. To preview your form, use the Preview Design button of the GUI Builder
toolbar. To inspect events associated with the SimpleBean object, switch to the Events
tab of the Properties window.

Adding simple properties

To add simple properties to a bean, add appropriate getXXX and setXXX methods (or isXXX
and setXXX methods for a boolean property).

The names of these methods follow specific rules called design patterns. These design pattern-
based method names allow builder tools such as the NetBeans GUI Builder, to provide the
following features:

Discover a bean's properties


Determine the properties' read/write attributes
Determine the properties' types
Locate the appropriate property editor for each property type
Display the properties (usually in the Properties window)
Alter the properties (at design time)

Adding a Title Property

1. Right-click on the Bean Patterns node in the MyBean class hierarchy.


2. Select Add|Property from the pop-up menu.
3. Fill out the New Property Pattern form as shown in the following figure and click OK.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 35
Web Technologies Lab Manual

The following code is automatically generated:

public class MyBean {

/** Creates a new instance of


MyBean */ public MyBean() {
}

/**
* Holds value of
property title. */
private String title;

/**
*Getter for property title.
* @return Value of property title.
*/
public String
getTitle() {
return
this.title;
}

/**
* Setter for property title.
* @param title New value of property title.
*/
public void
setTitle(String title) {

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 36
Web Technologies Lab Manual

this.title = title;
}

Now make your bean visual by extending the JComponent class and implement the
Serializable interface. Then, add the paintComponent method to represent your bean.

import java.awt.Graphics;
import
java.io.Serializable;
import
javax.swing.JComponent;

/**
* Bean with a simple
property "title". */
public class MyBean
extends
JComponent
implements
Serializable
{
private String title;

public String getTitle()


{
return this.title;
}

public void setTitle( String title )


{
this.title = title;
}

protected void paintComponent( Graphics g )


{
g.setColor( getForeground() );

int height =
g.getFontMetrics().getHeight(); if
( this.title != null )
g.drawString(this.title, 0, height );
}
}

Inspecting Properties

Select the MyBean component in the Other Components node in the Inspector window. Now
you can analyze the title property in the Properties window and change it. To change the title
property press the "..." button and enter any string you wish.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 37
Web Technologies Lab Manual

The following figure represents the title property set to the "The title" value.

The NetBeans GUI Builder enables you to restrict the changing of a property value. To restrict
the changing of the title property, right-click the title property in the Bean Patterns node of the
MyBean project. Select Properties from the pop-up menu and the Properties window appears.
Choose one of the following property access types from the Mode combo box:

Read/Write
Read only
Write only

The Read only property has only the get method only, while the Write only property has only
the set method only. The Read/Write type property has both of these methods

Bound properties support the PropertyChangeListener (in the API reference documentation)
class.

Sometimes when a Bean property changes, another object might need to be notified of the
change, and react to the change. Whenever a bound property changes, notification of the change
is sent to interested listeners.

The accessor methods for a bound property are defined in the same way as those for simple
properties. However, you also need to provide the event listener registration methods
forPropertyChangeListener classes and fire a PropertyChangeEvent (in the API reference
documentation) event to the PropertyChangeListener objects by calling their propertyChange
methods
The convenience PropertyChangeSupport (in the API reference documentation) class enables
your bean to implement these methods. Your bean can inherit changes from the
PropertyChangeSupportclass, or use it as an inner class.
In order to listen for property changes, an object must be able to add and remove itself from the
listener list on the bean containing the bound property. It must also be able to respond to the
event notification method that signals a property change.
The PropertyChangeEvent class encapsulates property change information, and is sent from
the property change event source to each object in the property change listener list with the
propertyChange method.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 38
Web Technologies Lab Manual

Implementing Bound Property Support Within a Bean


To implement a bound property in your application, follow these steps:
1. Import the java.beans package. This gives you access to the PropertyChangeSupport
class.
2. Instantiate a PropertyChangeSupport object. This object maintains the property change
listener list and fires property change events. You can also make your class a
PropertyChangeSupport subclass.
3. Implement methods to maintain the property change listener list. Since a
PropertyChangeSupport subclass implements these methods, you merely wrap calls to
the property-change support object's methods.
4. Modify a property's set method to fire a property change event when the property is
changed.
Creating a Bound Property
To create the title property as a bound property for the MyBean component in the NetBeans
GUI Builder, perform the following sequence of operations:
1. Right-click the Bean Patterns node in the MyBean class hierarchy.
2. Select Add|Property from the pop-up menu.
3. Fill the New Property Pattern form as shown on the following figure and click OK.

4. Note that the title property and the multicast event source pattern
PropertyChangeListener were added to the Bean Patterns structure.

You can also modify existing code generated in the previous lesson to convert the title and lines
properties to the bound type as follows (where newly added code is shown in bold):

import java.awt.Graphics;
import
java.beans.PropertyChangeListener
; import
java.beans.PropertyChangeSupport;
import java.io.Serializable;
import javax.swing.JComponent;

/**

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 39
Web Technologies Lab Manual

* Bean with bound


properties. */
public class MyBean
extends
JComponent
implements
Serializable
{
private String title;
private String[] lines = new String[10];

private final PropertyChangeSupport pcs = new PropertyChangeSupport( this );

public String getTitle()


{
return this.title;
}

public void setTitle( String title )


{
String old =
this.title;
this.title = title;
this.pcs.firePropertyChange( "title", old, title );
}

public String[] getLines()


{
return this.lines.clone();
}

public String getLines( int index )


{
return this.lines[index];
}

public void setLines( String[] lines )


{
String[] old =
this.lines;
this.lines = lines;
this.pcs.firePropertyChange( "lines", old, lines );
}

public void setLines( int index, String line )


{
String old =
this.lines[index];
this.lines[index] = line;
this.pcs.fireIndexedPropertyChange( "lines", index, old, lines );
}

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 40
Web Technologies Lab Manual

public void addPropertyChangeListener( PropertyChangeListener listener )


{
this.pcs.addPropertyChangeListener( listener );
}

public void removePropertyChangeListener( PropertyChangeListener listener )


{
this.pcs.removePropertyChangeListener( listener );
}

protected void paintComponent( Graphics g )


{
g.setColor( getForeground() );

int height =
g.getFontMetrics().getHeight();
paintString( g, this.title, height );

if ( this.lines != null )
{
int step = height;
for ( String line : this.lines )
paintString( g, line, height
+= step );
}
}

private void paintString( Graphics g, String str, int height )


{
if ( str != null )
g.drawString( str, 0, height );
}
}
A bean property is constrained if the bean supports the VetoableChangeListener(in the
API reference documentation) and PropertyChangeEvent(in the API reference
documentation) classes, and if the set method for this property throws a
PropertyVetoException(in the API reference documentation).

Constrained properties are more complicated than bound properties because they also
support property change listeners which happen to be vetoers.

The following operations in the setXXX method for the constrained property must be
implemented in this order:

1. Save the old value in case the change is vetoed.


2. Notify listeners of the new proposed value, allowing them to veto the change.
3. If no listener vetoes the change (no exception is thrown), set the property to the new
value.

The accessor methods for a constrained property are defined in the same way as those for simple
properties, with the addition that the setXXX method throws a PropertyVetoException exception.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 41
Web Technologies Lab Manual

The syntax is as follows:

public void
setPropertyName(PropertyType pt)
throws PropertyVetoException
{code}

Handling Vetoes

If a registered listener vetoes a proposed property change by throwing a


PropertyVetoException exception, the source bean with the constrained property is
responsible for the following actions:

Catching exceptions.
Reverting to the old value for the property.
Issuing a new VetoableChangeListener.vetoableChange call to all listeners to report the
reversion.

The VetoableChangeListener class throws a PropertyVetoException and handles the


PropertyChangeEvent event fired by the bean with the constrained property.

The VetoableChangeSupport provides the following operations:

Keeping track of VetoableChangeListener objects.


Issuing the vetoableChange method on all registered
listeners. Catching any vetoes (exceptions) thrown by
listeners.
Informing all listeners of a veto by calling vetoableChange again, but with the old
property value as the proposed "new" value.

Creating a Constrained Property


To create a constrained property, set the appropriate option in the New Property Pattern form
as shown on the following figure.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 42
Web Technologies Lab Manual

Note that the Multicast Source Event Pattern - vetoableChangeListener was added to the
Bean Patterns hierarchy.

You can also modify the existing code generated in the previous lesson to make the title and
lines properties constrained as follows (where newly added code is shown in bold):
import java.io.Serializable;
import
java.beans.PropertyChangeListener;
import
java.beans.PropertyChangeSupport;
import
java.beans.PropertyVetoException;
import
java.beans.VetoableChangeListener;
import
java.beans.VetoableChangeSupport;
import java.awt.Graphics;
import javax.swing.JComponent;

/**
* Bean with constrained
properties. */
public class MyBean
extends
JComponent
implements
Serializable
{
private String title;
private String[] lines = new String[10];
private final PropertyChangeSupport pcs = new PropertyChangeSupport(
this ); private final VetoableChangeSupport vcs = new
VetoableChangeSupport( this );

public String getTitle()


{
return this.title;
}
/**
* This method was modified to throw the PropertyVetoException

* if some vetoable listeners reject the new


title value */
public void setTitle( String
title ) throws
PropertyVetoException
{
String old = this.title;
this.vcs.fireVetoableChange( "title",
old, title ); this.title = title;

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 43
Web Technologies Lab Manual

this.pcs.firePropertyChange( "title", old, title );


}

public String[] getLines()


{
return this.lines.clone();
}

public String getLines( int index )


{
return this.lines[index];
}
/**
* This method throws the PropertyVetoException
* if some vetoable listeners reject the new
lines value */
public void setLines( String[]
lines ) throws
PropertyVetoException
{
String[] old = this.lines;
this.vcs.fireVetoableChange( "lines", old,
lines ); this.lines = lines;
this.pcs.firePropertyChange( "lines", old, lines );
}

public void setLines( int index,


String line ) throws
PropertyVetoException
{
String old = this.lines[index];
this.vcs.fireVetoableChange( "lines",
old, line ); this.lines[index] = line;
this.pcs.fireIndexedPropertyChange( "lines", index, old, line );
}

public void addPropertyChangeListener( PropertyChangeListener listener )


{
this.pcs.addPropertyChangeListener( listener );
}

public void removePropertyChangeListener( PropertyChangeListener listener )


{
this.pcs.removePropertyChangeListener( listener );
}
/**
* Registration of the
VetoableChangeListener */
public void addVetoableChangeListener( VetoableChangeListener listener )
{
this.vcs.addVetoableChangeListener( listener );

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 44
Web Technologies Lab Manual

public void removeVetoableChangeListener( VetoableChangeListener listener )

{
this.vcs.removeVetoableChangeListener( listener );
}

protected void paintComponent( Graphics g )


{
g.setColor( getForeground() );

int height =
g.getFontMetrics().getHeight();
paintString( g, this.title, height );

if ( this.lines != null )
{
int step = height;
for ( String line : this.lines )
paintString( g, line, height
+= step );
}
}
private void paintString( Graphics g, String str, int height )
{
if ( str != null )
g.drawString( str, 0, height );
}
}
An indexed property is an array of properties or objects that supports a range of values and
enables the accessor to specify an element of a property to read or write.
Indexed properties are specified by the following methods:
//Methods to access individual values
public PropertyElement getPropertyName(int index)
public void setPropertyName(int index, PropertyElement element)
and
//Methods to access the entire indexed
property array public PropertyElement[]
getPropertyName()
public void setPropertyName(PropertyElement element[])
Note that the distinction between the get and set methods for indexed properties is subtle. The
get method either has an argument that is the array index of the property, or returns an array.
The set method either has two arguments, namely an integer array index and the property
element object that is being set, or has the entire array as an argument.

Creating an Indexed Property


To create an indexed property for your MyBean component, right-click the Bean Patterns
node and select Add|Indexed Property from the pop-up menu. Set up Non-Index Options as
shown in the following figure.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 45
Web Technologies Lab Manual

The code in the Source window will be changed automatically as follows:

import java.awt.Graphics;
import
java.io.Serializable;
import
javax.swing.JComponent;

/**
* Bean with simple
property 'title'. */
public class MyBean
extends
JComponent
implements
Serializable
{
private String title;

public String getTitle()


{
return this.title;
}

public void setTitle( String title )


{
this.title = title;
}

protected void paintComponent( Graphics g )


{
g.setColor( getForeground() );

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 46
Web Technologies Lab Manual

int height =
g.getFontMetrics().getHeight(); if
( this.title != null )
g.drawString(this.title, 0, height );
}

/**
* Holds value of
property lines. */
private String[] lines;

/**
* Indexed getter for property lines.
* @param index Index of the property.
* @return Value of the property
at index. */
public String getLines(int
index) { return
this.lines[index];
}

/**
* Getter for property lines.
* @return Value of
property lines. */
public String[]
getLines() {
return this.lines;
}

/**
* Indexed setter for property lines.
* @param index Index of the property.
* @param lines New value of the property
at index. */
public void setLines(int index,
String lines) { this.lines[index] =
lines;
}

/**
* Setter for property lines.
* @param lines New value of
property lines. */
public void
setLines(String[] lines) {
this.lines = lines;
}
}
Add the following code to the MyBean.java component to present the user with a list of
choices. You can provide and change these choices at design time. (Newly added code is
shown in bold.)

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 47
Web Technologies Lab Manual

import java.awt.Graphics;
import
java.io.Serializable;
import
javax.swing.JComponent;

/**
* Bean with a simple
property "title" * and an
indexed property "lines". */
public class MyBean
extends
JComponent
implements
Serializable
{
private String title;
private String[] lines = new String[10];

public String getTitle()


{
return this.title;
}

public void setTitle( String title )


{
this.title = title;
}

public String[] getLines()


{
return this.lines.clone();
}
public String getLines( int index )
{
return this.lines[index];
}

public void setLines( String[] lines )


{
this.lines = lines;
}
public void setLines( int index, String line )
{
this.lines[index] = line;
}
protected void paintComponent( Graphics g )
{
g.setColor( getForeground() );

int height =
g.getFontMetrics().getHeight();

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 48
Web Technologies Lab Manual

paintString( g, this.title, height );

if ( this.lines != null )
{
int step = height;
for ( String line : this.lines )
paintString( g, line, height +=
step );
}
}
private void paintString( Graphics g, String str, int height )
{
if ( str != null )
g.drawString( str, 0, height );
}
}

The following figure represents the lines property in the Properties window.

Notice that this property has a null value. To set up an alternative value, press the "..." button.
The form shown in the following figure enables you to add ten items for the lines property list.
First remove the default null items. Then add custom items to the list by entering each item value
into the Item field and pressing the Add button each time.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 49
Web Technologies Lab Manual

Using the NetBeans GUI Builder to Set Events

In the lesson "Using the NetBeans GUI Builder," you learned how to create a MyBean
component, add the yourName property, and design a simple form. Now you will set an event
by which a value entered in the JTextField component is stored in the yourName property.
Use the GUI Builder as follows to set such an event:

1. Left click the MyForm node.


2. Switch to the Connection Mode by clicking the appropriate button on the GUI Builder
toolbar.
3. In the Design Area or Inspector window select the OK button (jButton1). Notice
that the button is highlighted in red when it is selected.
4. In the Inspector window select the myBean1 component.
5. In the Connection wizard's Select Source Event page, select the
action|actionPerformed[jButton1ActionPerformed1] event by expanding the event
type directory nodes, as represented in the following figure.

6. Click the Next button.


7. In the Specify Target Operation page, specify the yourName property in the MyBean
component, and click the Next button.
8. In the Enter Parameters page, specify the target property by selecting the Property radio
button.
9. Press the ellipsis (...) button to display the Select Property dialog box.
10. In the Select Property dialog box select the jTextField component from the Component
combobox and choose the text property from the list that is presented, as shown on the
following figure.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 50
Web Technologies Lab Manual

11. Click the Finish button.


The Source Editor window is now displayed. Since the GUI Builder automatically
generates the code to connect the form's components, the following code will be added to
the MyForm class:
private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{ myBean1.setYourName(jTextField1.getText());
}
Editing Bean Info with the NetBeans BeanInfo Editor
To open the BeanInfo dialog box, expand the appropriate class hierarchy to the bean Patterns
node. Right-click the bean Patterns node and choose BeanInfo Editor from the pop-up menu.
All elements of the selected class that match bean-naming conventions will be displayed at the
left in the BeanInfo Editor dialog box as shown in the following figure:

Select one of the following nodes to view and edit its properties at the right of the dialog box:

BeanInfo
Bean
Properties
Methods
Event Sources

Special symbols (green and red) appear next to the subnode to indicate whether an element will

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 51
Web Technologies Lab Manual

be included or excluded from the BeanInfo class.

If the Get From Introspection option is not selected, the node's subnodes are available for
inclusion in the BeanInfo class. To include all subnodes, right-click a node and choose Include
All. You can also include each element individually by selecting its subnode and setting the
Include in BeanInfo property. If the Get From Introspection option is selected, the setting the
properties of subnodes has no effect in the generated BeanInfo code.

The following attributes are available for the nodes for each bean, property, event sources, and
method:

Name - A name of the selected element as it appears in code.


Preferred - An attribute to specify where this property appears in the Inspector
window under the Properties node.
Expert - An attribute to specify where this property appears in the Inspector window
under the Other Properties node.
Hidden - An attribute to mark an element for tool
use only. Display Name Code - A display name
of the property.

Short Description Code - A short description of the property.


Include in BeanInfo - An attribute to include the selected element in the
BeanInfo class. Bound - An attribute to make the bean property bound.
Constrained - An attribute to make the bean property constrained.
Mode - An attribute to set the property's mode and generate getter and setter
methods. Property Editor Class - An attribute to specify a custom class to act as a
property editor for the property.

6. Apache Tomcat Installation

Tomcat Installation
Location
1. JDK Location

Let the JDK be installed in the directory C:\Java\jdk1.3.0\


Set the following environment variable (using System Properties/Environment)
JAVA_HOME=C:\Java\jdk1.3.0\
2. Tomcat Location

Let Tomcat be installed in the directory: C:\Java\Jakarta\Tomcat\jakarta-tomcat-3.2.3\


Let's call this directory TH (for Tomcat Home)

Set the following environment variable (using System Properties/Environment)

TOMCAT_HOME=C:\Java\Jakarta\Tomcat\jakarta-tomcat-3.2.3\

3.. Start and Stop

To start Tomcat, go to TH/bin and at the command line run startup.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 52
Web Technologies Lab Manual

To stop Tomcat, in the same command window, run shutdown.

To verify that Tomcat is running, in a browser window go to http://localhost:8080/index.html


which will show you a page with Tomcat info and examples.

4.. Directories

TH has a directory named webapps, this is the default directory for your web applications. Put
your .war files in the webapps directory.

2. Deploying Applications Of Servlets Classes

This section will explain how to deploy an application that consists of Servlet classes.

2.1. Creating Classes

Assume that we have:

1. An application in a package named pack1


2. The application consists of one Java class C1.java
3. C1 is a Servlet, i.e. it extends HttpServlet class.
4. C1 is in the pack1 package.
5. Compile C1.java to get C1.class

2.2. Deploying In Default Directory

1. In TH\webapps\ create a directory named ap1


2. In ap1 create a directory named WEB-INF
3. In WEB-INF create a directory named classes
4. In classes create a directory named pack1
5. By now we have the following path: TH\webapps\ap1\WEB-INF\classes\pack1\
6. Copy C1.class into pack1 directory.

2.2.1. Running
To test the Servlet, go to this URL in the browser http://localhost:8080/ap1/servlet/pack1.C1
This will run your Servlet. Notice that the use of the word servlet in the URL's path does not
correspond to an actual directory.

2.2.2. Note
If the Servlet class did not have a package we would have copied it in TH\webapps\ap1\WEB-
INF\classes\ (no pack1 directory), and would run it with the URL
http://localhost:8080/ap1/servlet/C1

2.3. Deploying In Any Directory

2.3.1. Preparing Directories

1. Assume that we want to install the application in a directory named C:\jap1\


2. In C:\jap1\ create a directory named WEB-INF

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 53
Web Technologies Lab Manual

3. In WEB-INF create a directory named classes


4. In classes create a directory named pack1
5. By now we have the following path: C:\jap1\WEB-INF\classes\pack1\
6. Copy C1.class into pack1 directory.

2.3.2. Modifying server.xml

1. Using a text editor, open the file TH\conf\server.xml


2. Find the </ContextManager> tag. (Note: this is an end tag)
3. Directly in the line before it, insert the following:
4. <Context path="/jap1"
5. docBase="c:/jap1"
6. crossContext="false"
7. debug="0"
8. reloadable="true"
> </Context>
9. Save and close the file.
This tells the server to map requests that start with /jap1 (after the server name and port
number) to the directory c:/jap1

2.3.3. Modifying web.xml

1. Using a text editor, create the file: C:\jap1\WEB-INF\web.xml


2. Copy the following text into the file:
3. <?xml version="1.0" encoding="ISO-8859-1"?>
4. <!DOCTYPE web-app
5. PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
6. "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
7.
8. <web-app>
9. <servlet>
10. <servlet-name> localAlias </servlet-name>
11. <servlet-class> pack1.C1 </servlet-class>
12. </servlet>
13. <servlet-mapping>
14. <servlet-name> localAlias </servlet-name>
15. <url-pattern> /MyServet </url-pattern>
16. </servlet-mapping>
</web-app>

17. Save and close the file.


This tells the server to map requests for /MyServlet to pack1.C1 Servlet class.

Note that the value of the <servlet-name> element, which is localAlias, is arbitrary and is not
visible outside the web.xml file.

2.3.4. Running
To test the Servlet, go to this URL in the browser: http://localhost:8080/jap1/MyServlet

This will run your Servlet.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 54
Web Technologies Lab Manual

Java Servlets
Java Servlets
Servlets are Java technology's answer to CGI programming. They are programs that run on a
Web server and build Web pages. Building Web pages on the fly is useful for a number of
reasons:

The Web page is based on data submitted by the user. For example the results pages
from search engines are generated this way, and programs that process orders for e-
commerce sites do this as well.
The data changes frequently. For example, a weather-report or news headlines page might
build the page dynamically, perhaps returning a previously built page if it is still up to date.
The Web page uses information from corporate databases or other such sources. For
example, you would use this for making a Web page at an on-line store that lists current
prices and number of items in stock.
Basic Servlet Structure
Here's the outline of a basic servlet that handles GET requests. GET requests are requests made
by browsers when the user types in a URL on the address line, follows a link from a Web page,
or makes an HTML form that does not specify a METHOD. Servlets can also very easily handle
POST requests, which are generated when someone creates an HTML form that specifies
METHOD="POST".
import
java.io.*;
import
javax.servlet.*;
import javax.servlet.http.*;
public class SomeServlet extends
HttpServlet { public void
doGet(HttpServletRequest request,
HttpServletResponse
response) throws
ServletException, IOException {
// Use "request" to read incoming HTTP headers (e.g. cookies)
// and HTML form data (e.g. data the user entered and submitted)
// Use "response" to specify the HTTP response line and headers
// (e.g. specifying the content type, setting cookies).
PrintWriter out = response.getWriter();
// Use "out" to send content to browser
}
}

To be a servlet, a class should extend HttpServlet and override doGet or doPost (or both),
depending on whether the data is being sent by GET or by POST. These methods take two
arguments: an
HttpServletRequest and an HttpServletResponse. The HttpServletRequest has methods
that let you find out about incoming information such as FORM data, HTTP request headers,
and the like. The HttpServletResponse has methods that lets you specify the HTTP response
line (200, 404, etc.), response headers (Content-Type, Set-Cookie, etc.), and, most importantly,
lets you obtain a PrintWriter used to send output back to the client. you have to import classes
in java.io (for PrintWriter, etc.), javax.servlet (for HttpServlet, etc.), and javax.servlet.http (for
HttpServletRequest and HttpServletResponse). Finally, note that
doGet and doPost are called by the service method, and sometimes you may want to override

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 55
Web Technologies Lab Manual

service directly, e.g. for a servlet that handles both GET and POST request.

Example 1:
A Servlet that Generates HTML
Most servlets generate HTML, not plain text. To do that, you need two additional steps: tell the
browser that you're sending back HTML, and modify the println statements to build a legal Web
page. The first step is done by setting the Content-Type response header. In general, headers can
be set via the setHeader method of HttpServletResponse, but setting the content type is such a
common task that there is also a special setContentType method just for this purpose. Note that
you need to set response headers before actually returning any of the content via the PrintWriter.
Here's an example:
HelloWWW.java
import
java.io.*;
import
javax.servlet.*;
import javax.servlet.http.*;
public class HelloWWW extends
HttpServlet { public void
doGet(HttpServletRequest request,
HttpServletResponse
response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out =
response.getWriter();
out.println(
"<HTML>\n" +
"<HEAD><TITLE>Hello
WWW</TITLE></HEAD>\n" +
"<BODY>\n" +
"<H1>Hello
WWW</H1>\n" +
"</BODY></HTML>
");
}
}

HelloWWW Result

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 56
Web Technologies Lab Manual

Reading Parameters
You can read parameters by using getParameter() method

Example:

String s1= request.getParameter("param1") ;

String s2= request.getParameter("param2") ;


String s3 = request.getParameter("param3") ;

How to acess/read initialization parameters define in web.xml from a servlet


1. Adding Init Parameter Entries in the web.xml file
Init parameters are added between the <init-param></init-param> tags under the
<servlet></servlet> tags in the web.xml file. For example, the following web.xml
entries show the init parameters for the servlet -

The init parameters defined for the example servlet are "userid" and "password".
web.xml for Servlet

<web-app>
--
<! --Initparametersfortheservlet>
------
------
… ….
--------
--- …..
………

<init-param> <param-
name>userid</param-name>
<param-value>1201</param-
value>
</init-
param>
<init-
param>
<param-
name>password</param-name>
<param-value>abcd</param-
value>
</init-
param>
</servlet
>
-------------
-------
</web-app>

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 57
Web Technologies Lab Manual

1. Reading the Init Parameters from the web.xml file

The ServletConfig object provides a handle to the initialization parameters defined in


web.xml. ServletConfig's method: getInitParameter() is used to retrieve the init
parameters. The following code snippet illustrates how to read the init parameters from
the init() and the service() methods of a servlet.

public void init(ServletConfig config) throws


ServletException { String id =
config.getInitParameter("userid");
String pwd = config.getInitParameter("password");
}

or
public void service(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {

String id = getServletConfig().getInitParameter("userid");
String pwd = getServletConfig().getInitParameter("passowrd");
}
To retrieve all the init parameters, use Enumeration and ServletConfig's
getInitParmeterNames(). For example,

public void init(ServletConfig config) throws


ServletException { Enumeration params =
config.getInitParameterNames();

// Print the init parameter names and values


to the console while
(params.hasMoreElements()) {
String name = (String) params.nextElement();
System.out.println("Parameter Name: " + name +
" Value: " + config.getInitParameter(name));
}
}

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 58
Web Technologies Lab Manual

7. State and session tracking with Java servlets

To solve the problem of maintaining persistence across HTTP connections, Netscape


Communications developed a specification for "cookies". Cookies are state objects stored
by a Web browser (or other HTTP client) and can be used by server-side applications to
store and retrieve information. Cookies can be created by servlets (or CGI scripts) and sent
to the browser. For every subsequent request made by the browser, the cookie is sent as
part of the HTTP request. This allows server-side applications to access state information,
without the effort of encoding it in a hyperlink or HTML form. Figure 1 shows an example
transaction between a server-side application and a browser where a cookie is stored and
then returned.

Figure 1. A cookie sent to an HTTP client is returned on subsequent requests.

Storing cookies from a Java servlet

Support for cookies has been included in the Servlet API and provides an extremely easy
interface for storing and retrieving cookies. Cookies are represented by the

javax.servlet.http.Cookie class. The constructor takes two strings as parameters — the name
of the cookie (which is fixed) and the value (which can be changed at a later date).

// Create a new cookie


Cookie myCookie = new Cookie ( "accountID" , "212994234");

Servlets that wish to set cookies must add their cookie to the response sent back to the browser.

HttpServletResponse offers an addCookie(Cookie) method, which can be invoked once or


multiple times to add additional cookies.

public void doGet(HttpServletRequest req, HttpServletResponse res)


{
// Store state information in browser
cookies res.addCookie (new Cookie
("thecounter", "1");

// Additional servlet code would go here.....


Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 59
Web Technologies Lab Manual

Reading cookies from a Java servlet

Accessing stored cookies from a servlet is also easy. Cookies are sent each time a request is
made, so that if a cookie is already stored in the browser, it can be accessed by invoking the
Cookies[] getCookies() method of javax.servlet.http.HttpServletRequest This returns an array of
Cookie objects, or

Null if no cookies are present.

// Get cookie array from


HttpServletRequest Cookie[]
cookieArray = request.getCookies();

// Guard statement to check for missing


cookies if (cookieArray != null)
{
// Print a list of all cookies sent by
browser for (int i =0; i<
cookieArray.length; i++)
{
Cookie c = cookieArray[i];
pout.println ("Name
: " + c.getName());
pout.println
("Value: " +
c.getValue());
}
}
else
pout.println ("No cookies present, or browser does not support cookies");

EXCERCISE

1. Assume four users user1,user2,user3 and user4 having the passwords pwd1,pwd2,pwd3 and
pwd4
respectively. Write a servelet for doing the following. Create a Cookie and ad and passwords to
this Cookie.

Read the user id and passwords entered in the Login form (week1) and
authenticate with the values (user id and passwords ) available in the cookies.
If he is a valid user(i.e., user-name and
password match) you should welcome him by name(user-name) else you should display “ You ar
an authenticated user-parameters“.Usetodo initthis.Store the user-names and passwords in the
web.xml and access them in the servlet by using the getInitParameters() method.

Design a login form that is shown below.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 60
Web Technologies Lab Manual

Store user id and password in web.xml file that is shown below


-----
------
<init-param>
<param-
name>userid</para
m-name> <param-
value>1201</para
m-value>
</i/init-param> <init-param>
<param-
name>password</para
m-name> <param-
value>abcd</param-
value>
</init-param> <init-param>
<param-
name>userid</para
m-name> <param-
value>1202</para
m-value>
</init-param> <init-param>
<param-
name>password</para
m-name> <param-
value>abcd</param-
value>
</init-param>
Retrieve the values I stored in web.xml file and compare them with the values entered in
the login page.

String id=getServletConfig().getInitParameter("userid");
String pwd = getServletConfig().getInitParameter("passowrd");

2. Convert the static web pages of assignments 2 into dynamic web pages using servlets and
cookies. Hint: Users information (user id, password, credit card number) would be stored
in web.xml. Each user should have a separate Shopping Cart.

Implementation:

Login page code

1. // get the user id and password String x=req.getParameter("a1"); String

y=req.getParameter("a2");

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 61
Web Technologies Lab Manual

2. // get the user id and password stored in cookies Cookie[] c=req.getCookies();

String a=c[0].getValue();

String b=c[1].getValue();

3. compare both values for equality if(x.equals(a)&& y.equals(b))

res.sendRedirect("sucess.html");

else

res.sendRedirect("failed.html");

Registration page code


1. get the values entered in the form by an user

String s1=req.getParameter("t1");

String s2=req.getParameter("t2");

2. add the entered values in cookies which are stored in users browser

Cookie c1=new Cookie("m",s1);

Cookie c2=new Cookie("m1",s2);

res.addCookie(c1);

res.addCookie(c2);

similarly the shopping cart options selected by the users can be stored in cookies so that each
user can have separate shopping cart

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 62
Web Technologies Lab Manual

8. JDBC

What is JDBC?
JDBC stands for "Java DataBase Connectivity". It is an API (Application Programming
Interface) which consists of a set of Java classes, interfaces and exceptions and a
specification to which both JDBC driver vendors and JDBC developers (like you) adhere
when developing applications.

Why use JDBC?


JDBC is there only to help you (a Java developer) develop data access applications without
having to learn and use proprietary APIs provided by different RDBMS vendors. You just
have to learn JDBC and then you can be sure that you'll be able to develop data access
applications which can access different RDBMS

using different JDBC drivers

To use a JDBC driver, simply use:

Class.forName("<driver name>")

For example:

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver ");
}
catch (ClassNotFoundException e)
{
System.err.println("Couldn’t find); driver"
}

The basic steps required in all Java programs to handle JDBC.


Step 1: Loading Drivers

First, you have to load the appropriate driver. You can use one driver from the available four.
However, the JDBC-ODBC driver is the most preferred among developers. In order to load the
driver, you have to give the following syntax:

Class.ForName("sun.jdbc.odbc.JdbcOdbcDriver");

Step 2: Making a Connection

The getConnection() method of the Driver Manager class is called to obtain the Connection
object. The syntax looks like this:

Connection conn = DriverManager.getConnection("jdbc:odbc:<DSN NAME>");

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 63
Web Technologies Lab Manual

Here, note that getConnection() is a static method, meaning it should be accessed along
with the class associated with the method. You have to give the Data Source Name as a
parameter to this method. (

Step 3: Creating JDBC Statements

A Statement object is what sends your SQL Query to the Database Management System. You
simply create a statement object and then execute it. It takes an instance of active connection to
create a statement object. We have to use our Connection object "conn" here to create the
Statement object "stmt". The code looks like this:

Statement stmt = conn.createStatement();

Step 4: Executing the Statement

In order to execute the query, you have to obtain the Result Set object (similar to Record Set in
Visual Basic) and a call to the executeQuery() method of the Statement interface. You have to
pass a SQL query like select * from students as a parameter to the executeQuery() method. If
your table name is different, you have to substitute that name in place of students. Actually, the
RecordSet object contains both the data returned by the query and the methods for data retrieval.

The code for the above step looks like this:

ResultSet rs = stmt.executeQuery("select * from students");

If you want to select only the name field, you have to issue a SQL command like Select Name
from Student. The executeUpdate() method is called whenever there is a delete or an update
operation.

Step 5: Looping Through the ResultSet

The ResultSet object contains rows of data that is parsed using the next() method, such as
rs.next(). We use the getXXX() method of the appropriate type to retrieve the value in each
field. For example, if your first field name is ID, which accepts Number values, then the
getInt() method should be used. In the same way, if the second field Name accepts integer
String values, then the getString() method should be used, like the code given below:

System.out.println(rs.getInt("ID"));

Step 6: Closing the Connection and Statement Objects.


After performing all the above steps, you have to close the Connection and RecordSet objects
appropriately by calling the close() method. For example, in our code above, we will close the
object as conn.close()and statement object as stmt.close().

How to Create a Data Source Name

Follow these steps to create a Data Source Name in Windows

Open ODBC 32-bit Icon from the control panel. (Start

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 64
Web Technologies Lab Manual

| Settings) Click on the Add button and select


Microsoft Access Driver. Select the appropriate driver
if you are using other databases.
Enter a name as Data Source Name and browse for your database by clicking the
Select button. You can also write a short description, but this is optional.
Finally, click on the Finish button.

Example:

Here is a small example of how to retrieve student data that is stored in a database
table.The table contains student name, roll number,branch.

<%@page

import="java.sql.*"%>

<%String

driver="jdbc:odbc:dsn1";

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con=null;

Statement s=null;

ResultSet rs=null;

try{

con=DriverManager.getConnection(driver);

s=con.createStatement();

catch(Exception e)

out.print("error");

}
rs=s.executeQuery("select * from student");%>
<html><body>
<h2 ALIGN="CENTER">STUDENT TABLE</h2>
<table border=5 align="center"> <tr><td><b>NAME</b>
</td>

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 65
Web Technologies Lab Manual

<td><b>BRANCH</b></td><td><b>ROLLNUMBER</b></td>
</tr></B>
<%while(rs.next())
{%>
<tr></td><td><%=rs.getString("NAME")%>
</td><td><%=rs.getString("BRANCH")%>
</td><td><%=rs.getInt("ROLLNUMBER")%></td></tr>
<%}%>
</table>
</body>
</html>
Exercise:
Write a java servlet which does the following job:
Insert the details of the 3 or 4 users who register with the web site by using
registration form. Authenticate the user when he submits the login form using the user
name and password from the database
Implementation of above program

1. create a table with the

following fields USERNAME

USERPSWD

2. Create a registration form that is similar to the shown below

Registration form:

3. Create a login form


Login Form:

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 66
Web Technologies Lab Manual

4. The java code for the sign in button of login page shown above:

import
java.io.*;
import
java.sql.*;
import
javax.servlet.*;
import javax.servlet.http.*;
public class AuthenticateServlet extends GenericServlet
{
Connection con;
public void init(ServletConfig config)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:studentdsn","abc","abc");
}
catch(Exception e)
{
e.printStackTrace();
}
}

public void service(ServletRequest req,ServletResponse res) throws


ServletException,IOException
{
Statement
st=null;
ResultSet
rs=null;

String
user=req.getParameter("usrname");
String
pwd=req.getParameter("password"
); res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");

out.println("<body
bgcolor=skyblue>"); try
{
st=con.createStatement();
String sql="select * from users where USERNAME='"+user+"' and
USERPSWD='"+pwd+"' "; rs=st.executeQuery(sql);
if(rs.next())
out.println("<h2>welcome to"+user+" login
page</h2>"); else

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 67
Web Technologies Lab Manual

{
out.println("invalid user/password");
out.println("<a href=login.html>login
again</a>");
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
if(rs!=
null)
rs.clo
se( );

if(st!=
null)
st.clo
se( );
}

catch(Exception e)
{
e.printStackTrace();
}
}
out.println("</body>");
out.println("</html>");
out.close();
}
public void destroy()
{
try
{
if(con!=null)
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 68
Web Technologies Lab Manual

9. JSP
JSP Overview
Java Server Pages (JSP) is a technology that lets you mix regular, static HTML with
dynamically-generated HTML. Many Web pages that are built by CGI programs are mostly
static, with the dynamic part limited to a few small locations. But most CGI variations,
including servlets, make you generate the entire page via your program, even though most of it
is always the same. JSP lets you create the two parts separately. Here's an example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0


Transitional//EN"> <HTML>
<HEAD><TITLE>Welcome to Our
Store</TITLE></HEAD> <BODY>
<H1>Welcome to Our
Store</H1>
<SMALL>Welcome,
<!-- User name is "New User" for first-time visitors -->
<% out.println(Utils.getUserNameFromCookie(request)); %>
To access your account settings, click
<A HREF="Account-
Settings.html">here.</A></SMALL> <P>
Regular HTML for all the rest of the on-line store's Webpage.
</BODY>
</HTML>

1 JSP Expressions

A JSP expression is used to insert Java values directly into the output. It has the
following form: <%= Java Expression %>
The Java expression is evaluated, converted to a string, and inserted in the page. This
evaluation is performed at run-time (when the page is requested), and thus has full
access to information about the request. For example, the following shows the date/time
that the page was requested:
Current time: <%= new java.util.Date() %>

2 JSP Scriptlets

If you want to do something more complex than insert a simple expression, JSP scriptlets let
you insert arbitrary code into the servlet method that will be built to generate the page. Scriptlets
have the following form: <% Java Code %>
example
<%
String queryData =
request.getQueryString();
out.println("Attached GET data: " +
queryData); %>
Note that code inside a scriptlet gets inserted exactly as written, and any static HTML (template
text) before or after a scriptlet gets converted to print statements. This means that scriptlets need
not contain complete Java

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 69
Web Technologies Lab Manual

statements, and blocks left open can affect the static HTML outside of the scriptlets. For
example, the following JSP fragment, containing mixed template text and scriptlets
<% if (Math.random() <
0.5) { %> Have a
<B>nice</B> day!
<% } else { %>
Have a
<B>lousy</B> day!
<% } %>
will get converted to
something like: if
(Math.random() < 0.5) {
out.println("Have a <B>nice</B> day!");
} else {
out.println("Have a <B>lousy</B> day!");
}
If you want to use the characters "%>" inside a scriptlet, enter "%\>" instead. Finally, note
that the XML equivalent of <% Code %> is
<jsp:scri
ptlet>
Code
</jsp:scri
ptlet>

JSP Declarations

A JSP declaration lets you define methods or fields that get inserted into the main body of
the servlet class (outside of the service method processing the request). It has the following
form:
<%! Java Code %>
Since declarations do not generate any output, they are normally used in conjunction with JSP
expressions or scriptlets. For example, here is a JSP fragment that prints out the number of times
the current page has been requested since the server booted (or the servlet class was changed
and reloaded):
<%! private int accessCount =
0; %> Accesses to page since
server reboot: <%=
++accessCount %>
As with scriptlets, if you want to use the characters "%>", enter "%\>" instead. Finally,
note that the XML equivalent of <%! Code %> is
<jsp:declara
tion> Code
</jsp:declar
ation>
JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the
following form: <%@ directive attribute="value" %>
However, you can also combine multiple attribute settings for a single
directive, as follows: <%@ directive attribute1="value1"

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 70
Web Technologies Lab Manual

attribute2="value2"
...
attributeN="valueN" %>
There are two main types of directive: page, which lets you do things like import classes,
customize the servlet superclass, and the like; and include, which lets you insert a file into the
servlet class at the time the JSP file is translated into a servlet.

1. The JSP page Directive

The page directive lets you define one or more of the following case-sensitive attributes:
import="package.class" or import="package.class1,...,package.classN". This lets you
specify what packages should be imported. For example:
<%@ page import="java.util.*" %>
The import attribute is the only one that is allowed to appear
multiple times. contentType="MIME-Type" or
contentType="MIME-Type; charset=Character-Set"
This specifies the MIME type of the output. The default is text/html. For
example, the directive <%@ page contentType="text/plain" %>

has the same effect as the scriptlet


<% response.setContentType("text/plain"); %>
session="true|false". A value of true (the default) indicates that the predefined variable
session (of type HttpSession) should be bound to the existing session if one exists,
otherwise a new session should be created and bound to it. A value of false indicates that
no sessions will be used, and attempts to access the variable session will result in errors
at the time the JSP page is translated into a servlet.

2 The JSP include Directive

This directive lets you include files at the time the JSP page is translated into a servlet. The
directive looks like this:
<%@ include file="relative url" %>
The URL specified is normally interpreted relative to the JSP page that refers to it, but, as with
relative URLs in general, you can tell the system to interpret the URL relative to the home
directory of the Web server by starting the URL with a forward slash. The contents of the
included file are parsed as regular JSP text, and thus can include static HTML, scripting
elements, directives, and actions.
To simplify code in JSP expressions and scriptlets, you are supplied with eight
automatically defined variables, sometimes called implicit objects. The available variables
are request, response, out, session, application, config, pageContext, and page.

JSP implicit objects

1 request

This is the HttpServletRequest associated with the request, and lets you look at the request
parameters (via getParameter), the request type (GET, POST, HEAD, etc.), and the incoming
HTTP headers (cookies, Referer, etc.). Strictly speaking, request is allowed to be a subclass of
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 71
Web Technologies Lab Manual

ServletRequest other than HttpServletRequest, if the protocol in the request is something other
than HTTP. This is almost never done in practice.

2 response

This is the HttpServletResponse associated with the response to the client. Note that, since the
output stream (see out below) is buffered, it is legal to set HTTP status codes and response
headers, even though this is not permitted in regular servlets once any output has been sent to the
client.

3 out

This is the PrintWriter used to send output to the client. However, in order to make the response
object (see the previous section) useful, this is a buffered version of PrintWriter called
JspWriter. Note that you can adjust the buffer size, or even turn buffering off, through use of the
buffer attribute of the page directive. Also note that out is used almost exclusively in scriptlets,
since JSP expressions automatically get placed in the output stream, and thus rarely need to refer
to out explicitly.

4 session

This is the HttpSession object associated with the request. Recall that sessions are created
automatically, so this variable is bound even if there was no incoming session reference. The
one exception is if you use the session attribute of the page directive to turn sessions off, in
which case attempts to reference the session variable cause errors at the time the JSP page is
translated into a servlet.

5 application

This is the ServletContext as obtained via getServletConfig().getContext().

6 config
This is the ServletConfig object for this page.

7 pageContext

JSP introduced a new class called PageContext to encapsulate use of server-specific features like
higher performance JspWriters. The idea is that, if you access them through this class rather than
directly, your code will still run on "regular" servlet/JSP engines.

8 page

This is simply a synonym for this, and is not very useful in Java. It was created as a
placeholder for the time when the scripting language could be something other than Java.
Comments and Character Quoting Conventions
There are a small number of special constructs you can use in various cases to insert comments
or characters that would otherwise be treated specially. Here's a summary:

Syntax
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 72
Web Technologies Lab Manual

<%-- Purpose
comm
ent -- A JSP comment. Ignored by JSP-to-scriptlet translator. Any embedded
%> JSP scripting elements, directives, or actions are ignored.
<!-- An HTML comment. Passed through to resultant HTML. Any embedded
comme JSP scripting elements, directives, or actions are executed normally.
nt -->
Used in template text (static HTML) where you really want "<%".
<\% Used in scripting elements where you really want "%>".
%\> A single quote in an attribute that uses single quotes. Remember, however, that
\' you can use either single or double quotes, and the other type of quote will then
be a regular character.
\" A double quote in an attribute that uses double quotes. Remember, however, that
you can use either single or double quotes, and the other type of quote will then be
%\> a regular character.
<\% %> in an
attribute. <%
in an
attribute.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 73
Web Technologies Lab Manual

Overview of JSTL SQL Tags

The JSTL SQL tag library provides various tags for accessing a database, creating
database tables, and updating, deleting, and querying a database. The syntax for including
the JSTL SQL tag library in a JSP page is the taglib directive:

<%@ taglib prefix="sql" uri=" http://java.sun.com/jsp/jstl/sql" %>

Table shows JSTL SQL's different tags. All of the attributes are of type
java.lang.String. Attributes are not required unless specified to be required in

Table 1.

Tag Name Description Attributes


var(required)-Scoped
Query variable
for the query result.

scope-Scope of variable.
Runs a SQL query.
The SQL query may be sql-SQL query statement
specified in the sql attribute
or dataSource-Datasource
in the query element. associated with the query.

startRow-Specifies the start


row of the result returned by
the query. The defa
which is also the index of the
start row of the original
result
set.

maxRows-The maximum
number of rows in the result
set. The default includes all
the rows.
Update Runs a SQL statement. The var-Scoped variable for the
SQL statement may be result of the SQL statement
specified in the sql attribute
or which is the update count of
the update element. The SQL the UPDATE, DELETE,
statement may be a
CREATE, INSERT statement.
UPDATE, INSERT, or
DELETE statement.
scope-Scope of variable.
sql-SQL statement which
may
be a CREATE, UPDATE,
INSERT, or DELETE
statement.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 74
Web Technologies Lab Manual

dataSource-Datasource
associated with the update
statement.
Param Specifies a parameter for a value-Parameter value
SQL statement.
dateParam Specifies a java.util.Date value-Parameter value for
DATE, TIME, or
parameter. TIMESTAMP
database data type.

type-“date” “time” or
“timestamp”
setDataSource Creates a datasource for a var-Scoped variable for
JSP page. datasource.

scope-Scope ofvariable.

dataSource-Datasource. A
JNDI datasource or a JDBC
parameters String.

Driver-JDBC driver class.

url-Database URL

user-Username

password-Password

Querying a Database Table

Now you'll see how to query the database table and display the results in an HTML table.

1. Add the taglib directives for the SQL taglib and the JSTL Core taglib to the JSP page.

<%@ taglib prefix="sql"


uri="http://java.sun.com/jsp/jstl/sql" %> <%@
taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core" %>

2. Also add a setDataSource tag for obtaining a connection with the database.
3. Add a sql:query tag to query the database.
4. In the sql:query tag specify the var attribute, which is a required attribute. The var
attribute is returned by the Query tag. Specify the SQL query in the sql attribute.

This adds the sql:query tag to the JSP page.

<sql:query var="catalog" sql="SELECT *


FROM CATALOG"> </sql:query>

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 75
Web Technologies Lab Manual

5. Add a <table> to display the result set of the Query tag. Add the table headers. A
row shall be added corresponding to each row in the result set. Add the JSTL 1.1
Core tag c:forEach to the <table> element.The var attribute of the c:forEach tag
specifies the variable corresponding to a row in the result set. The items attribute
specifies the EL binding to iterate over the rows in the result set returned by the
Query tag. The c:forEach tag in the catalogQuery.jsp JSP is:
6. <c:forEach var="journal" items="${catalog.rows}">

</c:forEach>

7. Output the values corresponding to each column in a row to the JSP table. The JSP
table values are added with the c:out tag. Add a c:out tag for each column. Specify
the EL expression to bind a column value in the value attribute. The journal is the
variable corresponding to a row in the result set. You obtain the column values
binding with the column names in the result set. For example, the EL expression to
bind the CatalogId column is ${journal.CatalogId}.
<tr>
<td><c:out
value="${journal.CatalogId}"/></t
d> </tr>
Similarly add c:out tags for the other columns in the result set. Now, the result set you
obtained with the Query tag is displayed in a HTML table.

Updating /inserting/deleting a Database Table

Follow these steps to update a database table row:

1. As in the previous sections, add taglib directives for the JSTL, SQL, and JSTL Core
tag libraries.
2. Set the datasource for the JSP page with the setDataSource tag.
3. Add a sql:update tag to run a UPDATE SQL statement. Add the
UPDATE/DELETE/INSERT SQL statement in the sql attribute of the sql:update
tag.

<sql:update sql="UPDATE CATALOG SET Title=?, Author=? WHERE


CatalogId=?">
</sql:update>

4. The SQL statement has placeholders for specifying IN

parameters for the UPDATE statement.

5. Specify the values for the IN parameters in the SQL statement with the sql: param
tags. Title, Author, and Catalog Id are IN parameters in the UPDATE statement.
Set a parameter value with the value attribute in the sql:param tag.

<sql:param value="Hibernate: The

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 76
Web Technologies Lab Manual

Definitive Guide"/> <sql:param


value="Elliott, James"/>
<sql: param value="catalog2"/>

Examples :

Setting a datasource

<sql:setDataSource
var="example"
driver="
sun.jdbc.odbc.JdbcOdbcDriv
er " url="
jdbc:odbc:studentdsn "
/>

Creation of database table


<sql:update var="newTable"
dataSource="${example}"> create table
mytable (
nameid int
primary key,
name
varchar(80)
)
</sql:update>

Inserting three rows into table


<sql:update var="updateCount"
dataSource="${example}"> INSERT INTO
mytable VALUES (1,'Paul Oakenfold')
</sql:update>
<sql:update var="updateCount"
dataSource="${example}"> INSERT INTO
mytable VALUES (2,'Timo Maas')
</sql:update>
<sql:update var="updateCount"
dataSource="${example}"> INSERT INTO
mytable VALUES (3,'Paul Adam')
</sql:update>

Selecting data from a table:


<sql:query
var="mydata">
SELECT *
FROM mytable
</sql:query>

Displaying data in an HTML table

<table border="1">

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 77
Web Technologies Lab Manual

<%-- Get the column names for the header of the


table --%> <c:forEach var="columnName"
items="${mydata.columnNames}">
<th><c:out
value="${columnName}"/></th
> </c:forEach>

<%-- Get the value of each column while iterating


over rows --%> <c:forEach var="row" items="${
mydata.rows}">
<tr>
<c:forEach var="column"
items="${row}"> <td><c:out
value="${column.value}"/></t
d>
</c:forEach>

</tr>
</c:forEach>
</table>

Updating first row in table

<sql:update var="updateCount" dataSource="${example}">


UPDATE mytable SET name=? <sql:param value="Scott Tiger"/>
WHERE nameid=1 </sql:update>
<%-- The Value for sql:param can be obtained from the JSP parameters --%>

Deleting second row from table


<sql:update var="updateCount"
dataSource="${example}"> DELETE
FROM mytable WHERE nameid=2
</sql:update>
<sql:query var=" mydata "
dataSource="${example}"> SELECT *
FROM mytable
</sql:query>
Deleting a table
<sql:update var="newTable"
dataSource="${example}"> drop table
mytable
</sql:update>

EXCERCISE
1. Write a JSP which does the following job:
Insert the details of the 3 or 4 users who register with the web site by using
registration form. Authenticate the user when he submits the login form using the user
name and password from the database
2. Create tables in the database which contain the details of items (books in our case like
Book name , Price, Quantity, Amount )) of each category. Modify your catalogue page
(week 2)in such a way that you should connect to the database and extract data from the

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 78
Web Technologies Lab Manual

tables and display them in the catalogue page using JDBC.


3. Redo the previous task using JSP by converting the static web pages of assignments 2 into
dynamic web pages. Create a database with user information and books information. The
books catalogue should be dynamically loaded from the database. Follow the MVC
architecture while doing the website.
Implementation of above programs
1. Create a table with the following fields USERNAME USERPSWD

2. Create a registration form that is similar to the shown below


Registration form(reg.jsp)

3. Create a login form


Login Form(login.jsp)

Follow the steps given the section of Overview of JSTL SQL Tags for implementation
above JSP pages.

Hint:
Use sql:update action with insert statement in reg.jsp page Use sql:query action in login.jsp
age.

Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 79

Você também pode gostar