WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ......

136
WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 1 JavaScript is a very powerful client-side scripting language. JavaScript is used mainly for enhancing the interaction of a user with the webpage. In other words, you can make your webpage more lively and interactive, with the help of JavaScript. JavaScript is also being used widely in game development and Mobile application development. JavaScript is a programming language that can be included on web pages to make them more interactive. You can use it to check or modify the contents of forms, change images, open new windows and write dynamic page content. You can even use it with CSS to make DHTML (Dynamic HyperText Markup Language). This allows you to make parts of your web pages appear or disappear or move around on the page. JavaScripts only execute on the page(s) that are on your browser window at any set time. When the user stops viewing that page, any scripts that were running on it are immediately stopped. The only exceptions are cookies or various client side storage APIs, which can be used by many pages to store and pass information between them, even after the pages have been closed. JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. JavaScript is a lightweight, interpreted programming language. Designed for creating network-centric applications. Complementary to and integrated with Java. Complementary to and integrated with HTML. Open and cross-platform Client-side JavaScript Client-side JavaScript is the most common form of the language. The script should be included in or referenced by an HTML document for the code to be interpreted by the browser. It means that a web page need not be a static HTML, but can include programs that interact with the user, control the browser, and dynamically create HTML content. The JavaScript client-side mechanism provides many advantages over traditional CGI server- side scripts. For example, you might use JavaScript to check if the user has entered a valid e- mail address in a form field. The JavaScript code is executed when the user submits the form, and only if all the entries are valid, they would be submitted to the Web Server. JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other actions that the user initiates explicitly or implicitly.

Transcript of WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ......

Page 1: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

1

JavaScript is a very powerful client-side scripting language. JavaScript is used mainly for

enhancing the interaction of a user with the webpage. In other words, you can make your

webpage more lively and interactive, with the help of JavaScript. JavaScript is also being

used widely in game development and Mobile application development.

JavaScript is a programming language that can be included on web pages to make them more

interactive. You can use it to check or modify the contents of forms, change images, open

new windows and write dynamic page content. You can even use it with CSS to make

DHTML (Dynamic HyperText Markup Language).

This allows you to make parts of your web pages appear or disappear or move around on the

page. JavaScripts only execute on the page(s) that are on your browser window at any set

time. When the user stops viewing that page, any scripts that were running on it are

immediately stopped.

The only exceptions are cookies or various client side storage APIs, which can be used by

many pages to store and pass information between them, even after the pages have been

closed.

JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript,

possibly because of the excitement being generated by Java. JavaScript made its first

appearance in Netscape 2.0 in 1995 with the name LiveScript.

• JavaScript is a lightweight, interpreted programming language.

• Designed for creating network-centric applications.

• Complementary to and integrated with Java.

• Complementary to and integrated with HTML.

• Open and cross-platform

Client-side JavaScript

Client-side JavaScript is the most common form of the language. The script should be

included in or referenced by an HTML document for the code to be interpreted by the

browser.

It means that a web page need not be a static HTML, but can include programs that interact

with the user, control the browser, and dynamically create HTML content.

The JavaScript client-side mechanism provides many advantages over traditional CGI server-

side scripts. For example, you might use JavaScript to check if the user has entered a valid e-

mail address in a form field.

The JavaScript code is executed when the user submits the form, and only if all the entries are

valid, they would be submitted to the Web Server.

JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and

other actions that the user initiates explicitly or implicitly.

Page 2: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

2

Advantages of JavaScript

The merits of using JavaScript are −

Less server interaction − You can validate user input before sending the page off to the

server. This saves server traffic, which means less load on your server.

Immediate feedback to the visitors − They don't have to wait for a page reload to see if they

have forgotten to enter something.

Increased interactivity − You can create interfaces that react when the user hovers over

them with a mouse or activates them via the keyboard.

Richer interfaces − You can use JavaScript to include such items as drag-and-drop

components and sliders to give a Rich Interface to your site visitors.

History

JavaScript was developed by Brendan Eich in 1995, which appeared in Netscape, a popular

browser of that time.

The language was initially called LiveScript and was later renamed JavaScript. There are

many programmers who think that JavaScript and Java are the same. In fact, JavaScript and

Java are very much unrelated. Java is a very complex programming language whereas

JavaScript is only a scripting language. The syntax of JavaScript is mostly influenced by the

programming language C.

JavaScript cannot run on its own. In fact, the browser is responsible for running JavaScript

code. When a user requests an HTML page with JavaScript in it, the script is sent to the

browser and it is up to the browser to execute it.

Page 3: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

3

Simple JavaScript Code

You should place all your JavaScript code within <script> tags (<script> and </script>) if you

are keeping your JavaScript code within the HTML document itself.

<script type="text/javascript">

JavaScript can be implemented using JavaScript statements that are placed within the

<script>... </script>.

You can place the <script> tags, containing your JavaScript, anywhere within your web page,

but it is normally recommended that you should keep it within the <head> tags.

The script tag takes two important attributes −

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>

First JavaScript Script

Let us take a sample example to print out "Hello World". We added an optional HTML

comment that surrounds our JavaScript code. This is to save our code from a browser that

does not support JavaScript.

The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we add that

to prevent a browser from reading the end of the HTML comment as a piece of JavaScript

code. Next, we call a function document.write which writes a string into our HTML

document.

This function can be used to write text, HTML, or both. Take a look at the following code.

Page 4: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

4

<html>

<body>

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

<!--

document.write("Hello World!")

//-->

</script>

</body>

</html>

This code will produce the following result – Hello World!

Whitespace and Line Breaks

JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You can

use spaces, tabs, and newlines freely in your program and you are free to format and indent

your programs in a neat and consistent way that makes the code easy to read and understand.

Semicolons are Optional

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 each of

your statements are placed on a separate line. For example, the following code could be

written without semicolons.

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

<!--

var1 = 10

var2 = 20

//-->

</script>

But when formatted in a single line as follows, you must use semicolons –

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

<!--

var1 = 10; var2 = 20;

//-->

</script>

Page 5: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

5

Case Sensitivity

JavaScript is a case-sensitive language. This means that the language keywords, variables,

function names, and any other identifiers must always be typed with a consistent

capitalization of letters.

So the identifiers Time and TIME will convey different meanings in JavaScript.

NOTE − Care should be taken while writing variable and function names in JavaScript.

Comments in JavaScript

✓ JavaScript comments can be used to explain JavaScript code, and to make it more

readable.

✓ JavaScript comments can also be used to prevent execution, when testing alternative

code.

Single Line Comments

Single line comments start with //.

Any text between // and the end of the line will be ignored by JavaScript (will not be

executed).

This example uses a single-line comment before each code line:

<!DOCTYPE html>

<html>

<body>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>

// Change heading:

document.getElementById("myH").innerHTML = "My First Page";

// Change paragraph:

document.getElementById("myP").innerHTML = "My first paragraph.";

</script>

<p><strong>Note:</strong> The comments are not executed.</p>

</body>

</html>

Page 6: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

6

Multi-line Comments

Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored by JavaScript.

This example uses a multi-line comment (a comment block) to explain the code:

<!DOCTYPE html>

<html>

<body>

<h1 id="myH"></h1>

<p id="myP"></p>

<script>

/*

The code below will change

the heading with id = "myH"

and the paragraph with id = "myp"

in my web page:

*/

document.getElementById("myH").innerHTML = "My First Page";

document.getElementById("myP").innerHTML = "My first paragraph.";

</script>

<p><strong>Note:</strong> The comment block is not executed.</p>

</body>

</html>

There is a flexibility given to include JavaScript code anywhere in an HTML document.

However the most preferred ways to include JavaScript in an HTML file are as follows −

✓ Script in <head>...</head> section.

✓ Script in <body>...</body> section.

✓ Script in <body>...</body> and <head>...</head> sections.

✓ Script in an external file and then include in <head>...</head> section.

In the following section, we will see how we can place JavaScript in an HTML file in

different ways.

JavaScript in <head>...</head> section

If you want to have a script run on some event, such as when a user clicks somewhere, then

you will place that script in the head as follows –

Page 7: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

7

<html>

<head>

<script type="text/javascript">

<!--

function sayHello() {

alert("Hello World")

}

//-->

</script>

</head>

<body>

<input type="button" onclick="sayHello()" value="Say Hello" />

</body>

</html>

JavaScript in <body>...</body> section

If you need a script to run as the page loads so that the script generates content in the page,

then the script goes in the <body> portion of the document. In this case, you would not have

any function defined using JavaScript. Take a look at the following code.

<html>

<head>Google</head>

<body>

<script type="text/javascript">

<!--

document.write("Hello World")

//-->

</script>

<p>This is web page body </p>

</body>

</html>

Page 8: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

8

JavaScript in <body> and <head> Sections

You can put your JavaScript code in <head> and <body> section altogether as follows –

<html>

<head>

<script type="text/javascript">

<!--

function sayHello() {

alert("Hello World")

}

//-->

</script>

</head>

<body>

<script type="text/javascript">

<!--

document.write("Hello World")

//-->

</script>

<input type="button" onclick="sayHello()" value="Say Hello" />

</body>

</html>

JavaScript in External File

JavaScript code can be used to multiple pages.

Here is an example to show how you can include an external JavaScript file in your HTML

code using script tag and its src attribute.

<head>

<script type="text/javascript" src="filename.js" ></script>

</head>

Page 9: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

9

To use JavaScript from an external file source, you need to write all your JavaScript source

code in a simple text file with the extension ".js" and then include that file as shown above.

JAVASCRIPT DOM MODEL

The Document Object Model (DOM) is a specification that determines a mapping between

programming language objects and the elements of an HTML document.

HTML DOM Objects

✓ Environment objects – Window, Navigator, Screen, History, Location, Document

✓ HTML objects – Anchor, Area, Base, Body, Button, Event, Form, Frame, Frameset,

Iframe, Image, Checkbox, FileUpload, Hidden, Password, Radio, Reset, Submit,

Text, Link, Meta, Object, Option, Select, Style, Table, Table Cell, Table Row,

TextArea.

HTML DOM: Document

The Document object represents an HTML document and can be used to access all

documents in a page.

A Document contains several collections – anchors, forms, images, links.

Has several properties – body, cookie, domain, lastModified, referrer, title, URL.

Has several useful methods – getElementById, getElementsByName,

getElementsByTagName, write, writeln, open, close.

When a web page is loaded, the browser creates a Document Object Model of the page.

The HTML DOM model is constructed as a tree of Objects:

With the object model, JavaScript gets all the power it needs to create dynamic HTML:

❖ JavaScript can change all the HTML elements in the page

Page 10: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

10

❖ JavaScript can change all the HTML attributes in the page

❖ JavaScript can change all the CSS styles in the page

❖ JavaScript can remove existing HTML elements and attributes

❖ JavaScript can add new HTML elements and attributes

❖ JavaScript can react to all existing HTML events in the page

❖ JavaScript can create new HTML events in the page

What is the DOM?

The DOM is a W3C (World Wide Web Consortium) standard.

The DOM defines a standard for accessing documents:

"The W3C Document Object Model (DOM) is a platform and language-neutral interface that

allows programs and scripts to dynamically access and update the content, structure, and

style of a document."

❖ The W3C DOM standard is separated into 3 different parts:

❖ Core DOM - standard model for all document types

❖ XML DOM - standard model for XML documents

❖ HTML DOM - standard model for HTML documents

What is the HTML DOM?

The HTML DOM is a standard object model and programming interface for HTML. It

defines:

❖ The HTML elements as objects

❖ The properties of all HTML elements

❖ The methods to access all HTML elements

❖ The events for all HTML elements

In other words: The HTML DOM is a standard for how to get, change, add, or delete HTML

elements.

JavaScript - HTML DOM Methods

• HTML DOM methods are actions you can perform (on HTML Elements).

• HTML DOM properties are values (of HTML Elements) that you can set or change.

The DOM Programming Interface

• The HTML DOM can be accessed with JavaScript (and with other programming

languages).

• In the DOM, all HTML elements are defined as objects.

• The programming interface is the properties and methods of each object.

• A property is a value that you can get or set (like changing the content of an HTML

element).

• A method is an action you can do (like add or deleting an HTML element).

Page 11: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

11

<!DOCTYPE html>

<html>

<body>

<h2>My First Page</h2>

<p id="demo"></p>

<script>

document.getElementById("demo").innerHTML = "Hello World!";

</script>

</body>

</html>

The getElementById Method

The most common way to access an HTML element is to use the id of the element.

In the example above the getElementById method used id="demo" to find the element.

The innerHTML Property

The easiest way to get the content of an element is by using the innerHTML property.

The innerHTML property is useful for getting or replacing the content of HTML elements.

The innerHTML property can be used to get or change any HTML element, including

<html> and <body>.

The HTML DOM document object is the owner of all other objects in your web page.

The HTML DOM Document Object

The document object represents your web page.

If you want to access any element in an HTML page, you always start with accessing the

document object.

Below are some examples of how you can use the document object to access and manipulate

HTML.

Page 12: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

12

Finding HTML Elements

Changing HTML Elements

Adding and Deleting Elements

Adding Events Handlers

JavaScript HTML DOM Elements

Finding HTML Elements

Often, with JavaScript, you want to manipulate HTML elements.

To do so, you have to find the elements first. There are a couple of ways to do this:

• Finding HTML elements by id

• Finding HTML elements by tag name

Page 13: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

13

• Finding HTML elements by class name

• Finding HTML elements by CSS selectors

• Finding HTML elements by HTML object collections

Finding HTML Element by Id

The easiest way to find an HTML element in the DOM, is by using the element id.

This example finds the element with id="intro":

<!DOCTYPE html>

<html> <body>

<p id="intro">Hello World!</p>

<p>This example demonstrates the <b>getElementById</b>

method!</p>

<p id="demo"></p>

<script>

var myElement = document.getElementById("intro");

document.getElementById("demo").innerHTML =

"The text from the intro paragraph is " + myElement.innerHTML;

</script>

</body>

</html>

If the element is found, the method will return the element as an object (in myElement).

If the element is not found, myElement will contain null.

Finding HTML Elements by Tag Name

This example finds all <p> elements:

Page 14: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

14

This example finds the element with id="main", and then finds all <p> elements inside

"main":

The HTML DOM allows JavaScript to change the content of HTML elements.

Changing the HTML Output Stream

JavaScript can create dynamic HTML content:

Date: Wed Feb 21 2018 13:29:40 GMT+0530 (India Standard Time)

In JavaScript, document.write() can be used to write directly to the HTML output stream:

Page 15: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

15

Changing HTML Content

The easiest way to modify the content of an HTML element is by using

the innerHTML property.

To change the content of an HTML element, use this syntax:

document.getElementById(id).innerHTML = new HTML

This example changes the content of a <p> element:

Example explained:

• The HTML document above contains a <p> element with id="p1"

• We use the HTML DOM to get the element with id="p1"

• A JavaScript changes the content (innerHTML) of that element to "New text!"

This example changes the content of an <h1> element:

Page 16: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

16

Example explained:

• The HTML document above contains an <h1> element with id="id01"

• We use the HTML DOM to get the element with id="id01"

• A JavaScript changes the content (innerHTML) of that element to "New Heading"

Changing the Value of an Attribute

To change the value of an HTML attribute, use this syntax:

document.getElementById(id).attribute = new value

This example changes the value of the src attribute of an <img> element:

Example explained:

• The HTML document above contains an <img> element with id="myImage"

• We use the HTML DOM to get the element with id="myImage"

• A JavaScript changes the src attribute of that element from "smiley.gif" to

"landscape.jpg"

Page 17: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

17

JavaScript HTML DOM - Changing CSS

The HTML DOM allows JavaScript to change the style of HTML elements.

Changing HTML Style

To change the style of an HTML element, use this syntax:

document.getElementById(id).style.property = new style

The following example changes the style of a <p> element:

Using Events

The HTML DOM allows you to execute code when an event occurs.

Events are generated by the browser when "things happen" to HTML elements:

• An element is clicked on

• The page has loaded

• Input fields are changed

This example changes the style of the HTML element with id="id1", when the user clicks a

button:

Page 18: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

18

JavaScript HTML DOM Events

HTML DOM allows JavaScript to react to HTML events:

A JavaScript can be executed when an event occurs, like when a user clicks on an HTML

element.

To execute code when a user clicks on an element, add JavaScript code to an HTML event

attribute:

onclick=JavaScript

Examples of HTML events:

• When a user clicks the mouse

• When a web page has loaded

• When an image has been loaded

• When the mouse moves over an element

• When an input field is changed

• When an HTML form is submitted

• When a user strokes a key

In this example, the content of the <h1> element is changed when a user clicks on it:

Page 19: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

19

In this example, a function is called from the event handler:

JavaScript HTML DOM EventListener

The addEventListener() method

The addEventListener() method attaches an event handler to the specified element.

The addEventListener() method attaches an event handler to an element without overwriting

existing event handlers.

You can add many event handlers to one element.

You can add many event handlers of the same type to one element, i.e two "click" events.

You can add event listeners to any DOM object not only HTML elements. i.e the window

object.

Add an event listener that fires when a user clicks a button:

Page 20: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

20

The addEventListener() method makes it easier to control how the event reacts to bubbling.

When using the addEventListener() method, the JavaScript is separated from the HTML

markup, for better readability and allows you to add event listeners even when you do not

control the HTML markup.

You can easily remove an event listener by using the removeEventListener() method.

element.addEventListener(event, function, useCapture);

The first parameter is the type of the event (like "click" or "mousedown").

The second parameter is the function we want to call when the event occurs.

The third parameter is a boolean value specifying whether to use event bubbling or event

capturing. This parameter is optional.

Note that you don't use the "on" prefix for the event; use "click" instead of "onclick".

Add an Event Handler to an Element

Alert "Hello World!" when the user clicks on an element:

Page 21: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

21

Add Many Event Handlers to the Same Element

The addEventListener() method allows you to add many events to the same element, without

overwriting existing events:

Add an Event Handler to the Window Object

The addEventListener() method allows you to add event listeners on any HTML DOM object

such as HTML elements, the HTML document, the window object, or other objects that

support events, like the xmlHttpRequest object.

Page 22: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

22

Date and Objects

JavaScript is an Object Oriented Programming (OOP) language. A programming language

can be called object-oriented if it provides four basic capabilities to developers −

• Encapsulation − the capability to store related information, whether data or methods,

together in an object.

• Aggregation − the capability to store one object inside another object.

• Inheritance − the capability of a class to rely upon another class (or number of

classes) for some of its properties and methods.

• Polymorphism − the capability to write one function or method that works in a

variety of different ways.

Objects are composed of attributes. If an attribute contains a function, it is considered to be a

method of the object, otherwise the attribute is considered a property.

Object Properties

Object properties can be any of the three primitive data types, or any of the abstract data

types, such as another object. Object properties are usually variables that are used internally

in the object's methods, but can also be globally visible variables that are used throughout

the page.

The syntax for adding a property to an object is −

objectName.objectProperty = propertyValue;

For example − The following code gets the document title using the "title"property of

the document object.

var str = document.title;

Page 23: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

23

Object Methods

Methods are the functions that let the object do something or let something be done to it.

There is a small difference between a function and a method – at a function is a standalone

unit of statements and a method is attached to an object and can be referenced by

the this keyword.

Methods are useful for everything from displaying the contents of the object to the screen to

performing complex mathematical operations on a group of local properties and parameters.

For example − Following is a simple example to show how to use the write() method of

document object to write any content on the document.

document.write("This is test");

User-Defined Objects

All user-defined objects and built-in objects are descendants of an object called Object.

The new Operator

The new operator is used to create an instance of an object. To create an object,

the new operator is followed by the constructor method.

In the following example, the constructor methods are Object(), Array(), and Date(). These

constructors are built-in JavaScript functions.

var employee = new Object();

var books = new Array("C++", "Perl", "Java");

var day = new Date("August 15, 1947");

The Object() Constructor

A constructor is a function that creates and initializes an object. JavaScript provides a

special constructor function called Object() to build the object. 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.

Example 1

Try the following example; it demonstrates how to create an Object.

<html>

<head>

<title>User-defined objects</title>

Page 24: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

24

<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>

Output

Book name is : Perl

Book author is : Mohtashim

Example 2

This example demonstrates how to create an object with a User-Defined Function.

Here this keyword is used to refer to the object that has been passed to a function.

<html>

<head>

<title>User-defined objects</title>

<script type="text/javascript">

function book(title, author){

this.title = title;

this.author = author;

Page 25: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

25

}

</script>

</head>

<body>

<script type="text/javascript">

var myBook = new book("Perl", "Mohtashim");

document.write("Book title is : " + myBook.title + "<br>");

document.write("Book author is : " + myBook.author + "<br>");

</script>

</body>

</html>

Output

Book title is : Perl

Book author is : Mohtashim

Defining Methods for an Object

The previous examples demonstrate how the constructor creates the object and assigns

properties. But we need to complete the definition of an object by assigning methods to it.

Example

Try the following example; it shows how to add a function along with an object.

<html>

<head>

<title>User-defined objects</title>

<script type="text/javascript">

// Define a function which will work as a method

Page 26: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

26

function addPrice(amount){

this.price = amount;

}

function book(title, author){

this.title = title;

this.author = author;

this.addPrice = addPrice; // Assign that method as property.

}

</script>

</head>

<body>

<script type="text/javascript">

var myBook = new book("Perl", "Mohtashim");

myBook.addPrice(100);

document.write("Book title is : " + myBook.title + "<br>");

document.write("Book author is : " + myBook.author + "<br>");

document.write("Book price is : " + myBook.price + "<br>");

</script>

</body>

</html>

Output

Book title is : Perl

Book author is : Mohtashim

Book price is : 100

Page 27: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

27

The 'with' Keyword

The ‘with’ keyword is used as a kind of shorthand for referencing an object's properties or

methods.

The object specified as an argument to with becomes the default object for the duration of

the block that follows. The properties and methods for the object can be used without

naming the object.

Syntax

The syntax for with object is as follows −

with (object){

properties used without the object name and dot

}

Example

Try the following example.

<html>

<head>

<title>User-defined objects</title>

<script type="text/javascript">

// Define a function which will work as a method

function addPrice(amount){

with(this){

price = amount;

}

}

function book(title, author){

this.title = title;

this.author = author;

this.price = 0;

this.addPrice = addPrice; // Assign that method as property.

Page 28: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

28

}

</script>

</head>

<body>

<script type="text/javascript">

var myBook = new book("Perl", "Mohtashim");

myBook.addPrice(100);

document.write("Book title is : " + myBook.title + "<br>");

document.write("Book author is : " + myBook.author + "<br>");

document.write("Book price is : " + myBook.price + "<br>");

</script>

</body>

</html>

Output

Book title is : Perl

Book author is : Mohtashim

Book price is : 100

Date Object

The Date object is used to work with dates and times.

Date objects are created with new Date().

There are four ways of instantiating a date:

var d = new Date();

var d = new Date(milliseconds);

var d = new Date(dateString);

var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

The Date object is a datatype built into the JavaScript language. Date objects are created

with the new Date( ) as shown below.

Page 29: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

29

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 UTC (universal, or GMT) time.

The ECMAScript standard requires the Date object to be able to represent any date and time,

to millisecond precision, within 100 million days before or after 1/1/1970. This is a range of

plus or minus 273,785 years, so JavaScript can represent date and time till the year 275755.

Syntax

You can use any of the following syntaxes to create a Date object using Date() constructor.

new Date( )

new Date(milliseconds)

new Date(datestring)

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

Note − Parameters in the brackets are always optional.

Here is a description of the parameters −

• No Argument − With no arguments, the Date() constructor creates a Date object set

to the current date and time.

• milliseconds − When one numeric argument is passed, it is taken as the internal

numeric representation of the date in milliseconds, as returned by the getTime()

method. For example, passing the argument 5000 creates a date that represents five

seconds past midnight on 1/1/70.

• datestring − When one string argument is passed, it is a string representation of a

date, in the format accepted by the Date.parse()method.

• 7 agruments − To use the last form of the constructor shown above. Here is a

description of each argument −

o year − Integer value representing the year. For compatibility (in order to

avoid the Y2K problem), you should always specify the year in full; use

1998, rather than 98.

o month − Integer value representing the month, beginning with 0 for January

to 11 for December.

o date − Integer value representing the day of the month.

o hour − Integer value representing the hour of the day (24-hour scale).

o minute − Integer value representing the minute segment of a time reading.

o second − Integer value representing the second segment of a time reading.

Page 30: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

30

o millisecond − Integer value representing the millisecond segment of a time

reading.

Date Properties

Here is a list of the properties of the Date object along with their description.

Sr.No Property & Description

1 constructor

Specifies the function that creates an object's prototype.

2 prototype

The prototype property allows you to add properties and methods to

an object

In the following sections, we will have a few examples to demonstrate the usage of different

Date properties.

Date Methods

Here is a list of the methods used with Date and their description.

Sr.No Method & Description

1 Date()

Returns today's date and time

2 getDate()

Returns the day of the month for the specified date according to local

time.

3 getDay()

Returns the day of the week for the specified date according to local

time.

Page 31: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

31

4 getFullYear()

Returns the year of the specified date according to local time.

5 getHours()

Returns the hour in the specified date according to local time.

6 getMilliseconds()

Returns the milliseconds in the specified date according to local time.

7 getMinutes()

Returns the minutes in the specified date according to local time.

8 getMonth()

Returns the month in the specified date according to local time.

9 getSeconds()

Returns the seconds in the specified date according to local time.

10 getTime()

Returns the numeric value of the specified date as the number of

milliseconds since January 1, 1970, 00:00:00 UTC.

11 getTimezoneOffset()

Returns the time-zone offset in minutes for the current locale.

12 getUTCDate()

Returns the day (date) of the month in the specified date according to

universal time.

13 getUTCDay()

Returns the day of the week in the specified date according to universal

time.

14 getUTCFullYear()

Page 32: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

32

Returns the year in the specified date according to universal time.

15 getUTCHours()

Returns the hours in the specified date according to universal time.

16 getUTCMilliseconds()

Returns the milliseconds in the specified date according to universal

time.

17 getUTCMinutes()

Returns the minutes in the specified date according to universal time.

18 getUTCMonth()

Returns the month in the specified date according to universal time.

19 getUTCSeconds()

Returns the seconds in the specified date according to universal time.

20 getYear()

Deprecated - Returns the year in the specified date according to local

time. Use getFullYear instead.

21 setDate()

Sets the day of the month for a specified date according to local time.

22 setFullYear()

Sets the full year for a specified date according to local time.

23 setHours()

Sets the hours for a specified date according to local time.

24 setMilliseconds()

Sets the milliseconds for a specified date according to local time.

Page 33: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

33

25 setMinutes()

Sets the minutes for a specified date according to local time.

26 setMonth()

Sets the month for a specified date according to local time.

27 setSeconds()

Sets the seconds for a specified date according to local time.

28 setTime()

Sets the Date object to the time represented by a number of milliseconds

since January 1, 1970, 00:00:00 UTC.

29 setUTCDate()

Sets the day of the month for a specified date according to universal

time.

30 setUTCFullYear()

Sets the full year for a specified date according to universal time.

31 setUTCHours()

Sets the hour for a specified date according to universal time.

32 setUTCMilliseconds()

Sets the milliseconds for a specified date according to universal time.

33 setUTCMinutes()

Sets the minutes for a specified date according to universal time.

34 setUTCMonth()

Sets the month for a specified date according to universal time.

35 setUTCSeconds()

Sets the seconds for a specified date according to universal time.

Page 34: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

34

36 setYear()

Deprecated - Sets the year for a specified date according to local time.

Use setFullYear instead.

37 toDateString()

Returns the "date" portion of the Date as a human-readable string.

38 toGMTString()

Deprecated - Converts a date to a string, using the Internet GMT

conventions. Use toUTCString instead.

39 toLocaleDateString()

Returns the "date" portion of the Date as a string, using the current

locale's conventions.

40 toLocaleFormat()

Converts a date to a string, using a format string.

41 toLocaleString()

Converts a date to a string, using the current locale's conventions.

42 toLocaleTimeString()

Returns the "time" portion of the Date as a string, using the current

locale's conventions.

43 toSource()

Returns a string representing the source for an equivalent Date object;

you can use this value to create a new object.

44 toString()

Returns a string representing the specified Date object.

45 toTimeString()

Returns the "time" portion of the Date as a human-readable string.

Page 35: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

35

46 toUTCString()

Converts a date to a string, using the universal time convention.

Regular Expression

A regular expression is an object that describes a pattern of characters.

The JavaScript RegExp class represents regular expressions, and both String

and RegExp define methods that use regular expressions to perform powerful pattern-

matching and search-and-replace functions on text.

What Is a Regular Expression?

A regular expression is a sequence of characters that forms a search pattern.

When you search for data in a text, you can use this search pattern to describe what you are

searching for.

A regular expression can be a single character, or a more complicated pattern.

Regular expressions can be used to perform all types of text search and text

replace operations.

Here is the description of the parameters −

• pattern − A string that specifies the pattern of the regular expression or another

regular expression.

• attributes − An optional string containing any of the "g", "i", and "m" attributes that

specify global, case-insensitive, and multiline matches, respectively.

Syntax

/pattern/modifiers;

Example

var patt = /w3schools/i

Example explained:

• /w3schools/i is a regular expression.

• w3schools is a pattern (to be used in a search).

• i is a modifier (modifies the search to be case-insensitive).

Using String Methods

Page 36: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

36

In JavaScript, regular expressions are often used with the two string methods: search() and

replace().

The search() method uses an expression to search for a match, and returns the position of

the match.

The replace() method returns a modified string where the pattern is replaced.

Using String search() With a Regular Expression

Use a regular expression to do a case-insensitive search for "w3schools" in a string:

Using String search() With String

The search method will also accept a string as search argument. The string argument will be

converted to a regular expression:

Page 37: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

37

Use String replace() With a Regular Expression

Using String replace() With a String

The replace() method will also accept a string as search argument:

Page 38: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

38

Regular Expression Modifiers

Modifiers can be used to perform case-insensitive more global searches:

Regular Expression Patterns

Brackets are used to find a range of characters:

What Is Exception Handling?

There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and

(c) Logical Errors.

Syntax Errors

Syntax errors, also called parsing errors, occur at compile time in traditional programming

languages and at interpret time in JavaScript.

For example, the following line causes a syntax error because it is missing a closing

parenthesis.

<script type="text/javascript">

<!--

window.print(;

//-->

</script>

When a syntax error occurs in JavaScript, only the code contained within the same thread as

the syntax error is affected and the rest of the code in other threads gets executed assuming

nothing in them depends on the code containing the error.

Page 39: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

39

Runtime Errors

Runtime errors, also called exceptions, occur during execution (after

compilation/interpretation).

For example, the following line causes a runtime error because here the syntax is correct, but

at runtime, it is trying to call a method that does not exist.

<script type="text/javascript">

<!--

window.printme();

//-->

</script>

Exceptions also affect the thread in which they occur, allowing other JavaScript threads to

continue normal execution.

Logical Errors

Logic errors can be the most difficult type of errors to track down. These errors are not the

result of a syntax or runtime error. Instead, they occur when you make a mistake in the logic

that drives your script and you do not get the result you expected.

You cannot catch those errors, because it depends on your business requirement what type

of logic you want to put in your program.

The try...catch...finally Statement

The latest versions of JavaScript added exception handling capabilities. JavaScript

implements the try...catch...finally construct as well as the throw operator to handle

exceptions.

You can catch programmer-generated and runtime exceptions, but you

cannot catch JavaScript syntax errors.

Here is the try...catch...finally block syntax –

<script type="text/javascript">

<!--

try {

// Code to run

Page 40: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

40

[break;]

}

catch ( e ) {

// Code to run if an exception occurs

[break;]

}

[ finally {

// Code that is always executed regardless of

// an exception occurring

}]

//-->

</script>

The try block must be followed by either exactly one catch block or one finally block (or

one of both). When an exception occurs in the try block, the exception is placed in e and

the catch block is executed. The optional finallyblock executes unconditionally after

try/catch.

Examples

Here is an example where we are trying to call a non-existing function which in turn is

raising an exception. Let us see how it behaves without try...catch−

<html>

<head>

<script type="text/javascript">

<!--

function myFunc()

{

var a = 100;

alert("Value of variable a is : " + a );

Page 41: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

41

}

//-->

</script>

</head>

<body>

<p>Click the following to see the result:</p>

<form>

<input type="button" value="Click Me" onclick="myFunc();" />

</form>

</body>

</html>

Now let us try to catch this exception using try...catch and display a user-friendly message.

You can also suppress this message, if you want to hide this error from a user.

<html>

<head>

<script type="text/javascript">

<!--

function myFunc()

{

var a = 100;

try {

alert("Value of variable a is : " + a );

}

Page 42: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

42

catch ( e ) {

alert("Error: " + e.description );

}

}

//-->

</script>

</head>

<body>

<p>Click the following to see the result:</p>

<form>

<input type="button" value="Click Me" onclick="myFunc();" />

</form>

</body>

</html>

You can use finally block which will always execute unconditionally after the try/catch.

Here is an example.

<html>

<head>

<script type="text/javascript">

<!--

function myFunc()

{

Page 43: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

43

var a = 100;

try {

alert("Value of variable a is : " + a );

}

catch ( e ) {

alert("Error: " + e.description );

}

finally {

alert("Finally block will always execute!" );

}

}

//-->

</script>

</head>

<body>

<p>Click the following to see the result:</p>

<form>

<input type="button" value="Click Me" onclick="myFunc();" />

</form>

</body>

</html>

The throw Statement

Page 44: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

44

You can use throw statement to raise your built-in exceptions or your customized

exceptions. Later these exceptions can be captured and you can take an appropriate action.

Example

The following example demonstrates how to use a throw statement.

<html>

<head>

<script type="text/javascript">

<!--

function myFunc()

{

var a = 100;

var b = 0;

try{

if ( b == 0 ){

throw( "Divide by zero error." );

}

else

{

var c = a / b;

}

}

catch ( e ) {

alert("Error: " + e );

}

}

//-->

Page 45: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

45

</script>

</head>

<body>

<p>Click the following to see the result:</p>

<form>

<input type="button" value="Click Me" onclick="myFunc();" />

</form>

</body>

</html>

You can raise an exception in one function using a string, integer, Boolean, or an object and

then you can capture that exception either in the same function as we did above, or in

another function using a try...catch block.

The onerror() Method

The onerror event handler was the first feature to facilitate error handling in JavaScript.

The error event is fired on the window object whenever an exception occurs on the page.

<html>

<head>

<script type="text/javascript">

<!--

window.onerror = function () {

alert("An error occurred.");

}

//-->

</script>

Page 46: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

46

</head>

<body>

<p>Click the following to see the result:</p>

<form>

<input type="button" value="Click Me" onclick="myFunc();" />

</form>

</body>

</html>

The onerror event handler provides three pieces of information to identify the exact nature

of the error −

• Error message − The same message that the browser would display for the given

error

• URL − The file in which the error occurred

• Line number− The line number in the given URL that caused the error

Here is the example to show how to extract this information.

Example

<html>

<head>

<script type="text/javascript">

<!--

window.onerror = function (msg, url, line) {

alert("Message : " + msg );

alert("url : " + url );

alert("Line number : " + line );

}

//-->

Page 47: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

47

</script>

</head>

<body>

<p>Click the following to see the result:</p>

<form>

<input type="button" value="Click Me" onclick="myFunc();" />

</form>

</body>

</html>

You can display extracted information in whatever way you think it is better.

You can use an onerror method, as shown below, to display an error message in case there

is any problem in loading an image.

<img src="myimage.gif" onerror="alert('An error occurred loading the image.')" />

You can use onerror with many HTML tags to display appropriate messages in case of

errors.

JavaScript Form Validation

HTML form validation can be done by JavaScript.

If a form field (fname) is empty, this function alerts a message, and returns false, to prevent

the form from being submitted:

JavaScript Example

function validateForm() {

var x = document.forms["myForm"]["fname"].value;

if (x == "") {

alert("Name must be filled out");

return false;

}

}

Page 48: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

48

The function can be called when the form is submitted:

Form validation normally used to occur at the server, after the client had entered all the

necessary data and then pressed the Submit button. If the data entered by a client was

incorrect or was simply missing, the server would have to send all the data back to the client

and request that the form be resubmitted with correct information. This was really a lengthy

process which used to put a lot of burden on the server.

JavaScript provides a way to validate form's data on the client's computer before sending it

to the web server. Form validation generally performs two functions.

• Basic Validation − First of all, the form must be checked to make sure all the

mandatory fields are filled in. It would require just a loop through each field in the

form and check for data.

• Data Format Validation − Secondly, the data that is entered must be checked for

correct form and value. Your code must include appropriate logic to test correctness

of data.

Example

We will take an example to understand the process of validation. Here is a simple form in

html format.

<html>

<head>

<title>Form Validation</title>

<script type="text/javascript">

<!--

// Form validation code will come here.

//-->

</script>

</head>

<body>

<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">

Page 49: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

49

<table cellspacing="2" cellpadding="2" border="1">

<tr>

<td align="right">Name</td>

<td><input type="text" name="Name" /></td>

</tr>

<tr>

<td align="right">EMail</td>

<td><input type="text" name="EMail" /></td>

</tr>

<tr>

<td align="right">Zip Code</td>

<td><input type="text" name="Zip" /></td>

</tr>

<tr>

<td align="right">Country</td>

<td>

<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>

</tr>

Page 50: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

50

<tr>

<td align="right"></td>

<td><input type="submit" value="Submit" /></td>

</tr>

</table>

</form>

</body>

</html>

Basic Form Validation

First let us see how to do a basic form validation. In the above form, we are

calling validate() to validate data when onsubmit event is occurring. The following code

shows the implementation of this validate() function.

<script type="text/javascript">

<!--

// Form validation code will come here.

function validate()

{

if( document.myForm.Name.value == "" )

{

alert( "Please provide your name!" );

document.myForm.Name.focus() ;

return false;

}

if( document.myForm.EMail.value == "" )

{

Page 51: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

51

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>

Data Format Validation

Now we will see how we can validate our entered form data before submitting it to the web

server.

The following example shows how to validate an entered email address. An email address

must contain at least a ‘@’ sign and a dot (.). Also, the ‘@’ must not be the first character of

the email address, and the last dot must at least be one character after the ‘@’ sign.

Page 52: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

52

Example

Try the following code for email validation.

<script type="text/javascript">

<!--

function validateEmail()

{

var emailID = document.myForm.EMail.value;

atpos = emailID.indexOf("@");

dotpos = emailID.lastIndexOf(".");

if (atpos < 1 || ( dotpos - atpos < 2 ))

{

alert("Please enter correct email ID")

document.myForm.EMail.focus() ;

return false;

}

return( true );

}

//-->

</script>

Built-in Functions and Objects

JavaScript has several "top-level" built-in functions. JavaScript also has four built in objects:

Array, Date, Math, and String. Each object has special-purpose properties and methods

associated with it. JavaScript also has constructors for Boolean and Number types.

JavaScript sports a number of built-in objects that extend the flexibility of the language.

These objects are Date, Math, String, Array, and Object. Several of these objects are

"borrowed" from the Java language specification, but JavaScript's implementation of them is

different.

In JavaScript, almost "everything" is an object.

• Booleans can be objects (if defined with the new keyword)

Page 53: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

53

• Numbers can be objects (if defined with the new keyword)

• Strings can be objects (if defined with the new keyword)

• Dates are always objects

• Maths are always objects

• Regular expressions are always objects

• Arrays are always objects

• Functions are always objects

• Objects are always objects

All JavaScript values, except primitives, are objects.

Math object

The JavaScript Math object allows you to perform mathematical tasks on numbers.

Math.round()

Math.round(x) returns the value of x rounded to its nearest integer:

Math.pow()

Math.pow(x, y) returns the value of x to the power of y:

Page 54: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

54

Math.sqrt()

Math.sqrt(x) returns the square root of x:

JavaScript Events

HTML events are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.

HTML Events

An HTML event can be something the browser does, or something a user does.

Here are some examples of HTML events:

• An HTML web page has finished loading

• An HTML input field was changed

• An HTML button was clicked

Often, when events happen, you may want to do something.

JavaScript lets you execute code when events are detected.

HTML allows event handler attributes, with JavaScript code, to be added to HTML

elements.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a button element:

Page 55: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

55

In the example above, the JavaScript code changes the content of the element with

id="demo".

In the next example, the code changes the content of its own element

(using this.innerHTML):

Common HTML Events

Here is a list of some common HTML events:

What can JavaScript Do?

Event handlers can be used to handle, and verify, user input, user actions, and browser

actions:

Page 56: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

56

• Things that should be done every time a page loads

• Things that should be done when the page is closed

• Action that should be performed when a user clicks a button

• Content that should be verified when a user inputs data

• And more ...

Many different methods can be used to let JavaScript work with events:

• HTML event attributes can execute JavaScript code directly

• HTML event attributes can call JavaScript functions

• You can assign your own event handler functions to HTML elements

• You can prevent events from being sent or being handled

• And more ...

DHTML WITH JAVASCRIPT

DHTML Stands for Dynamic Hyper Text Markup Language.

DHTML is NOT a language or a web standard.

To most people DHTML means the combination of HTML, JavaScript, DOM and CSS.

According to the World Wide Web Consortium (W3C):

"Dynamic HTML is a term used by some vendors to describe the combination of HTML,

style sheets and scripts that allows documents to be animated."

One of the most popular uses of JavaScript is DHTML (Dynamic Hyper Text Markup

Language). Strictly speaking, DHTML is using JavaScript to modify the CSS styles of

HTML elements. All current browsers support much more than I will describe at this stage of

the tutorial. For now, I will concentrate on the capabilities introduced by 4th generation

browsers. Old browser versions (such as Netscape 4 and Opera 6-) limit the abilities of '4th

generation' DHTML, as these can only handle basic DHTML. However, they still provide

easily enough flexibility to make features like pop-up menus, message scrollers, mouse trails

or falling snow effects.

<!DOCTYPE html>

<html lang="en-US">

<head>

<title>An Example for DHTML</title>

</head>

<body>

<p id="p1">MJR COLLEGE oF ENGINEERING & TECHNOLOGY</p>

<input type="button" value="Hide text"

onclick="document.getElementById('p1').style.visibility='hidden'" />

<input type="button" value="Show text"

onclick="document.getElementById('p1').style.visibility='visible'" />

Page 57: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

57

</body>

</html>

JavaScript can create dynamic HTML content:

Date: Sat Feb 24 2018 06:57:25 GMT+0530 (India Standard Time)

JavaScript Alone

If you have studied JavaScript, you already know that the statement:

document.write()

can be used to display dynamic content to a web page.

Example

Using JavaScript to display the current date:

<html>

<body>

<script type="text/javascript">

document.write(Date());

</script>

</body>

</html>

JavaScript and the HTML DOM

With HTML 4, JavaScript can also be used to change the inner content and attributes of

HTML elements dynamically.

To change the content of an HTML element use:

document.getElementById(id).innerHTML=new HTML

To change the attribute of an HTML element use:

document.getElementById(id).attribute=new value

JavaScript and HTML Events

New to HTML 4 is the ability to let HTML events trigger actions in the browser, like starting

a JavaScript when a user clicks on an HTML element.

Page 58: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

58

To execute code when a user clicks on an element, use the following event attribute:

onclick=JavaScript

JavaScript and CSS

With HTML 4, JavaScript can also be used to change the style of HTML elements.

To change the style of an HTML element use:

document.getElementById(id).style.property=new style

▪ DHTML allows scripting languages to change variables in a web page's definition

language, which in turn affects the look and function of otherwise "static" HTML

page content, after the page has been fully loaded and during the viewing process.

Thus the dynamic characteristic of DHTML is the way it functions while a page is

viewed, not in its ability to generate a unique page with each page load.

▪ Dynamic HTML or DHTML, is a collection of technologies used together to create

interactive and animated web sites by using a combination of a HTML and CSS or

JavaScript.

▪ DHTML allows authors to add effects to their pages that are otherwise difficult to

achieve. For example, DHTML allows the page author to:

▪ Animate text and images in their document, independently moving each element from

any starting point to any ending point, following a predetermined path or one chosen

by the user.

▪ Embed a ticker that automatically refreshes its content with the latest news, stock

quotes, or other data.

▪ Use a form to capture user input, and then process and respond to that data without

having to send data back to the server.

▪ Include rollover buttons or drop-down menus.

SERVLETS

Page 59: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

59

Java Servlets are programs that run on a Web or Application server and act as a middle layer

between a requests coming from a Web browser or other HTTP client and databases or

applications on the HTTP server.

Using Servlets, you can collect input from users through web page forms, present records

from a database or another source, and create web pages dynamically.

Java Servlets often serve the same purpose as programs implemented using the Common

Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.

Performance is significantly better.

Servlets execute within the address space of a Web server. It is not necessary to create a

separate process to handle each client request.

Servlets are platform-independent because they are written in Java.

Java security manager on the server enforces a set of restrictions to protect the resources on a

server machine. So servlets are trusted.

The full functionality of the Java class libraries is available to a servlet. It can communicate

with applets, databases, or other software via the sockets and RMI mechanisms that you have

seen already.

Servlets Architecture

The following diagram shows the position of Servlets in a Web Application.

Servlets Tasks

Servlets perform the following major tasks −

Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web

page or it could also come from an applet or a custom HTTP client program.

Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,

media types and compression schemes the browser understands, and so forth.

Page 60: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

60

Process the data and generate the results. This process may require talking to a database,

executing an RMI or CORBA call, invoking a Web service, or computing the response

directly.

Send the explicit data (i.e., the document) to the clients (browsers). This document can be

sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.

Send the implicit HTTP response to the clients (browsers). This includes telling the browsers

or other clients what type of document is being returned (e.g., HTML), setting cookies and

caching parameters, and other such tasks.

Servlets Packages

Java Servlets are Java classes run by a web server that has an interpreter that supports the

Java Servlet specification.

Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a

standard part of the Java's enterprise edition, an expanded version of the Java class library

that supports large-scale development projects.

These classes implement the Java Servlet and JSP specifications. At the time of writing this

tutorial, the versions are Java Servlet 2.5 and JSP 2.1.

Java servlets have been created and compiled just like any other Java class. After you install

the servlet packages and add them to your computer's Classpath, you can compile servlets

with the JDK's Java compiler or any other current compiler.

A Servlet is a class, which implements the javax.servlet.Servlet interface. However instead of

directly implementing the javax.servlet.Servlet interface we extend a class that has

implemented the interface like javax.servlet.GenericServlet or javax.servlet.http.HttpServlet.

Servlet Exceution

Page 61: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

61

This is how a servlet execution takes place when client (browser) makes a request to the

webserver.

Servlet architecture includes:

a) Servlet Interface

To write a servlet we need to implement Servlet interface. Servlet interface can be

implemented directly or indirectly by extending GenericServlet or HttpServlet class.

b) Request handling methods

There are 3 methods defined in Servlet interface: init(), service() and destroy().

The first time a servlet is invoked, the init method is called. It is called only once during the

lifetime of a servlet. So, we can put all your initialization code here.

The Service method is used for handling the client request. As the client request reaches to

the container it creates a thread of the servlet object, and request and response object are also

created. These request and response object are then passed as parameter to the service

method, which then process the client request. The service method in turn calls the doGet or

doPost methods (if the user has extended the class from HttpServlet ).

c) Number of instances

Basic Structure of a Servlet

public class firstServlet extends HttpServlet {

public void init() {

/* Put your initialization code in this method,

* as this method is called only once */

}

public void service() {

// Service request for Servlet

}

public void destroy() {

Page 62: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

62

// For taking the servlet out of service, this method is called only once

}

}

SERVLETS - ENVIRONMENT SETUP

A development environment is where you would develop your Servlet, test them and finally

run them.

Like any other Java program, you need to compile a servlet by using the Java

compiler javac and after compilation the servlet application, it would be deployed in a

configured environment to test and run.

This development environment setup involves the following steps −

Setting up Java Development Kit

This step involves downloading an implementation of the Java Software Development

Kit SDKSDKand setting up PATH environment variable appropriately.

You can download SDK from Oracle's Java site − Java SE Downloads.

Once you download your Java implementation, follow the given instructions to install and

configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to

the directory that contains java and javac, typically java_install_dir/bin and java_install_dir

respectively.

If you are running Windows and installed the SDK in C:\jdk1.8.0_65, you would put the

following line in your C:\autoexec.bat file.

set PATH = C:\jdk1.8.0_65\bin;%PATH%

set JAVA_HOME = C:\jdk1.8.0_65

Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select

Properties, then Advanced, then Environment Variables. Then, you would update the PATH

value and press the OK button.

On Unix Solaris,Linux,etc.Solaris,Linux,etc., if the SDK is installed in /usr/local/jdk1.8.0_65

and you use the C shell, you would put the following into your .cshrc file.

setenv PATH /usr/local/jdk1.8.0_65/bin:$PATH

setenv JAVA_HOME /usr/local/jdk1.8.0_65

Alternatively, if you use an Integrated Development Environment IDEIDE like Borland

JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to

confirm that the IDE knows where you installed Java.

Setting up Web Server − Tomcat

Page 63: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

63

A number of Web Servers that support servlets are available in the market. Some web servers

are freely downloadable and Tomcat is one of them.

Apache Tomcat is an open source software implementation of the Java Servlet and Java

Server Pages technologies and can act as a standalone server for testing servlets and can be

integrated with the Apache Web Server. Here are the steps to setup Tomcat on your machine

• Download latest version of Tomcat from https://tomcat.apache.org/.

• Once you downloaded the installation, unpack the binary distribution into a

convenient location. For example in C:\apache-tomcat-8.0.28 on windows, or

/usr/local/apache-tomcat-8.0.289 on Linux/Unix and create CATALINA_HOME

environment variable pointing to these locations.

Tomcat can be started by executing the following commands on windows machine −

%CATALINA_HOME%\bin\startup.bat

or

C:\apache-tomcat-8.0.28\bin\startup.bat

Tomcat can be started by executing the following commands on

Unix Solaris,Linux,etc.Solaris,Linux,etc.machine −

$CATALINA_HOME/bin/startup.sh

or

/usr/local/apache-tomcat-8.0.28/bin/startup.sh

After startup, the default web applications included with Tomcat will be available by

visiting http://localhost:8080/. If everything is fine then it should display following result −

Page 64: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

64

Further information about configuring and running Tomcat can be found in the

documentation included here, as well as on the Tomcat web site − http://tomcat.apache.org

Tomcat can be stopped by executing the following commands on windows machine −

C:\apache-tomcat-8.0.28\bin\shutdown

Tomcat can be stopped by executing the following commands on

Unix Solaris,Linux,etc.Solaris,Linux,etc.machine −

/usr/local/apache-tomcat-8.0.28/bin/shutdown.sh

Setting Up the CLASSPATH

Since servlets are not part of the Java Platform, Standard Edition, you must identify the

servlet classes to the compiler.

If you are running Windows, you need to put the following lines in your C:\autoexec.bat file.

set CATALINA = C:\apache-tomcat-8.0.28

set CLASSPATH = %CATALINA%\common\lib\servlet-api.jar;%CLASSPATH%

Alternatively, on Windows NT/2000/XP, you could go to My Computer −> Properties −>

Advanced −> Environment Variables. Then, you would update the CLASSPATH value and

press the OK button.

Page 65: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

65

On Unix Solaris,Linux,etc.Solaris,Linux,etc., if you are using the C shell, you would put the

following lines into your .cshrc file.

setenv CATALINA = /usr/local/apache-tomcat-8.0.28

setenv CLASSPATH $CATALINA/common/lib/servlet-api.jar:$CLASSPATH

Servlets - Life Cycle

A servlet life cycle can be defined as the entire process from its creation till the destruction.

The following are the paths followed by a servlet.

• The servlet is initialized by calling the init() method.

• The servlet calls service() method to process a client's request.

• The servlet is terminated by calling the destroy() method.

• Finally, servlet is garbage collected by the garbage collector of the JVM.

Now let us discuss the life cycle methods in detail.

The init() Method

The init method is called only once. It is called only when the servlet is created, and not

called for any user requests afterwards. So, it is used for one-time initializations, just as with

the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the

servlet, but you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user

request resulting in a new thread that is handed off to doGet or doPost as appropriate. The

init() method simply creates or loads some data that will be used throughout the life of the

servlet.

The init method definition looks like this −

public void init() throws ServletException {

// Initialization code...

}

The service() Method

The service() method is the main method to perform the actual task. The servlet container

(i.e. web server) calls the service() method to handle requests coming from the client(

browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and

calls service. The service() method checks the HTTP request type (GET, POST, PUT,

DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Page 66: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

66

Here is the signature of this method −

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

}

The service () method is called by the container and service method invokes doGe, doPost,

doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service()

method but you override either doGet() or doPost() depending on what type of request you

receive from the client.

The doGet() and doPost() are most frequently used methods with in each service request.

Here is the signature of these two methods.

The doGet() Method

A GET request results from a normal request for a URL or from an HTML form that has no

METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Servlet code

}

The doPost() Method

A POST request results from an HTML form that specifically lists POST as the METHOD

and it should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Servlet code

}

The destroy() Method

The destroy() method is called only once at the end of the life cycle of a servlet. This

method gives your servlet a chance to close database connections, halt background threads,

write cookie lists or hit counts to disk, and perform other such cleanup activities.

After the destroy() method is called, the servlet object is marked for garbage collection. The

destroy method definition looks like this −

public void destroy() {

// Finalization code...

Page 67: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

67

}

Architecture Diagram

The following figure depicts a typical servlet life-cycle scenario.

• First the HTTP requests coming to the server are delegated to the servlet container.

• The servlet container loads the servlet before invoking the service() method.

• Then the servlet container handles multiple requests by spawning multiple threads,

each thread executing the service() method of a single instance of the servlet.

Servlets – Examples

Servlets are Java classes which service HTTP requests and implement

the javax.servlet.Servlet interface. Web application developers typically write servlets that

extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface

and is specially designed to handle HTTP requests.

Sample Code

Following is the sample source code structure of a servlet example to show Hello World −

// Import required java libraries

import java.io.*;

import javax.servlet.*;

Page 68: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

68

import javax.servlet.http.*;

// Extend HttpServlet class

public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {

// Do required initialization

message = "Hello World";

}

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Set response content type

response.setContentType("text/html");

// Actual logic goes here.

PrintWriter out = response.getWriter();

out.println("<h1>" + message + "</h1>");

}

public void destroy() {

// do nothing.

}

}

Compiling a Servlet

Let us create a file with name HelloWorld.java with the code shown above. Place this file at

C:\ServletDevel (in Windows) or at /usr/ServletDevel (in Unix). This path location must be

added to CLASSPATH before proceeding further.

Assuming your environment is setup properly, go in ServletDevel directory and compile

HelloWorld.java as follows −

$ javac HelloWorld.java

If the servlet depends on any other libraries, you have to include those JAR files on your

CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using

any other library in Hello World program.

Page 69: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

69

This command line uses the built-in javac compiler that comes with the Sun Microsystems

Java Software Development Kit (JDK). For this command to work properly, you have to

include the location of the Java SDK that you are using in the PATH environment variable.

If everything goes fine, above compilation would produce HelloWorld.classfile in the same

directory. Next section would explain how a compiled servlet would be deployed in

production.

Servlet Deployment

By default, a servlet application is located at the path <Tomcat-

installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-

installationdirectory>/webapps/ROOT/WEB-INF/classes.

If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class

must be located in WEB-INF/classes/com/myorg/MyServlet.class.

For now, let us copy HelloWorld.class into <Tomcat-

installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries

in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/

<servlet>

<servlet-name>HelloWorld</servlet-name>

<servlet-class>HelloWorld</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloWorld</servlet-name>

<url-pattern>/HelloWorld</url-pattern>

</servlet-mapping>

Above entries to be created inside <web-app>...</web-app> tags available in web.xml file.

There could be various entries in this table already available, but never mind.

You are almost done, now let us start tomcat server using <Tomcat-

installationdirectory>\bin\startup.bat (on Windows) or <Tomcat-

installationdirectory>/bin/startup.sh (on Linux/Solaris etc.) and finally

type http://localhost:8080/HelloWorld in the browser's address box. If everything goes

fine, you would get the following result.

Page 70: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

70

SERVLETS - FORM DATA

You must have come across many situations when you need to pass some information from

your browser to web server and ultimately to your backend program. The browser uses two

methods to pass this information to web server. These methods are GET Method and POST

Method.

GET Method

The GET method sends the encoded user information appended to the page request. The page

and the encoded information are separated by the ? questionmarkquestionmark symbol as

follows −

http://www.test.com/hello?key1 = value1&key2 = value2

The GET method is the default method to pass information from browser to web server and it

produces a long string that appears in your browser's Location:box. Never use the GET

method if you have password or other sensitive information to pass to the server. The GET

method has size limitation: only 1024 characters can be used in a request string.

This information is passed using QUERY_STRING header and will be accessible through

QUERY_STRING environment variable and Servlet handles this type of requests

using doGetmethod.

POST Method

A generally more reliable method of passing information to a backend program is the POST

method. This packages the information in exactly the same way as GET method, but instead

of sending it as a text string after a ? question mark in the URL it sends it as a separate

message. This message comes to the backend program in the form of the standard input

which you can parse and use for your processing. Servlet handles this type of requests

using doPost method.

Page 71: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

71

Reading Form Data using Servlet

Servlets handles form data parsing automatically using the following methods depending on

the situation −

• getParameter − You call request.getParameter method to get the value of a form

parameter.

• getParameterValues − Call this method if the parameter appears more than once and

returns multiple values, for example checkbox.

• getParameterNames − Call this method if you want a complete list of all parameters

in the current request.

GET Method Example using URL

Here is a simple URL which will pass two values to HelloForm program using GET method.

http://localhost:8080/HelloForm?first_name = ZARA&last_name = ALI

Given below is the HelloForm.java servlet program to handle input given by web browser.

We are going to use getParameter method which makes it very easy to access passed

information −

// Import required java libraries

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

// Extend HttpServlet class

public class HelloForm extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Set response content type

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String title = "Using GET Method to Read Form Data";

String docType =

"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

Page 72: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

72

out.println(docType +

"<html>\n" +

"<head><title>" + title + "</title></head>\n" +

"<body bgcolor = \"#f0f0f0\">\n" +

"<h1 align = \"center\">" + title + "</h1>\n" +

"<ul>\n" +

" <li><b>First Name</b>: "

+ request.getParameter("first_name") + "\n" +

" <li><b>Last Name</b>: "

+ request.getParameter("last_name") + "\n" +

"</ul>\n" +

"</body>

</html>"

);

}

}

Assuming your environment is set up properly, compile HelloForm.java as follows −

$ javac HelloForm.java

If everything goes fine, above compilation would produce HelloForm.class file. Next you

would have to copy this class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-

INF/classes and create following entries in web.xml file located in <Tomcat-installation-

directory>/webapps/ROOT/WEB-INF/

<servlet>

<servlet-name>HelloForm</servlet-name>

<servlet-class>HelloForm</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloForm</servlet-name>

<url-pattern>/HelloForm</url-pattern>

</servlet-mapping>

Page 73: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

73

Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your

browser's Location:box and make sure you already started tomcat server, before firing above

command in the browser. This would generate following result −

USING GET METHOD TO READ FORM DATA

• First Name: ZARA

• Last Name: ALI

GET Method Example Using Form

Here is a simple example which passes two values using HTML FORM and submit button.

We are going to use same Servlet HelloForm to handle this imput.

<html>

<body>

<form action = "HelloForm" method = "GET">

First Name: <input type = "text" name = "first_name">

<br />

Last Name: <input type = "text" name = "last_name" />

<input type = "submit" value = "Submit" />

</form>

</body>

</html>

Keep this HTML in a file Hello.htm and put it in <Tomcat-

installationdirectory>/webapps/ROOT directory. When you would

access http://localhost:8080/Hello.htm, here is the actual output of the above form.

First Name: Last Name:

Try to enter First Name and Last Name and then click submit button to see the result on your

local machine where tomcat is running. Based on the input provided, it will generate similar

result as mentioned in the above example.

POST Method Example Using Form

Let us do little modification in the above servlet, so that it can handle GET as well as POST

methods. Below is HelloForm.java servlet program to handle input given by web browser

using GET or POST methods.

// Import required java libraries

Page 74: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

74

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

// Extend HttpServlet class

public class HelloForm extends HttpServlet {

// Method to handle GET method request.

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Set response content type

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String title = "Using GET Method to Read Form Data";

String docType =

"<!doctype html public \"-//w3c//dtd html 4.0 " +

"transitional//en\">\n";

out.println(docType +

"<html>\n" +

"<head><title>" + title + "</title></head>\n" +

"<body bgcolor = \"#f0f0f0\">\n" +

"<h1 align = \"center\">" + title + "</h1>\n" +

"<ul>\n" +

" <li><b>First Name</b>: "

+ request.getParameter("first_name") + "\n" +

" <li><b>Last Name</b>: "

+ request.getParameter("last_name") + "\n" +

"</ul>\n" +

"</body>

</html>"

);

Page 75: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

75

}

// Method to handle POST method request.

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

Now compile and deploy the above Servlet and test it using Hello.htm with the POST method

as follows −

<html>

<body>

<form action = "HelloForm" method = "POST">

First Name: <input type = "text" name = "first_name">

<br />

Last Name: <input type = "text" name = "last_name" />

<input type = "submit" value = "Submit" />

</form>

</body>

</html>

Here is the actual output of the above form, Try to enter First and Last Name and then click

submit button to see the result on your local machine where tomcat is running.

First Name: Last Name:

Based on the input provided, it would generate similar result as mentioned in the above

examples.

Passing Checkbox Data to Servlet Program

Checkboxes are used when more than one option is required to be selected.

Here is example HTML code, CheckBox.htm, for a form with two checkboxes

<html>

Page 76: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

76

<body>

<form action = "CheckBox" method = "POST" target = "_blank">

<input type = "checkbox" name = "maths" checked = "checked" /> Maths

<input type = "checkbox" name = "physics" /> Physics

<input type = "checkbox" name = "chemistry" checked = "checked" />

Chemistry

<input type = "submit" value = "Select Subject" />

</form>

</body>

</html>

The result of this code is the following form

Maths Physics Chemistry

Given below is the CheckBox.java servlet program to handle input given by web browser for

checkbox button.

// Import required java libraries

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

// Extend HttpServlet class

public class CheckBox extends HttpServlet {

// Method to handle GET method request.

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Set response content type

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String title = "Reading Checkbox Data";

String docType =

Page 77: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

77

"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

out.println(docType +

"<html>\n" +

"<head><title>" + title + "</title></head>\n" +

"<body bgcolor = \"#f0f0f0\">\n" +

"<h1 align = \"center\">" + title + "</h1>\n" +

"<ul>\n" +

" <li><b>Maths Flag : </b>: "

+ request.getParameter("maths") + "\n" +

" <li><b>Physics Flag: </b>: "

+ request.getParameter("physics") + "\n" +

" <li><b>Chemistry Flag: </b>: "

+ request.getParameter("chemistry") + "\n" +

"</ul>\n" +

"</body>

</html>"

);

}

// Method to handle POST method request.

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

For the above example, it would display following result −

READING CHECKBOX DATA

• Maths Flag : : on

• Physics Flag: : null

Page 78: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

78

• Chemistry Flag: : on

Reading All Form Parameters

Following is the generic example which uses getParameterNames method of

HttpServletRequest to read all the available form parameters. This method returns an

Enumeration that contains the parameter names in an unspecified order

Once we have an Enumeration, we can loop down the Enumeration in standard way by,

using hasMoreElements method to determine when to stop and using nextElement method to

get each parameter name.

// Import required java libraries

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

// Extend HttpServlet class

public class ReadParams extends HttpServlet {

// Method to handle GET method request.

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Set response content type

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String title = "Reading All Form Parameters";

String docType =

"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

out.println(docType +

"<html>\n" +

"<head><title>" + title + "</title></head>\n" +

Page 79: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

79

"<body bgcolor = \"#f0f0f0\">\n" +

"<h1 align = \"center\">" + title + "</h1>\n" +

"<table width = \"100%\" border = \"1\" align = \"center\">\n" +

"<tr bgcolor = \"#949494\">\n" +

"<th>Param Name</th>

<th>Param Value(s)</th>\n"+

"</tr>\n"

);

Enumeration paramNames = request.getParameterNames();

while(paramNames.hasMoreElements()) {

String paramName = (String)paramNames.nextElement();

out.print("<tr><td>" + paramName + "</td>\n<td>");

String[] paramValues = request.getParameterValues(paramName);

// Read single valued data

if (paramValues.length == 1) {

String paramValue = paramValues[0];

if (paramValue.length() == 0)

out.println("<i>No Value</i>");

else

out.println(paramValue);

} else {

// Read multiple valued data

out.println("<ul>");

for(int i = 0; i < paramValues.length; i++) {

out.println("<li>" + paramValues[i]);

}

out.println("</ul>");

}

}

out.println("</tr>\n</table>\n</body></html>");

Page 80: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

80

}

// Method to handle POST method request.

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

doGet(request, response);

}

}

Now, try the above servlet with the following form −

<html>

<body>

<form action = "ReadParams" method = "POST" target = "_blank">

<input type = "checkbox" name = "maths" checked = "checked" /> Maths

<input type = "checkbox" name = "physics" /> Physics

<input type = "checkbox" name = "chemistry" checked = "checked" /> Chem

<input type = "submit" value = "Select Subject" />

</form>

</body>

</html>

Now calling servlet using the above form would generate the following result −

READING ALL FORM PARAMETERS

Param Name Param Value(s)

maths on

chemistry on

Page 81: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

81

You can try the above servlet to read any other form's data having other objects like text box,

radio button or drop down box etc.

Session Tracking in Servlets or Session Handling

Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known as session

management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking techniques.

Each time user requests to the server, server treats the request as the new request. So we need

to maintain the state of an user to recognize to particular user.

HTTP is stateless that means each request is considered as the new request. It is shown in the

figure given below:

Why use Session Tracking?

To recognize the user It is used to recognize the particular user.

Session Tracking Techniques

There are four techniques used in Session tracking:

1. Cookies

2. Hidden Form Field

3. URL Rewriting

4. HttpSession

Cookies

A webserver can assign a unique session ID as a cookie to each web client and for

subsequent requests from the client they can be recognized using the recieved cookie.

Page 82: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

82

This may not be an effective way because many time browser does not support a cookie, so I

would not recommend to use this procedure to maintain the sessions.

Hidden Form Fields

A web server can send a hidden HTML form field along with a unique session ID as follows

<input type = "hidden" name = "sessionid" value = "12345">

This entry means that, when the form is submitted, the specified name and value are

automatically included in the GET or POST data. Each time when web browser sends

request back, then session_id value can be used to keep the track of different web browsers.

This could be an effective way of keeping track of the session but clicking on a regular (<A

HREF...>) hypertext link does not result in a form submission, so hidden form fields also

cannot support general session tracking.

URL Rewriting

You can append some extra data on the end of each URL that identifies the session, and the

server can associate that session identifier with data it has stored about that session.

For example, with http://tutorialspoint.com/file.htm;sessionid = 12345, the session identifier

is attached as sessionid = 12345 which can be accessed at the web server to identify the

client.

URL rewriting is a better way to maintain sessions and it works even when browsers don't

support cookies. The drawback of URL re-writing is that you would have to generate every

URL dynamically to assign a session ID, even in case of a simple static HTML page.

The HttpSession Object

Apart from the above mentioned three ways, servlet provides HttpSession Interface which

provides a way to identify a user across more than one page request or visit to a Web site

and to store information about that user.

The servlet container uses this interface to create a session between an HTTP client and an

HTTP server. The session persists for a specified time period, across more than one

connection or page request from the user.

You would get HttpSession object by calling the public method getSession()of

HttpServletRequest, as below −

HttpSession session = request.getSession();

You need to call request.getSession() before you send any document content to the client.

Here is a summary of the important methods available through HttpSession object −

Page 83: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

83

Sr.No. Method & Description

1

public Object getAttribute(String name)

This method returns the object bound with the specified name in this

session, or null if no object is bound under the name.

2

public Enumeration getAttributeNames()

This method returns an Enumeration of String objects containing the

names of all the objects bound to this session.

3

public long getCreationTime()

This method returns the time when this session was created,

measured in milliseconds since midnight January 1, 1970 GMT.

4

public String getId()

This method returns a string containing the unique identifier

assigned to this session.

5

public long getLastAccessedTime()

This method returns the last accessed time of the session, in the

format of milliseconds since midnight January 1, 1970 GMT

6

public int getMaxInactiveInterval()

This method returns the maximum time interval (seconds), that the

servlet container will keep the session open between client accesses.

7

public void invalidate()

This method invalidates this session and unbinds any objects bound

to it.

8

public boolean isNew(

This method returns true if the client does not yet know about the

session or if the client chooses not to join the session.

9

public void removeAttribute(String name)

This method removes the object bound with the specified name from

this session.

Page 84: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

84

10

public void setAttribute(String name, Object value)

This method binds an object to this session, using the name

specified.

11

public void setMaxInactiveInterval(int interval)

This method specifies the time, in seconds, between client requests

before the servlet container will invalidate this session.

Session Tracking Example

This example describes how to use the HttpSession object to find out the creation time and

the last-accessed time for a session. We would associate a new session with the request if

one does not already exist.

// Import required java libraries

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

// Extend HttpServlet class

public class SessionTrack extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Create a session object if it is already not created.

HttpSession session = request.getSession(true);

// Get session creation time.

Date createTime = new Date(session.getCreationTime());

// Get last access time of this web page.

Date lastAccessTime = new Date(session.getLastAccessedTime());

Page 85: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

85

String title = "Welcome Back to my website";

Integer visitCount = new Integer(0);

String visitCountKey = new String("visitCount");

String userIDKey = new String("userID");

String userID = new String("ABCD");

// Check if this is new comer on your web page.

if (session.isNew()) {

title = "Welcome to my website";

session.setAttribute(userIDKey, userID);

} else {

visitCount = (Integer)session.getAttribute(visitCountKey);

visitCount = visitCount + 1;

userID = (String)session.getAttribute(userIDKey);

}

session.setAttribute(visitCountKey, visitCount);

// Set response content type

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String docType =

"<!doctype html public \"-//w3c//dtd html 4.0 " +

"transitional//en\">\n";

out.println(docType +

"<html>\n" +

"<head><title>" + title + "</title></head>\n" +

Page 86: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

86

"<body bgcolor = \"#f0f0f0\">\n" +

"<h1 align = \"center\">" + title + "</h1>\n" +

"<h2 align = \"center\">Session Infomation</h2>\n" +

"<table border = \"1\" align = \"center\">\n" +

"<tr bgcolor = \"#949494\">\n" +

" <th>Session info</th><th>value</th>

</tr>\n" +

"<tr>\n" +

" <td>id</td>\n" +

" <td>" + session.getId() + "</td>

</tr>\n" +

"<tr>\n" +

" <td>Creation Time</td>\n" +

" <td>" + createTime + " </td>

</tr>\n" +

"<tr>\n" +

" <td>Time of Last Access</td>\n" +

" <td>" + lastAccessTime + " </td>

</tr>\n" +

"<tr>\n" +

" <td>User ID</td>\n" +

" <td>" + userID + " </td>

</tr>\n" +

"<tr>\n" +

Page 87: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

87

" <td>Number of visits</td>\n" +

" <td>" + visitCount + "</td>

</tr>\n" +

"</table>\n" +

"</body>

</html>"

); } }

Compile the above servlet SessionTrack and create appropriate entry in web.xml file. Now

running http://localhost:8080/SessionTrack would display the following result when you

would run for the first time –

Page 88: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

88

Deleting Session Data

When you are done with a user's session data, you have several options −

• Remove a particular attribute − You can call public void removeAttribute(String

name) method to delete the value associated with a particular key.

• Delete the whole session − You can call public void invalidate()method to discard an

entire session.

• Setting Session timeout − You can call public void setMaxInactiveInterval(int

interval) method to set the timeout for a session individually.

• Log the user out − The servers that support servlets 2.4, you can call logout to log

the client out of the Web server and invalidate all sessions belonging to all the users.

• web.xml Configuration − If you are using Tomcat, apart from the above mentioned

methods, you can configure session time out in web.xml file as follows.

<session-config>

<session-timeout>15</session-timeout>

</session-config>

The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes

in Tomcat.

The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session

in seconds. So if your session is configured in web.xml for 15 minutes,

getMaxInactiveInterval( ) returns 900.

Page 89: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

89

Understanding the Cookies in Servlet

A cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and

domain qualifiers, a maximum age, and a version number.

How Cookie works

By default, each request is considered as a new request. In cookies technique, we add cookie

with response from the servlet. So cookie is stored in the cache of the browser. After that if

request is sent by the user, cookie is added with request by default. Thus, we recognize the

user as the old user.

Types of Cookie

There are 2 types of cookies in servlets.

1. Non-persistent cookie

2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It

is removed only if user logout or signout.

Advantage of Cookies

1. Simplest technique of maintaining the state.

2. Cookies are maintained at client side.

Disadvantage of Cookies

1. It will not work if cookie is disabled from the browser.

2. Only textual information can be set in Cookie object.

Page 90: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

90

Cookie class

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot

of useful methods for cookies.

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Method Description

public void setMaxAge(int

expiry)

Sets the maximum age of the cookie in seconds.

public String getName() Returns the name of the cookie. The name cannot be changed

after creation.

public String getValue() Returns the value of the cookie.

public void setName(String

name)

changes the name of the cookie.

public void setValue(String

value)

changes the value of the cookie.

Other methods required for using Cookies

For adding cookie or getting the value from the cookie, we need some methods provided

by other interfaces. They are:

1. public void addCookie(Cookie ck):method of HttpServletResponse interface is

Page 91: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

91

used to add cookie in response object.

2. public Cookie[] getCookies():method of HttpServletRequest interface is used to

return all the cookies from the browser.

How to create Cookie?

Let's see the simple code to create cookie.

1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object

2. response.addCookie(ck);//adding cookie in the response

How to delete Cookie?

Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.

1. Cookie ck=new Cookie("user","");//deleting value of cookie

2. ck.setMaxAge(0);//changing the maximum age to 0 seconds

3. response.addCookie(ck);//adding cookie in the response

How to get Cookies?

Let's see the simple code to get all the cookies.

1. Cookie ck[]=request.getCookies();

2. for(int i=0;i<ck.length;i++){

3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie

4. }

Simple example of Servlet Cookies

In this example, we are storing the name of the user in the cookie object and accessing it in

another servlet. As we know well that session corresponds to the particular user. So if you

access it from too many browsers with different values, you will get the different value.

Page 92: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

92

index.html

1. <form action="servlet1" method="post">

2. Name:<input type="text" name="userName"/><br/>

3. <input type="submit" value="go"/>

4. </form>

FirstServlet.java

1. import java.io.*;

2. import javax.servlet.*;

3. import javax.servlet.http.*;

4.

5.

6. public class FirstServlet extends HttpServlet {

7.

8. public void doPost(HttpServletRequest request, HttpServletResponse response){

9. try{

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String n=request.getParameter("userName");

out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object

response.addCookie(ck);//adding cookie in the response

//creating submit button

out.print("<form action='servlet2'>");

out.print("<input type='submit' value='go'>");

out.print("</form>");

out.close();

}catch(Exception e){System.out.println(e);}

}

}

Page 93: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

93

SecondServlet.java

1. import java.io.*;

2. import javax.servlet.*;

3. import javax.servlet.http.*;

4. public class SecondServlet extends HttpServlet {

5. public void doPost(HttpServletRequest request, HttpServletResponse response){

6. try{

7. response.setContentType("text/html");

8. PrintWriter out = response.getWriter();

9. Cookie ck[]=request.getCookies();

10. out.print("Hello "+ck[0].getValue());

11.

12. out.close();

13. }catch(Exception e){System.out.println(e);}

14. } }

web.xml

1. <web-app>

2. <servlet>

3. <servlet-name>s1</servlet-name>

4. <servlet-class>FirstServlet</servlet-class>

5. </servlet>

6.

7. <servlet-mapping>

8. <servlet-name>s1</servlet-name>

9. <url-pattern>/servlet1</url-pattern>

10. </servlet-mapping>

11.

12. <servlet>

13. <servlet-name>s2</servlet-name>

14. <servlet-class>SecondServlet</servlet-class>

15. </servlet>

16.

17. <servlet-mapping>

18. <servlet-name>s2</servlet-name>

19. <url-pattern>/servlet2</url-pattern>

20. </servlet-mapping>

21. </web-app>

Page 94: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

94

Installing and Configuring Apache Tomcat Web Server :

1. Introduction

1.1 Web Application (Webapp)

A web application (or webapp), unlike standalone application, runs over the Internet.

Examples of webapps are google, amazon, ebay, facebook and twitter.

A webapp is typically a 3-tier (or multi-tier) client-server database application run over the

Internet as illustrated in the diagram below. It comprises five components:

1. HTTP Server: E.g., Apache HTTP Server, Apache Tomcat Server, Microsoft

Internet Information Server (IIS), nginx, Google Web Server (GWS), and others.

2. HTTP Client (or Web Browser): E.g., Internet Explorer (MSIE), FireFox,

Chrome, Safari, and others.

3. Database: E.g., Open-source MySQL, Apache Derby, mSQL, SQLite, PostgreSQL,

OpenOffice's Base; Commercial Oracle, IBM DB2, SAP SyBase, MS SQL Server, MS

Access; and others.

4. Client-Side Programs: could be written in HTML Form, JavaScript, VBScript,

Flash, and others.

5. Server-Side Programs: could be written in Java Servlet/JSP, ASP, PHP, Perl,

Python, CGI, and others.

The typical use-case is:

1. A user, via a web browser (HTTP client), issues a URL request to an HTTP server to

start a webapp.

2. The HTTP server returns an HTML form (client-side program), which is loaded into

the client's browser.

3. The user fills up the query criteria inside the form and submits the form.

Page 95: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

95

4. The client-side program sends the query parameters to a server-side program.

5. The server-side program receives the query parameters, queries the database based on

these parameters, and returns the query result to the client-side program.

6. The client-side program displays the query result on the browser.

7. The process repeats for the next request.

Installation of Apache Tomcat 7

Let's start the installation of Tomcat 7 on different OSes. The steps involved to install the

software on Windows are discussed first, and then we move on to the Linux environment.

Installation on a Windows environment

In this topic, we will discuss the steps involved during the software installation of Tomcat 7.

Following are the steps:

1. Download the latest stable version from the Tomcat official site, http://

tomcat.apache.org/download-70.cgi. We are downloading the 32-bit/64-bit Windows Service

Installer (pgp, md5). Once the download is complete, save it in the software folder.

2. Double-click on apache-tomcat-7.0.14.exe. It will launch the setup wizard.

3. Then, click on Next button to continue, as shown in the following screenshot:

4. An agreement pop-up is displayed. Click on I Agree. It means we agree to use Tomcat 7 as

per the GPL license, as shown in the following screenshot:

Page 96: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

96

6. The following window shows us the different components we need to install:

6. In the next step, we have to configure the username and password for the Tomcat Manager,

as shown in the following screenshot. We have set the Username and Password to admin.

Click on Next.

Page 97: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

97

7. In the next window, it will pick up the Java version from the JAVA_HOME variable,

if the variables are properly defined, as shown in the following screenshot:

8. The next window displays the installation path of Tomcat. By default, we use

C:\Program Files\Apache Software Foundation\Tomcat 7.0. In case we want to

change it, then we have to click on Browse and select the desired path. Click on

Install, as shown in the following screenshot:

Page 98: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

98

9. It's the final step of the Tomcat 7 installation. This will display the successful

implementation of Tomcat, as shown in the following screenshot:

Startup and shutdown of Tomcat services

Page 99: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

99

We have now completed the installation of Apache Tomcat on both the OSes. Now, it's time

to start the services and verify the setup we have created up to now. So why waste time, let's

rock and roll.

Services in Windows

In Windows, we can start/stop the services using two methods: • Through the Microsoft

Management Console (MMC): Go to Start | Run | services.msc. When the MMC opens, as

shown in the following screenshot, you can start/stop services based on the requirement:

Apache monitor console:

Tomcat comes with a very handy tool for administration, which is popularly known as the

Apache monitoring console. It's very useful in managing the Tomcat instance (service

recycle, enabling logs, and JVM configuration).The following screenshot shows the recycle

process using the Tomcat monitoring console. To start/stop services, go to Start | Programs |

Apache-Tomcat7 |apache-tomcat monitor Start/Stop.

Verification of Tomcat status

Page 100: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

100

Once we have executed the startup scripts, the next step is the verification of the Tomcat

services, to check whether services are coming up fine or not. By default, Tomcat runs on

HTTP port 8080 and can be accessed on the web browser using the URL,

http://localhost:8080. We then find the Tomcat welcome page, which shows that Tomcat is

installed correctly and running fine in the environment, as shown in the following screenshot:

Once the welcome page for Tomcat 7 is displayed, we can verify the server status by clicking

on Server Status.

It will prompt for the user ID/password. Remember, we have created a user admin that the

user ID will be used here for access, as shown in the following screenshot:

Page 101: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

101

DATABASE CONNECTIVITY: JDBC perspectives, JDBC program example

Java JDBC

Java JDBC is a java API to connect and execute query with the database. JDBC API uses

jdbc drivers to connect with the database.

Why use JDBC

Before JDBC, ODBC API was the database API to connect and execute query with the

database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform

dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses

JDBC drivers (written in Java language).

Do You Know

o How to connect Java application with Oracle and Mysql database using JDBC?

o What is the difference between Statement and PreparedStatement interface?

o How to print total numbers of tables and views of a database using JDBC ?

o How to store and retrieve images from Oracle database using JDBC?

o How to store and retrieve files from Oracle database using JDBC?

What is API

API (Application programming interface) is a document that contains description of all the

features of a product or software. It represents classes and interfaces that software programs

can follow to communicate with each other. An API can be created for applications, libraries,

operating systems, etc.

JDBC Driver

JDBC Driver is a software component that enables java application to interact with the

database.There are 4 types of JDBC drivers:

1. JDBC-ODBC bridge driver

2. Native-API driver (partially java driver)

Page 102: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

102

3. Network Protocol driver (fully java driver)

4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-

ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is

now discouraged because of thin driver.

Advantages:

o easy to use.

o can be easily connected to any database.

Disadvantages:

o Performance degraded because JDBC method call is converted into the ODBC

function calls.

o The ODBC driver needs to be installed on the client machine.

2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts

JDBC method calls into native calls of the database API. It is not written entirely in java.

3) Network Protocol driver

The Network Protocol driver uses middleware (application server) that converts JDBC calls

directly or indirectly into the vendor-specific database protocol. It is fully written in java.

4) Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database protocol.

That is why it is known as thin driver. It is fully written in Java language.

Page 103: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

103

5 Steps to connect to the database in java

There are 5 steps to connect any java application with the database in java using JDBC. They

are as follows:

o Register the driver class

o Creating connection

o Creating statement

o Executing queries

o Closing connection

1) Register the driver class

The forName() method of Class class is used to register the driver class. This method is

used to dynamically load the driver class.

Syntax of forName() method

2) Create the connection object

The getConnection() method of DriverManager class is used to establish connection with

the database.

Syntax of getConnection() method

3) Create the Statement object

The createStatement() method of Connection interface is used to create statement. The

object of statement is responsible to execute queries with the database.

Page 104: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

104

Syntax of createStatement() method

4) Execute the query

The executeQuery() method of Statement interface is used to execute queries to the

database. This method returns the object of ResultSet that can be used to get all the records

of a table.

Syntax of executeQuery() method

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The

close() method of Connection interface is used to close the connection.

Syntax of close() method

Example to connect to the Oracle database in java

For connecting java application with the oracle database, you need to follow 5 steps to

perform database connectivity. In this example we are using Oracle10g as the database. So

we need to know following information for the oracle database:

Page 105: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

105

1. Driver class: The driver class for the oracle database

is oracle.jdbc.driver.OracleDriver.

2. Connection URL: The connection URL for the oracle10G database

is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the

database, thin is the driver, localhost is the server name on which oracle is running,

we may also use IP address, 1521 is the port number and XE is the Oracle service

name. You may get all these information from the tnsnames.ora file.

3. Username: The default username for the oracle database is system.

4. Password: Password is given by the user at the time of installing the oracle

database.

Example to Connect Java Application with Oracle database

In this example, system is the username and oracle is the password of the Oracle database.

1. import java.sql.*;

2. class OracleCon{

3. public static void main(String args[]){

4. try{

5. //step1 load the driver class

6. Class.forName("oracle.jdbc.driver.OracleDriver");

7. //step2 create the connection object

8. Connection con=DriverManager.getConnection(

9. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

10.

11. //step3 create the statement object

12. Statement stmt=con.createStatement();

13.

14. //step4 execute query

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

16. while(rs.next())

17. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

18.

19. //step5 close the connection object

20. con.close();

21.

22. }catch(Exception e){ System.out.println(e);}

23.

24. } }

Page 106: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

106

Example to connect to the mysql database in java

For connecting java application with the mysql database, you need to follow 5 steps to

perform database connectivity.

In this example we are using MySql as the database. So we need to know following

informations for the mysql database:

1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.

2. Connection URL: The connection URL for the mysql database

is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,

localhost is the server name on which mysql is running, we may also use IP address,

3306 is the port number and sonoo is the database name. We may use any database, in

such case, you need to replace the sonoo with your database name.

3. Username: The default username for the mysql database is root.

4. Password: Password is given by the user at the time of installing the mysql database.

In this example, we are going to use root as the password.

Let's first create a table in the mysql database, but before creating table, we need to create

database first.

Example to Connect Java Application with mysql database

In this example, sonoo is the database name, root is the username and password.

1. import java.sql.*;

2. class MysqlCon{

3. public static void main(String args[]){

4. try{

5. Class.forName("com.mysql.jdbc.Driver");

6. Connection con=DriverManager.getConnection(

7. "jdbc:mysql://localhost:3306/sonoo","root","root");

8. //here sonoo is database name, root is username and password

9. Statement stmt=con.createStatement();

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

11. while(rs.next())

12. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

13. con.close();

14. }catch(Exception e){ System.out.println(e);}

15. }

16. }

Page 107: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

107

JSP: Understanding Java Server Pages

JSP is a server side technology that does all the processing at server. It is used for creating

dynamic web applications, using java as programming language.

JSP technology is used to create web application just like Servlet technology. It can be

thought of as an extension to servlet because it provides more functionality than servlet such

as expression language, jstl etc.

A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain than

servlet because we can separate designing and development. It provides some additional

features such as Expression Language, Custom Tag etc.

Advantage of JSP over Servlet

There are many advantages of JSP over servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to servlet technology. We can use all the features of servlet in

JSP. In addition to, we can use implicit objects, predefined tags, expression language and

Custom tags in JSP, that makes JSP development easy.

2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with

presentation logic. In servlet technology, we mix our business logic with the presentation

logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The servlet

code needs to be updated and recompiled if we have to change the look and feel of the

application.

4) Less code than Servlet

In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the

code. Moreover, we can use EL, implicit objects etc.

Life cycle of a JSP Page

The JSP pages follows these phases:

o Translation of JSP Page

o Compilation of JSP Page

o Classloading (class file is loaded by the classloader)

o Instantiation (Object of the Generated Servlet is created).

Page 108: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

108

o Initialization ( jspInit() method is invoked by the container).

o Reqeust processing ( _jspService() method is invoked by the container).

o Destroy ( jspDestroy() method is invoked by the container).

Creating a simple JSP Page

To create the first jsp page, write some html code as given below, and save it by .jsp

extension. We have save this file as index.jsp. Put it in a folder and paste the folder in the

web-apps directory in apache tomcat to run the jsp page.

index.jsp

Let's see the simple example of JSP, here we are using the scriptlet tag to put java code in the

JSP page. We will learn scriptlet tag later.

1. <html>

2. <body>

3. <% out.print(2*5); %>

4. </body>

5. </html>

It will print 10 on the browser.

How to run a simple JSP Page ?

Follow the following steps to execute this JSP page:

o Start the server

o put the jsp file in a folder and deploy on the server

o visit the browser by the url http://localhost:portno/contextRoot/jspfile e.g.

http://localhost:8888/myapplication/index.jsp

Do I need to follow directory structure to run a simple JSP ?

No, there is no need of directory structure if you don't have class files or tld files. For

example, put jsp files in a folder directly and deploy that folder.It will be running fine.But if

you are using bean class, Servlet or tld file then directory structure is required.

Directory structure of JSP

The directory structure of JSP page is same as servlet. We contains the jsp page outside the

WEB-INF folder or in any directory.

Page 109: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

109

The JSP API

The JSP API consists of two packages:

1. javax.servlet.jsp

2. javax.servlet.jsp.tagext

javax.servlet.jsp package

The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as

follows:

1. JspPage

2. HttpJspPage

The classes are as follows:

o JspWriter

o PageContext

o JspFactory

o JspEngineInfo

o JspException

o JspError

The JspPage interface

Page 110: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

110

According to the JSP specification, all the generated servlet classes must implement the

JspPage interface. It extends the Servlet interface. It provides two life cycle methods.

Methods of JspPage interface

1. public void jspInit(): It is invoked only once during the life cycle of the JSP when

JSP page is requested firstly. It is used to perform initialization. It is same as the init()

method of Servlet interface.

2. public void jspDestroy(): It is invoked only once during the life cycle of the JSP

before the JSP page is destroyed. It can be used to perform some clean up operation.

The HttpJspPage interface

The HttpJspPage interface provides the one life cycle method of JSP. It extends the JspPage

interface.

Method of HttpJspPage interface:

1. public void _jspService(): It is invoked each time when request for the JSP page

comes to the container. It is used to process the request. The underscore _ signifies

that you cannot override this method.

Example

<HTML>

<BODY>

Hello BeginnersBook Readers!

Current time is: <%= new java.util.Date() %>

</BODY>

</HTML>

Page 111: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

111

Your First JSP

Let’s start learning JSP with a simple JSP.

<%-- JSP comment --%>

<HTML>

<HEAD>

<TITLE>MESSAGE</TITLE>

</HEAD>

<BODY>

<%out.print("Hello, Sample JSP code");%>

</BODY>

</HTML>

The above JSP generates the following output:

Hello, Sample JSP code.

Servlet Vs JSP

Like JSP, Servlets are also used for generating dynamic webpages. Here is the comparison

between them.

The major difference between them is that servlet adds HTML code inside java while JSP

adds java code inside HTML. There are few other noticeable points that are as follows:

Servlets –

1. Servlet is a Java program which supports HTML tags too.

2. Generally used for developing business layer(the complex computational code) of an

enterprise application.

3. Servlets are created and maintained by Java developers.

JSP –

1. JSP program is a HTML code which supports java statements too.To be more precise,

JSP embed java in html using JSP tags.

2. Used for developing presentation layer of an enterprise application

3. Frequently used for designing websites and used by web developers.

Advantages of JSP

1. JSP has all the advantages of servlet, like: Better performance than CGI Built in session

features, it also inherits the the features of java technology like – multithreading,

exception handling, Database connectivity,etc.

Page 112: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

112

2. JSP Enables the separation of content generation from content presentation. Which

makes it more flexible.

3. With the JSP, it is now easy for web designers to show case the information what is

needed.

4. Web Application Programmers can concentrate on how to process/build the

information.

SP pages are saved with .jsp extension which lets the server know that this is a JSP page and

needs to go through JSP life cycle stages.

In my previous post about JSP introduction, I explained that JSP is not processed as such,

they first gets converted into Servelts and then the corresponding servlet gets processed by

Server.

The steps in the life cycle of jsp page are:

1. Translation

2. Compilation

3. Loading

4. Instantiation

5. Initialization

6. RequestProcessing

7. Destruction

Page 113: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

113

Let see the Life cycle of JSP in more detail –

1) As stated above whenever container receives request from client, it does translation only

when servlet class is older than JSP page otherwsie it skips this phase (reason I explained

above).

2) Then the container –

• compiles the corresponding servlet program

• Loads the corresponding servlet class

• Instantiates the servlet class

• Calls the jspInit() method to initialize the servlet instance( Jsp container will do this

job only when the instance of servlet file is not running or if it is older than the jsp file.)

[code language=”java”]

public void jspInit()

{

//code to intialize Servlet instances

}[/code]

3) A new thread is then gets created, which invokes the_jspService() method, with a request

(HttpServletRequest) and response (HttpServletRespnse) objects as parameters -shown

below.

[code language=”java”]

void _jspService( HttpServletRequest req, HttpServletResponse res)

{

//code goes here

}[/code]

4) Invokes the jspDestroy() method to destroy the instance of the servlet class. code will

look like below –

[code language=”java”]

public void jspDestory()

{

//code to remove the instances of servlet class

}[/code]

JSP Directives – Page, Include and TagLib

Directives control the processing of an entire JSP page. It gives directions to the server

regarding processing of a page.

JSP directives provides the instructions and directions to the web container about how to

control the processing JSP page.

Page 114: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

114

Syntax:

<%@ directiveName attributeName=”attributValue” %>

Types of JSP directives.

1. page directive.

2. include directive.

3. taglib directive.

JSP page directive:

Page directive is used to provide the instructions to the web container that are specific to the

current JSP page. It defines the page specific attributes like scripting language, error page etc.

Page directive attributes.

1. import

2. session

3. buffer

4. autoflush

5. contentType

6. isErrorPage

7. errorPage

8. isThreadSafe

9. language

10. info

Import Attribute Of JSP Page Directive

This attribute is used to import interface, classes or whole package. You can import more

than one package separated by commas.

Syntax: <%@page import=”value1,value2…”%>

Page 115: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

115

Session Attribute Of JSP Page Directive

This attribute checks whether JSP page is in a particular HTTP session or not. It can have true

or false value. Default value is true.

Syntax: <%@ page session=”value”%>

Page 116: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

116

Buffer Attribute In JSP Page Directive

This attribute is used to define the buffer size.

Syntax: <%@ page buffer=”value”%>

Page 117: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

117

AutoFlush Attribute In JSP Page Directive

This attribute is used to control the behaviour of the buffer. Buffer will be flushed

automatically when full if autoFlush is true otherwise throw an exception.

Syntax: <%@ page autoFlush=”value”%>

Page 118: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

118

ContentType Attribute In JSP Page Directive

This attribute is used to set the content type of the current JSP page.

Syntax:<%@ page contentType=”value”%>

Page 119: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

119

isErrorPage attribute:

This attribute is used specify that current jsp page can be used as an error page. It can have

true or false value.

Syntax: <%@ page isErrorPage=”value”%>

errorPage attribute:

This attribute is used to specify the URL of JSP page which is used as error page. An error

page should have isErrorPage attribute true.

Syntax: <%@ page errorPage=”value”%>

Page 120: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

120

Page 121: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

121

IsThreadSafe Attribute In JSP Page Directive

This attribute is used to specify whether this page supports multithreading or not. It can have

true or false value.

Syntax: <%@ page isThreadSafe=”value”%>

Page 122: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

122

Language Attribute In JSP Page Directive

This attribute is used to specify the scripting language for the current page.

Syntax: <%@ page language=”value”%>

Info Attribute In JSP Page Directive

This attribute is used to provide the JSP page description.

Syntax: <%@ page info=”value”%>

Page 123: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

123

JSP Include Directive

JSP include directive is used to merge or include the content of other resource into the current

JSP page during translation phase. Other resource can be jsp, html or a text file. It provides

the facility of code reusability.

Syntax: <%@ include file=”Relative

URL” %>

Page 124: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

124

JSP Taglib Directive

JSP taglib directive is used in case of custom tags. It specifies the tag library used for custom

tags. We will learn more about taglib directive in custom tag section.

Page 125: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

125

Attributes of JSP taglib directive:

1. uri.

2. prefix.

1. uri: This attribute specify the location of the tag library.

2. prefix: This attribute is to inform the web container that this markup is used for custom

actions.

Syntax: <%@ taglib uri=”uri” prefix=”prefixForCustomTag”>

Page 126: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

126

JSTL (JSP Standard Tag Library)

JSTL stands for JSP Standard Tag Library. It provides the no. of tags used for iteration,

condition checking, manipulating XML documents etc.

Advantages of JSTL:

1. 1. Code reusability.

2. 2. Scriplet tags are not needed.

Types of JSTL tags:

1. JSTL Core Tags

2. JSTL Formatting tags

3. JSTL SQL tags

4. JSTL XML tags

5. JSTL Functions

Page 127: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

127

1. JSTL Core Tags: These tags are used for iteration, condition checking, URL

management etc. Core tags are most commonly used.

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

2. JSTL Formatting tags: These tags are used for formatting the text, date, numbers etc.

Syntax: <%@ taglib uri=”http://java.sun.com/jsp/jstl/fmt” prefix=”fmt”%>

3. SQL tags: Theses tags are used for interacting with databases like Oracle, MySQL etc.

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

4. XML tags: These tags are used forcreating and manipulating XML documents.

Syntax: <%@ taglib uri=”http://java.sun.com/jsp/jstl/xml” prefix=”x”%>

5. JSTL Functions: These function tags are mainly used for manipulating strings.

Syntax: <%@ taglib uri=”http://java.sun.com/jsp/jstl/functions” prefix=”fn” %>

Creating HTML forms by embedding JSP code

Forms are an important aid to making the Web interactive. With JavaServer Pages, handling

forms is easy--they do most of the work required to get to the information submitted with a

form. Learn how to do it, without going nuts.

Page 128: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

128

A Simple HTML Form

To start off the exploration of HTML forms, it's best to start with a small form and expand

from there. Also, it's better to start with a JSP rather than a servlet, because it is easier to

write out the HTML. Most of the form handling for JSPs and servlets is identical, so after you

know how to retrieve form information from a JSP, you know how to do it from a servlet.

Listing 3.1 shows an HTML file containing a simple input form that calls a JSP to handle the

form.

The browser uses two methods to pass this information to the web server. These methods are

the GET Method and the POST Method.

The Methods in Form Processing

Let us now discuss the methods in Form Processing.

GET method

The GET method sends the encoded user information appended to the page request. The

page and the encoded information are separated by the ? character as follows –

http://www.test.com/hello?key1=value1&key2=value2

The GET method is the default method to pass information from the browser to the web

server and it produces a long string that appears in your browser's Location:box. It is

recommended that the GET method is better not used. if you have password or other

sensitive information to pass to the server.

The GET method has size limitation: only 1024 characters can be in a request string.

This information is passed using QUERY_STRING header and will be accessible through

QUERY_STRING environment variable which can be handled

using getQueryString() and getParameter() methods of request object.

POST method

A generally more reliable method of passing information to a backend program is the POST

method.

This method packages the information in exactly the same way as the GET method, but

instead of sending it as a text string after a ? in the URL it sends it as a separate message.

This message comes to the backend program in the form of the standard input which you

can parse and use for your processing.

JSP handles this type of requests using getParameter() method to read simple parameters

and getInputStream() method to read binary data stream coming from the client.

Page 129: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

129

Reading Form Data using JSP

JSP handles form data parsing automatically using the following methods depending on the

situation −

• getParameter() − You call request.getParameter() method to get the value of a

form parameter.

• getParameterValues() − Call this method if the parameter appears more than once

and returns multiple values, for example checkbox.

• getParameterNames() − Call this method if you want a complete list of all

parameters in the current request.

• getInputStream() − Call this method to read binary data stream coming from the

client.

GET Method Example Using URL

The following URL will pass two values to HelloForm program using the GET method.

http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI

Below is the main.jsp JSP program to handle input given by web browser. We are going to

use the getParameter() method which makes it very easy to access the passed information −

<html>

<head>

<title>Using GET Method to Read Form Data</title>

</head>

<body>

<h1>Using GET Method to Read Form Data</h1>

<ul>

<li><p><b>First Name:</b>

<%= request.getParameter("first_name")%>

</p></li>

<li><p><b>Last Name:</b>

Page 130: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

130

<%= request.getParameter("last_name")%>

</p></li>

</ul>

</body>

</html>

Now type http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI in your

browser's Location:box. This will generate the following result –

Using GET Method to Read Form Data

• First Name: ZARA

• Last Name: ALI

GET Method Example Using Form

Following is an example that passes two values using the HTML FORM and the submit

button. We are going to use the same JSP main.jsp to handle this input.

<html>

<body>

<form action = "main.jsp" method = "GET">

First Name: <input type = "text" name = "first_name">

<br />

Last Name: <input type = "text" name = "last_name" />

<input type = "submit" value = "Submit" />

</form>

</body>

Page 131: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

131

</html>

Keep this HTML in a file Hello.htm and put it in <Tomcat-installation-

directory>/webapps/ROOT directory. When you would

access http://localhost:8080/Hello.htm, you will receive the following output.

Name:

Last Name:

< p>Try to enter the First Name and the Last Name and then click the submit button to see

the result on your local machine where tomcat is running. Based on the input provided, it will

generate similar result as mentioned in the above example.

POST Method Example Using Form

Let us do a little modification in the above JSP to handle both the GET and the POST

method. Below is the main.jsp JSP program to handle the input given by web browser using

the GET or the POST methods.

Infact there is no change in the above JSP because the only way of passing parameters is

changed and no binary data is being passed to the JSP program. File handling related

concepts will be explained in separate chapter where we need to read the binary data stream.

<html>

<head>

<title>Using GET and POST Method to Read Form Data</title>

</head>

<body>

<center>

<h1>Using GET Method to Read Form Data</h1>

<ul>

<li><p><b>First Name:</b>

<%= request.getParameter("first_name")%>

</p></li>

Page 132: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

132

<li><p><b>Last Name:</b>

<%= request.getParameter("last_name")%>

</p></li>

</ul>

</body>

</html>

Following is the content of the Hello.htm file −

<html>

<body>

<form action = "main.jsp" method = "POST">

First Name: <input type = "text" name = "first_name">

<br />

Last Name: <input type = "text" name = "last_name" />

<input type = "submit" value = "Submit" />

</form>

</body>

</html>

Let us now keep main.jsp and hello.htm in <Tomcat-

installationdirectory>/webapps/ROOT directory. When you

access http://localhost:8080/Hello.htm, you will receive the following output.

Name:

Last Name:

Try to enter the First and the Last Name and then click the submit button to see the result on

your local machine where tomcat is running.

Based on the input provided, you will receive similar results as in the above examples.

Passing Checkbox Data to JSP Program

Checkboxes are used when more than one option is required to be selected.

Page 133: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

133

Following is an example HTML code, CheckBox.htm, for a form with two checkboxes.

<html>

<body>

<form action = "main.jsp" method = "POST" target = "_blank">

<input type = "checkbox" name = "maths" checked = "checked" /> Maths

<input type = "checkbox" name = "physics" /> Physics

<input type = "checkbox" name = "chemistry" checked = "checked" /> Chemistry

<input type = "submit" value = "Select Subject" />

</form>

</body>

</html>

The above code will generate the following result −

Maths Physics Chemistry

Following is main.jsp JSP program to handle the input given by the web browser for the

checkbox button.

<html>

<head>

<title>Reading Checkbox Data</title>

</head>

<body>

<h1>Reading Checkbox Data</h1>

<ul>

<li><p><b>Maths Flag:</b>

<%= request.getParameter("maths")%>

</p></li>

Page 134: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

134

<li><p><b>Physics Flag:</b>

<%= request.getParameter("physics")%>

</p></li>

<li><p><b>Chemistry Flag:</b>

<%= request.getParameter("chemistry")%>

</p></li>

</ul>

</body>

</html>

The above program will generate the following result −

Reading Checkbox Data

• Maths Flag :: on

• Physics Flag:: null

• Chemistry Flag:: on

Reading All Form Parameters

Following is a generic example which uses getParameterNames() method of

HttpServletRequest to read all the available form parameters. This method returns an

Enumeration that contains the parameter names in an unspecified order.

Once we have an Enumeration, we can loop down the Enumeration in the standard manner,

using the hasMoreElements() method to determine when to stop and using

the nextElement() method to get each parameter name.

<%@ page import = "java.io.*,java.util.*" %>

<html>

<head>

<title>HTTP Header Request Example</title>

</head>

<body>

Page 135: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

135

<center>

<h2>HTTP Header Request Example</h2>

<table width = "100%" border = "1" align = "center">

<tr bgcolor = "#949494">

<th>Param Name</th>

<th>Param Value(s)</th>

</tr>

<%

Enumeration paramNames = request.getParameterNames();

while(paramNames.hasMoreElements()) {

String paramName = (String)paramNames.nextElement();

out.print("<tr><td>" + paramName + "</td>\n");

String paramValue = request.getHeader(paramName);

out.println("<td> " + paramValue + "</td></tr>\n");

}

%>

</table>

</center>

</body>

</html>

Following is the content of the Hello.htm −

<html>

<body>

<form action = "main.jsp" method = "POST" target = "_blank">

<input type = "checkbox" name = "maths" checked = "checked" /> Maths

<input type = "checkbox" name = "physics" /> Physics

<input type = "checkbox" name = "chemistry" checked = "checked" /> Chem

Page 136: WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2 · DHTML (Dynamic HyperText Markup Language). ... The Document Object Model (DOM) is a specification that determines a mapping between

WEB TECHNOLOGY - JAVASCRIPT, SERVLETS, JSP UNIT-2

136

<input type = "submit" value = "Select Subject" />

</form>

</body>

</html>

Now try calling JSP using the above Hello.htm; this would generate a result something like

as below based on the provided input −