Sunteți pe pagina 1din 66

MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

5.1 HYPER TEXT MARKUP LANGUAGE (HTML)

HTML (Hypertext Markup Language) is used to create document on the World


Wide Web. It is simply a collection of certain key words called „Tags‟ that are helpful in writing the
document to be displayed using a browser on Internet. It is a platform independent language that can
be used on any platform such as Windows, Linux, Macintosh, and so on. To display a document in
web it is essential to mark-up the different elements (headings, paragraphs, tables, and so on) of the
document with the HTML tags. To view a mark-up document, user has to open the document in a
browser. A browser understands and interpret the HTML tags, identifies the structure of the
document (which part are which) and makes decision about presentation (how the parts look) of the
document.

5.1.1 CREATING A HTML DOCUMENT

The essential tags that are required to create a HTML document are:
 <HTML>.............</HTML>
 <HEAD>.............</HEAD>
 <BODY>.............</BODY>

5.1.1.1 HTML Tag <HTML>

The <HTML> tag encloses all other HTML tags and associated text within your
document. It is an optional tag. You can create an HTML document that omits these tags, and your
browser can still read it and display it. But it is always a good form to include the start and stop tags.
The format is:

<HTML>
Your Title and Document (contains text with HTML tags) goes here
</HTML>

Most HTML tags have two parts, an opening tag and closing tag. The closing tag is the same as the
opening tag, except for the slash.

5.1.1.2 HEAD Tag <HEAD>

HEAD tag comes after the HTML start tag. It contains TITLE tag to give the document a
title that displays on the browsers title bar at the top.The Format is:

Dept.of Computer Science And Applications, SJCET, Palai Page 260


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

<HEAD>
<TITLE>
Your title goes here
</TITLE>
</HEAD>

5.1.1.3 BODY Tag <BODY>

The BODY tag contains all the text and graphics of the document with all the HTML
tags that are used for control and formatting of the page.The Format is:

<BODY>
Your Document goes here
</BODY>

An HTML document, web page can be created using a text editor,Notepad or WordPad. All the
HTML documents should have the extension .htm or .html. It require a web browser like Internet
Explorer or Netscape Navigator/Communicator to view the document.Some of the attributes used
with body tag are given below:

BGCOLOR: used to set the background color for the document


TEXT: used to set the color of the text of the document
LEFTMARGIN: set the left hand margin of the document
TOPMARGIN: set the left hand margin of the document
BACKGROUND: It is used to point to an image file (the files with an extension .gif, .jpeg) that will
be used as the background of the document.

5.1.2 CLASSIFICATION OF TAGS

There are two types of tags:

Container Tags
Tags which have both the opening and closing i.e. <TAG> and </TAG> are called
container tags. They hold the text and other HTML tags in between the tags. The <HTML>,
<HEAD>, <TITLE> and <BODY> tags are all container tags.

Empty Tags
Tags, which have only opening and no ending, are called empty tags. The <HR>, which
is used to draw Horizontal, rule across the width of the document, and line break <BR> tags are
empty tags.

Dept.of Computer Science And Applications, SJCET, Palai Page 261


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

5.1.3 FORMATTING WEB PAGE


HTML tags used for formatting a web page are:

 Section Heading Tag: <H1>.............<H6>


HTML has six header tags <H1>, <H2>...........<H6> used to specify section headings. Text
with header tags is displayed in larger and bolder fonts than the normal body text by a web
browser. Every header leaves a blank line above and below it when displayed in browser.

 Paragraph tag: <P>


This tag <P> indicates a paragraph, used to separate two paragraphs with a blank line.

 Line Break Tag: <BR>


The empty tag <BR> is used, where the text needs to start from a new line and not continue on
the same line. To get every sentence on a new line, it is necessary to use a line break.

 Horizontal Rule Tag: <HR>


An empty tag <HR> basically used to draw lines and horizontal rules. It can be used to separate
two sections of text.

ATTRIBUTES

WIDTH:Specifies an exact width of HR in pixels, or a relative width as percentage of the


document width.
ALIGN: Set the alignment of the rule to LEFT, RIGHT and CENTER. It is applicable if it is not
equal to width of the page.
NOSHADE: If a solid bar is required, this attribute is used; it specifies that the horizontal rule
should not be shaded at all.
COLOR: Set the color of the Horizontal rule.

5.1.3.1 CHARACTER FORMATTING TAGS

The character formatting tags are used to specify how a particular text should displayed
on the screen to distinguish certain characters within the document. The most common character
formatting tags are:

Boldface <B>: displays text in BOLD


Italics <I>: displays text in Italic
Subscript <SUB>: displays text in Subscript
Superscript <SUP>: displays text in Superscript

Dept.of Computer Science And Applications, SJCET, Palai Page 262


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

Small <SMALL>: displays text in smaller font as compared to normal font


Big <BIG>: displays text in larger font as compared to normal font
Font Colors and Size:<FONT>
By using <FONT> Tag one can specify the colors, size of the text.
Attributes of <FONT> are:

COLOR: Sets the color of the text that will appear on the screen.
SIZE: Sets the size of the text, takes value between 1 and 7, default is 3.
FACE: Sets the normal font type, provided it is installed on the user‟s machine.

Eg: <FONT FACE="ARIAL"> the text will be displayed in Arial</FONT>

5.1.3.2 COMMENTS IN HTML

The comment tag is used to insert a comment in the HTML source code. A comment can
be placed anywhere in the document and the browser will ignore everything inside the brackets. You
can use comments to write notes to yourself, or write a helpful message to someone looking at your
source code.

Syntax : <!-- This is a comment -->

5.1.3.3 LIST
HTML Supports several ways of arranging items in lists. The most commonly used are:

• Ordered List (Numbered List)


• Unordered List (Bulleted List)

Ordered List <OL>


Ordered list also called as Numbered list, is used to present a numbered list of item in the
order of importance or the item (paragraph) is marked with a number. An ordered list starts with the
<ol> tag. Each list item starts with the <li> tag.The attribute TYPE : allows marking list items with
different types. By default the list Item markers are set to numbers 1,2,3… so on.

Unordered List <UL>


Unordered List also called as bulleted list, used to present list of items marked with
bullets. An unordered list starts with in <UL> followed by <LI> (List Item) tag. Use of <UL> is very
similar to <OL> (ordered list).

Dept.of Computer Science And Applications, SJCET, Palai Page 263


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

Definition List
A definition list is not a list of items. This is a list of terms and explanation of the terms.
A definition list starts with the <dl> tag. Each definition-list term starts with the <dt> tag. Each
definition-list definition starts with the <dd> tag.

5.1.3.4 USING GRAPHICS IN WEB PAGE <IMG>


Images can be placed in a web page by using <IMG> tag. There are many image formats
available today, but the most widely used among them are gif and jpeg. The gif format is considered
superior to the jpeg format for its clarity and ability to maintain the originality of an image without
lowering its quality.

It is an empty tag (only start tag, no end tag) and is written as:
<IMG SRC = image_URL> where SRC attribute is mandatory
SRC – Source of the image file image
URL – represents the image file with its location.

Attributes used with <IMG> are: -

ALIGN- used to set the alignment of the text adjacent to the image.

ALIGN = LEFT - Displays image on left side and the subsequent text flows around the right hand
side of that image
ALIGN = RIGHT - Displays the image on the right side and the subsequent text flows around the
left hand side of that image
ALIGN = TOP - Aligns the text with the top of the image
ALIGN = MIDDLE - Aligns the text with the middle of the image
ALIGN=BOTTOM - Aligns the text with the bottom of the image

HEIGHT AND WIDTH- Controls the Height and Width of an image


VSPACE and HSPACE- White space around an image can be provided by using HSPACE
(Horizontal Space) and VSPACE (Vertical Space) attributes of the <IMG> tag.
ALT- is used to give alternative text that can be displayed in place of the image. This is required
when the user needs to stop display of images while retrieving a document in order to make the
retrieval faster, or when the browser does not support
BORDER-Border around the image can be controlled by using BORDER attribute of <IMG> tag.
By default image displays with a thin border.

Anchor Tag: <A> (WORKING WITH LINKS)


Web pages are linked to one another through Hypertext Links. Section of text or image in
the HTML document can be linked to an external document or to a specific place within the same

Dept.of Computer Science And Applications, SJCET, Palai Page 264


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

document. The text or image that provides such linkage is known as Hypertext.HTML provides <A>
Anchor Tag to create links. The format of using anchor tag is as follows:

<A HREF ="URL"> Make Me The Link </A>

HREF (Hyper Link Reference) is a mandatory attribute used to refer the URL of the resource.

URL (Uniform Resource Locator) is an address tells the browser about the file to link to. It
identifies file locations (Addresses) on the web or on the local hard drive. These addresses can be
those of HTML documents or elements such as images, scripts, applets and other files. It is always
enclosed in quotes.

5.1.3.5 TABLES

Tables are used in web pages for two major purposes:

 Arranging information in a table

 Creating a page layout with the use of hidden tables.

Tables are defined with the <table> tag. A table is divided into rows (with the <tr> tag),
and each row is divided into data cells (with the <td> tag). The letters td stands for table data, which
is the content of a data cell. A data cell can contain text, images, lists, paragraphs, forms, horizontal
rules, tables, etc. Headings in a table are defined with the <th> tag.

Eg: <table border="1">


<tr> <td>row 1, cell 1</td>
<td>row 1, cell 2</td> </tr>
<tr> <td>row 2, cell 1</td>
<td>row 2, cell 2</td></tr>
</table>

Above code will create a table with 2 rows and 2 columns

The following properties can be added to the <table> tag. Table properties are set for the
entire table. If certain properties are set for single cells, they will have higher priority than the
settings for the table as a whole

Property Description
align= left align table
left center table

Dept.of Computer Science And Applications, SJCET, Palai Page 265


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

center right align table


right
background=filename image inserted behind the table
bgcolor=#rrggbb background color
border=n border thickness
bordercolor=#rrggbb border color
bordercolordark=#rrggbb border shadow
cellpadding=n distance between cell and content
cellspacing=n space between cells
protects agains linebreaks, even
nowrap though the content might be wider
than the browser window.
frame=
void, removes all outer borders
above, shows border on top of table
below, shows border on bottom of table
lhs, shows border on left side of table
rhs, shows border on right side of table
hsides, shows border on both horizontal sides
vsides, shows border on both vertical sides
box shows border on all sides of table
valign=
top aligns content to top of cells
bottom aligns content to bottom of cells

Table: 5.1

5.1.4 HTML FORMS

Html Forms are used to create GUIs on Web pages. Usually the purpose is to ask the user
for information, which is then sent back to the server. A form can contain input elements like text
fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain select lists,
textarea, fieldset, legend, and label elements.

The tag <form> and </form> are used to add a form. All kinds of HTML tags can be
added between the <form> and </form> tags. It informs browser that any thing specified between
these tags belong to form

Dept.of Computer Science And Applications, SJCET, Palai Page 266


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

Attributes

 NAME= "..." Name of the form


 ACTION="..." - The address of the script to process this form input.
 METHOD=" " - The method used to send the data from the form to the server. The options are
POST and GET. Normally POST is used.

5.1.4.1 THE INPUT ELEMENT

The most important form element is the input element. The input element is used to
select user information. An input element can vary in many ways, depending on the type attribute. An
input element can be of type text field, checkbox, password, radio button, submit button, and
more.<input >is the tag used to create input elements. The attribute type determines the specific sort
of input element to be created.The syntax is:

<input type =“” specifies type of form element


name =““ specifies name of the control that identifies it.
value =““ default value of control
align =““ align controls w.r.t to form margins
size =““ suggested number of characters for text input
maxlength = “ ” > maximum number of characters for text input)

The most used input types are described below.

5.1.4.2 TEXT FIELDS

<input type="text" /> defines a one-line input field that a user can enter text into.

Eg: <form>
First name: <input type="text" name="firstname" /> <br />
Last name: <input type="text" name="lastname" />
</form>

5.1.4.3 RADIO BUTTONS

<input type="radio" /> defines a radio button. Radio buttons let a user select ONLY ONE of a limited
number of choices.

Eg:<form>
<input type="radio" name="sex" value="male" /> Male <br />
<input type="radio" name="sex" value="female" /> Female
</form>

Dept.of Computer Science And Applications, SJCET, Palai Page 267


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

5.1.4.4 CHECKBOXES

<input type="checkbox" /> defines a checkbox. Checkboxes let a user select ONE or MORE options
of a limited number of choices

Eg: form>
Bike: <input type="checkbox" name="vehicle" value="Bike"/> <br />
Car: <input type="checkbox" name="vehicle" value="Car"/><br />
</form>

5.1.4.5 SUBMIT BUTTON

<input type="submit" /> defines a submit button.

A submit button is used to send form data to a server. The data is sent to the page specified in the
form's action attribute. The file defined in the action attribute usually does something with the
received input.

Eg: <form name="input" action="html_form_submit.jsp" method="get">


Username:<input type="text" name="user"/>
<input type="submit" value="Submit" />
</form>

5.1.5 FRAMES

Frames allow for multiple ".html" documents to be displayed inside of one browser window at a
time. Each HTML document is called a frame, and each frame is independent of the others.

5.1.5.1 THE FRAMESET TAG

The <frameset> tag defines the general layout of a web page that uses 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 defines one particular window (frame) within a frameset. It has the SRC attribute,
which indicates the URL of the page that goes in the frame.

5.1.5.2 VERTICAL & HORIZONTAL FRAMESET

Setting the rows attribute defines the number of horizontal subspaces in a frameset.
Setting the cols attribute defines the number of vertical subspaces. Both attributes may be set
simultaneously to create a grid.

Dept.of Computer Science And Applications, SJCET, Palai Page 268


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

If the rows attribute is not set, each column extends the entire length of the page. If the
cols attribute is not set, each row extends the entire width of the page. If neither attribute is set, the
frame takes up exactly the size of the page.

frameset cols="25%,75%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>

In the example above 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.

<html>
<frameset rows="30%,40%,30>
<frame src="frame_a.htm">
<frame src="frame_b.htm">
<frame src="frame_c.htm">
</frameset>
</html>

In the example below we have a frameset with three rows. The first row is set to 30% of
the width of the browser window. The second row is set to 40% of the width of the browser window.
The third row is set to 30% browser window. The HTML document "frame_a.htm" is put into the
first row, HTML document "frame_b.htm" is put into the second row and the HTML document
"frame_c.htm" is put into the third row.

5.2 CLIENT SIDE & SERVER SIDE SCRIPTING

In computer programming, a script is a program or sequence of instructions that is


interpreted or carried out by another program rather than by the computer processor. A scripting
language or script language is a programming language that supports the writing of scripts. Scripting
languages are mostly associated with the World Wide Web where they have been used extensively to
create dynamic web pages. For Web pages they are instructions either to the Web server(server-side
scripting) or to the Web Browser (client-side scripting)

CLIENT SIDE SCRIPTING

The client is the system on which the Web browser is running. Client-side scripts are
often embedded within an HTML or XHTML document (hence known as an "embedded script"), but
they may also be contained in a separate file, to which the document (or documents) that use it make

Dept.of Computer Science And Applications, SJCET, Palai Page 269


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

reference (hence known as an "external script"). Upon request, the necessary files are sent to the
user's computer by the web server (or servers) on which they reside. The user's web browser executes
the script, then displays the document, including any visible output from the script. Client-side scripts
may also contain instructions for the browser to follow in response to certain user actions, (e.g.,
clicking a button). Often, these instructions can be followed without further communication with the
server.

The process with client-side scripting can be generalized in the following steps:

 The user requests a Web page from the server


 The server finds the page and sends it to the user
 The page is displayed on the browser with any scripts running during or after display

Client-side scripting is used to make Web pages change after they arrive
at the browser. Client-side scripts rely on the user's computer. The source code is transferred from the
web server to the user‟s computer over the internet and run directly in the browser. So user's web
browser should understand the scripting language in which client-side scripts are written. JavaScript,
VB script etc are some of the examples of Client Side scripting languages

SERVER SIDE SCRITPING

Server-side scripts are executed by the web server when the user requests a document.
They produce output in a format understandable by web browsers (usually HTML), which is then
sent to the user's computer. The user cannot see the script's source code (unless the author publishes
the code separately), and may not even be aware that a script was executed. They have greater access
to the information and functions available on the server. Documents produced by server-side scripts
may, in turn, contain client-side scripts. Server-side scripts require that their language's interpreter be
installed on the server, and produce the same output regardless of the client's browser, operating
system, or other system details.

The process is:

 user requests a Web page from the server


 script in the page is interpreted by the server creating or changing the page content to suit the
user and the occasion.
 page in its final form is sent to the user and then cannot be changed using server-side scripting

PHP, JSP and ASP are some of examples of Server side scripting languages. The primary
advantage to server-side scripting is the ability to highly customize the response based on the user's
requirements, access rights, or queries into data stores

Dept.of Computer Science And Applications, SJCET, Palai Page 270


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

5.3 JAVA SCRIPT

JavaScript is a Client Side Scripting Language designed for creating dynamic Web pages. It
was released by Netscape and Sun Microsystems in 1995. JavaScript code is typically embedded in
the HTML, to be interpreted and run by the client's browser. JavaScript was influenced by many
languages and was designed to look like Java, but to be easier for non- programmers to work with.

JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
Because you can use spaces, tabs, and newlines freely in your program so you are free to format and
indent your programs in a neat and consistent way that makes the code easy to read and understand.
Simple statements in JavaScript are generally followed by a semicolon character, just as they are in
C, C++, and Java. JavaScript, however, allows you to omit this semicolon if your statements are each
placed on a separate line. JavaScript is a case-sensitive language. So identifiers Time, TIme
and TIME will have different meanings in JavaScript.

5.3.1 Uses of JavaScript

 JavaScript gives HTML designers a programming tool - HTML authors are normally not
programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can
put small "snippets" of code into their HTML pages
 JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
document.write("<h1>" + name + "</h1>") can write a variable text into an HTML page
 JavaScript can react to events - A JavaScript can be set to execute when something happens,
like when a page has finished loading or when a user clicks on an HTML element
 JavaScript can read and write HTML elements - A JavaScript can read and change the
content of an HTML element
 JavaScript can be used to validate data - A JavaScript can be used to validate form data
before it is submitted to a server. This saves the server from extra processing
 JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the
visitor's browser, and - depending on the browser - load another page specifically designed for that
browser
5.3.2 JAVASCRIPT SYNTAX:
The HTML <script> tag is used to insert a JavaScript into an HTML page. Scripts can be
in the either <head> section or <body> section. The <script> tag alert the browser program to begin
interpreting all the text between these tags as a script.

<script ...>
JavaScript code </script>
The script tag takes two important attributes:

Dept.of Computer Science And Applications, SJCET, Palai Page 271


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

 language: This attribute specifies what scripting language you are using. Typically, its value
will be javascript. Although recent versions of HTML (and XHTML, its successor) have phased out
the use of this attribute.

 type: This attribute is what is now recommended to indicate the scripting language in use and its
value should be set to "text/javascript".

So your JavaScript segment will look like:

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


JavaScript code
</script>

Eg: <SCRIPT language ="JavaScript"type="text/javascript">


alert("Welcome to the script tag test page.")
</SCRIPT>

JavaScript in a page will be executed immediately while the page loads into the browser. This is
not always what we want. Sometimes we want to execute a script when a page loads, or at a later
event, such as when a user clicks a button. When this is the case we put the script inside a function

Scripts in <head>

Scripts to be executed when they are called, or when an event is triggered, are placed in
functions. Put your functions in the head section, this way they are all in one place, and they do not
interfere with page content.

EXAMPLE:

<html>
<head> <script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script> </head>
<body onload="message()"> </body>
< /html>

Dept.of Computer Science And Applications, SJCET, Palai Page 272


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

Scripts in <body>

If you don't want your script to be placed inside a function, or if your script should write page
content, it should be placed in the body section.

EXAMPLE:

<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body> /html>

5.3.3 USING AN EXTERNAL JAVASCRIPT

If you want to run the same JavaScript on several pages, without having to write the same
script on every page, you can write a JavaScript in an external file. Save the external JavaScript file
with a .js file extension. The external script cannot contain the <script></script> tags. Inorder to use
the external script, point to the .js file in the "src" attribute of the <script> tag:

EXAMPLE:
<html>
<head> <script type="text/javascript" src="xxx.js">
</script>
</head>
<body> </body></html>

Note: Remember to place the script exactly where you normally would write the script!

5.3.4 JAVASCRIPT DATA TYPES

In JavaScript, there are three primary data types, two composite data types, and two special data
types.

5.3.4.1 PRIMARY DATA TYPES

The primary (primitive) data types are String, Number and Boolean

Dept.of Computer Science And Applications, SJCET, Palai Page 273


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

String Data Type:

String value is a chain of zero or more Unicode characters (letters, digits, and punctuation
marks). You use the string data type to represent text in JavaScript. You include string literals in your
scripts by enclosing them in single or double quotation marks. Double quotation marks can be
contained in strings surrounded by single quotation marks, and single quotation marks can be
contained in strings surrounded by double quotation marks. Notice that JavaScript does not have a
type to represent a single character. To represent a single character in JavaScript, you create a string
that consists of only one character

In JavaScript, there is no distinction between integer and floating-point values; a JavaScript number
can be either (internally, JavaScript represents all numbers as floating-point values).

Integer Values

Integer values can be positive whole numbers, negative whole numbers, and 0. They can
be represented in base 10 (decimal), base 16 (hexadecimal), and base 8 (octal). Most numbers in
JavaScript are written in decimal.

You denote hexadecimal ("hex") integers by prefixing them with a leading "0x" (zero and x|X).
They can contain digits 0 through 9, and letters A through F (either uppercase or lowercase) only.
The letters A through F are used to represent, as single digits, 10 through 15 in base 10. That is, 0xF
is equivalent to 15, and 0x10 is equivalent to 16. You denote octal integers by prefixing them with a
leading "0" (zero). They can contain digits 0 through 7 only

Floating-point Values

Floating-point values can be whole numbers with a decimal portion. Additionally, they
can be expressed in scientific notation. That is, an uppercase or lowercase "e" is used to represent
"ten to the power of". JavaScript represents numbers using the eight byte IEEE 754 floating-point
standard for numerical representation

Boolean Type

Whereas the string and number data types can have a virtually unlimited number of different values,
the Boolean data type can only have two. They are the literals true and false. A Boolean value is a
truth-value: it specifies whether the condition is true or not.

5.3.4.2 COMPOSITE DATA TYPES

Composite data types, also called complex types, consist of more than one component. For
composite data types we will look at objects, which contain properties and methods including some
special pre-defined objects that JavaScript provides, as well as arrays which contain a sequential list
of elements

Dept.of Computer Science And Applications, SJCET, Palai Page 274


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

Objects

An object is a collection of named values, called the properties of that object. Functions
associated with an object are referred to as the methods of that object.

Arrays

An Array is an ordered collection of data values. In JavaScript, an array is just an object that has
an index to refer to its contents. In other words, the fields in the array are numbered, and you can
refer to the number position of the field.

5.3.4.3 SPECIAL DATA TYPES

Java Script supports two special data types null and un-defined which represents
nonexistence or incomplete existence.

Null Data type

The null data type has only one value in JavaScript: null. The null keyword cannot be
used as the name of a function or variable. A variable that contains null contains no valid Number,
String, Boolean, Array, or Object. You can erase the contents of a variable (without deleting the
variable) by assigning it the null value.

Undefined Data type

The undefined value is returned when you use an object property that does not exist, or a
variable that has been declared, but has never had a value assigned to it. You can check to see if a
variable exists by comparing it to undefined, although you can check if its type is undefined by
comparing the type of the variable to the string "undefined".

5.3.5 LITERALS

JavaScript literals are the notation for representing a fixed data value that appears directly
in a JavaScript program. JavaScript Literals helps us to assign values (initialize) to various JavaScript
Variables; such as numbers, strings, and Booleans; It can also be used to initialize arrays and objects.

EXAMPLE:

var intNum = 82 // 82 is a integer literal


var PI = 3.14 // 3.14 is a float literal
var strInfo="This is a string" // this is a string literal
var isMale=true // A Boolean value literal
var arrAnimal={"cat","dog"} // array literals

Dept.of Computer Science And Applications, SJCET, Palai Page 275


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

5.3.6 JAVASCRIPT VARIABLES

Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then refer to the data
simply by naming the container.In JavaScript you don't have to declare a variable's data type before
using it. Any variable can hold any JavaScript data type

There are rules and conventions in naming variables in any programming language. It is
good practice to use descriptive names for variables. The following are the JavaScript rules:

• The keyword var is optional (but it‟s good style to use it)
• Variables names must begin with a letter or underscore
• Variable names are case-sensitive
• Variables are untyped (they can hold values of any type)
• Variables declared within a function are local to that function
• Variables declared outside a function are accessible throughout the page

EXAMPLE:

var num = “1”;


var name = “Kaushal”;
var phone = “123-456-7890”;

5.3.7 OPERATORS

Java script supports operators that belongs to the following categories:

arithmetic
bitwise
relational
logical

5.3.7.1 ARITHMETIC OPERATORS

Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The operands of the arithmetic operators must be of a numeric type. The following table lists
the arithmetic operators:

Operator Description

+ Adds two operands


- Subtracts second operand from

Dept.of Computer Science And Applications, SJCET, Palai Page 276


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

the first

* Multiply both operands


/ Divide numerator by denominator
% remainder after an integer division
Increment operator, increases
++
integer value by one
Decrement operator, decreases
--
integer value by one
Table: 5.2

5.3.7.2 RELATIONAL OPERATORS

Relational operators determine the relationship that one operand has to the other. Specifically,
they determine equality and ordering

Operator Description
Checks if the value of two operands are equal or not, if
==
yes then condition becomes true.
Checks if the value of two operands are equal or not, if
!=
values are not equal then condition becomes true.
Returns true if the operands are equal and of the same
=== type.

Returns true if the operands are not equal and/or not of


!==
the same type.
Checks if the value of left operand is greater than the
> value of right operand, if yes then condition becomes
true.
Checks if the value of left operand is less than the
< value of right operand, if yes then condition becomes
true.
Table : 5.3 Checks if the value of left operand is greater than or
>= equal to the value of right operand, if yes then
condition becomes true.
Checks if the value of left operand is less than or equal
<= to the value of right operand, if yes then condition
becomes true.

(Table: 5.3)

Dept.of Computer Science And Applications, SJCET, Palai Page 277


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

5.3.7.3 THE LOGICAL OPERATORS

The Boolean logical operators shown here operate only on boolean operands. All of the binary
logical operators combine two boolean values to form a resultant boolean value

Operator Description
Called Logical AND operator. If both the operands are non
&&
zero then then condition becomes true.
Called Logical OR Operator. If any of the two operands are
||
non zero then then condition becomes true.
Called Logical NOT Operator. If a condition is true then
!
Logical NOT operator will make false.
Table: 5.4

5.3.7.4 BITWISE OPERATORS

These operators act upon the individual bits of their operands

Called Bitwise AND operator. It performs a Boolean AND operation on


&
each bit of its integer arguments.
Called Bitwise OR Operator. It performs a Boolean OR operation on each
|
bit of its integer arguments.
Called Bitwise XOR Operator. It performs a Boolean exclusive OR
^ operation on each bit of its integer arguments. Exclusive OR means that
either operand one is true or operand two is true, but not both.
Called Bitwise NOT Operator. It is a is a unary operator and operates by
~
reversing all bits in the operand.
Called Bitwise Shift Left Operator. It moves all bits in its first operand to
the left by the number of places specified in the second operand. New bits
<< are filled with zeros. Shifting a value left by one position is equivalent to
multiplying by 2, shifting two positions is equivalent to multiplying by 4,
etc.
Called Bitwise Shift Right with Sign Operator. It moves all bits in its first
operand to the right by the number of places specified inthe second
operand. The bits filled in on the left depend on the sign bit of the original
operand, in order to preserve the sign of the result. If the first operand is
>>
positive, the result has zeros placed in the high bits; if the first operand is
negative, the result has ones placed in the high bits. Shifting a value right
one place is equivalent to dividing by 2 (discarding the remainder),
shifting right two places is equivalent to integer division by 4, and so on.

Table: 5.5

Dept.of Computer Science And Applications, SJCET, Palai Page 278


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

5.3.7.5 SPECIAL OPERATORS

Conditional Operator

Conditional operator is denoted by "?:" This is often used as a short if/else type statement. A
condition is placed before question mark(?) and a value is placed on each side of colon( : )

General form:
variable = (condition) ? val1 : val2;

It evaluates the condition, if it's True then the variable takes the value 'VAL1', otherwise, takes the
value 'VAL2'.

delete

This operator deletes an object, an object‟s property, or an element at a specified index in an


array. The operator can also delete variables which are not declared with the var statement.

Syntax

delete objectName
delete objectName.property
delete objectName[index]

instanceof

The instanceof operator is used to check the type of an object at run time. The instanceof
operator returns a boolean value that indicates if an object is an instance of a particular class.

var result = objectName instanceof objectType

EXAMPLE:

var theDay = new Date(1995, 12, 17);


if (theDay instanceof Date) {
// statements to execute
}

new
creates an instance of a user-defined object type or of one of the predefined object types

SYNTAX: var objectName = new objectType(param1, param2, ...., paramN);

Dept.of Computer Science And Applications, SJCET, Palai Page 279


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

typeof

The typeof operator returns a string indicating the type of the unevaluated operand. There are six
possible values that typeof returns: object, boolean, function, number, string, and undefined

Syntax: typeof operand OR


typeof (operand)

EXAMPLE:

var shape = "round"; typeof shape; // returns "string"


var size = 1; typeof size; // returns "number"
var today = new Date(); typeof today; // returns "object"

5.3.8 ARRAYS

An array is a variable that can store many variables within it. Creating an array is slightly
different from creating a normal variable. Because JavaScript has variables and properties associated
with arrays, you have to use a special function to create a new array.

To create an array of N elements, you can write

var myArray = new Array(N); where index of array runs from 0 to N-1.

The Array object has predefined properties and methods. The Property "length" tells the no.of
elements in the array. It also Consists of various methods like reverse(), push(), concat(), etc to
manipulate its elements.

Method Description
Returns a new array comprised of this array joined with
concat()
other array(s) and/or value(s).
Joins all elements of an array into a string.
join()

Removes the last element from an array and returns that


pop() element
Adds one or more elements to the end of an array and
push()
returns the new length of the array.
Reverses the order of the elements of an array -- the first
reverse()
becomes the last, and the last becomes the first.
Sorts the elements of an array.
sort()

(Table:5.6)

Dept.of Computer Science And Applications, SJCET, Palai Page 280


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

All JavaScript variables are objects. Array elements are objects. Functions are objects.Because of
this, you can have variables of different types in the same Array

Following are some of the examples that demonstrates the functionalities of an array

var Car = new Array(3);


Car[0] = "Ford";
Car[1] = "Toyota";
Car[2] = "Honda";

// Create an array of three elements with initial values


var Car2 = new Array("Ford", "Toyota", "Honda");

// Create an array of three elements with initial values


var Car3 = ["Ford", "Toyota", "Honda"];

// An array of 3 elements with initial values of different types


var tmp3 = new Array(1, "a", true);

//Makes tmp3 an array of 100 elements. tmp[3] to tmp[98] are undefined.


tmp3[99] = "Something";

5.3.9 EXPRESSION

An expression is any valid set of literals, variables and operators that evaluates to a single value. The
value may be a number, a string, or a logical value. There are two types of expressions:
 those that assign a value to a variable

Ex: x = 7
 those that simply have a value

Ex: 3 + 4 -simply evaluates to 7; it does not perform an assignment

JavaScript has the following kinds of expressions:

 Arithmetic: evaluates to a number


 String: evaluates to a character string
 Logical: evaluates to true or false

Dept.of Computer Science And Applications, SJCET, Palai Page 281


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

5.3.10 CONTROL STRUCTURES

Java Script supports the following control structures:

if STATEMENT:

The if statement is the fundamental control statement that allows JavaScript to make
decisions and execute statements conditionally

if (expression)
{
Statement(s) to be executed if expression is true
}

if...else STATEMENT:

The if...else statement is the next form of control statement that allows JavaScript to execute
statements in more controlled way.

if (expression)
{
Statement(s) to be executed if expression is true
}
else
{
Statement(s) to be executed if expression is false
}

else if... STATEMENT:

The if...else if... statement is the one level advance form of control statement that allows
JavaScript to make correct decision out of several conditions.

if (expression 1)
{
Statement(s) to be executed if expression 1 is true
}
else if (expression 2)
{
Statement(s) to be executed if expression 2 is true
}
else if (expression 3)
{

Dept.of Computer Science And Applications, SJCET, Palai Page 282


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

Statement(s) to be executed if expression 3 is true


}
else
{
Statement(s) to be executed if no expression is true
}

switch STATEMENT:

The basic syntax of the switch statement is to give an expression to evaluate and several
different statements to execute based on the value of the expression. The interpreter checks each case
against the value of the expression until a match is found. If nothing matches, a default condition
will be used.
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}

THE WHILE LOOP

The most basic loop in JavaScript is the while loop

while (expression)
{
Statement(s) to be executed if expression is true
}

DO...WHILE LOOP:

The do...while loop is similar to the while loop except that the condition check happens at the
end of the loop. This means that the loop will always be executed at least once, even if the condition
is false

Dept.of Computer Science And Applications, SJCET, Palai Page 283


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

do
{
Statement(s) to be executed;

} while (expression);

FOR LOOP
The for loop is the most compact form of looping and includes the following three
important parts:

The loop initialization is where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins. The test statement which will test if the
given condition is true or not. If condition is true then code given inside the loop will be executed
otherwise loop will come out. The iteration statement where you can increase or decrease your
counter. You can put all the three parts in a single line separated by a semicolon.

for (initialization; test condition; iteration statement)


{
Statement(s) to be executed if test condition is true
}

5.3.11 JAVASCRIPT FUNCTIONS

Java script Function is a reusable code-block that is execute when the function is called.
You may call a function from anywhere within the page (or even from other pages if the function is
embedded in an external .js file).Functions can be defined either <head> or <body> section. As a
convention, they are typically defined in the <head> section. They are are created by the help of
“function” keyword, The syntax of JavaScript function is as follows:

function function_name(arguments)
{
statement here
}
The { and the } defines the start and end of the function. While defining
JavaScript function its important to remember that the keyword function should be in lowercase
other wise JavaScript won't understand it as function. If you write function in uppercase the code will
generate error. In the JavaScript semicolon is optional but its better to put semi-colon as part of best
practices. All the java script code are written inside the curly braces. JavaScript provides many built
in functions that ease the development of JavaScript programs
EXAMPLE:

<html>

Dept.of Computer Science And Applications, SJCET, Palai Page 284


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

<head>
<script type="text/javascript">
function displaymessage() {
alert("Hello World!")
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!“
onclick="displaymessage()" >
</form>
</body>
</html>

In addition to the functions created by user, java script has got a set of built-in functions:

Name Description Example


eval(String) evaluates an expression contained within eval("3 + 4"); // Returns 7 (Number)
strings
isFinite(x) var v1==isFinite(”123”);//true
Returns true if the given argument is a
finite, legal number
var v2==isFinite(”25/12/86”);//false
isNaN(x) var ssn=“123-45-6789”;
Determines whether given argument is “Not
var check=isNaN(ssn);//true
a Number”. Returns true if the given
argument is not a number
Converts string literals to integers.Parses up parseInt("3 chances") //returns 3
parseInt(s)
to any character that is not part of a valid parseInt(" 5 alive") /returns5
integer parseInt("How are you")
// returns NaN

(Table: 5.7)
5.3.12 OBJECTS

JavaScript supports programming with objects. Every object has its own properties and
methods. These properties define the characteristics of an object. To refer to a property of an object
use objectName.propertyName. Methods are the actions that the object can perform or that can be
performed on the object. To refer to a method of an object use objectName.methodName()

Dept.of Computer Science And Applications, SJCET, Palai Page 285


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

Some of the built-in objects of JavaScript are:

(Table:5.8)
5.3.12.1 MATH OBJECT

The math object provides you properties and methods for mathematical constants and
functions. Unlike the other global objects, Math is not a constructor. All properties and methods of
Math are static and can be called by using Math as an object without creating it.

Eg: var pi_val = Math.PI;


var sine_val = Math.sin(30);

Important Methods are:

Method Description
abs() Returns the absolute value of a
number.
pow() Returns base to the exponent power.
random() Returns a pseudo-random number
between 0 and 1.
round() Returns the value of a number
rounded to the nearest integer
sqrt() Returns the square root of a number.

(Table: 5.9)
5.3.12.2 DATE OBJECT

The Date object is a data type built into the JavaScript language. Date objects are created
with the new Date( ). Once a Date object is created, a number of methods allow you to operate on it.
Most methods simply allow you to get and set the year, month, day, hour, minute, second, and
millisecond fields of the object, using either local time or GMT.

Dept.of Computer Science And Applications, SJCET, Palai Page 286


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

The Syntax is:

new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])

Method Description

Date() Returns today's date and time

getDay() Returns the day of the week for the specified date
according to local time.
getFullYear() Returns the year of the specified date according to
local time.
getHours() Returns the hour in the specified date according to
local time.
getTime() Returns the numeric value of the specified date as
the number of milliseconds since January 1, 1970,
00:00:00 UTC.

Table: 5.10

5.3.12.3 THE STRING OBJECT


The String object provides methods and properties for string manipulation and
formatting.

Method Description
charAt() Returns the character at the specified index.
concat() Combines the text of two strings and returns a new string.
substr() Returns the characters in a string beginning at the
specified location through the specified number of
characters.
valueOf() Returns the primitive value of the specified object

Table: 5.11

5.3.12.4 USER DEFINED OBJECT

There are 2 different ways to create a new object:

 Define and create a direct instance of an object.

 Use a function to define an object, then create new object instances.

Dept.of Computer Science And Applications, SJCET, Palai Page 287


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

CREATING DIRECT INSTANCES

All user-defined objects and built-in objects are descendants of an object called Object.
JavaScript provides a special constructor function called Object() to build the object. To create an
object, the new operator is followed by the constructor method. The return value of the Object()
constructor is assigned to a variable. The variable contains a reference to the new object. The
properties assigned to the object are not variables and are not defined with the var keyword.

var objectname=new Object();

EXAMPLE:

This example creates a new instance of an object, and adds four properties to it:

<html>
<head>
<title>User-defined objects</title>
<script type="text/javascript">
var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object
book.author = "Mohtashim";
</script>
</head>
<body>
<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>
</body>
</html>

USING AN CONSTRUCTOR FUNCTION

You can define your own custom objects using a constructor function. Java script objects inherits all
the variables and statements of the constructor function on which they are based. Any javascript
function can serve as a constructor.

function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;

Dept.of Computer Science And Applications, SJCET, Palai Page 288


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

this.eyecolor=eyecolor;
}

Once you have a constructor function, you can create new instances of the object.

var m1=new person("John","Doe",50,"blue");


var m2=new person("Sally","Rally",48,"green");

To delete a specific property in custom object use delete operator

delete objectname.property

It is possible to create functions that will be used as a method of object and defining methods to an
object is done inside the constructor function

EXAMPLE:

<html>
<body>
<script>
function display()
{ document.write("<br/>name:"+this.firstname);
document.write("<br/>Last name:"+this.lastname);
document.write("<br/>Age:"+this.age);
}
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
this.display_details=display;
}
var m1=new person("John","Doe",50,"blue");
document.write("<br/><h2>details of first person:</h2>");
m1.display_details();
var m2=new person("Sally","Rally",48,"green");
document.write("<br/><h2>details of second person:</h2>");
m2.display_details();
</script>
</body>
</html>

Dept.of Computer Science And Applications, SJCET, Palai Page 289


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

5.3.13 JAVASCRIPT EVENTS

The building blocks of an interactive web page is the JavaScript event system. An event in
JavaScript is something that happens with or on the webpage. Every element on a web page is
capable of creating certain events.

A few example of events are:

A mouse click
The webpage loading
Mousing over a hot spot on the webpage, also known as hovering
Selecting an input box in an HTML form
A keystroke

Code that executes in response to a specific event is called an event handler. The event handler
code is included as an attribute of the element that initiates the event. The synatx of an event handler
within an element is:
<event_handler=“javascript code”>
For example, we can add to a button element a click attribute that is assigned some java script code
which will run when a user clicks on the button.

<input type=“button” onclick=“alert(“you clicked a button”)”>

The following table shows a list of some of the event handlers and situations when events are
triggered:

Event handler Triggered when

onChange The value of the text field, text area, or a drop down list is modified

onClick A link, an image or a form element is clicked once

onDblClick The element is double-clicked

onMouseDown The user presses the mouse button

Dept.of Computer Science And Applications, SJCET, Palai Page 290


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

onLoad A document or an image is loaded

onSubmit A user submits a form

onUnLoad The user closes a document or a frame

onResize A form is resized by the user

(Table:5.12)

EXAMPLE:

<form>
<input type=button Value="Don't Press Me"
onClick="alert('now you are in trouble!')“ >
</form>

5.4 BROWSER OBJECT MODEL

The Browser Object Model (BOM) defines a hierarchy of objects and their relationships, which
are used to manipulate or obtain information about the browser. The objects in the browser-object-
model are automatically created when a browser opens a web page. At the very top of this browser
hierarchy is the Window object. This represents the entire browser, with its toolbars, menus, status
bar, the page itself, and a whole lot more besides. Underneath the Window Object there are lots of
other objects you can access. These allow you do things like, redirecting the user to a different web
page, get the size of the browser window, access all the HTML elements on the page

window

navigator screen history location document frames[]

(Fig:5.1)

Dept.of Computer Science And Applications, SJCET, Palai Page 291


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

Object Description
window The object that relates to the current browser window.

document An object that contains the various (X)HTML elements and text
fragments that make up a document. In the traditional JavaScript object
model, the Document object relates roughly to the <body> tag.
frames[] An array of the frames if the Window object contains any. Each frame in
turn references another Window object that may also contain more
frames.
history
An object that contains the current window's history list, namely, the
collection of the various URLs visited by the user recently.
location Contains the current location of the document being viewed in the form
of a URL and its constituent pieces.
navigator An object that describes the basic characteristics of the browser, notably
its type and version.

(Table:5.13)

5.4.1 WINDOW OBJECT

The window object represents the browser window the document is being displayed in. It
is created for each window that appears on the screen. A window can be the main window, a frame
set or individual frame or even a new window created with Java Script. It contains information about
both the display window and the browser displaying the document. It also contains methods for
generating error messages and prompt boxes and have information on things that have been move to
the Windows clipboard from that page. The Window object is the global object within the browser,
ie, all other accessible programmatic elements within the browser hang off it. This includes the
scripts you write and the variables you create within those scripts. As the global object, it is not
technically necessary to write "window" before properties and methods of the window object.

PROPERTIES

closed- Returns a Boolean value indicating whether a window has been closed or not.
document- Returns the Document object for the window
innerHeight -Sets or returns the inner height of a window's content area
name- sets or returns the name of a window
Frames[]-returns an array listing the Frame objects in a window
innerWidth-Sets or returns the inner width of a window's content area
Opener- refers to window that opened another window

Dept.of Computer Science And Applications, SJCET, Palai Page 292


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

METHODS

alert()-Displays an alert box with a message and an OK button


confirm()-Displays a dialog box with a message and an OK and a Cancel button
open()-Opens a new browser window
prompt()-Displays a dialog box that prompts the visitor for input

5.4.2 DOCUMENT OBJECT

Document object represents the Web page that is loaded in the browser window, and the content
displayed on that page. All elements on a web page are contained within document object, and each
element is represented in java script by its own objects.

PROPERTIES

bgColor- Gets/sets the background color of the current document.


Forms-Returns a list of the FORM elements within the current -document.
lastModified-Returns the date on which the document was last modified.
Links-Returns a list of all the hyperlinks in the document.
Title-Returns the title of the current document

METHODS

getElementsByName()- Returns a list of elements with the given name.


getElementById()- Returns an object reference to the identified element
write()-Writes one or more HTML expressions to a document in the specified window
captureEvents()-Sets the document to capture all events of the specified type.
open() - opens a new document
close() - closes the document

EXAMPLE:
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
document.write("<H1>Welcome all </H1><BR>")
</script>

Dept.of Computer Science And Applications, SJCET, Palai Page 293


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

</body>
</html>

5.5 FORMS

Forms are one of the most common web page elements which is used to collect
information from users and transmit that information to a server for processing. There are 4 primary
elements used within <form> element to create form controls:<input>,<button>,<select> and
<textarea>.The <input> element is the most commonly used form element used to create form
controls (interface elements) like Text boxes, Password boxes, radio buttons, check boxes, push
buttons, submit buttons etc..

<form>
input elements
< /form>

Two important attributes associated with form tag are action and method

<form action=“formprocessor.html” method=“get”>


</form>

EXAMPLE:

<html>
<body>
<FORM action="Formprocessor.html" method="post">
<P>Text Field: <INPUT type="text" name="firstname"><BR><BR>
Password: <input type="password" name="pwd"><BR><BR>
email: <INPUT type="text" name="email"><BR><BR><BR>
<INPUT type="radio" name="sex" value="Male"> Male
<INPUT type="radio" name="sex" value="Female"> Female<BR><BR>
<input type="checkbox" name="vehicle" value="Bike">I have a bike
<input type="checkbox" name="vehicle" value="Car">I have a car<br><BR>
<INPUT type="submit" value="Send">
</P>
</form> </body>
</html>

The above example illustrates how to generate various control fields using the input element of form
tag

Dept.of Computer Science And Applications, SJCET, Palai Page 294


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

JavaScript can be used to validate data in HTML forms before sending off the content to a server.
Form data that typically are checked by a JavaScript could be:

has the user left required fields empty?


has the user entered a valid e-mail address?
has the user entered a valid date?
has the user entered text in a numeric field?

Each time you add a set of <form> and </form> tags to an HTML document, a form object is
created and the attributes of form element are represented by properties of Form object. The
Document object has a forms[] array which contains all the forms on a web page. Form object has
an elements[] array which can be used to access each element in a form

To access forms using Java Script, you can use any one of the following options:

 Use forms array of document object


 Name the form in the opening form tag and use that name to access form
 Give the form an id in opening form tag and access from using the
document.getElementById() method

Java script uses Form object to access form controls and verify form information, which represents a
form on a web page. The form object contains properties, methods and events that you can use to
manipulate form and form controls.

PROPERTIES:

 action: returns the value that represents the value of action attribute in the form tag
 method: returns a string that represents the value of method attribute in form tag
 length: the value of total number of elements in an html form
 name: value of name attribute in html form tag
 element: an array that includes an array element for each form element in an html form

With the help of hierarchy of objects available in browser object model it is possible to access the
various interface elements available in an HTML page and validate them using java Script.

EXAMPLE:
<html>
<head>
<body>
<script type="text/javascript">

Dept.of Computer Science And Applications, SJCET, Palai Page 295


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

function prop()
{
alert("The form goes to:"+document.info_form.action);
}
</script>
</head>
<body>
<form action="http://someplace.com" name="info_form">
Name:<input type="text"/></br>
<input type="button" value="clickme" onclick="prop()"/>
</form>
</body>
</html>

The syntax for accessing text entries:

<INPUT TYPE = TEXT> is document.formName.elementName.value where value


is a keyword, formName and elementName are the names you gave your form and text input
element

EXAMPLE:
<form action="/cgi-bin/test.cgi" name="myForm“>
Name:<input type="text" name="Name" />
</form>
myTextVariable = myForm.name.value

5.5.1 FORM FIELD VALIDATION

To validate the contents of the form before sending it to server you need to know when the
user tries to submit form.When user clicks the submit button, a submit event occurs, which can be
captured by „onsubmit‟ event handler. The javascript code which validates the form elements can be
given to the onsubmit event handler so that the form will be submitted only if the validation process
is successful

EXAMPLE:

html><head>
<title>Form Validation</title>
<script type="text/javascript">
function validate()
{
if( document.myForm.Name.value == "" ){

Dept.of Computer Science And Applications, SJCET, Palai Page 296


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

alert( "Please provide your name!" );


document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ){
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
</script>
</head><body>
<form action="/cgi-bin/test.cgi" name="myForm"
onsubmit="return(validate());">
Name:<input type="text" name="Name"/><br>
EMail: <input type="text" name="EMail"/><br>
Zip Code:<input type="text" name="Zip"/><br>
Country:
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
<td><input type="submit" value="Submit" />
</form>
</body>

Dept.of Computer Science And Applications, SJCET, Palai Page 297


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

</html>

5.6 FRAMES
A frame is a window within a window.Using frames allows you to divide a browser window into a
collection of panes. Each pane can then be used to display a separate document. The <frameset> tag
defines how the frames are to be laid out on the screen. It has two attributes to do this, cols, which
specifies how many columns to split the screen into, and rows, which specifies how many rows to
split the screen into

EXAMPLE:

Frame1.html

<html>
<body>
I am frame1.html
</body>
</html>

Frame2.html

<html>
<body>
I am frame2.html
</body>
</html>

Frameset.html

<html>
<frameset cols="20%,80%">
<frame src="frame1.html"></frame>
<frame src="frame2.html"></frame>
</frameset>
</html>

The Frame object represents an HTML frame and for each <frame> tag in an HTML
document, a Frame object is created. These objects are created automatically by the browser and help
users to control loading and accessing of frames. As far as JavaScript is concerned, each frame can be
treated as a separate window. In fact, each frame has its own Window object. Each frame is stored as

Dept.of Computer Science And Applications, SJCET, Palai Page 298


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

an element in the frames[] array of the Window object of the parent window for that frame. To access
frames using Java Script, you can use any one of the following options.

 Use frames array of window object


 Name the frame in frame tag and use that name to access frame

PROPERTIES

Name- The name of the frame. It is defined using the name attribute of the <frame> tag.
length - The length of the frames array.
parent - The parent of the current frame.
self - The current frame.

PARENT AND TOP

The Window object has properties top and parent which is specifically designed to address the
situation of having a hierarchical arrangement of windows. window.parent refers to the Window
object of the parent window.

Example: window.parent.frame2.someElement

window.top is a reference to the Window object of the top window element in the window hierarchy.
If you have multiple levels of nested frames, you can get to the top of the frameset hierarchy

5.6.1 JAVA SCRIPT & FRAMES

We can use java script to pass values from one frame to another.The following example changes the
value of a text box in a frame on the right from a frame on the left side. First, set up a little frameset.
This will require 3 separate html pages:

frm1.html frm2.html frm_script.html

frm1.html

<HTML><HEAD>
<TITLE>JavaScript & Frames</TITLE>
</HEAD>
<BODY>
<FORM>
<INPUT type="button" value="What is cool?"
onClick="parent.right_frame.document.form1.text1.value='Me!'">

Dept.of Computer Science And Applications, SJCET, Palai Page 299


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

</FORM></BODY></HTML>

frm2.html

<html>
<head>
<title>javascript example</title>
</head>
<body>
<form name="form1">
<input type="text" name="text1" size="25" value="">
</form>
</body>
</html>

frm_script.html

<HTML>
<HEAD>
<TITLE>Frames Values</TITLE>
</HEAD>
<FRAMESET cols="20%,80%">
<FRAME SRC="frm1.html" name="left_frame">
<FRAME SRC="frm2.html" name="right_frame">
</FRAMESET>
</HTML>

5.7 SERVLET

A servlet is a server-side software program, written in Java code, that handles messaging
between a client and server. The Java Servlet API defines a standard interface for the request and
response messages so your servlets can be portable across platforms and across different Web
application servers. Servlets can respond to client requests by dynamically constructing a response
that is sent back to the client.

Because servlets are written in the Java programming language, they have access to the
full set of Java APIs. This makes them ideal for implementing complex business application logic
and especially for accessing data elsewhere in the enterprise. The Java Database Connectivity
(JDBC) API, which allows Java programs to access relational databases (and is beyond the scope of
this tutorial), is one example. Because there are no graphics associated with servlets, access to the
GUI Java APIs (the AWT) is not relevant. A single servlet can be invoked multiple times to serve

Dept.of Computer Science And Applications, SJCET, Palai Page 300


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

requests from multiple clients. A servlet can handle multiple requests concurrently and can
synchronize requests.Servlets can forward requests to other servers and servlets

5.7.1 HOW DOES A SERVLET WORK?

A servlet runs inside a Java-enabled application server. Application servers are a special
kind of Web server; they extend the capabilities of a Web server to handle requests for servlets,
enterprise beans, and Web applications. There is a distinct difference between a Web server and an
application server. While both can run in the same machine, the Web server runs client code such as
applets and the application server runs the servlet code. The server itself loads, executes, and
manages servlets. The server uses a Java byte code interpreter to run Java programs; this is called the
Java Virtual Machine(JVM).

(Fig:5.2)
The basic flow is as follows:

 The client sends a request to the server.


 The server instantiates (loads) the servlet and creates a thread for the servlet process. Note
that servlet is loaded upon the first request; it stays loaded until the server shuts down.
 The server sends the request information to the servlet.
 The servlet builds a response and passes it to the server.
 The server sends the response back to the client.

The servlet dynamically constructs the response using information from the client request, plus data
gathered from other sources if needed. Such sources could be other servlets, shared objects, resource
files, and databases. Shared resources, for example, could include in-memory data such as instance or
class variables and external objects such as files, database connections, and network connections.

Dept.of Computer Science And Applications, SJCET, Palai Page 301


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

Servlets may be used at different levels on a distributed framework. The following are some
examples of servlet usage:

 To accept form input and generate HTML Web pages dynamically.


 As part of middle tiers in enterprise networks by connecting to SQL databases via JDBC.
 In conjunction with applets to provide a high degree of interactivity and dynamic Web content
generation.
 For collaborative applications such as online conferencing.
 A community of servlets could act as active agents which share data with each other.
 Servlets could be used for balancing load among servers which mirror the same content.

5.7.2 FEATURES OF SERVLET

5.7.2.1 PORTABILITY

Servlets are highly portable crosswise operating systems and server implementations because the
servlets are written in java and follow well known standardized APIs. Servlets are writing once, run
anywhere (WORA) program, because we can develop a servlet on Windows machine running the
tomcat server or any other server and later we can deploy that servlet simply on any other operating
system like Unix. Servlets are extremely portable so we can run in any platform. So we can call
servlets are platform independent one. Servlets are written entirely in java.

5.7.2.2 POWERFUL

Servlets can harness the full power of the core Java APIs: networking and URL access,
multithreading, image manipulation, data compression, database connectivity, internationalization,
remote method invocation (RMI), CORBA connectivity, and object serialization, among others.
Servlets are also well suited for enabling client/server communication. With a Java-based applet and
a Java-based servlet, you can use RMI and object serialization to handle client/server communication,
which means that you can leverage the same custom code on the client as on the server.

5.7.2.3 EFFICIENCY

The servlet remains in the server‟s memory as a single object instance, when the servlet get
loaded in the server. The servlets are highly scalable because multiple concurrent requests are
handled by separate threads. That is we can handle N number of threads by using a single servlet
class

Dept.of Computer Science And Applications, SJCET, Palai Page 302


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

5.7.2.4 SAFETY

As servlets are written in java, servlets inherit the strong type safety of java language. In java
automatic garbage collection mechanism and a lack of pointers protect the servlets from memory
management problems. Servlets can handle errors safely, due to Java's exception-handling
mechanism. If a servlet divides by zero or performs some other illegal operation, it throws an
exception that can be safely caught and handled by the server, which can politely log the error and
apologize to the user. If a C++-based server extension were to make the same mistake, it could
potentially crash the server..

5.7.2.5 INTEGRATION

Servlets are tightly integrated with the server. Servlet can use the server to translate the file
paths, perform logging, check authorization, and MIME type mapping etc.

5.7.2.6 EXTENSIBILITY

The servlet API is designed in such a way that it can be easily extensible. As it stands today, the
servlet API support Http Servlets, but in later date it can be extended for another type of servlets.
Java Servlets are developed in java which is robust, well-designed and object oriented language
which can be extended or polymorphed into new objects. So the java servlets take all these
advantages and can be extended from existing class to provide the ideal solutions. So servlets are
more extensible and reliable.

5.7.2.7 PERFORMANCE

Due to interpreted nature of java, programs written in java are slow. But the java servlets runs
very fast. These are due to the way servlets run on web server. For any program initialization takes
significant amount of time. But in case of servlets initialization takes place first time it receives a
request and remains in memory till times out or server shut downs. After servlet is loaded, to handle a
new request it simply creates a new thread and runs service method of servlet. In comparison to
traditional CGI scripts which creates a new process to serve the request.

5.7.3 SERVLET CONTAINER

The servlet container is a part of a Web server or application server that provides the
network services over which requests and responses are sent. Servlets are managed by the servlet
container, or servlet engine.When the Webserver receives a request that is for a servlet, the request is
passed to the servlet container. The container makes sure the servlet is loaded and calls it. Container
is responsible for instantiating, invoking, and destroying servlet components.When the servlet is
finished, the. the container reinitializes itself and returns control to the Webserver.

Dept.of Computer Science And Applications, SJCET, Palai Page 303


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

A servlet container uses a Java Virtual Machine to run servlet code as requested by a web
server. The servlet container is also responsible for managing other aspects of the servlet lifecycle:
user sessions, class loading, servlet contexts (which we will discuss in the next session), servlet
configuration information, servlet persistence, and temporary storage

Eg: Tomcat is the Servlet Engine or servlet container than handles servlet requests for Apache

5.7.4 THE SERVLET API

The Java Servlet API is a set of classes and interfaces that define a standard interface between a Web
client and a Web server. The API encases requests as objects so the server can pass them to the
servlet; the responses are similarly encapsulated so the server can pass them back to a client.

The Servlet API consists of two packages, javax.servlet and javax.servlet.http. The javax is there
because servlets are a standard extension to Java, rather than a mandatory part of the API. This means
that while servlets are official Java, Java virtual machine developers aren‟t required to include the
classes for them in their Java development and execution environments

5.7.4.1 THE JAVAX.SERVLET PACKAGE

The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate. The following table summarizes the core interfaces that are
provided in this package. The most significant of these is Servlet. All servlets must implement this
interface or extend a class that implements the interface.The ServletRequest and ServletResponse
interfaces are also very important.

Interface Description

Servlet Declares life cycle methods for a servlet.


ServletConfig Allows servlets to get initialization parameters.
ServletContext Enables servlets to log events and access information about their
environment.
ServletRequest Used to read data from a client request.
ServletResponse Used to write data to a client response.
SingleThreadModel Indicates that the servlet is thread safe

The following table summarizes the core classes that are provided in the javax.servlet package.

Dept.of Computer Science And Applications, SJCET, Palai Page 304


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

Class Description

GenericServlet Implements the Servlet and ServletConfig interfaces.


ServletInputStream Provides an input stream for reading requests from a client.

ServletOutputStream Provides an output stream for writing responses to a client.


ServletException Indicates a servlet error occurred.

5.7.4.2 THE JAVAX.SERVLET.HTTP PACKAGE

The javax.servlet.http package contains a number of interfaces and classes that are
commonly used by servlet developers. These classes and interfaces makes it easy to build servlets
that work with HTTP requests and responses.

The following list summarizes the core interfaces that are provided in this package:

Interface Description

HttpServletRequest Enables servlets to read data from an HTTP request.


HttpServletResponse Enables servlets to write data to an HTTP response.
HttpSession Allows session data to be read and written.
HttpSessionBindingListener Informs an object that it is bound to or unbound from a session.

The following list summarizes the core classes that are provided in this package. The
most important of these is HttpServlet. ServletOutputStream Servlet developers typically extend this
class in order to process HTTP requests.

Class Description

Cookie Allows state information to be stored on a client machine.


HttpServlet Provides methods to handle HTTP requests and responses.
HttpSessionEvent Encapsulates a session-changed event.
HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a session
value, or that a session attribute changed.

Dept.of Computer Science And Applications, SJCET, Palai Page 305


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

(Fig: 5.3)

5.7.4.3 HTTP REQUEST & RESPONSE

HTTP request is a message sent from the client to the server. The beginning of the HTTP
request will have the request line, which will be followed by up to three headers: a general header, a
request header, and an entity header. After that will be the message body.

The request line specifies the method type (such as GET or POST) and the version of HTTP to use.
When a request is submitted from a Web page, it is almost always a GET or a POST method. It
specifies the manner that the servlet expects to receive from the web server the collection of data
submitted by the user. A GET method is commonly used when the amount of form data is small.It
contacts server and sends data in single step and appends data to action URL separated by question
mark in the form URL?name=value&name=value& name=value and is commonly used to
retrieve an HTML document or an image. The POST method is used when the form data is too
large. It supplies parameters to the server through the body section of the request and is therefore
harder to see.

The general header has basic information about the connection, such as cache details, the date,
and how the data are encoded during transfer. The request header is specific to what a request needs;
it defines things such as what languages, encodings, and character sets the client is willing to accept.
The entity headers provide information about the entity body (which is really just the message body
after being decoded) that the request will be providing (such as POST data or a file that is being
uploaded). This data includes the content length in bytes (which is critical and must be accurate) and
the content type. The body of the http request contains the user-entered data or uploaded files which
need to be sent to the server.

Dept.of Computer Science And Applications, SJCET, Palai Page 306


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

The HTTP response begins with a status line. The status line informs the consumer of the HTTP
version in use, a status code (a 3-digit number such as 404 or 200, generated by the server to reflect
the outcome of the request and a reason explaining the code. After the status line are the general
headers, the response header, and the entity headers, followed by the message body. The response
headers contain information about the server and about further access to the resource identified by the
Request. In An HTTP message may have a body of data sent after the header lines. In a response,
this is where the requested resource is returned to the client

5.7.5 SERVLET ARCHITECTURE

( Fig:5.4)

A servlet is any class that either implement the Servlet interface or extend a class that
implements the Servlet interface. Most user-written servlet classes are extensions to HttpServlet
which is an extension of GenericServlet, which implements the Servlet Interface and it includes
methods for handling HTTP-specific data. For example, it provides a number of methods such as
doGet(), doPost(), and doPut(), to handle particular types of HTTP requests (GET, POST, and so on).

5.7.5.1 LIFE CYCLE OF A SERVLET

Three methods are central to the life cycle of a servlet. These are init( ), service( ), and
destroy( ). They are implemented by every servlet and are invoked at specific times by the server

Dept.of Computer Science And Applications, SJCET, Palai Page 307


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

(Fig:5.5)

init()
When a server loads a servlet, it runs the servlet's init method. Even though most servlets
are run in multi-threaded servers, there are no concurrency issues during servlet initialization. This is
because the server calls the init method once, when it loads the servlet, and will not call it again
unless it is reloading the servlet. It is possible to pass initialization parameters to the servlet so it may
configure itself. After the init() method runs, the servlet container marks the servlet as available.

service()
After the server loads and initializes the servlet, the servlet is able to handle client
requests. It processes them in its service method. Each client's request has its call to the service
method. The service( ) method receives the client's request, checks the type of request (GET, POST,
PUT, DELETE, TRACE, OPTION) and call the appropriate method: doGet, doPost, doPut,
doDelete, doTrace, doOption. The service() method can have access to all the resources created in
the init() method

Servlets can run multiple service methods at a time. It is important, therefore, that service
methods be written in a thread-safe manner. If, for some reason, a server should not run multiple
service methods concurrently, the servlet should implement the SingleThreadModel interface. This
interface guarantees that no two threads will execute the servlet's service methods concurrently.

destroy()

If the Servlet is no longer needed for servicing any request, the servlet container calls the
destroy() method . Like the init() method this method is also called only once throughout the life
cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any
request for service and the servlet releases all the resources associated with it. Java Virtual Machine
claims for the memory associated with the resources for garbage collection.

Dept.of Computer Science And Applications, SJCET, Palai Page 308


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

When there are simultaneous requests to a servlet, the server handles each client request by
creating a new thread for each request. This thread is used again and again each time the same client
makes a request to the servlet. For example a servlet is loaded by the Web application server. There
is one instance of a servlet object at a time, and it remains persistent for the life of the servlet. Two
browser clients request the services of the servlet. The server creates a handler thread, for each
request, against the instance object. Each thread has access to variables that were initialized when the
servlet was loaded and each thread handles its own requests. The server sends responses back to the
appropriate client.

5.7.6 CREATING A SERVLET

The Servlet interface class is the central abstraction of the Java Servlet API. This class
defines the methods that manage the servlet and its communications with clients. When a servlet
accepts a service call from a client, it receives two objects, ServletRequest and ServletResponse.
The ServletRequest class encapsulates the communication from the client to the server, while the
ServletResponse class encapsulates the communication from the servlet back to the client.

The ServletRequest interface allows the servlet access to information such as the names
of the parameters passed in by the client, the protocol (scheme) being used by the client, and the
names of the remote host that made the request and the server that received it. It also provides the
servlet with access to the input stream, ServletInputStream, through which the servlet gets data
from clients that are using application protocols such as the HTTP POST and PUT methods.
Subclasses of ServletRequest allow the servlet to retrieve more protocol-specific data. For example,
HttpServletRequest contains methods for accessing HTTP-specific header information.

The ServletResponse interface gives the servlet methods for replying to the client. It
allows the servlet to set the content length and mime type of the reply, and provides an output stream,
ServletOutputStream, and a Writer through which the servlet can send the reply data. Subclasses of
ServletResponse give the servlet more protocol-specific capabilities. For example,
HttpServletResponse contains methods that allow the servlet to manipulate HTTP-specific header
information.

5.7.6.1 HTTPSERVLET CLASS

HttpServlet is an abstract class that simplifies writing HTTP servlets. It extends the
GenericServlet base class and provides a framework for handling the HTTP protocol. Because it is
an abstract class, servlet writers must subclass it and override at least one method. The methods
normally overridden are doGet() and doPost, which respond to HTTP request types get and post
These methods are called by the default implementation of the service() method, which figures out
what kind of request is being made and then invokes the appropriate method. Methods doGet and
doPost receive as arguments an HttpServletRequest object and an HttpServletResponse object that
enable interaction between the client and the server. Important methods of the HttpServlet class are
summarized in Table below

Dept.of Computer Science And Applications, SJCET, Palai Page 309


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

Method Description

void doGet(HttpServletRequest req,


Performs an HTTP GET.
HttpServletResponse res)
throws IOException, ServletException

void doPost(HttpServletRequest req,


Performs an HTTP POST.
HttpServletResponse res)
throws IOException, ServletException
Called by the server when an HTTP
void service(HttpServletRequestreq, request arrives for this servlet. The
HttpServletResponse res) arguments provide access to the HTTP
throws IOException, ServletException request and
response, respectively.
Returns the time (in milliseconds since
long getLastModified(HttpServletRequest midnight, January 1, 1970, GMT) when
req) the requested resource was last
modified.

Table: 5.14

5.7.6.2 HTTPSERVLETREQUEST INTERFACE

When a servlet is asked to handle a request, it typically needs specific information about the
request so that it can process the request appropriately. The Web server that executes the servlet
creates an request object that implements HttpServletRequest and passes this to the servlet's service
method (which, in turn, passes it to doGet or doPost).With this object, the servlet can determine the
actual request (e.g., protocol, URL, type), access parts of the raw request (e.g., headers, input
stream), and get any client-specific request parameters (e.g., form variables, extra path information)

Methods

String getParameter( String name ) - Returns the value associated with a parameter sent to the
servlet as part of a GET or POST request

Enumeration getParameterNames() - Returns the names of all the parameters sent to the servlet as
part of a POST request

String[] getParameterValues( String name ) -Returns a String array containing the values for a
specified servlet parameter.

Cookie[] getCookies() - Returns an array of Cookie objects stored on the client by the server.
Cookies can be used to uniquely identify clients to the servlet

Dept.of Computer Science And Applications, SJCET, Palai Page 310


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

HttpSession getSession(boolean create) - Gets the current valid session associated with this
request, if create is false or, if necessary, creates a new session for the request, if create is true.

5.7.6.3 HTTPSERVLETRESPONSE INTERFACE

In order to do anything useful, a servlet must send a response to each request that is made
to it. In an HTTP servlet, the response can include three components: a status code, any number of
HTTP headers, and a response body. HttpServletResponse interface include different methods
needed to create and manipulate a servlet‟s output. Every call to doGet or doPost for an HttpServlet
receives an object that implements interface HttpServletResponse. The Web server that executes the
servlet creates an HttpServletResponse object and passes this to the servlet's service method (which,
in turn, passes it to doGet or doPost

Methods

void addCookie( Cookie cookie ) - Used to add a Cookie to the header of the response to the client

ServletOutputStream getOutputStream() – Obtains a byte-based output stream enabling binary


data to be sent to the client

PrintWriter getWriter() -Obtains a character-based output stream enabling text data to be sent to
the client

void setContentType( String type ) =Specifies the MIME type of the response to the browser. The
MIME type helps the browser determine how to display the data (or possibly what other application
to execute to process the data).

Eg:MIME type "text/html" indicates that the response is an HTML document, so the browser
displays the HTML

void sendRedirect()-Redirect an HTTP request to another URL

Example: Here we will develop a servlet that handles an HTTP GET request. The servlet is invoked
when a form on a Web page is submitted. The example contains two files. A Web page is defined in
HelloForm.html and a servlet is defined in HelloServlet.java. The HTML source code for
HelloForm.html is shown below. It defines a form that contains a select text box to enter your name
and a submit button. Notice that the action parameter of the form tag specifies a URL. The URL
identifies a servlet to process the HTTP GET request

HelloForm.html

<html><body>
<form method="GET" action="HelloServlet">
Please enter your name:
<input type="text" name="user_name">
<input type="submit" value="OK">
</form>

Dept.of Computer Science And Applications, SJCET, Palai Page 311


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

</body></html>

HelloServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
ServletOutputStream out = response.getOutputStream();
String userName = request.getParameter("user_name");
out.println("<html><head>");
out.println("\t<title>Hello Servlet</title>");
out.println("</head><body>");
out.println("\t<h1>Hello, " + userName + "</h1>");
out.println("</body></html>");
}
}
The source code for HelloServlet.java is shown in the following listing. The
doGet( ) method is overridden to process any HTTP GET requests that are sent to this servlet. It uses
the getParameter( ) method of HttpServletRequest to obtain the value entered by the user. The call
to setContentType( ) establishes the MIME type of the HTTP response. In this program, the MIME
type is text/html. This indicates that the browser should interpret the content as HTML source
code.Next, the getOutputStream() method obtains a ServletOutputStream. Anything written to
this stream is sent to the client as part of the HTTP response. Then println( ) is used to write some
simple HTML source code as the HTTP response.

5.8 Session Tracking

HTTP is a stateless protocol, where information is not automatically saved between


HTTP requests. There are many situations in which we need to shared data between the servlets
which are successively invoked during a session.ie there is a need to maintain the conversational
state. This is done by session tracking. For example :A shopping cart application in which the client
keeps on adding items into his cart using multiple requests .
The different methods to achieve session tracking are:

Dept.of Computer Science And Applications, SJCET, Palai Page 312


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

 Hidden fields
 URL rewriting
 Cookies
 Session tracking API

5.8.1 COOKIES
Cookies are the mostly used technology for session tracking. It serve as a facility for
servers to send information to a client. This information is then housed on the client, from which the
server can later retrieve the information They are generally used to store basic user identification or
configuration information

Java Servlets (which reside on the server) send cookies to clients by adding fields to their HTTP
response headers. Similarly, clients return cookies to servers by adding fields to HTTP request
headers. When a client application (e.g., a Web browser) receives a cookie from a web server, the
client application stores the cookie locally. Upon subsequent request to the web server, the cookie
will be returned.

The content and names of the cookies are opaque to the browser. The browser keeps the cookies
separate for each of the hosts that it is communicating with. In a way, the cookies belong to the server
even though they are stored in the browser. A single browser can store 300 cookies where size of
each cookie is limited to 4KB

The cookie mechanism provides a limited amount of storage space which the server can
make use of on each user‟s browser. Servers use cookies to mark each user‟s browser so the server
can identify which requests are coming from which browser. The browser is very careful not to mix
cookies from different servers. Each cookie is marked with the domain name of the server that set the
cookie and cookies are only sent back on requests destined for the server that initially set the cookie.
Disadvantage is that, the users can opt to disable cookies using their browser preferences. In such
case, the browser will not save the cookie at client computer and session tracking fails

5.8.1.2 THE COOKIE CLASS

A Java cookie is an object of the javax.servlet.http.Cookie class. Common applications for cookies
include storing user preferences, automating low security user sign-on facilities, and helping collect
data used for "shopping cart" style applications

Cookies are created with the Cookie constructor.


Cookie(String name, String value)

Here, the name and value of the cookie are supplied as arguments to the constructor

A servlet can write a cookie to a user‟s machine via the addCookie( ) method of the

Dept.of Computer Science And Applications, SJCET, Palai Page 313


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

HttpServletResponse interface. The data for that cookie is then included in the header of the HTTP
response that is sent to the browser.

Cookies are passed back to servers using fields added to HTTP request headers. In this
API, HTTP request fields are retrieved using the getCookies method of HttpServletRequest
Interface.This returns all of the cookies found in the request.

Some of the information that is saved for each cookie includes the following:

■ The name of the cookie


■ The value of the cookie
■ The expiration date of the cookie
■ The domain and path of the cookie

The expiration date determines when this cookie is deleted from the user‟s machine. If an
expiration date is not explicitly assigned to a cookie, it is deleted when the current browser session
ends. Otherwise, the cookie is saved in a file on the user‟s machine. The domain and path of the
cookie determine when it is included in the header of an HTTP request. If the user enters a URL
whose domain and path match these values, the cookie is then supplied to the Web server. Otherwise,
it is not.

The methods of the Cookie class are summarized in Table

Method Description
void setComment(String c) Sets the comment to c.
void setDomain(String d) Sets the domain to d.
Sets the maximum age of the cookie to secs This is the
number of seconds after which the cookie is deleted.
void setMaxAge(int secs) Passing –1 causes the cookie to be removed when the
browser is terminated.

Sets the path to p.


void setPath(String p)
void setValue(String v) Sets the value to v.
Sets the cookie protocol version to v, which will be 0 or 1.
void setVersion(int v)
Returns the maximum specified age of the cookie. If none
int getMaxAge() was specified, a negative value is returned, indicating the
default behaviour described with setMaxAge
String getName() Returns the name of the cookie.
String getValue() Returns the value of the cookie.

(Table:5.15)

Dept.of Computer Science And Applications, SJCET, Palai Page 314


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

EXAMPLE:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UseCookies extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException, IOException
{
PrintWriter out;
response.setContentType("text/html");
out = response.getWriter();
Cookie cookie = new Cookie("CName","CookieValue");
cookie.setMaxAge(100);
response.addCookie(cookie);
out.println("<HTML><HEAD><TITLE>");
out.println(" Use of cookie in servlet");
out.println("</TITLE></HEAD><BODY BGCOLOR='cyan'>");
out.println(" <b>This is a Cookie example</b>");
out.println("</BODY></HTML>");
out.close();
}
}

5.8.2 SESSION API

Using sessions in servlets is quite straightforward, and involves looking up the session object
associated with the current request, creating a new session object when necessary, looking up
information associated with a session, storing information in a session, and discarding completed or
abandoned session.

The first time a user connects to a session enabled servlet, the servlet simply creates a
javax.servlet.http.HttpSession object. The servlet can then bind data to this object, so subsequent
requests can read the data. After a certain amount of inactive time, the session object is destroyed. A
servlet uses the getSession() method of HttpServletRequest to retrieve the current session object.
This method takes a single boolean argument.If you pass true, and there is no current session object,
the method creates and returns a new HttpSession object. If you pass false, the method returns null if
there is no current session object.

Dept.of Computer Science And Applications, SJCET, Palai Page 315


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

5.8.2.1 HTTPSESSION INTERFACE

The HttpSession interface is implemented by services to provide an association between


an HTTP client and HTTP server. This association, or session, persists over multiple connections
and/or requests during a given time period. Sessions are used to maintain state and user identity
across multiple page requests.

HttpSession defines methods which store standard session properties, such as an


identifier for the session, and the context for the session. Several of its methods are summarized in
the table below. All of these methods throw an IllegalStateException if the session has already been
invalidated.

Method Description
Object getAttribute(String attr) Returns the value associated with the name passed in
attr. Returns null if attr is not found
Enumeration getAttributeNames( ) Returns an enumeration of the attribute names
associated with the session.
void removeAttribute(String attr) Removes the attribute specified by attr from the
session
void setAttribute(String attr, Object val) Associates the value passed in val with the attribute
name passed in attr.

(Table:5.16)

5.8.2.2 THE SESSION LIFE CYCLE

Sessions do not last forever. A session either expires automatically, after a set time of inactivity
(for the Java Web Server the default is 30 minutes), or manually, when it is explicitly invalidated by
a servlet. When a session expires (or is invalidated), the HttpSession object and the data values it
contains are removed from the system.Beware that any information saved in a user's session object is
lost when the session is invalidated. If you need to retain information beyond that time, you should
keep it in an external location (such as a database) and store a handle to the external data in the
session object (or your own persistant cookie).

There are several methods involved in managing the session life cycle:

public boolean HttpSession.isNew()

This method returns whether the session is new. A session is considered new if it has been
created by the server but the client has not yet acknowledged joining the session. For example, if a
server supports only cookie-based sessions and a client has completely disabled the use of cookies,
calls to the getSession() method of HttpServletRequest always return new sessions.

Dept.of Computer Science And Applications, SJCET, Palai Page 316


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

public void HttpSession.invalidate()- This method causes the session to be immediately invalidated.
All objects stored in the session are unbound.

public long HttpSession.getCreationTime()-This method returns the time at which the session was
created, as a long value that represents the number of milliseconds since the epoch (midnight,
January 1, 1970, GMT).

public long HttpSession.getLastAccessedTime()- This method returns the time at which the client
last sent a request associated with this session, as a long value that represents the number of
milliseconds since the epoch.Each of these methods can throw a java.lang.IllegalStateException if the
session being accessed is invalid.

5.9 JSP (Java Server Pages)

Servlets are powerful and sometimes they are a bit cumbersome when it comes to
generating complex HTML. Most servlets contain a little code that handles application logic and a lot
more code that handles output formatting. This can make it difficult to separate and reuse portions of
the code when a different output format is needed. For these reasons, web application developers turn
towards JSP as their preferred servlet environment. JSP has been built on top of the Servlet API and
utilizes Servlet semantics.

Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites.
JSP provide excellent server side scripting support for creating database driven web applications. JSP
enable the developers to directly insert java code into html file, this makes the development process
very simple and its maintenance also becomes very easy. JSP pages are efficient, it loads into the
web servers memory on receiving the request very first time and the subsequent calls are served
within a very short period of time.

JSP have the following advantages:

 They have built-in support for HTTP sessions, which makes application programming possible.

 They have full access to Java technology–network awareness, threads, and database
connectivity

 They are automatically recompiled when necessary.

 Because they exist in the ordinary Web server document space, addressing JSP pages is simpler
than addressing servlets.

 Because JSP pages are HTML-like, they have greater compatibility with Web development
tools

Dept.of Computer Science And Applications, SJCET, Palai Page 317


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

5.9.1 HOW JSP WORKS


A JSP page exists in three forms:

JSP source code :This is the form the developer actually writes. It exists in a text file with an
extension of .jsp, and consists of a mix of HTML template code, Java language statements, and JSP
directives and actions that describe how to generate a Web page to service a particular request.

Java source code : The JSP container translates the JSP source code into the source code for an
equivalent Java servlet as needed. This source code is typically saved in a work area and is often
helpful for debugging.

Compiled Java class: Like any other Java class, the generated servlet code is compiled into byte
codes in a .class file, ready to be loaded and executed.

To process a JSP file, we need a JSP container or engine that can be connected with a
web server or can be accommodated inside a web server. Firstly when a web browser seeks a JSP file
through an URL from the web server, the web server recognizes the .jsp file extension in the URL
requested by the browser and understands that the requested resource is a JavaServer Page. Then the
web server passes the request to the JSP engine. The JSP page is then translated into a Java class,
which is then compiled into a servlet.

This translation and compilation phase occurs only when the JSP file is requested for the
first time, or if it undergoes any changes to the extent of getting retranslated and recompiled. For
each additional request of the JSP page thereafter, the request directly goes to the servlet byte code,
which is already in memory. Thus when a request comes for a servlet, an init() method is called when
the Servlet is first loaded into the virtual machine, to perform any global initialization that every
request of the servlet will need. Then the individual requests are sent to a service() method, where the
response is put together. The servlet creates a new thread to run service() method for each request.
The request from the browser is converted into a Java object of type HttpServletRequest, which is
passed to the Servlet along with an HttpServletResponse object that is used to send the response back
to the browser. The servlet code performs the operations specified by the JSP elements in the .jsp file.

5.9.2 Components of a JSP Page

A .jsp file can contain JSP elements, fixed template data(HTML), or any combination of
the two.JSP elements are instructions to the JSP container about what code to generate and how it
should operate. These elements have specific start and end tags that identify them to the JSP
compiler. Template data is everything else that is not recognized by the JSP container. Template data
(usually HTML) is passed through unmodified, so the HTML that is ultimately generated contains
the template data exactly as it was coded in the .jsp file.

Dept.of Computer Science And Applications, SJCET, Palai Page 318


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

There are five types of JSP tags:

 Directive tag
 Comment Tag
 Expression tag
 Declaration statement tag
 Scriplet tag

5.9.2.1 DIRECTIVES
A JSP directive commands the jsp virtual engine to perform a specific task.They have the
general form:

<%@ directive-name [attribute="value" attribute="value" ...] %>

There are three standard directives available in all compliant JSP environments:
 page
 include
 taglib

The page Directive


The page directive apply different properties for the page like language support, page information
and import etc. by using the different attributes of the directives It has the following syntax:
<%@ page [attribute="value" attribute="value" ...] %>
Following are names of some of important the attributes of the page directive used in JSP

 import: : This attribute imports the java packages and it's classes .We can import more than
one java packages and classes by separating with comma (,)

Eg: <%@ page import="java.util.*" %>

 contentType: This attribute specifies the MIME type and the character encoding i.e. used for
the JSP response

Eg:<%@ page contentType="text/plain" %>

 isThreadSafe="true|false":„true‟ indicated that multiple requests can be processed


simultaneously with a single servlet instance .„false‟ indicates that only one request can be
processed at a time.

Eg: <%@page isThreadSafe=”false”/>

The include Directive

Dept.of Computer Science And Applications, SJCET, Palai Page 319


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

The include directive merges the contents of another file at translation time into the .jsp source
input stream, much like a #include C preprocessor directive. The syntax is
<%@ include file="filename" %>
where filename is an absolute or relative pathname interpreted according to the current
servlet context.

Eg: <%@ include file="/doc/legal/disclaimer.html" %>

The taglib Directive

JSP technology supports the development of reusable modules called custom actions. A custom
action is invoked by using a custom tag in a JSP page and tag library is a collection of custom tags.
You declare that a JSP page will use tags defined in a tag library by including a taglib directive in the
page before any custom tag is used. The syntax of the directive is:

<%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %>

where tagLibraryURI is the URL of a Tag Library Descriptor and tagPrefix is a unique prefix used
to identify custom tags used later in the page.

Eg: <%@ taglib uri="/tlds/FancyTableGenerator.tld" prefix="ft" %>

and if FancyTableGenerator.tld defines a tag named table, then the page can contain tags of the
following type

<ft:table>
...
</ft:table>

5.9.2.2 COMMENTS

The JSP specification provides two means of including comments in a JSP page: one for hidden
comments only visible in the JSP page itself and one for comments included in
the HTML or XML output generated by the page. The former type has the syntax
<%- - This is a hidden JSP comment - -%>

and the latter looks like this:

<!- - This is included in the generated HTML - ->


When the JSP compiler encounters the start tag <%- - of a JSP comment, it ignores everything
from that point in the file until it finds the matching end tag - -%>. This means JSP comments can be
used to disable (or "comment out") sections of the JSP page.

Dept.of Computer Science And Applications, SJCET, Palai Page 320


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

The other comment type uses the normal HTML or XML comment tag. Comments
of this type are passed through unaltered to the response output stream and are included in the
generated HTML. They are invisible in the browser window, but can be seen by invoking the View
Source menu option.

5.9.2.3 EXPRESSIONS

JSP provides a simple means for accessing the value of a Java variable or other expression and
merging that value with the HTML in the page. The syntax is
<%= expression %>

where exp is any valid Java expression. The expression can have any data value, as long as it can be
converted to a string.

Eg:<%= new java.util.Date() %>

5.9.2.4 SCRIPTLETS

A scriptlet consists of one or more valid Java statements. A scriptlet is a block of Java code that
is executed at request-processing time. A scriptlet is enclosed between "<%" and "%>". What the
scriptlet actually does depends on the code, and it can produce output into the output stream to the
client. Multiple scriptlets are combined in the compiled class in the order in which they appear in the
JSP. Scriptlets like any other Java code block or method, can modify objects inside them as a result
of method invocations. Scriptlets have the following form:

<% Java Code %>


Eg: <% System.out.println( "Evaluating date now);
java.util.Date date = new java.util.Date(); %>

5.9.2.5 DECLARATIONS

A declaration is a block of Java code in a JSP that is used to define class-wide variables and
methods in the generated class file. Declarations are initialized when the JSP page is initialized and
have class scope. Anything defined in a declaration is available throughout the JSP, to other
declarations, expressions or code. It has the following form:

<%! //start of declaration tag


statement1;
statement2; //variables or methods declaration
..........;
..........;
%> //end of declaration tag

Dept.of Computer Science And Applications, SJCET, Palai Page 321


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

Since declarations do not generate any output, they are normally used in conjunction with JSP
expressions or scriptlets
Eg: <%!
private int example = 0 ;
private int test = 5 ;
%>

JSP PAGE EXAMPLE:

<html>
<head>
<title> Hello JSP </title>
</head>
<body>
<p> Hello World:
<%= new java.util.Date() %>
</p>
</body>
</html>

This extract shows the part of above jsp that produces the output

out = pageContext.getOut();
_jspx_out = out;

out.write("<html>\r\n");
out.write("<head> ");
out.write("<title> Hello JSP ");
out.write("</title> ");
out.write("</head>\r\n");
out.write("<body> \r\n");
out.write("<p> Hello World:\r\n ");
out.print( new java.util.Date() );
out.write("\r\n");
out.write("</p>\r\n");
out.write("</body>\r\n");
out.write("</html>\r\n");

Dept.of Computer Science And Applications, SJCET, Palai Page 322


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

5.9.3 VARIABLE DECLARATION

It is possible to declare variables in jsp by using the same coding techniques which is used in
java .Declarations can be used to define and initialize variables in jsp. The variables will be available
to scriptlets, expressions, and other declarations.

Eg: <%! int age=29;%>


your age is:<%=age%>

5.9.4 METHOD DEFINITIONS

Declarations can be used to define additional methods. The syntax is no different than for any
other method definitions, except for the <%! and %> delimiters. Once the method is defined it can be
called by using an expression tag.JSP virtual engine resolves the tag that calls method by replacing
tag by result returned by the method.

Eg:<HTML>
<HEAD>
<TITLE>JSP PROGRAMMING</HEAD>
<BODY>
<%! boolean curve(int grade)
{
return 10+grade;
}%>
<P your curved grade is:<%=curve(80)%></P>
</BODY></HTML>

5.9.5 IMPLICIT OBJECTS

JSP container provides a list of instantiated objects for you to access different kind of
data in a web application. These objects are called implicit objects because they are automatically
instantiated. These objects are implicitly available inside scriptlets and expressions (but not
declarations).
e.g. request, response, session etc

5.9.5.1 REQUEST OBJECT

The request object. contains a reference to the HttpServletRequest object.This object


encapsulates the details of the HTTP request generated by the Web browser or other
Client - its parameters, attributes, headers, and data.

Following are some useful methods of the request Object:

Dept.of Computer Science And Applications, SJCET, Palai Page 323


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

String getParameter(String name): Given the name of a single-valued form parameter, returns its
value.
Enumeration getParameterNames() : Returns an enumeration of the names of all form parameters
passed to this request.
HttpSession getSession(boolean create) : Returns the current HttpSession object. If one does not
exist, either creates a new one or returns null, depending on the create flag.

5.9.5.2 RESPONSE OBJECT

This object encapsulates the output returned to the HTTP client, providing the page auth
or with a means for setting response headers and the status code. It also has methods for accessing the
response output stream, but the JSP specification prohibits directly accessing this stream.

boolean isCommitted() : Returns a flag indicating whether the HTTP response has already been
returned to the client.
void setHeader(String name, String value) : Sets an HTTP header with the specified name and
value.
void setStatus(int sc): Sets the HTTP status to the specified value.

5.9.5.3 SESSION OBJECT

HTTP is a stateless protocol, which means it doesn‟t remember from one request to the
next anything about previous requests. In any web application user moves from one page to another
and it becomes necessary to track the user data and objects throughout the application. JSP provide
an implicit object "session", which can be use to save the data specific to a particular user. It persists
between HTTP requests and can store named objects of any kind. By default, the JSP container
creates an HttpSession object or accesses the currently active one. If you do not need to retain objects
between requests, you can turn off automatic
session creation by specifying session="false" in the page directive.

Object getAttribute(String name) : Returns the object with the specified name, if it exists in the
session

Enumeration getAttributeNames() : Returns an enumeration of the names of all the objects stored
in the session.

String getId() : Returns the unique session ID. This ID must be stored by the client (Web
browser) between requests and passed back to the JSP container to identify which session is required.

Dept.of Computer Science And Applications, SJCET, Palai Page 324


MODULE V MCA-301 Java and Web Programming ADMN 2011-‘14

5.9.6 COOKIES

A cookie is a small, named data element the server passes to a client with a Set-Cookie
header as part of the HTTP response. The client is expected to store the cookie and return it to the
server with a Cookie header on subsequent requests to the same server. Along with the name and
value, the cookie may contain:
 An expiration date, after which the client is no long expected to retain the cookie.
If no date is specified, the cookie expires as soon as the browser session ends.
 A domain name, such as servername.com, which restricts the subset of URLs for which
the cookie is valid. If unspecified, the cookie is returned with all requests to the
originating Web server.
 A path name that further restricts the URL subset.
 A secure attribute, which, if present, indicates the cookie should only be returned if the
connection uses a secure channel,

A cookie can be created and read by using methods of Cookie class.

<html>
<head>
<title>JSP PROGRAMMING</head>
<body>
<%! String MyCookieName=‘userID’;
String MyCookieValue=‘ JK1234’
response.addCookie(new Cookie(,MyCookieName, MyCookieValue); %>
</body>
</html>

Dept.of Computer Science And Applications, SJCET, Palai Page 325

S-ar putea să vă placă și