Escolar Documentos
Profissional Documentos
Cultura Documentos
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.
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
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
<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.
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
Note that you need an exclamation point after the opening bracket, but not before the closing
bracket.
HTML Links
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 <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:
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 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.
The name attribute is used to create a named anchor. The name of the anchor can be any text you
care to use.
…… …………..
…………..
</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.
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 4
Web Technologies Lab Manual
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)
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
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>
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>
1. Coffee
2. Milk
Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.
Forms
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.
<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>
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
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
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>
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
HTML Images
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 8
Web Technologies Lab Manual
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.
<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 is used to define an "alternate text" for an image. The value of the alt attribute is
an author-defined text:
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
HTML Backgrounds
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">
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
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 10
Web Technologies Lab Manual
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.
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
$ 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:
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 12
Web Technologies Lab Manual
5) REGISTRATION PAGE:
What is CSS?
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:
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:
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 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:
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>
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:
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")}
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:
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.
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:
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
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.
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.
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 21
Web Technologies Lab Manual
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
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:
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
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 22
Web Technologies Lab Manual
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+$)/
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.
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).
if(document.myform.tb1.value.search(num1)==-1)
var num2=/\d{4}/
if(document.myform.tb2.value.search(num2)==-1)
var num3=/\d{4}/
if(document.myform.tb3.value.search(num3)==-1)
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)
XML
What is XML?
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 25
Web Technologies Lab Manual
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.
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>
<?xml version="1.0"?>
<!DOCTYPE documentelement
[definition]> External Definition:
<?xml version="1.0"?>
<!DOCTYPE documentelement SYSTEM "documentelement.dtd">
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.
<?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.
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
<lastname>Refsnes</lastname>
<age>36</age>
<dateborn>1970-
03-27</dateborn>
<xsd:element name="lastname"
type="xsd:string"/> <xsd:element
name="age" type="xsd:integer"/>
<xsd:element name="dateborn"
type="xsd:date"/>
XSD Attributes
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 30
Web Technologies Lab Manual
where xxx is the name of the attribute and yyy specifies the data type of the attribute.
Example
<lastname lang="EN">Smith</lastname>
Complex elements
A complex element is an XML element that contains other elements and/or attributes.
empty elements
elements that contain only other
elements elements that contain
only text
elements that contain both other elements and text
<product pid="1345"/>
<employee>
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>
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
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;
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">
<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.
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:
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 35
Web Technologies Lab Manual
/**
* 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;
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
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
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 40
Web Technologies Lab Manual
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 );
}
}
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:
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
public void
setPropertyName(PropertyType pt)
throws PropertyVetoException
{code}
Handling Vetoes
Catching exceptions.
Reverting to the old value for the property.
Issuing a new VetoableChangeListener.vetoableChange call to all listeners to report the
reversion.
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 );
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 43
Web Technologies Lab Manual
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 44
Web Technologies Lab Manual
{
this.vcs.removeVetoableChangeListener( listener );
}
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.
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 45
Web Technologies Lab Manual
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;
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];
int height =
g.getFontMetrics().getHeight();
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 48
Web Technologies Lab Manual
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
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:
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 50
Web Technologies Lab Manual
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
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:
Tomcat Installation
Location
1. JDK Location
TOMCAT_HOME=C:\Java\Jakarta\Tomcat\jakarta-tomcat-3.2.3\
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 52
Web Technologies Lab Manual
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.
This section will explain how to deploy an application that consists of Servlet classes.
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
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 53
Web Technologies Lab Manual
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
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:
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
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,
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 58
Web Technologies Lab Manual
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).
Servlets that wish to set cookies must add their cookie to the response sent back to the browser.
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
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.
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 60
Web Technologies Lab Manual
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:
y=req.getParameter("a2");
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 61
Web Technologies Lab Manual
String a=c[0].getValue();
String b=c[1].getValue();
res.sendRedirect("sucess.html");
else
res.sendRedirect("failed.html");
String s1=req.getParameter("t1");
String s2=req.getParameter("t2");
2. add the entered values in cookies which are stored in users browser
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.
Class.forName("<driver name>")
For example:
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver ");
}
catch (ClassNotFoundException e)
{
System.err.println("Couldn’t find); driver"
}
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");
The getConnection() method of the Driver Manager class is called to obtain the Connection
object. The syntax looks like this:
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. (
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:
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.
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.
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"));
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 64
Web Technologies Lab Manual
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
USERPSWD
Registration 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();
}
}
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:
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.
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" %>
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.
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
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
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:
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.
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.
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.
url-Database URL
user-Username
password-Password
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.
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.
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.
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.
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.
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 76
Web Technologies Lab Manual
Examples :
Setting a datasource
<sql:setDataSource
var="example"
driver="
sun.jdbc.odbc.JdbcOdbcDriv
er " url="
jdbc:odbc:studentdsn "
/>
<table border="1">
Shri Vishnu Engineering College for Women (Autonomous)/ Dept. of CSE Page 77
Web Technologies Lab Manual
</tr>
</c:forEach>
</table>
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
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