0% found this document useful (0 votes)
23 views

JSPand Servlet

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

JSPand Servlet

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 119

M.Sc.

Computer Science (Thiruvalluvar University)


JSP AND SERVLET PROGRAMMING

(Prepared by G.SEKAR, M.Sc., M.Phil., MBA, (Ph.D))

UNIT-I

JavaScript
Introduction to JavaScript

JavaScript was released by Netscape and Sun Microsystems in 1995. However, JavaScript is not the same thing as Java.

JavaScript:

• It is a programming language.
• It is an interpreted language.
• It is object-based programming.
• It is widely used and supported
• It is accessible to the beginner.

Uses of JavaScript
• Use it to add multimedia elements. With JavaScript you can show, hide, change, resize images, and create image
rollovers. You can create scrolling text across the status bar.
• Create pages dynamically. Based on the user's choices, the date, or other external data, JavaScript can produce
pages that are customized to the user.
• Interact with the user. It can do some processing of forms and can validate user input when the user submits the
form.

Writing JavaScript

JavaScript code is typically embedded in the HTML, to be interpreted and run by the client's browser. Here are some rules
to remember when writing JavaScript commands.
• JavaScript code is case sensitive
• White space between words and tabs are ignored
• Line breaks are ignored except within a statement
• JavaScript statements end with a semi- colon;

Syntax: The SCRIPT Tag

The <SCRIPT> tag alerts a browser that JavaScript code follows. It is typically embedded in the HTML.
<SCRIPT language = "JavaScript">
statements
</SCRIPT>

SCRIPT Example
The below code can be written inside <Head> tag of html or inside <Body> tag of html.

<SCRIPT language = "JavaScript">


alert("Welcome to the script tag test page.")
</SCRIPT>
1
Implementing JavaScript
There are commonly two ways to add JavaScript commands to the Web Pages.
• Internal code
• External file
• Inline file

External File
One can use the SRC attribute of the <SCRIPT> tag to call JavaScript code from an external text file. This is useful if one
have a lot of code or to use the same code in several pages, because any number of pages can call the same external
JavaScript file. The text file itself contains no HTML tags. It is called by the following tag:
<SCRIPT SRC="filename.js">
</SCRIPT>
Example
<SCRIPT language = "JavaScript" SRC = "external.js">
</SCRIPT>

Internal code
One can write java script code inside the script tags. This script tag can be placed anywhere in the Html code.
Example:
<script type="text/javascript">
// JavaScript code here
</script>

Inline code

Java script can be used as inline code also as below:

<INPUT TYPE="text" onChange="


if (parseInt(this.value) <= 5) {
alert('Please enter a number greater than 5.');}">

Variables:

JavaScript variables are "containers" for storing information

var x=5; var y=6; var z=x+y;

DataTypes:

There are three primitive data types available in JavaScript: String, Number and Boolean.

var carname="Maruti 800";


or
var carname=new String;
carname = Maruti 800";

var x=34.00;
or
var x= new Number;
x = 34.00;

var y= new Boolean;


y = true;
or
var y = true;
2
Operators

JavaScript language supports following type of operators.

Arithmetic Operators
Comparison Operators
Logical (or Relational) Operators
Assignment Operators
Conditional (or ternary) Operators

The Arithmetic Operators:

There are following arithmetic operators supported by JavaScript language:

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

+ Adds two operands A + B will give 30


- Subtracts second operand from the first A - B will give -10
* Multiply both operands A * B will give 200
/ Divide numerator by denumerator B / A will give 2
% Modulus Operator and remainder of after an integer division B % A will give 0
++ Increment operator, increases integer value by one A++ will give 11
-- Decrement operator, decreases integer value by one A-- will give 9

The Comparison Operators:

There are following comparison operators supported by JavaScript language

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

== Checks if the value of two operands is equal or not, if yes then (A == B) is not true.
condition becomes true.

!= Checks if the value of two operands is equal or not, if values are (A != B) is true.
not equal then condition becomes true.

> Checks if the value of left operand is greater than the value of (A > B) is not true.
right operand, if yes then condition becomes true.

< Checks if the value of left operand is less than the value of right (A < B) is true.
operand, if yes then condition becomes true.

3
>= Checks if the value of left operand is greater than or equal to the (A >= B) is not true.
value of right operand, if yes then condition becomes true.

<= Checks if the value of left operand is less than or equal to the (A <= B) is true.
value of right operand, if yes then condition becomes true.

The Logical Operators:

There are following logical operators supported by JavaScript language

Assume variable A holds 10 and variable B holds 20 then:

Operator Description Example

&& Called Logical AND operator. If both the operands are non zero (A && B) is true.
then condition becomes true.

|| Called Logical OR Operator. If any of the two operands are non (A || B) is true.
zero then condition becomes true.
! Called Logical NOT Operator. Use to reverses the logical state of !(A && B) is false.
its operand. If a condition is true then Logical NOT operator will
make false.

The Bitwise Operators:

There are following bitwise operators supported by JavaScript language.


Assume variable A holds 2 and variable B holds 3 then:

Operator Description Example

& Called Bitwise AND operator. It performs a Boolean AND (A & B) is 2 .


operation on each bit of its integer arguments.

| Called Bitwise OR Operator. It performs a Boolean OR operation (A | B) is 3.


on each bit of its integer arguments.

^ Called Bitwise XOR Operator. It performs a Boolean exclusive (A ^ B) is 1.


OR operation on each bit of its integer arguments.

~ Called Bitwise NOT Operator. It is a unary operator and operates (~B) is -4 .


by reversing all bits in the operand.

<< Called Bitwise Shift Left Operator. It moves all bits in its first (A << 1) is 4.
operand to the left by the number of places specified in the second
operand. New bits are filled with zeros.

4
>> Called Bitwise Shift Right with Sign Operator. It moves all bits in (A >> 1) is 1.
its first operand to the right by the number of places specified in
the second operand. The bits filled in on the left depend on the
sign bit of the original operand, in order to preserve the sign of the
result. If the first operand is positive, the result has zeros placed in
the high bits; if the first operand is negative, the result has ones
placed in the high bits.

>>> Called Bitwise Shift Right with Zero Operator. This operator is (A >>> 1) is 1.
just like the >> operator, except that the bits shifted in on the left
are always zero,

The Assignment Operators:

There are following assignment operators supported by JavaScript language:

Operator Description Example

= Simple assignment operator, Assigns values from right side C = A + B will assign value of A + B
operands to left side operand into C

+= Add AND assignment operator, It adds right operand to the left C += A is equivalent to C = C + A
operand and assign the result to left operand
-= Subtract AND assignment operator, It subtracts right operand C -= A is equivalent to C = C - A
from the left operand and assign the result to left operand
*= Multiply AND assignment operator, It multiplies right operand C *= A is equivalent to C = C * A
with the left operand and assign the result to left operand

/= Divide AND assignment operator, It divides left operand with the C /= A is equivalent to C = C / A
right operand and assign the result to left operand

%= Modulus AND assignment operator, It takes modulus using two C %= A is equivalent to C = C % A


operands and assign the result to left operand

Miscellaneous Operator

The Conditional Operator (? :) - There is an operator called conditional operator. This first evaluates an expression for a
true or false value and then execute one of the two given statements depending upon the result of the evaluation. The
conditional operator has this syntax:

Operator Description Example

?: Conditional Expression If Condition is true ? Then value X : Otherwise value Y

5
Conditional Structure

Conditional statements are used to perform different actions for different decisions. In JavaScript we have the following
conditional statements:

if statement - use this statement to execute some code only if a specified condition is true
if...else statement - use this statement to execute some code if the condition is true and another code if the
condition is false
if...else if....else statement - use this statement to select one of many blocks of code to be executed
switch statement - use this statement to select one of many blocks of code to be executed

If Statement

Use the if statement to execute some code only if a specified condition is true.

Syntax
if (condition)
{
code to be executed if condition is true
}
Example
Make a "Good day" greeting if the time is less than 20:00:
if (time<20)
{
x="Good day";
}
The result of x will be:
Good day

If...else Statement

Use the if....else statement to execute some code if a condition is true and another code if the condition is not true.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example
If the time is less than 20:00, get a "Good day" greeting, otherwise get a "Good evening" greeting
if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}

6
The result of x will be:
Good day

If...else if...else Statement

Use the if....else if...else statement to select one of several blocks of code to be executed.

Syntax

if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if neither condition1 nor condition2 is true
}

Example:

If the time is less than 10:00, get a "Good morning" greeting, if not, but the time is less than 20:00, get a "Good day"
greeting, otherwise get a "Good evening" greeting:
if (time<10)
{
x="Good morning";
}
else if (time<20)
{
x="Good day";
}
else
{
x="Good evening";
}
The result of x will be:
Good day

Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax

switch(n)
{
case 1:
execute code block 1
break;

7
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}

First we have a single expression n (most often a variable), that is evaluated once. The value of the expression is then
compared with the values for each case in the structure. If there is a match, the block of code associated with that case is
executed. Use break to prevent the code from running into the next case automatically.

Example

Display today's weekday-name. Note that Sunday=0, Monday=1, Tuesday=2, etc:

var day=new Date().getDay();


switch (day)
{
case 0:
x="Today it's Sunday";
break;
case 1:
x="Today it's Monday";
break;
case 2:
x="Today it's Tuesday";
break;
case 3:
x="Today it's Wednesday";
break;
case 4:
x="Today it's Thursday";
break;
case 5:
x="Today it's Friday";
break;
case 6:
x="Today it's Saturday";
break;
}

The result of x will be:

Today it's Thursday

8
Looping Structure

JavaScript supports different kinds of loops:

for - loops through a block of code a number of times


for/in - loops through the properties of an object
while - loops through a block of code while a specified condition is true
do/while - also loops through a block of code while a specified condition is true

The For Loop

The for loop is often the tool helps to loops through a block of code a number of times. The for loop has the following
syntax:

for (statement 1; statement 2; statement 3)


{
the code block to be executed
}

Statement 1 is executed before the loop (the code block) starts.


Statement 2 defines the condition for running the loop (the code block).
Statement 3 is executed each time after the loop (the code block) has been executed.

Example
for (var i=0; i<5; i++)
{
x=x + "The number is " + i + "<br>";
}

The For/In Loop

The JavaScript for/in statement loops through the properties of an object:

Example

var person={fname:"John",lname:"Doe",age:25};

for (x in person)
{
txt=txt + person[x];
}

The While Loop

The while loop loops through a block of code as long as a specified condition is true.

Syntax:
while (condition)
{
code block to be executed
}
9
Example

The loop in this example will continue to run as long as the variable i is less than 5:

Example

while (i<5)
{
x=x + "The number is " + i + "<br>";
i++;
}

The Do/While Loop

The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the
condition is true, and then it will repeat the loop as long as the condition is true.

Syntax:
do
{
code block to be executed
}
while (condition);

Example

The example below uses a do/while loop. The loop will always be executed at least once, even if the condition is false,
because the code block is executed before the condition is tested:

do
{
x=x + "The number is " + i + "<br>";
i++;
}
while (i<5);

Dialog Boxes

JavaScript has three kinds of dialog boxes: Alert box, Confirm box, and Prompt box.

Alert Box

An alert box is used to give provide proper alert message to the user. When an alert box pops up, the user will have to
click "OK" to proceed.

Syntax
window.alert("sometext");

The window.alert method can be written without the window prefix.


10
Example

<html>
<head>
<script>
function myFunction()
{
alert("I am an alert box!");
}
</script>
</head>
<body>
<input type="button" onclick="myFunction()" value="Show alert box">
</body>
</html>

Confirm Box

A confirm box is often used the user to verify or accept something. When a confirm box pops up, the user will have to
click either "OK" or "Cancel" to proceed. If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.

Syntax
window.confirm("sometext");

The window.confirm() method can be written without the window prefix.

Example

var r=confirm("Press a button");


if (r==true)
{
x="You pressed OK!";
}
else
{
x="You pressed Cancel!";
}

Prompt Box

A prompt box is often used the user to input a value before entering a page. When a prompt box pops up, the user will
have to click either "OK" or "Cancel" to proceed after entering an input value. If the user clicks "OK" the box returns the
input value. If the user clicks "Cancel" the box returns null.

Syntax
window.prompt("sometext","defaultvalue");

The window.prompt() method can be written without the window prefix.

11
Example

var person=prompt("Please enter your name","Harry Potter");


if (person!=null && person!="")
{
x="Hello " + person + "! How are you today?";
}

Arrays

Arrays are zero-indexed lists of values. They are a handy way to store a set of related items of the same type (such as
strings), though in reality, an array can include multiple types of items, including other arrays.

A simple array: var myArray = [ 'hello', 'world' ];

Accessing array items by index

var myArray = [ 'hello', 'world', 'good', 'morning' ];


alert(myArray[3]); // alerts 'morning'

Testing the size of an array

var myArray = [ 'hello', 'world' ];


alert(myArray.length); // alerts 2

Changing the value of an array item

var myArray = [ 'hello', 'world' ];


myArray[1] = 'changed';

Adding elements to an array

var myArray = [ 'hello', 'world' ];


myArray.push('new');

User Defined Function

A function is a block of code that will be executed when "someone" calls it.

JavaScript Function Syntax

A function is written as a code block (inside curly { } braces), preceded by the function keyword:

function functionname()
{
some code to be executed
}

The code inside the function will be executed when "someone" calls the function. The function can be called directly
when an event occurs (like when a user clicks a button), and it can be called from "anywhere" by JavaScript code.

12
Example:

<html>
<head>
<script>
function myFunction()
{
alert("Hello World!");
}
</script>
</head>

<body>
<button onclick="myFunction()">Try it</button>
</body>
</html>

Functions can also have arguments.


Example:

<button onclick="myFunction('Sai','Teacher')">Try it</button>

<script>
function myFunction(name,job)
{
alert("Welcome " + name + ", the " + job);
}
</script>

Functions can return values to the calling environment.

function myFunction(a,b)
{
return a*b;
}
<button onclick="myFunction(10,20)">Try it</button>

Built-in Functions

String:

Java Script string object is used to perform string manipulations.

String Object Methods:

Method Description

charAt() Returns the character at the specified index

concat() Joins two or more strings, and returns a copy of the joined strings

13
indexOf() Returns the position of the first found occurrence of a specified value in a string

lastIndexOf() Returns the position of the last found occurrence of a specified value in a string

Searches for a match between a substring (or regular expression) and a string, and replaces the
replace()
matched substring with a new substring

Searches for a match between a regular expression and a string, and returns the position of the
search()
match

Extracts the characters from a string, beginning at a specified start position, and through the
substr()
specified number of character

substring() Extracts the characters from a string, between two specified indices

toLowerCase() Converts a string to lowercase letters

toUpperCase() Converts a string to uppercase letters

Example:

var str = "Hello World";


var str1 = "Hello ";
var str2 = "world!";

var n = str.charAt(2) ; // l
var n = str1.concat(str2); // Hello world!

var str="Hello world, welcome to the universe.";


var n=str.indexOf("welcome"); // 13

var str="Hello planet earth, you are a great planet.";


var n=str.lastIndexOf("planet"); // 36

var str="Visit Microsoft!";


var n=str.replace("Microsoft","AGC"); // Visit AGC

var str="Visit AGC!";


var n=str.search("AGC"); // 6

var str="Hello world!";


var n=str.substr(2,3) ; // llo

document.write(str.substring(3)+"<br>"); // lo world!
document.write(str.substring(3,7)); // lo w
document.write(str.toLowerCase()); // hello world!
document.write(str.toUpperCase()); // HELLO WORLD!
14
Math:

The Math object allows us to perform mathematical tasks. The Math object includes several mathematical constants and
methods.

Syntax for using properties/methods of Math:

var x=Math.PI;
var y=Math.sqrt(16);

Mathematical Constants

JavaScript provides eight mathematical constants that can be accessed from the Math object.

Math.E
Math.PI
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E

Math Object Methods:

Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm (base E) of x
max(x,y,z,...,n) Returns the number with the highest value
min(x,y,z,...,n) Returns the number with the lowest value
pow(x,y) Returns the value of x to the power of y
random() Returns a random number between 0 and 1
round(x) Rounds x to the nearest integer
sin(x) Returns the sine of x (x is in radians)
sqrt(x) Returns the square root of x
tan(x) Returns the tangent of an angle

15
Example:
Math.abs(-7.25); // 7.25
Math.ceil(1.4) // 2
Math.floor(1.6); // 1
Math.pow(4,3); // 64
Math.random(); // 0.7492686821638224

Math.round(2.5); // 3
Math.max(5,10); // 10
Math.min(5,10); // 5

Date:

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

Date Object Methods:

Method Description
getDate() Returns the day of the month (from 1-31)
getDay() Returns the day of the week (from 0-6)
getMonth() Returns the month (from 0-11)
getFullYear() Returns the year (four digits)
getYear() Returns the year (two digits) (Deprecated)

getHours() Returns the hour (from 0-23)


getMinutes() Returns the minutes (from 0-59)
getSeconds() Returns the seconds (from 0-59)
getMilliseconds() Returns the milliseconds (from 0-999)
setDate() Sets the day of the month of a date object
setDay() Sets the day of the week(0-6)
setMonth() Sets the month of a date object
setYear() Set the year of a date object (Deprecated)
setFullYear() Sets the year (four digits) of a date object
setHours() Sets the hour of a date object
setMinutes() Set the minutes of a date object
setSeconds() Sets the seconds of a date object

16
Example:

var d = new Date();


var n = d.getDate(); // 19
var n = d.getDay(); // 5
var n = d.getMonth(); // 7
var n = d.getFullYear(); // 2013
var n = d.getYear(); // 13

Array:

Array Object Property:

length Sets or returns the number of elements in an array

Array Object Methods:

Method Description
join() Joins all elements of an array into a string
reverse() Reverses the order of the elements in an array
pop() Removes the last element of an array, and returns that element
push() Adds new elements to the end of an array, and returns the new length
shift() Removes the first element of an array, and returns that element

sort() Sorts the elements of an array

Example:

var fruits = ["Banana", "Orange", "Apple", "Mango"];


var energy = fruits.join(); // Banana,Orange,Apple,Mango
fruits.reverse(); // Mango,Apple,Orange,Banana
fruits.pop(); // The result of fruits will be Banana,Orange,Apple
fruits.push("Kiwi"); // The result of fruits will be Banana,Orange,Apple,Kiwi
fruits.shift(); // The result of fruits will be Orange,Apple,Kiwi
fruits.sort(); // The result of fruits will be Apple,Kiwi,Orange

User Defined Object:

Everything in JavaScript is an Object: a String, a Number, an Array, a Function.... In addition, JavaScript allows
us to define our own objects.

Functions can be used to construct user defined object:

function book(title, author){


this.title = title;
this.author = author;
}
17
Creating JavaScript Object Instances

Once we have an object constructor, we can create new instances of the object, like below:

var Book1=new book("C","Balagurusamy");


var Book2=new book("C++","Murali");

Defining Methods for an Object:

Methods can also be added to definitions an objects in java script.

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

Document Object

When an HTML document is loaded into a web browser, it becomes a document object. The document object is
the root node of the HTML document and the "owner" of all other nodes: (element nodes, text nodes, attribute
nodes, and comment nodes). The document object provides properties and methods to access all node objects,
from within JavaScript. The document is a part of the window object and can be accessed as window.document.

Hierarchy of few important objects:

18
JavaScript Document Objects Properties

Name Description
alinkColor A string that specifies the ALINK attribute.
anchors An array containing an entry for each anchor in the document.
applets An array containing an entry for each applet in the document.
bgColor A string that specifies the BGCOLOR attribute.
classes Creates a Style object that can specify the styles of HTML tags with a specific CLASS attribute.
cookie Specifies a cookie.
fgColor A string that specifies the TEXT attribute.
formName A separate property for each named form in the document.
forms An array a containing an entry for each form in the document.
height The height of the document, in pixels.
ids Creates a Style object that can specify the style of individual HTML tags.
images An array containing an entry for each image in the document.
lastModified A string that specifies the date the document was last modified.
layers Array containing an entry for each layer within the document.
linkColor A string that specifies the LINK attribute.
links An array containing an entry for each link in the document.
plugins An array containing an entry for each plug-in in the document.
title A string that specifies the contents of the TITLE tag.
URL A string that specifies the complete URL of a document.
vlinkColor A string that specifies the VLINK attribute.
width The width of the document, in pixels.

JavaScript Document Objects Methods

Name Description
captureEvents Sets the document to capture all events of the specified type.
close Closes an output stream and forces data to display.
getSelection Returns a string containing the text of the current selection.
handleEvent Invokes the handler for the specified event.
open Opens a stream to collect the output of write or writeln methods.
releaseEvents Sets the window or document to release captured events of the specified type, sending the event to
objects further along the event hierarchy.
routeEvent Passes a captured event along the normal event hierarchy.
write Writes one or more HTML expressions to a document in the specified window.
writeln Writes one or more HTML expressions to a document in the specified window and follows them with a
newline character.

19
Example:

<html>
<body>
<form name="Form1"></form>
<form name="Form2"></form>
<form></form>
<script language = ―JavaScript‖>
document.write("<h1>Hello World!</h1>");
document.write(document.forms.length);
</script>

</body>
</html>

History Object

The history object contains the URLs visited by the user (within a browser window). The history object is part
of the window object and is accessed through the window.history property. There is no public standard that
applies to the history object, but all major browsers support it.

History Object Properties

Property Description
length Returns the number of URLs in the history list

History Object Methods

Method Description

back() Loads the previous URL in the history list

forward() Loads the next URL in the history list

go() Loads a specific URL from the history list

Example:

Create a back button on a page:

<html>
<head>
<script>
function goBack()
{
window.history.back()
}
</script>
</head>
<body>
20
<input type="button" value="Back" onclick="goBack()">

</body>
</html>

Navigator Object

The window.navigator object contains information about the visitor's browser.

Example:

<html>
<body>
<div id="example"></div>
<script language=‖JavaScript‖>
txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>";
txt+= "<p>Browser Name: " + navigator.appName + "</p>";
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>";
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>";
txt+= "<p>Platform: " + navigator.platform + "</p>";
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>";
txt+= "<p>User-agent language: " + navigator.systemLanguage + "</p>";
document.getElementById("example").innerHTML=txt;
</script>
</body></html>
Output:

Browser CodeName: Mozilla


Browser Name: Netscape
Browser Version: 5.0 (Windows)
Cookies Enabled: true
Platform: Win32
User-agent header: Mozilla/5.0 (Windows NT 5.1; rv:22.0) Gecko/20100101 Firefox/22.0
User-agent language: undefined

Form Object & Elements

The Form object represents an HTML form. For each <form> tag in an HTML document, a Form object is
created. Forms are used to collect user input, and contain input elements like text fields, checkboxes, radio-
buttons, submit buttons and more. A form can also contain select menus, textarea, fieldset, legend, and label
elements. Forms are used to pass data to a server.

Form Object Collections

Collection Description
elements[] Returns an array of all elements in a form

21
Form Object Properties

Property Description
acceptCharset Sets or returns the value of the accept-charset attribute in a form
action Sets or returns the value of the action attribute in a form
enctype Sets or returns the value of the enctype attribute in a form

length Returns the number of elements in a form


method Sets or returns the value of the method attribute in a form(GET, POST etc
name Sets or returns the value of the name attribute in a form
target Sets or returns the value of the target attribute in a form

Form Object Methods

Method Description
reset() Resets a form
submit() Submits a form

Form Object Events

Event The event occurs when...


onreset The reset button is clicked
onsubmit The submit button is clicked

Form object also supports standard properties and events.

Example:

<html>
<body>

<form id="frm1" action="form_action.jsp">


First name: <input type="text" name="fname" value="Donald"><br>
Last name: <input type="text" name="lname" value="Duck"><br>
<input type="submit" value="Submit">
</form>
<p>Return the value of each element in the form:</p>
<script>
var x=document.getElementById("frm1");
for (var i=0;i<x.length;i++)
{
document.write(x.elements[i].value);
document.write("<br>");
}
</script>

</body>
</html>
22
Form Elements:

1. TextBox
<Input type=‖text‖ name=‖age‖ value=‖30‖>
2. Password
<Input type=‖password‖ name=‖pass‖ value=‖**‖>
3. Button
<Input type=‖button‖ name=‖click me‖ value=‖click‖>
<Input type=‖reset‖ name=‖res‖ value=‖click‖>
<Input type=‖submit‖ name=‖sub‖ value=‖click‖>
4. Checkbox
<Input name=‖check1‖ type=‖checkbox‖ value=‖click‖ CHECKED>
5. Radio button
<Input type=‖radio‖ name=‖sex‖ value=‖M‖ checked>
<Input type=‖radio‖ name=‖sex‖ value=‖F‖>
6. Textarea
<Input type=‖textarea‖ name=‖t1‖ >
Enter data
</textarea>
7. Select & option
<select name=‖degree‖ size=2>
<option selected>BSC
<option>MSC
<option>MPHIL
</select>
Multiple key word can be included to make a list as a multi selection list.
8. Hidden
<Input type=‖hidden‖ name = ―hid1‖ …>

Properties of Form Elements:

Property Name Form Element Name Description


Text
Password
TextArea
Button
Radio Indicates the name of the object. This name can be used for referencing the
Name
CheckBox object in future, when required
Select
Submit
Reset
Hidden
Text
Password
TextArea
Button
Radio
Value Indicates the current value of the element
CheckBox
Select
Submit
Reset
Hidden

23
Text
Default Value Password Default value of the element
TextArea
Radio
Checked Indicates the current status of the object, whether checked or unchecked
CheckBox
Radio
DefaultChecked Indicates the default status of the element
CheckBox
Length Radio Indicates the number of radio buttons in the group
Select
Index Indicates the index of the current selected item
Radio
Text Select Value of the text displayed in the menu for the specific option
SelectedIndex Select Index of the selected element
DefaultSelected Select Indicates whether the option is selected by default in the option tag
Selected Select Indicates the current status of the option

Events:

Events are signals generated when specific actions occur. JavaScript is aware of these signals, and scripts can be
built to react to these events. Examples of events include when a user clicks on a hypertext link, changes data
in a form entry field, or when a page finishes loading. A complete list of the events available in JavaScript
appears in below Table

Event Handlers

In order to take advantage of events in JavaScript, it is necessary to use event handlers. Event handlers are scripts, in the
form of attributes of specific HTML tags, which the programmer can write. The event handlers are executed when the
specified events occur. The basic format of an event handler is:

<HTML_TAG OTHER_ATTRIBUTES eventHandler="JavaScript Program">

Example:

<INPUT TYPE="text" name=”address” onChange="return Validate()”>

Validate() is a JavaScript function.

Methods related with events of Form Elements:

Method Name Form Element Name Description


Text
onFocus() Password Fires when the form cursor enters into an object
TextArea
Text
onBlur() Password Fires when the form cursor is moved away from an object
TextArea
Text
onSelect() Password Fires when text is selected in an object
TextArea
24
Text
Password
onChange()
TextArea
Fires when text is changed in an object

Button
Radio
onClick() CheckBox
Submit Fires when an object is clicked on
Reset
Button
Radio
onDblClick() CheckBox Fires when an object is double clicked by mouse
Submit
Reset
onkeypress Major Elements Fires when the user presses a key on the associated element
onkeydown Major Elements Fires when the user depresses a key (but not yet released) on the associated
element.
onkeyup Major Elements Fires when the user releases a key after having depressed it on the associated
element.
onMousemove Major Elements Fires when the mouse move over an element
onmouseout Major Elements Fires when the mouse leaves an item
onmouseup Major Elements Fires when the mouse button released
onmousedown Major Elements Fires when the mouse button pressed
onSubmit Form onsubmit event occurs when the submit button in a form is clicked.
onReset Form onreset event occurs when the reset button in a form is clicked.
onLoad Body The onload event occurs immediately after a page is loaded
onUnLoad The onunload event occurs once a page has unloaded (or the browser window
has been closed).
Example : window.onunload=function(){SomeJavaScriptCode};

Example:

Sample Key board events:

document.onkeypress=function(e){
var e=window.event || e
alert("CharCode value: "+e.charCode)
alert("Character: "+String.fromCharCode(e.charCode))
}

Sample Mouse events

Execute a JavaScript when moving the mouse pointer over an element:

<div onmousemove="myFunction()">Move the cursor over me</div>

Sample Form onsubmit

<html>
<head>
<script>

25
function greeting()
{
alert("Welcome " + document.forms["frm1"]["fname"].value + "!")
}
</script>
</head>
<body>

What is your name?<br>


<form name="frm1" action="submit.htm" onsubmit="greeting()">
<input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>

Timer event

With JavaScript, it is possible to execute some code at specified time-intervals. This is called timing events.It's
very easy to time events in JavaScript. The two key methods that are used are:

setInterval() - executes a function, over and over again, at specified time intervals
setTimeout() - executes a function, once, after waiting a specified number of milliseconds

The setInterval() and setTimeout() are both methods of the Window object.

Example Timer to display the current time:

<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>

<script>
var myVar=setInterval(function(){myTimer()},1000);
function myTimer()
{
var d=new Date();
var t=d.toLocaleTimeString();
document.getElementById("demo").innerHTML=t;
}
function myStopFunction()
{
clearInterval(myVar);
}
</script>

26
UNIT-II

Database programming with JDBC

JDBC Introduction:

JDBC: JavaDatabaseConnectivity version was released in October of 1996. JDBC provides a set of API's which
allows Java programmers to incorporate database services into their application. JDBC also includes specifications for
database drivers which hide the implementation details of a particular database from the API-level developers, driver
which allows a single application to access several different database through several different drivers simultaneously, and
a mapping between standard database data types and Java classes and primitive. The JDBC design is more based on
ODBC.

Need for JDBC

Application developers can use ODBC (Open Database Connectivity) on the Java platform. It's an established standard
API for database access. ODBC isn't appropriate for direct use from the Java programming language because it uses a C
interface. The JDBC API was modeled after ODBC, but, because JDBC is a Java API, it offers a natural Java interface for
working with SQL. JDBC is needed to provide a "pure Java" solution for application development.

Database Drivers: A program installed on a workstation or server to allow programs on that system to interact with a
DBMS.

JDBC Architecture:-

JDBC defines a uniform interface for accessing various relational databases. JDBC is a core part of the Java platform
and is included in the standard JDK distribution.

The primary function of the JDBC API is to provide a means for the developer to issue SQL statements and process
the results in a consistent, database-independent manner. JDBC provides rich, object-oriented access to databases by
defining classes and interfaces that represent objects such as:

1. Database connections
2. SQL statements
3. Result Set
4. Database metadata
5. Prepared statements
6. Callable statements
7. Database drivers
8. Driver manager

The JDBC API uses a Driver Manager and database-specific drivers to provide transparent connectivity to
heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The
Driver Manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. The
location of the driver manager with respect to the JDBC drivers and the servlet is shown below.

27
Layers of the JDBC Architecture

A JDBC driver translates standard JDBC calls into a network or database protocol or into a database library API call that
facilitates communication with the database. This translation layer provides JDBC applications with database
independence. If the back-end database changes, only the JDBC driver need be replaced with few code modifications
required. There are four distinct types of JDBC drivers.

Type 1 JDBC-ODBC Bridge. Type 1 drivers act as a "bridge" between JDBC and another database connectivity
mechanism such as ODBC. The JDBC- ODBC Bridge provides JDBC access using most standard ODBC drivers. This
driver is included in the Java 2 SDK within the sun.jdbc.odbc package. In this driver the java statements are converted to
a jdbc statements. JDBC statements calls the ODBC by using the JDBC-ODBC Bridge. And finally the query is executed
by the database. This driver has serious limitation for many applications.

Type 1 JDBC Architecture

28
Type 2 Java to Native API. Type 2 drivers use the Java Native Interface (JNI) to make calls to a local database library
API. This driver converts the JDBC calls into a database specific call for databases such as SQL, ORACLE etc. This
driver communicates directly with the database server. It requires some native code to connect to the database. Type 2
drivers are usually faster than Type 1 drivers. Like Type 1 drivers, Type 2 drivers require native database client libraries
to be installed and configured on the client machine.

Type 2 JDBC Architecture

Type 3 Java to Network Protocol or All- Java Driver. Type 3 drivers are pure Java drivers that use a proprietary
network protocol to communicate with JDBC middleware on the server. The middleware then translates the network
protocol to database-specific function calls. Type 3 drivers are the most flexible JDBC solution because they do not
require native database libraries on the client and can connect to many different databases on the back end. Type 3 drivers
can be deployed over the Internet without client installation.

Java-------> JDBC statements------> SQL statements ------> databases.

Type 3 JDBC Architecture

29
Type 4 Java to Database Protocol. Type 4 drivers are pure Java drivers that implement a proprietary database protocol
(like Oracle's SQL*Net) to communicate directly with the database. Like Type 3 drivers, they do not require native
database libraries and can be deployed over the Internet without client installation. One drawback to Type 4 drivers is that
they are database specific. Unlike Type 3 drivers, if our back-end database changes, we may save to purchase and deploy
a new Type 4 driver (some Type 4 drivers are available free of charge from the database manufacturer). However, because
Type drivers communicate directly with the database engine rather than through middleware or a native library, they are
usually the fastest JDBC drivers available. This driver directly converts the java statements to SQL statements.

Type 4 JDBC Architecture

If one does not have the opportunity or inclination to install and configure software on each client, then Type 1 and Type
2 drivers cannot be used. Type 1 and Type 2 drivers are typically free of cost. Type 3 drivers advantages are
flexibility and interoperability against performance and one can connect different databases. Type 4 drivers can
be used for better performance.

The JDBC API supports both two-tier and three-tier processing models for database access.

Figure 1: Two-tier Architecture for Data Access.

In the two-tier model, a Java application talks directly to the data source. This requires a JDBC driver that can
communicate with the particular data source being accessed. A user's commands are delivered to the database or
other data source, and the results of those statements are sent back to the user. The data source may be located
on another machine to which the user is connected via a network. This is referred to as a client/server
configuration, with the user's machine as the client, and the machine housing the data source as the server. The
network can be an intranet, which, for example, connects employees within a corporation, or it can be the
Internet.

30
Figure 2: Three-tier Architecture for Data Access.

In the three-tier model, commands are sent to a "middle tier" of services, which then sends the commands to the
data source. The data source processes the commands and sends the results back to the middle tier, which then
sends them to the user. The three-tier model is very attractive because the middle tier makes it possible to
maintain control over access and the kinds of updates that can be made to corporate data. Another advantage is
that it simplifies the deployment of applications. Finally, in many cases, the three-tier architecture can provide
performance advantages.

Installing and configure ODBC:

When we install JDK, the JDBC-ODBC Bridge will be installed automatically.

Configure Type-1 Driver:

Goto ControlPanel->Administrative Tools->Data Sources(ODBC)

Now a window will be opened.

In Userdsn or Systemdsn tab, click Add

Select the suitable driver for our Database.

For eg.. Microsoft Access Driver[*.mdb,*.accdb] for Microsoft Access Database or Microsoft ODBC for Oracle or Oracle
in XE

31
Click Finish

Then a window corresponding to selected driver will be opened.

Sample Connection Parameters:(for Access)

Data Source Name: emp


Select a database by clicking the select button then click ok.

32
JDBC APIs for database Connectivity:

java.sql package:

Provides the API for accessing and processing data stored in a data source (usually a relational database) using the Java TM
programming language.

Interface Summary

Array The mapping in the Java programming language for the SQL type ARRAY.
Blob The representation (mapping) in the JavaTM programming language of an SQL BLOB value.
CallableStatement The interface used to execute SQL stored procedures.
Clob The mapping in the JavaTM programming language for the SQL CLOB type.
Connection A connection (session) with a specific database.
DatabaseMetaData Comprehensive information about the database as a whole.
Driver The interface that every driver class must implement.
NClob The mapping in the JavaTM programming language for the SQL NCLOB type.
ParameterMetaData An object that can be used to get information about the types and properties for each parameter

marker in a PreparedStatement object.

PreparedStatement An object that represents a precompiled SQL statement.


Ref The mapping in the Java programming language of an SQL REF value, which is a reference to an
SQL structured type value in the database.

ResultSet A table of data representing a database result set, which is usually generated by executing a
statement that queries the database.

ResultSetMetaData An object that can be used to get information about the types and properties of the columns in a
ResultSet object.
RowId The representation (mapping) in the Java programming language of an SQL ROWID value.
Savepoint The representation of a savepoint, which is a point within the current transaction that can be
referenced from the Connection.rollback method.
SQLData The interface used for the custom mapping of an SQL user-defined type (UDT) to a class in the
Java programming language.

SQLInput An input stream that contains a stream of values representing an instance of an SQL structured type
or an SQL distinct type.

SQLOutput The output stream for writing the attributes of a user-defined type back to the database.
SQLXML The mapping in the JavaTM programming language for the SQL XML type.
Statement The object used for executing a static SQL statement and returning the results it produces.

33
Class Summary
Date A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value.

DriverManager The basic service for managing a set of JDBC drivers.


DriverPropertyInfo Driver properties for making a connection.
SQLPermission The permission for which the SecurityManager will check when code that is running in an applet
calls the DriverManager.setLogWriter method or the DriverManager.setLogStream (deprecated)
method.

Time A thin wrapper around the java.util.Date class that allows the JDBC API to identify this as an SQL
TIME value.

Timestamp A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL
TIMESTAMP value.

Types The class that defines the constants that are used to identify generic SQL types, called JDBC types.

Database Connectivity:

Establishing a connection using JDBC is a two step process. First the JDBC Driver is to be loaded and second step is to
make a connection.

#Load the driver


Driver can be loaded by using a built-in static method called forName of built -in class called Class.

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

ForName () takes string as an argument. sun.jdbc.odbc is package name and JdbcOdbcDriver is a class. It creates an
instance of the driver and registers it with the DriverManager.

# Get the connection

After the driver has been loaded, it is easy to make a connection. We need to make a call to the static method
DriverManager.getConnection(), which returns a connection to the database.

DriverManger.getConnection("jdbc:odbc:dsn","uid","pwd");

getConnection method is provided in three forms

getConnection(String url)
getConnection(String url, String uid, String password)
getConnection(String url,Properties arguments)

The URL used to establish database connection is of the following form.

jdbc:subprotocol:subname

34
All jdbc database protocol begins with jdbc. Subprotocol is to identify the connection mechanism. Subname identifies the
database.
getConnection() return an object that implements Connection interface.

Database URL

A database URL (or JDBC URL) is a platform independent way of addressing a database. A database/JDBC URL is of the
form
jdbc:[subprotocol]:[node]/[databaseName]
If we are accessing a database called employee on the server oracleserver.test.com using the xyz subprotocol, the database
URL could be:
jdbc:xyz:oracleserver.test.com/employee
Notice that the ordinary URL is of the form [protocol]://[node]/[path], such as http://www.jguru.com/index.html. The jdbc
database URL mimics the ordinary URL, just adding a sub protocol, and - depending on the driver implementation -
omitting the double slashes.
If the database resides on the same computer node as the java program, the hostname part and the corresponding double
slashes of the jdbc can be skipped:
jdbc:odbc:employee
All standard database URLs should commence with the string jdbc.

Query with JDBC


Performing basic SQL commands
In order to execute an SQL command using JDBC, create an Object for the statement interface. The Object for the
statement Object can be created by invoking Connection.createStatement() method. This method will return a JDBC
statement will be used to send SQL statements to the database.

Ex. Statement stmt = conn.createStatement();


Statement interface:
The statement interface has the following three methods to process the SQL commands from the application
executeQuery() - returns ResultSet object
executeUpdate() - returns integer
execute() - return Boolean

1. executeQuery() method execute an SQL statement that queries a database .Like

select * from emp.

Resultset res =Statement.executeQuery(“select * from emp”);

35
2. executeUpdate() method executes an SQL statement that updates the database like insert,update,delete,create,drop
etc.,and returns integer value of the update count associated with the SQL statement or 0 if the statement did not
return a result.
Statement stmt = conn.createStatement();
Stmt.executeUpdate(―insert into emp values(1000,‘1‘,10000);‖);

3. execute() method execute an SQL statement that is written as a string object. It returns a Boolean value indicating
whether a ResultSet object was produced as the result of SQL statement's execution.

Processing the Results (ResultSet Interface):

ResultSet is the representation of the Query result returning one row at a time. It is a replicate of database query
result. It holds number of methods to retrieve the record detail as well as the field details. To retrieve record details the
following methods are being used.

Methods Description
next() Move to the next record
first() Move to the first record in the set
last() Move to the last record in the set
previous() Move to the previous record
absolute(n) Move to the position n in the result set
relative(n) Move to the relative record from present record

When the database query is executed(such as select) the results of the query are returned as a table of data
organised according to rows and columns. The ResultSet interface is used to provide access to this tabular data. Query
results are returned as ResultSet objects that provides access to the tabular data, one row at a time. A ResultSet object
maintains a pointer to a row within the tabular results. This pointer is referred to as a cursor. When a ResultSet object is
returned from the Query, the cursor initially points immediately before the first row of the table. The next() of the
ResultSet is used to move the cursor to the next row of the table. The next() returns boolean value true if the next row is
returned and false if end of the table is reached. The get methods of ResultSet interface allow us to retrieve the
information contained in particular column of current row. These methods convert the column data from its SQL type to
Java type.

To retrieve the field information the following methods are being used.

Methods Description
getDouble() Double data type of java will be returned
getInt() Integer data type of java will be returned
getDate() Date data type will be returned
getTime(0 Time data type will be returned
getString() String data type will be returned

PreparedStatement:

PreparedStatement interface extends the statement interface to define methods that are used to work with precompiled
SQL statement. The use of precompiled SQL statements is to provide more efficiency in frequently used SQL statements.
PreparedStatement objects may be used with parameterized SQL statements .These parameterized SQL statements replace
a constant SQL expression with a question mark(?). The parameterized fields are said to be instantiated by IN parameter

36
values. The PreparedStatement interface provides several set methods for setting the values of IN parameter.These
methods are organized into the type of value to which a parameter is to be set.

Ex.

PreparedStatement psmt = conn.prepareStatement(“insert into emp values(?,?,?)”);


psmt.setInt(1,25);
psmt.setDouble(2,200.00);
psmt.setString(3,’abc’);
psmt.executeUpdate();

Callable Statement

The CallableStatement interface extends the PrepardStatement interface to execute stored SQL
procedures.CallableStatement object is created by method of Connection interface called prepareCall().It may be
parameterized using question marks in the same manner as that discussed for the PreparedStatement interface.However
the CallableStatement allows some parameter to be OUT parameter, which are used to return value from SQL procedure
call. The registerOutParameter() method of CallableStatement is used to identify the type of OUT parameter.

CallableStatement csmt = conn.prepareCall(“emp_ins(?,?,?)”);


csmt.setInt(1,25);
csmt.setDouble(2,200.00);
csmt.setString(3,’abc’);
csmt.executeUpdate();

Sample Programs

Program 1 reading records from database:

import java.sql.*;
class select
{
public static void main(String s[])
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:employee","system","admin");
Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
{
System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString("job")+"\t"+rs.getString(5));
}
}
catch(Exception e)

{
e.printStackTrace();
37
}
}
}
Program 2 insert record into database

import java.sql.*;
class insert{
public static void main(String s[])
{
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection conn=DriverManager.getConnection("Jdbc:Odbc:gokul","system","manager");
Statement stmt=conn.createStatement();
int a=stmt.executeUpdate("insert into emp(empno,ename)values(800,'dinesh')");
System.out.println(a+"rows successfully slected");
}
catch(Exception e)
{
e.printStackTrace();
}

}
}

Program 3 update records in database

import java.sql.*;
public class update{
public static void main(String arg[])
{

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:emp","student","student");
Statement stmt=conn.createStatement();
int a=stmt.executeUpdate("update empset sal=4000 where sal<8000");
System.out.println(a+"rows updated");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

38
MetaData

JDBC Meta Data is the collective information about the data structure and property of a column available in table.
The meta data of any table tells us the name of the columns, datatype used in column and constraint used to enter the
value of data into column of the table. There are two types of metadata available as below
DataBaseMetaData: This interface provides a variety of information about database. DatabaseMetaData object is
returned by Connection interface method called getMetaData(). Over 100 methods are defined in this interface to retrieve
almost any kind of information about database structure and capabilities.

ResultSetMetaData: This interface provides methods that are used to obtain information about ResultSet objects. The
getColumnCount() returns the numbers of columns in a tabular data accessed by a resultSet..getColumnName() returns
name of the columns in the database.The getType() returns the column SQL type. Other methods of ResultSetMetaData
are used to access additional column properties such as the column‘s display width, number of formats, and read/write
status.

Program 5 Database metadata

import java.sql.*;
class dbmeta{
public static void main(String s[]){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:student","std","std");
DatabaseMetaData dbm=conn.getMetaData();
System.out.println("The Database name is"+dbm.getDatabaseProductName());
System.out.println("The Database version is"+dbm.getDatabaseProductVersion());
}
catch(Exception e){}
}}

Program 6 resultset metadata

import java.sql.*;
class rsmeda{
public static void main(String s[]){

try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:gokul","std","std");
Statement stmt=conn.createStatement();
String sql="select * from emp";
ResultSet rs=stmt.executeQuery(sql);

ResultSetMetaData rms=rs.getMetaData();
int col=rms.getColumnCount();
for(int i=1;i<=col;i++)
{
System.out.print(rms.getColumnName(i)+"\t");
39
}
while(rs.next())

{
for(int j=1;j<=col;j++)
{
System.out.print(rs.getString(j)+"\t");
}
}
}
catch(Exception e)
{e.printStackTrace();
}
}
}

Scrollable Resultsets:

A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, one can iterate through it only
once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable and/or
updatable. In the scrollable resultSet the cursors can move in both forward and reverse direction from the current
position. The sensitivity of the ResultSet object is determined by one of three different ResultSet types:
 TYPE_FORWARD_ONLY — the result set is not scrollable i.e. the cursor moves only forward, from before the first
row to after the last row.

 TYPE_SCROLL_INSENSITIVE — the result set is scrollable; its cursor can move both forward and backward
relative to the current position, and it can move to an absolute position

 TYPE_SCROLL_SENSITIVE — the result set is scrollable; its cursor can move both forward and backward relative
to the current position, and it can move to an absolute position.

A result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is
TYPE_SCROLL_SENSITIVE does.

Ex.
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE);
ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
// rs will be scrollable
Updatable Resultsets

An updatable result set allows modification to data in a table through the result set. If the database does not support
updatable result sets, the result sets returned from executeQuery() will be read-only. To get updatable results, the
Statement object used to create the result sets must have the concurrency type ResultSet.CONCUR_UPDATABLE. The
query of an updatable result set must specify the primary key as one of the selected columns and select from only one
table. For some drivers, `SELECT * FROM my_table' will return a read-only result set, so we need to specify the column
names.

40
Ex.
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT a, b FROM my_table");
// rs will be scrollable and will be updatable

TYPE_SCROLL_INSENSITIVE -> Updates to the database will not be reflected immediately till closing the resultset
TYPE_SCROLL_SENSITIVE -> Updates to the database will be reflected immediately

The updater methods may be used in two ways:

1. To update a column value in the current row. In a scrollable ResultSet object, the cursor can be
moved backwards and forwards, to an absolute position, or to a position relative to the current row.
The following code fragment updates the NAME column in the fifth row of the ResultSet object rs
and then uses the method updateRow to update the data source table from which rs was derived.

rs.absolute(5); // moves the cursor to the fifth row of rs


rs.updateString("NAME", "raja"); // updates the
// NAME column of row 5 to be raja
rs.updateRow(); // updates the row in the data source

2. To insert column values into the insert row. An updatable ResultSet object has a special row
associated with it that serves as a staging area for building a row to be inserted. The following code
fragment moves the cursor to the insert row, builds a three-column row, and inserts it into rs and into
the data source table using the method insertRow.

rs.moveToInsertRow(); // moves cursor to the insert row


rs.updateString(1, "kannan"); // updates the
// first column of the insert row to be kannan
rs.updateInt(2,35); // updates the second column to be 35
rs.updateBoolean(3, true); // updates the third column to true
rs.insertRow();
rs.moveToCurrentRow();

41
Distributed Computing Using RMI:

Introduction to RMI

The Java Remote Method Invocation (RMI) system allows an object running in one Java virtual machine (JVM) to invoke
methods on an object running in another Java virtual machine. RMI provides for remote communication between
programs written in the Java programming language.

RMI Architecture

RMI applications often comprise two separate programs, a server and a client. A typical server program creates
some remote objects, makes references to these objects accessible, and waits for clients to invoke methods on
these objects. A typical client program obtains a remote reference to one or more remote objects on a server and
then invokes methods on them. RMI provides the mechanism by which the server and the client communicate
and pass information back and forth. Such an application is sometimes referred to as a distributed object
application.

(1) Application Layer:

It‘s a responsible for the actual logic (implementation) of the client and server applications.

Generally at the server side class contain implementation logic and also apply the reference to the appropriate object
as per the requirement of the logic in application.

(2) Proxy Layer:

It‘s also called the ―Stub/Skeleton layer‖.

A Stub class is a client side proxy handles the remote objects which are getting from the reference.

A Skeleton class is a server side proxy that set the reference to the objects which are communicates with the Stub.

42
(3) Remote Reference Layer (RRL):

It‘s a responsible for managing the references made by the client to the remote object on the server so it is available
on both JVM (Client and Server).

The Client side RRL receives the request for methods from the Stub that is transferred into byte stream process called
serialization (Marshaling) and then these data are send to the Server side RRL.

The Server side RRL doing reverse process and convert the binary data into object. This process called deserialization
or unmarshaling and then sent to the Skeleton class.

(4) Transport Layer:

It‘s also called the ―Connection layer‖.

It‘s a responsible for the managing the existing connection and also setting up new connections.

Distributed object applications need to do the following:

Locate remote objects. Applications can use various mechanisms to obtain references to remote
objects. For example, an application can register its remote objects with RMI's simple naming
facility, the RMI registry. Alternatively, an application can pass and return remote object references
as part of other remote invocations.
Communicate with remote objects. Details of communication between remote objects are handled
by RMI. To the programmer, remote communication looks similar to regular Java method
invocations.
Load class definitions for objects that are passed around. Because RMI enables objects to be
passed back and forth, it provides mechanisms for loading an object's class definitions as well as for
transmitting an object's data.

Example:

Steps for Developing the RMI Application:

(1) Define the remote interface

Calculator.java
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface Calculator extends Remote


{
public long add(long a,long b) throws RemoteException;
}

(2) Define the class and implement the remote interface (methods) in this class

CalculatorImpl.java

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

43
public class CalculatorImpl extends UnicastRemoteObject implements Calculator
{
protected CalculatorImpl() throws RemoteException
{
super();
}
public long add(long a, long b) throws RemoteException
{
return a+b;
}
}

(3) Define the Server side class

CalculatorServer.java

import java.rmi.Naming;

public class CalculatorServer


{
CalculatorServer()
{
try
{
Calculator c = new CalculatorImpl();
Naming.rebind("rmi://127.0.0.1:1099/CalculatorService", c);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new CalculatorServer();
}
}

(4) Define the Client side class

CalculatorClient.java

import java.rmi.Naming;
public class CalculatorClient
{
public static void main(String[] args)
{
try
{
Calculator c = (Calculator) Naming.lookup("//127.0.0.1:1099/CalculatorService");
44
System.out.println("addition : "+c.add(10, 15));
}
catch (Exception e)
{
System.out.println(e);
}
}
}

(5) Compile the all four source(java) files


javac Calculator.java
javac CalculatorImpl.java
javac CalculatorServer.java
javac CalculatorClient.java

(6) Generate the Stub/Skeleton class by command rmic


rmic CalculatorImpl

(7) Start the RMI remote Registry


start rmiregistry

(8) Run the Server side class


java CalculatorServer

(9) Run the Client side class(at another JVM)


open another cmd and again go to same path
java CalculatorClient

Output:

45
46
UNIT-III
JSP Programming:

JSP development

JSP, a specification of Sun Microsystems, first appeared in 1998. The official versions, 1.0 and 1.1, both appeared in
1999, and both were very popular.

Java Server Pages(JSP) is a template for a web page that uses Java code to generate an HTML document dynamically.
JSPs are run in a server-side component known as a JSP container, which translates them into equivalent java servlets. For
this reason, Servlets and JSPs are intimately related.

Advantages of JSP inherited from Servlets:

1. Persistent in memory and multithreaded , hence they have better scalability and performance than normal CGI
program
2. No special client setup needed.
3. Built-in support for HTTP Sessions
4. Full access to java technology: networking, threading, database connectivity etc.

Advantages of JSP their own:

1. Automatically recompiled when necessary.


2. No special URL mapping required to address JSP pages
3. JSP pages are HTML like, they have greater compatibility with Web development tools.

Three forms of JSP page:

JSP Source Translation Generated Compilation Compiled


Code Servlet Source Servlet Class
Code

Basic JSP LifeCycle

A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a servlet life
cycle with an additional step which is required to compile a JSP into servlet.

The following are the paths followed by a JSP

Compilation
Initialization
Execution
Cleanup

47
The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows:

JSP Compilation:

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has
never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.

The compilation process involves three steps:

1. Parsing the JSP.


2. Turning the JSP into a servlet.
3. Compiling the servlet.

JSP Initialization:

When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to perform JSP-
specific initialization, override the jspInit() method:

public void jspInit(){

// Initialization code...

Typically initialization is performed only once and as with the servlet init method, you generally initialize database
connections, open files, and create lookup tables in the jspInit method.

JSP Execution:

This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed. Whenever a browser
requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.

The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as follows:

48
void _jspService(HttpServletRequest request, HttpServletResponse response)
{
// Service handling code...
}
The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that
request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET, POST,
DELETE etc.

JSP Cleanup:

The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container. The
jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when you need to
perform any cleanup, such as releasing database connections or closing open files.

The jspDestroy() method has the following form:

public void jspDestroy()


{
// Your cleanup code goes here.
}

JSP Elements:
There are three types of JSP elements:

1. Directives
2. Scripting elements, including expressions, scriptlets, and declarations
3. Actions

Directive Elements

JSP directives provide directions and instructions to the container, telling it how to handle certain aspects of JSP
processing. A JSP directive affects the overall structure of the servlet class. It usually has the following form:

<%@ directive attribute="value" %>

Directives can have a number of attributes which can list down as key-value pairs and separated by commas. The blanks
between the @ symbol and the directive name, and between the last attribute and the closing %>, are optional.

There are three types of directive tag:

Directive Description

<%@ page ... %> Defines page-dependent attributes, such as scripting language, error page, and
buffering requirements.

<%@ include ... %> Includes a file during the translation phase.

<%@ taglib ... %> Declares a tag library, containing custom actions, used in the page

49
1. The page Directive:

The page directive is used to provide instructions to the container that pertain to the current JSP page. It is possible to
code page directives anywhere in the JSP page. By convention, page directives are coded at the top of the JSP page.

Following is the basic syntax of page directive:

<%@ page attribute="value" %>

Alternate XML equivalent of the above syntax as follows:

<jsp:directive.page attribute="value" />

Attributes:

Following is the list of attributes associated with page directive:

Attribute Purpose

buffer Specifies a buffering model for the output stream.

autoFlush Controls the behavior of the servlet output buffer.

contentType Defines the character encoding scheme.

errorPage Defines the URL of another JSP that reports on Java unchecked runtime exceptions.

isErrorPage Indicates if this JSP page is a URL specified by another JSP page's errorPage
attribute.

extends Specifies a superclass that the generated servlet must extend

import Specifies a list of packages or classes for use in the JSP as the Java import statement
does for Java classes.

info Defines a string that can be accessed with the servlet's getServletInfo() method.

isThreadSafe Defines the threading model for the generated servlet.

language Defines the programming language used in the JSP page.

session Specifies whether or not the JSP page participates in HTTP sessions

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

isScriptingEnabled Determines if scripting elements are allowed for use.

50
Examples:

<%@ page import = ―java.io.*‖ %>

<%@ page info = ―Sample shopping jsp page‖ %>

2. The include Directive:

The include directive is used to includes a file during the translation phase. This directive tells the container to merge the
content of other external files with the current JSP during the translation phase. It is possible to code include directives
anywhere in the JSP page.

The general usage form of this directive is as follows:

<%@ include file="relative url" >

The filename in the include directive is actually a relative URL. If one just specify a filename with no associated path, the
JSP compiler assumes that the file is in the same directory as our JSP.

The XML equivalent of the above syntax as follows:

<jsp:directive.include file="relative url" />

Example:

<%@ include file = ―/doc/hello.html‖ %>

3. The taglib Directive:

The Java Server Pages API allows us to define custom JSP tags that look like HTML or XML tags and a tag library is a
set of user-defined tags that implement custom behavior. The taglib directive declares that our JSP page uses a set of
custom tags, identifies the location of the library, and provides a means for identifying the custom tags in our JSP page.

The taglib directive follows the following syntax:

<%@ taglib uri="uri" prefix="prefixOfTag" >

Where the uri attribute value resolves to a location the container understands and the prefix attribute informs a container
what bits of markup are custom actions.

We can write XML equivalent of the above syntax as follows:

<jsp:directive.taglib uri="uri" prefix="prefixOfTag" />

Example:
<%@ taglib uri= ―/tlds/mytld1.tld‖ prefix= ―ft‖ %>
mytld1.tld defines one tag named table as below
<ft:table> …… </ft:table>.

51
Scripting elements

1. Expressions:

JSP provides a simple means for accessing the value of a Java variable or other expression and merging that value with
the HTML in the page. An expression is transformed into a statement that converts the value of the expression into a
String object and inserts it into the implicit out object.

The syntax is

<%= expression %> where expression is a valid Java expression


Example:

1. Simple primitive numeric value


Simple Math: 2 + 2 = <%= 2+2 %>

2. Expression involve method call:


The current time is <%= new java.util.Date() %>

The above code will generate the servlet code as


out.write(―The current time is ―;
out.print(new java.util.Date(0);
out.write(―\r\n‖);

The Java expression between <%= and %> delimiters can be as a complex as desired, the only requirement being that it
must be capable of being evaluated as a java String.

2. Scriptlets:

In JSP technology, a scriptlet is a piece of Java-code embedded in the HTML-like JSP code. The scriptlet is everything
inside the <% %> tags. Between these the user can add any valid Scriplet i.e. any valid Java Code.

Syntax:
<% statement; [statement;….] %>
Example:

<HTML>
<BODY>
<%
// This scriptlet declares and initializes "date"
java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
// This scriptlet generates HTML output
out.println( String.valueOf( date ));
%>
</BODY>
</HTML>

52
Scriptlet handling by the JSP container:

The JSP compiler simply includes the contents of scriptlet code in the body of the _jspService\() method. A JSP page may
contain any number of scriptlets. If multiple scriptlets exist, they are each appended to the _jspService () method in the
order in which they are coded. A scriptlet may contain an open curly brace that is closed in another scriptlet. The
generated _jspService() method consists of up to three types of statements, depending on the contents of the JSP page:
Code to handle HTML template data and expressions
The contents of any scriptlets
Container-generated initialization and exit code
Code to handle HTML template data and expressions

Any characters in the JSP page not inside a JSP element(a directive, expression, scriptlet, or actions) are considered part
of a fixed HTML template. The JSP container creates out.write() or out.print() statements that write these characters to the
response output stream. For example, this code

<li> Employee Name </li>


Will be converted as
out.write(―<li> Employee Name </li>\\r\n‖);

Scriptlet contents:

Anything found between <% and %> tags is copied word by word to the _jspService() method.

Scriptlet content:

<table border = ―0‖ align=―center‖ width=‖50‖>


<tr>
<th align=‖right‖>Celsius</th>
<th align=‖right‖>Farenheit</th>
</th>
<%
for(int c=0;c<=100;c+=10)
{
int f = 32 + 9 * c/5;
out.print(―<tr>‖);
out.print(―<td>‖+c+‖</td><td>‖+f+‖</td>‖);
out.print(―<\tr>‖);
}
%>
</table>

JSP container generated _jspService() content:

//<HTML>
out.write(―<table border = \―0\‖ align=\―center\‖ width=\‖50\‖>\r\n‖
+ ―<tr>\r\n‖
+ ―<th align=\‖right\‖>Celsius</th>\r\n‖
+ ―<th align=\‖right\‖>Farenheit</th>\r\n‖
+‖</th>\r\n‖);
for(int c=0;c<=100;c+=10)
{
int f = 32 + 9 * c/5;
out.print(―<tr>‖);
out.print(―<td>‖+c+‖</td><td>‖+f+‖</td>‖);
53
out.print(―<\tr>‖);
}
out.write(―</table>\r\n);

Container generated initialization and exit code:

In addition to code that the JSP page written by the developer, _jspService() begins and ends with statements that
initialize and release objects needed in the method. The exact code generated is implementation dependent and specific to
the JSP container vendor.

Sample code:

Public void _jspService(HttpServletRequest request, HttpServletResponse response) throws IOException,


ServletException
{
JspFactory _jspxFactory = null:
,,,
---
}
finally
{
If (_jspFactory != null)
_jspFactory.releasePageContext(pageContext);
}

3. Declarations:

It is possible to add variable and method declarations in a JSP page. These variables and methods can be used
in scriptlets and expressions. To add a declaration, one must use the <%! Java Statements %> sequences to
enclose the declarations. Like a scriptlet, the code inside the declaration delimiters is copied verbatim to the
generated java servlet. Scriptlets are copied to the inside of the –jspService() method, whereas declarations are
written outside the method as top-level members of the enclosing class.

Uses of declaration:

Declarations can contain any valid java code, but they are most commonly used in three contexts

1. Variable declaration: Both class and instance variables can be declared and initialized
2. Method definitions: Complex scriptlets code can be restructured into a main routine that calls other
methods
3. Inner classes: Additional classes can be defined and made available to scriptlets, expressions and other
declaration code

Example:

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


<HTML>
<BODY>
<%!
Date theDate = new Date();

54
Date getDate()
{
System.out.println( "In getDate() method" );
return theDate;
}
%>
Hello! The time is now <%= getDate() %>
</BODY>
</HTML>

Action elements

Standard action

JSP Standard action are predefined tags which perform some action based on information that is required at the exact time
the JSP page is requested by a browser. An action can, for instance, access parameters sent with the request to do a
database lookup. It can also dynamically generate HTML, such as a table filled with information retrieved from an
external system. They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a
request to a new page, to generate a browser-specific code, etc. The JSP standard actions affect the overall runtime
behavior of a JSP page and also the response sent back to the client.

Action element Description


<jsp:useBean> Makes a JavaBeans component available in a page
Gets a property value from a JavaBeans component and adds
<jsp:getProperty>
it to the response
<jsp:setProperty> Sets a JavaBeans component property value
Includes the response from a servlet or JSP page during the
<jsp:include>
request processing phase
<jsp:forward> Forwards the processing of a request to servlet or JSP page
Adds a parameter value to a request handed off to another servlet
<jsp:param>
or JSP page using <jsp:include> or <jsp:forward>
Generates HTML that contains the appropriate browser-dependent
<jsp:plugin> elements (OBJECT or EMBED) needed to execute an applet with
the Java Plug-in software

1. <jps : param>

Basically, <jsp:param> is use to pass one or more name/value pairs as request parameters to other resources like JSP page,
servlet or other resource that can process the parameter. This tag can be enclose in any other action tags, where passing of
parameters is required, for example--<jsp: forward> & <jsp:include>

Syntax:
<jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />

The name attribute specifies the parameter name and takes a case-sensitive literal string. The value attribute specifies
the parameter value and takes either a case-sensitive literal string or an expression that is evaluated at request time.

jsp:forward page="jspparam2.jsp">
<jsp:param name="myParam" value="Sai"/>
<jsp:param name="Age" value="15"/>
</jsp:forward>

55
jspparam2.jsp
This page has 2 forwarded parameters : <br>
<b>Name:</b> <%= request.getParameter("myParam") %><br>
<b>Age:</b> <%= request.getParameter("Age") %>

2. <jsp : include>

The jsp:include action is interpreted each time a request is made. The syntax is as below:

<jsp:include page=‖resourcename‖ flush=‖true‖ />

The included resourcename must be relative URL specification, containing only path information. The resource name is
mapped to the current servlet context in the same way as the filename in an include directive. The flush attribute is
mandatory and indicate whether to force the output buffer used by the JspWriter to be written to the client before the
resource is included.

Working principle:

When a <jsp:include> action is parsed by the JSP compiler, but rather than being executed at compilation time, it is
converted into Java code that invokes the named resource at request time. The resource can be a static data source, file or
a dynamic source such as a JSP page or a servlet.

Flowers1.jsp

<h2>Flowers</h3>
Most popular flowers are:
<jsp:include page=‖/flower_list‖ flush=‖true‖ />
All are beautiful

Flower_list is a servlet that generates the below code using its response object write method

<ol>
<li>lotus</li>
<li>rose</li>
<li>lily</li>
</ol>

The HTML sent to the Web browser is exactly the same as if flowers.jsp contained the below code:

<h2>Flowers</h3>
Most popular flowers are:
<ol>
<li>lotus</li>
<li>rose</li>
<li>lily</li>
</ol>
All are beautiful

56
Rules for Include action:

1. The page invoked by the jsp:include action has access to all the implicit objects available in the calling JSP.
2. It cannot alter the response headers
3. The page it refers can be a runtime expression
4. Execution time is slightly slower

3. <jsp : forward>

The <jsp:forward> forwards the request information from one resource to the other, for example, one jsp file to other. To
forward a request from one page to other, following syntax is required which forwards the request to other page. If a string
or an expression represents the URL to forward the page, use the syntax:

<jsp:forward page="relativeURL" />

If we want to send one or more name/value pairs as a parameters, use the syntax:

<jsp:forward page="relativeURL" >


<jsp:param name="parameterName" value=‖ parameterValue" />
</jsp:forward>

Example code of forward.jsp:

<%@ page language ="java" %>


<html>
<head><title>jsp forwarding a request</title></head>
<jsp:forward page="/jsp/welcome.jsp"/>
</html>

The above jsp page forwards the request to welcome.jsp page by using <jsp:forward page="/jsp/welcome.jsp"/>

Here is the code of welcome.jsp

<%@page language="java" %>


<html>
<head><title>jsp forwarding a request</title></head>
<body>
<h3><b>Welcome!</b></h3>
This is a JSP forward request Example.
Request is forward here.
</body>
</html>

57
4. <jsp : plugin>

The <jsp:plugin> action is use to download a plugin (an Applet or a Bean) to the client Web browser to execute it. The
<jsp:plugin> tag is replaced by either an <object> or <embed> tag, whichever is most appropriate for the client Web
browser (the <object> tag is for browsers that use HTML 4.0). The <jsp:params> element sends parameter names and
values to an applet or Bean at startup. The <jsp:fallback> element provides a message for the user if the plugin does not
start. If the plugin starts but the applet or Bean does not, the plugin usually displays a popup window explaining the error
to the user.

Syntax :

<jsp:plugin type="bean|applet"
code="classFileName"
codebase="classFileDirectoryName"
[ height="displayPixels" ]
[ width="displayPixels" ] [ <jsp:params>
[ <jsp:params>
name="parameterName" value="parameterValue" /> ]+
</jsp:params> ]
[ <jsp:fallback> text message for user </jsp:fallback> ]
.........
.........
</jsp:plugin>

Example:

<body bgcolor="white">
<h3> The given below applet is imported to this file : </h3>
<jsp:plugin type="applet" code="Pluginexample.class" codebase="applet"
height="300" width="300">
<jsp:fallback>
Plugin tag not supported by browser.
</jsp:fallback>
</jsp:plugin>
</body>

Jsp Comments:

Jsp comments are converted by the jsp engine into java comments in the source code of the servlet that implements the Jsp
page. The jsp comment doesn‘t appear in the output produced by the jsp page when it runs. Jsp comments do not increase
the size of the file; jsp comments are useful to increase the readability of the jsp page.
In Jsp two types of comments are allowed in the Jsp page:
1) Hidden comment: This comment will not appear in the output.
<%-- Hidden comment --%>
2) Output comment: This type of comment will appear in the output.
<!-- Output comment>

Template Data:

Template data is just HTML or XML; the JSP processor passes it on to output untouched.

58
Example:

<%@ page language ="java" %>


<html>
<head><title>jsp forwarding a request</title></head>
<Body>
<H1> Sample Forward checking page</H1> // Template data
<jsp:forward page="/jsp/welcome.jsp"/>
</html>
Scope of JSP variables:

There are four scopes available for a variable in JSP as described in the below table:

Scope Description
application Variables placed in this scope persist for the life of an application.
page Variables placed in this scope persist until the current JSP‘s service( ) method completes.
Included JSPs cannot see page scope variables from the page including them. Also, this scope is
exclusive to JSPs.
request Variables placed in this scope persist until processing for the current request is completed. This
scope differs from page scope because multiple servlets may be executed during the lifespan of a
request. Page scope variables persist only for the execution of one servlet.
session Variables placed in this scope persist until the current user‘s session is invalidated or expires. This
scope is valid only if the JSP or servlet in question is participating in a session

Example:

Scope1.jsp

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


<c:set var="Pag" value="Page Value" scope="page" />
<c:set var="Req" value="Request Value" scope="request" />
<c:set var="Ses" value="Session Value" scope="session" />
<c:set var="App" value="Application Value" scope="application" />
<html>
<body>
<b>Page Scope</b> ::<c:out value="${Pag}" /><br>
<b>Request Scope</b> ::<c:out value="${Req}" /><br>
<b>Session Scope</b> ::<c:out value="${Ses}" /><br>
<b>Application Scope</b>::<c:out value="${App}" /><br>
<a href="scope2.jsp">Go nextpage for Session,Application Scope</a>
</body>
</html>

Result

Page Scope ::Page Value


Request Scope ::Request Value
Session Scope ::Session Value
Application Scope::Application Value
Goto to next page to know the Session,Application Scope

59
Scope2.jsp

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


<html>
<body>
<b>Page Scope</b> ::<c:out value="${Pag}" /><br>
<b>Request Scope</b> ::<c:out value="${Req}" /><br>
<b>Session Scope</b> ::<c:out value="${Ses}" /><br>
<b>Application Scope</b>::<c:out value="${App}" /><br>
</body>
</html>

Result

Page Scope ::
Request Scope ::
Session Scope ::Session Value
Application Scope ::Application Value

In the above example "scope1.jsp" variables are set in all the four scopes are displayed. When clicked on a link and
moved to the next page "scope2.jsp" to display all the variables only the session and application scope variables are
displayed as there is no page, request scope for the second page.

Application Using implicit objects

1. The request object:

The request object retrieves values whatever client passes to the server by an HTTP request. Let if user submits the html
form with some data to be send to the server, is received by the HTTP request object of the JSP. To access the HTML
form data one to use the request object and it's several methods like getParameter().It is an implicit object of class
"HttpServletRequest". All the things like headers, cookies or parameters are sent from the client browser to the server
during an HTTP request object which most common use of the request object is to obtain parameter or query string
values.
Methods of the request object:

Method Description

getParameter(String name)
Returns the value of a request parameter as a String, or null if the
parameter does not exist.
getParameterNames()
Returns an Enumeration of String objects containing the names of the
parameters contained in this request.
getParameterValues(String name)
Returns an array of String objects containing all of the values the given
request parameter has, or null if the parameter does not exist.
getCookies()
Gets the array of cookies found in this request. See below for more
details on working with cookies.
getQueryString() Gets any query string that is part of the HTTP request URI.
getRequestURI() Gets the URI to the current JSP page.
getHeaderNames() Returns an enumerator of all HTTP header names.
Returns the value of an HTTP header such as "QUERY_STRING" or
getHeader(String hdr)
"URL". The method getHeaderNames() can be used to determine what
60
headers are available. See example below.
getAttribute(String) Retrieves the object associated with the named attribute.
Retrieves the names of all attributes currently associated with the
getAttributeNames()
session.
setAttribute(String, object) Sets the object to the named attribute. attribute created if it doesn't exist.
removeAttribute(String) Removes the object bound with the specified

Example:

Following program reads two parameters from the request object and returns the message to the client

Request.html

<html>
<head><title>Request Object In JSP.</title></head>
<body>
<form action="RequestObjectInJSP.jsp" method="post">
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td>User Name: </td>
<td><input type="text" size="20" name="txtUserName" />
</tr>
<tr>
<td>Password: </td>
<td><input type="password" size="20" name="txtPassword" />
</tr>
<tr>
<td>&nbsp;</td>
<td><input type="submit" value="Submit" name="B1" /></td>
</tr>
</table>
</form>
</body>
</html>

RequestObjectInJSP.jsp

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


<%
String username, password;
if(request.getParameter("txtUserName") == null)
username = "";
else
username = request.getParameter("txtUserName");

if(request.getParameter("txtPassword") == null)
password = "";
else
password = request.getParameter("txtPassword");
%>
<table align="center" bgcolor="ffff00" border="1" cellspacing=
"0" cellpadding="0">
<tr>
<td align><b>Your User Name: </b></td>
<td><%=username %><br/></td>
</tr>

61
<tr>
<td><b>Your Password: </b></td>
<td><%=password %></td>
</tr>
</table>

Output:

2. The response object:

Using 'response' object, reply is sent back to the browser. It is an implicit object of class "HttpServletResponse" and using
this object; response parameters can be modified or set. The response object handles the output of the client. The response
object is generally used by cookies. The response object is also used with HTTP Headers.

The following table summarizes the most useful methods available to the response object.

Method Description

setContentType() Sets the MIME type and character encoding for the page.

Adds the specified cookie to the response. It can be called multiple times to set
addCookie(Cookie)
more than one cookie.

containsHeader(name) Checks whether the response already includes this header.

setHeader(name, value) Creates an HTTP Header.

Sends a temporary redirect response to the client using the specified redirect
sendRedirect(String)
location URL.

sendError(int status_code) Sends an error response to the client using the specified status code

Example:

In this example, first page is login html page which sends login info. to the JSP page which redirects to another page
according to the correct or incorrect login. It has two separate pages - one for incorrect login & another for correct login.

62
response-redirect.html

<html>
<head>
<title>Redirecting Page</title>
</head>
<body>
<form method = "post" action = "response-redirect-main.jsp">
<font size = 4>Enter your name<input type = "text" name = " name"></font><br>
<font size = 4>Enter your password<input type="password" name = "pwd" ></font><br><br>
<input type = "submit" name = "submit" value = "submit" >
</form>
</body>
</html>
response-redirect-main.jsp

<%
String name = request.getParameter("name");
String password = request.getParameter("pwd");
if(name.equals("Williams") && password.equals("abcde"))
{
response.sendRedirect("response-redirect-success.html");
}
else
{
response.sendRedirect("response-redirect-fail.html");
}
%>

3. The out object:

Out object denotes the Output stream in the context of page. The class or the interface name of the object out is
"jsp.JspWriter". This object is instantiated implicitly from JSP Writer class and can be used for displaying anything within
delimiters.

Out Object Methods:

Method Description

Clear Clears the output buffer

clearBuffer Clears the buffer and does not throw an exception when the buffer is flushed

flush flush the buffer by writing the contents to the client

getBufferSize return the size of the buffer

getRemaining return the number of empty bytes in the buffer

newLine write a newline character to the output

63
print writes the value to the output without a newline character

println write the value to the output, including the newline character

Example:

<HTML>
<BODY>
<%
// This scriptlet declares and initializes "date"
System.out.println( "Evaluating date now" );
java.util.Date date = new java.util.Date();
%>
Hello! The time is now
<%
out.println( date );
out.println( "<BR>Your machine's address is " );
out.println( request.getRemoteHost());
%>
</BODY>
</HTML>

4. The session object:

The session implicit object is used to provide an association between the client and the server. This
association, or session, persists over multiple connections and/or requests during a given time period. Sessions
are used to maintain state and user identity across multiple page requests. A session can be maintained either by
using cookies or by URL rewriting.

The following table summarizes the most useful methods available to the session object.

Method Description

A session is considered to be "new" if it has been created by the server, but the
isNew()
client has not yet acknowledged joining the session.

invalidate() Discards the session, releasing any objects stored as attributes.

getAttribute(String) Retrives the object associated with the named attribute.

getAttributeNames() Retrives the names of all attributes currently associated with the session.

setAttribute(String, object) Sets the object to the named attribute. attribute created if it doesn't exist.

removeAttribute(String) Removes the object bound with the specified name from this session.

64
Example: Here is a set of pages that put a user's name in the session, and display it elsewhere.

Displayname.html

<HTML>
<BODY>
<FORM METHOD=POST ACTION="session.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>

session.jsp

<%@page language="java" %>


<%
String name = request.getParameter( "username" );
session.setAttribute( "theName", name );
%>
<HTML>
<HEAD><TITLE>CLICK TO CONTINUE</TITLE></HEAD>
<BODY>
<A HREF="sessionresult.jsp">Click to Continue</A>
</BODY>
</HTML>

sessionresult.jsp

<%@page language="java" session="true" %>


<HTML>
<HEAD><TITLE>DISPALYING YOUR NAME</TITLE></HEAD>

<BODY>
<font color=red size="10">Hello, <%= session.getAttribute( "theName" ) %></font>
</BODY>
</HTML>

5. The config object:

The config object is an object of type javax.servlet.ServletConfig. The ServletConfig for this JSP page. Has a page
scope. The config can be used to retrieve the configuration(initialization) parameters that are specific to a JSP page.
These parameters are set up within the deployment descriptor. The config object can be used to retrieve the
ServletContext object through its getServletContext() method.

65
The following table summarizes the most useful methods available to the config object.

Method Description
Returns a String containing the value of the named initialization parameter
getInitParameter(String name);

Returns the names of the servlet's initialization parameters as an Enumeration of


getInitParameterNames() String objects
Returns the name of the servlet instance.
getServletName()
Returns a reference to the ServletContext in which the caller is executing
getServletContext()

Example: To retrieve information about the initialization parameters


index.html

<html>
<body>
<input type = "text" name = 'uname'/>
<input type = "submit" name = 'go'/>
</body>
</html>
Web.xml

<web-app>
<servlet>
<servlet-name>action</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver. </param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

Welcome.jsp

<html>
<body>
<%
out.print("welcome"+request.getParameter("uname"));
String driver = config.getParameter("dname");
out.print("driver name is ="+driver);

%>
</body>
</html>

66
6. The exception object:

The JSP implicit exception object is an instance of the java.lang.Throwable class. It is available in JSP error pages only. It
represents the occurred exception that caused the control to pass to the JSP error page.

The important methods available in exception object are below:

Method Description

Returns a detailed message about the exception that has occurred.


getMessage()

Returns the cause of the exception as represented by a Throwable object


getCause()
Returns the name of the class concatenated with the result of getMessage()
toString()
Prints the result of toString() along with the stack trace to System.err, the error
printStackTrace() output stream

Returns an array containing each element on the stack trace.


getStackTrace()

Fills the stack trace of this Throwable object with the current stack trace, adding
fillInStackTrace() to any previous information in the stack trace.

Main.jsp

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

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

ShowError.jsp

<%@ page isErrorPage="true" %>


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

Output:

java.lang.RuntimeException: Error condition!!!


......
Opps...
Sorry, an error occurred.

Here is the exception stack trace:

7. The application object:

This implicit object application represents the application to which the JSP belongs. JSPs are grouped into
applications according to their URLs where the first directory name in a URL defines the application. The
application object contains methods that provide information about the JSP Container, support for logging
plus utility methods for example translating a relative URL to an absolute path.

The following table summarizes the most useful methods available to the session object.

Method Description

Returns the object named objName or returns null if the objName does
getAttribute(String objName)
not exist.

Returns an Enumeration containing the attribute names available within


getAttributeNames()
the application.

setAttribute(String objName,
Stores the object with the given object name in this application.
Object object)

removeAttribute(String objName) Removes the objName object from the application.

getMajorVersion() Returns the major version of the Servlet API for the JSP COntainer.

Returns information about the JSP Container, typically, name and product
getServerInfo()
version.

getResourceAsStream(Path) Translates the resource URL into an input stream for reading.

log(Message) Writes a text string to the JSP Containers default log file.

68
Example: Retrieve an attribute from application object

Applicationdemo.jsp

<%
String theSharedObject = (String) application.getAttribute("message");
%>
<HTML>
<HEAD>
<TITLE>Application Object - Page 2</TITLE>
</HEAD> <BODY>
This page retrieves the message that was stored in the
<i>application</i> object by another page.
<P>
The message is <b><%= theSharedObject %></b>
</BODY>
</HTML>

Handling Errors and Exception

Dealing with exception in the page directive:

The two attributes of page directive errorPage and isErrorPage are used to deal with exception. In this case we must define
and create a page to handle the exceptions. The page in which there is a possibility of generating exception, define the
errorPage attribute of page directive. This attribute sets a url (relative path starting from the "/" which refers from the root
directory of our JSP application). If any exception is generated the attribute refers to the file which is mentioned in the
given url. If one does not specify the url then the attribute refers to the current page of the JSP application if any exception
generated.

Example:

Index.jsp

<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/></form>

process.jsp

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


<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>

69
Error.jsp

<%@ page isErrorPage="true" %>

<h3>Sorry an exception occured!</h3>

Exception is: <%= exception %>

Output:

Dealing with exception in the Deployment Descriptor

The deployment descriptor allows us to specify application-wide error handlers for errors in the application. This provides
a way to specify different error pages for exceptions that might occur within a single page. If a given exception or HTTP
error occurs anywhere in the application, the deployment descriptor identifies an error page that can be served to the
client. A specific error page identified in a JSP page takes precedence over the error page identified in the deployment
descriptor. We can specify error pages for JSP exceptions and for HTTP errors. Error page elements come immediately
after the <welcome-file-list> element in the deployment descriptor. The web-xml file is called the deployment descriptor.
web.xml (deployment descriptor) file is available in WEB-INF folder.

Example:

inputData.html

<html>
<head>
<title>InputData.html</title>
</head>
<body>
<form action="../JSPFILE/Calculator.jsp">
<input type="text" name="n1"> <br>
<input type="text" name="n2"> <br>
<input type="submit" value="ADD">
</form>
</body>
</html>
70
Calculator.jsp

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>


<html>
<head>
<title> Calculator.jsp </title>
</head>

<body>
<%
int i1 = Integer.parseInt(request.getParameter("n1"));
int i2 = Integer.parseInt(request.getParameter("n2"));
int add = i1 + i2;
out.print("Addition = "+add);
%>

</body>
</html>

Error.jsp

<%@ page language="java" import="java.util.*" isErrorPage="true"%>


<html>
<head>
<title>Error.jsp</title>
</head>
<body>
Your page generate an Exception. <br>
<%= exception.getMessage() %>
</body>
</html>

web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app version="2.5"
----
-----
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<error-page>
<exception-type>java.lang.NumberFormatException</exception-type>
<location>/Error.jsp</location>
</error-page>
</web-app>

Input the integer value in textfields and click ADD button.

The browser display the below message,

Addition = 11

71
Now, input the float value in any of the text field and click ADD button so the browser display the message,

Your page generates an Exception.


For input string: "6.3"

This deployment descriptor entry means that whenever a web component throws a NumberFormatException from any
web page in the whole application(web project), the web container call the Error.jsp file, which simply reports the error
message in web browser.

Adding exception handling in JSP pages

Apart from the two techniques described in the previous sections(error page and deployment descriptor), If we want to
handle errors within the same page and want to take some action instead of firing an error page, we can make use of
try....catch block.

Following is a simple example which shows how to use try...catch block. Let us put following code in main.jsp:

<html>
<head>
<title>Try...Catch Example</title>
</head>
<body>
<%
try{
int i = 1;
i = i / 0;
out.println("The answer is " + i);
}
catch (Exception e){
out.println("An exception occurred: " + e.getMessage());
}
%>
</body>
</html>

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

An exception occurred: / by zero

Including and forwarding from -JSP pages

Include Action:

Refer <jsp:include> details available in standard action section

Forward Action:

Refer <jsp:forward> details available in standard action section

72
UNIT-IV
Servlet Programming:

Introduction to Servlets

A Servlet is a dynamically loaded module that services requests from a Web server. It runs entirely inside Java
virtual Machine. As Servlet is running on server side, it does not depend on browser compatibility. Execution of Java
Servlet is shown in the below fig.

Request
Web Web Server
Servlet
Browser

Response

1. The request submitted by client is carried by the web browser to the web server
2. The web server handover the request to the servlet program
3. The servlet program process the data and sends the results to web server
4. The web server sends the result to the client

Applications of Java Servlet:

1. Deploying web sites


2. E-Commerce applications

Advantages of Java Servlet

1. Efficient : After the servlet is loaded, handling new requests is only a matter of calling a service method which is
a more efficient method.
2. Persistent: Servlet maintains state between requests. When a servlet is loaded, it stays in memory while serving
incoming requests.
3. Portable: Servlets are portable since they are developed using the language Java which is platform independent.
4. Robust: Java provides a very well defined exception handling. Since servlets are developed using Java, it is robust
solutions.
5. Extensible: Being developed in an Object oriented language servlets can be extended and polymorphed into new
Objects that better suits our needs
6. Secure: Servlets can take the advantage of Java security manager and it can inherit the security provided by the
web server.

Servlets Implementation

A servlet is a small Java program that runs within a Web Server. Servlets receive and respond to requests from
Web clients, usually across HTTP, the HyperText Transfer Protocol.

To implement this interface, one can write a generic servlet that extends javax.servlet.GenericServlet or
an HTTP servlet that extends javax.servlet.http.HttpServlet.

There are methods available to initialize a servlet, to service requests, and to remove a servlet from the server.
These are known as life-cycle methods and are called in the following sequence:
73
1. The servlet is constructed, and then initialized with the init method.
2. Any calls from clients to the service method are handled.
3. The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and
finalized.

The Servlet Interface (javax.servlet.Servlet)

At the heart of the servlet architecture is the interface javax.servlet.Servlet. It provides framework for all the servlets. The
three lifecycle methods are present in this interface which should be implemented by all the servlets. The methods
available in this interface as below:

Method Description
public abstract void init(ServletConfig config) Initializes the servlet. The method is called once, automatically, by
throws ServletException the servlet engine when it loads the servlet.
public abstract ServletConfig getServletConfig() Returns a servlet config object, which contains any initialization
parameters and startup configuration for this servlet.
public abstract void service(ServletRequest req, Carries out a single request from the client. The method implements
ServletResponse res) throws a request and response paradigm. The request object contains
ServletException, IOException information about the service request, including parameters
provided by the client. The response object is used to return
information to the client.
public abstract String getServletInfo() Returns a string containing information about the servlet, such as its
author, version, and copyright.
public abstract void destroy() Cleans up whatever resources are being held (e.g., memory, file
handles, threads) and makes sure that any persistent state is
synchronized with the servlet's current in-memory state. The
method is called once, automatically, by the network service when
it unloads the servlet.

The Generic Servlet class

This class is created to provide a basic foundation of new Servlets. It also provides default life cycle methods of the
servlets. GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet may be directly extended by
a servlet, although it's more common to extend a protocol-specific subclass such as HttpServlet. GenericServlet makes
writing servlets easier. It provides simple versions of the lifecycle methods init and destroy and of the methods in the
ServletConfig interface. GenericServlet also implements the log method, declared in the ServletContext interface. To
write a generic servlet, one need only override the abstract service method. The GenericServlet class contains
the following methods:

Method Description
Void destroy() Called by the servlet container to indicate to a servlet that the
servlet is being taken out of service.
Void init A convenience method which can be overridden so that there's no
need to call super.init(config)
Void log(String msg) Writes the specified message to a servlet log file, prepended by the
servlet's name.
Void service(ServletRequest req, Called by the servlet container to allow the servlet to respond to a
ServletResponse res) request

74
The single thread Model interface

The simplest way to ensure that a servlet is thread safe is to implement the SingleThreadModel interface. This interface
defines no methods(marker interface) and simply serves as a flag to the server. If a servlet implements the
SingleThreadModel interface, the server guarantees that no more than one thread can execute the service(), doGet() and
doPost(0 method at a time for a particular servlet instance. This interface is deprecated in servlet API 2.4 because it does
not solve all the thread safe issues. Alternative techniques like synchronized block to be used in place of this interface.

Example:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyServlet extends HttpServlet implements SingleThreadModel{

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.print("welcome");
try{Thread.sleep(10000);}catch(Exception e){e.printStackTrace();}
out.print(" to servlet");
out.close();
}

The Http Servlet class

An abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides a framework
for handling the HTTP protocol. Because it is an abstract class, servlet writers must subclass it and override at least one
method.

Method Description
protected void doGet(HttpServletRequest req, Services all Get requests for the servlet
HttpServletResponse resp) throws ServletException,
IOException

protected void doPost(HttpServletRequest req, Services all Post requests for the servlet
HttpServletResponse resp) throws ServletException,
IOException

protected void doPut(HttpServletRequest req, Services all Put requests for the servlet. The PUT
HttpServletResponse resp) throws ServletException, operation is analogous to sending a file via FTP
IOException

protected void doDelete(HttpServletRequest req, Services all Delete requests to remove URL from
HttpServletResponse resp) throws ServletException, server
75
IOException

protected void doTrace(HttpServletRequest req, Performs the HTTP TRACE operation; the default
HttpServletResponse resp) throws ServletException, implementation of this method causes a response
IOException with a message containing all of the headers sent in
the trace request.
protected void service(HttpServletRequest req, This is an HTTP-specific version of the
HttpServletResponse resp) throws ServletException, Servlet.service method, which accepts HTTP
IOException specific parameters.

Protected void doOptions (HttpServletRequest req, Called by the server (via the service method) to
HttpServletResponse resp) allow a servlet to handle a OPTIONS request( to
determine the options and/or requirements
associated with a resource, or the capabilities of a
server). Ex. Allow: HEAD,GET,PUT, DELETE,
OPTIONS

Servlet Exceptions

The Servlet Exception class

java.lang.Object
|
+--java.lang.Throwable
|
+--java.lang.Exception
|
+--javax.servlet.ServletException

This class defines a servlet exception that a servlet throws while processing the client requests.

Constructor Summary

ServletException()
Constructs a new servlet exception.

ServletException(java.lang.String message)
Constructs a new servlet exception with the specified message.

ServletException(java.lang.String message, java.lang.Throwable rootCause)


Constructs a new servlet exception when the servlet needs to throw an exception and include a message about the
"root cause" exception that interfered with its normal operation, including a description message.

ServletException(java.lang.Throwable rootCause)
Constructs a new servlet exception when the servlet needs to throw an exception and include a message about the
"root cause" exception that interfered with its normal operation.

76
Method Summary

java.lang.Throwable
Returns the exception that caused this servlet exception.
getRootCause()

Example:

public class Calculate extends HttpServlet


{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
PrintWriter pw=res.getWriter();
int number1=Integer.parseInt(req.getParameter("num1"));
int number2=Integer.parseInt(req.getParameter("num2"));
int sum=number1+number2;
pw.println("Sum of the numbers is&nbsp;&nbsp;"+sum);
}
}

The unavailable Exception class

java.lang.Object
|
+--java.lang.Throwable
|
+--java.lang.Exception
|
+--javax.servlet.ServletException
|
+--javax.servlet.UnavailableException

This is a special kind of exception telling the server that this particular servlet is currently not available. It has two kinds
of unavailability:

Permanent unavailable
This servlet is now and forever in the future unavailable. If another class in spite of this fact asks this exception
for how long it is unavailable it returns a negative number of seconds. (-1 as a matter of fact)

Temporary unavailable
The servlet is currently unavailable, but will be available within a certain number of seconds. A class can ask the
exception for that number of seconds.

Servlet Lifecycle

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.

77
The init() method :

The init method is designed to be called only once. It is called when the servlet is first created, and not called again for
each user request. 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 we can also specify that the servlet be loaded
when the server is first started.

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.

The destroy() method :

The destroy() method is called only once at the end of the life cycle of a servlet. This method gives our 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:

Life cycle architecture diagram:

The following figure has shown 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.

78
Servlet Request and Response

A Generic servlet override its service() method to handle requests as appropriate for the servlet

Request
GenericServlet
Client Web service() method
Server
Response

ServletRequest and ServletResponse are two interfaces that serve as the backbone of servlet technology implementation.

They belong to the javax.servlet package.

Signature: public interface ServletRequest

It is used to provide client request information to a servlet. The servlet container creates a ServletRequest object
and sends it as an argument to the servlet‘s service method.

Signature: public interface ServletResponse

It assists a servlet in sending a response to the client. The servlet container creates a ServletResponse object and
passes it as an argument to the servlet‘s service method. Data that needs to be sent to the client will be put inside
the ServletResponse object. To send binary data back to the client, use the ServletOutputStream from the
ServletResponse object by calling the getOutputStream() method. To send character data to the client, the
PrintWriter object returned by getWriter() should be used.

ServletRequest interface methods summary:

Method Description
public abstract Object getAttribute(String name) Returns the value of the named attribute of the request
public abstract Enumeration getAttributeNames() Returns an enumeration of attribute names contained in this
request.
public abstract String getCharacterEncoding() Returns the character set encoding for the input of this request.

public abstract int getContentLength() Returns the size of the request entity data, or -1 if not known.
public abstract String getContentType() Returns the Internet Media Type of the request entity data, or
null if not known. Same as the CGI variable CONTENT_TYPE.
public abstract ServletInputStream getInputStream() Returns an input stream for reading binary data in the request
throws IOException body.
public abstract String getParameter(String name) Returns a string containing the lone value of the specified
parameter, or null if the parameter does not exist.
public abstract Enumeration getParameterNames() Returns the parameter names for this request as an enumeration
of strings, or an empty enumeration if there are no parameters or
the input stream is empty.
public abstract String[] getParameterValues(String Returns the values of the specified parameter for the request as
name) an array of strings, or null if the named parameter does not exist.

public abstract String getServerName() Returns the host name of the server that received the request.

public abstract int getServerPort() Returns the port number on which this request was received.
public abstract String getRemoteHost() Returns the fully qualified host name of the agent that sent the
request.
79
ServletResponse interface methods summary:

Method Description
public abstract String getCharacterEncoding() Returns the character set encoding used for this MIME
body. The character encoding is either the one specified
in the assigned content type, or one which the client
understands. Defauot set is text/plain
public abstract ServletOutputStream Returns an output stream for writing binary response
getOutputStream() throws IOException data.
public abstract PrintWriter getWriter() throws Returns a print writer for writing formatted text
IOException responses.
public abstract void setContentLength(int len) Sets the content length for this response.
public abstract void setContentType(String Sets the content type for this response.
type)

The HttpServletRequest interface

This interface gets data from the client to the servlet for use in the HttpServlet.service method. It allows the HTTP-
protocol specified header information to be accessed from the service method.

Method Description
getAttribute(String name) Returns the value of the named attribute as an Object
public abstract Cookie[] getCookies() Gets the array of cookies found in this request.
public abstract String getHeader(String name) Gets the value of the requested header field of this request.
public abstract String getMethod() Gets the HTTP method (for example, GET, POST, PUT) with
which this request was made.
public abstract String getQueryString() Gets any query string that is part of the HTTP request URI.
public abstract HttpSession getSession(boolean Gets the current valid session associated with this request
create)
Public void setAttribute(java.lang.String name, Stores an attribute in this request. Attributes are reset between
java.lang.Object o) requests.
Public Enumeration getAttributeNames() Returns an Enumeration containing the names of the attributes
available to this request.
public java.lang.String Returns the value of a request parameter as a String
getParameter(java.lang.String name)
public java.util.Enumeration getParameterNames() Returns an Enumeration of String objects containing the names
of the parameters contained in this request.
public java.lang.String[] Returns an array of String objects containing all of the values
getParameterValues(java.lang.String name) the given request parameter has
public java.lang.String getRemoteAddr() Returns the Internet Protocol (IP) address of the client that sent
the request.
public java.lang.String getRemoteHost() Returns the fully qualified name of the client that sent the
request, or the IP address of the client if the name cannot be
determined.

The Http servlet Response Interface

This interface allows a servlet's service method to manipulate HTTP-protocol specified header information and return data
to its client.

80
Method Description
public java.io.PrintWriter getWriter() Returns a PrintWriter object that can send character
throws java.io.IOException text to the client.
java.lang.String getContentType() Returns the Content-Type of the content of this
part
public abstract String encodeURL(String url) Encodes the specified URL by including the
session ID in it, or, if encoding is not needed,
returns the URL unchanged.
public void addCookie(Cookie cookie) Adds the specified cookie to the response

public abstract void setStatus(int sc, Sets the status code and response message for this
String sm) response.

public void sendRedirect(java.lang.String location) Sends a temporary redirect response to the client
throws java.io.IOException using the specified redirect location URL.
public void setHeader(java.lang.String name, Sets a response header with the given name and
java.lang.String value) value

Session Tracking Approaches

Session: A session is a conversation between the server and a client. A conversation consists series of continuous request
and response.

Necessary of session maintenance: When there is a series of continuous request and response from a same client to a
server, the server cannot identify from which client it is getting requests. Because HTTP is a stateless protocol. When
there is a need to maintain the conversational state, session tracking is needed. For example, in a shopping cart application
a client keeps on adding items into his cart using multiple requests. When every request is made, the server should
identify in which client‘s cart the item is to be added. So in this scenario, there is a certain need for session tracking.

Session tracking methods:

1. User authorization
2. Hidden form fields
3. URL rewriting
4. Cookies
5. Session tracking API

The first four methods are traditionally used for session tracking in all the server-side technologies. The session tracking
API method is provided by the underlying technology (java servlet or PHP or likewise). Session tracking API is built on
top of the first four methods.

URL Rewriting
If the browser does not support cookies, URL rewriting provides with another session tracking alternative. URL rewriting
is a method in which the requested URL is modified to include a session ID.

Original URL: http://server:port/servlet/ServletName

Rewritten URL: http://server:port/servlet/ServletName?sessionid=7456

When a request is made, additional parameter is appended with the url at the end. In general added additional parameter
will be sessionid or sometimes the userid. It will suffice to track the session. This type of session tracking doesn‘t need
81
any special support from the browser. Disadvantage is, implementing this type of session tracking is tedious. We need to
keep track of the parameter as a chain link until the conversation completes and also should make sure that, the parameter
doesn‘t clash with other application parameters.

Example:
URLRewritingServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class URLRewritingServlet extends HttpServlet {
//Initialize global variables
public void init(ServletConfig config)throws ServletException {
super.init(config);
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>URL Rewriting</title></head>");
out.println("<body>");
// Encode a URL string with the session id appended
// to it.
String url = response.encodeRedirectURL(
"http://localhost:8000/servlet/checkout?sid=5748");
// Redirect the client to the new URL
response.sendRedirect(url);
out.println("</body></html>");
out.close();
}
//Get Servlet information
public String getServletInfo() {
return "URLRewritingServlet Information";
}
}

This servlet services a GET request and redirects the client to a new URL. This new URL has the string sid=5748
appended to it. This string represents a session ID. When the servlet that services the redirection receives the request, it
will be able to determine the current user based on the appended value. At that point, the servlet can perform a database
lookup on the user and her actions based on this ID. Two methods are involved in this redirection. The first is
HttpServletResponse.encodeRedirectURL (), which takes a String that represents a redirection URL and encodes it for use
in the second method. The second method used is the HttpServletRequest.sendRedirect() method. It takes the String
returned from the encodeRedirectString() and sends it back to the client for redirection. The advantage of URL rewriting
over hidden form fields is the capability to include session tracking information without the use of forms. Even with this
advantage, it is still a very arduous coding process.

Hidden Form Fields


Using hidden form fields is one of the simplest session tracking techniques. Hidden form fields are HTML input types that
are not displayed when read by a browser. The following sample HTML listing includes hidden form fields:

<HTML>
<BODY>
<FORM ACTION="http://localhost:8080/ HiddenFieldServlet " METHOD="post">
82
<INPUT TYPE="hidden" NAME="name" VALUE="sai">
<INPUT TYPE=‖hidden‖ NAME=‖technology‖ VALUE=‖servlet‖>
<INPUT TYPE="hidden" NAME="id" VALUE="1000">
<INPUT TYPE=‖hidden‖ NAME=‖session‖ VALUE=‖12345‖>
<INPUT TYPE="submit">
</FORM>
</BODY>
</HTML>

Hidden fields like the above can be inserted in the webpages and information can be sent to the server for session
tracking. These fields are not visible directly to the user, but can be viewed using view source option from the browsers.
This type doesn‘t need any special configuration from the browser of server and by default available to use for session
tracking.

HiddenFieldServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class HiddenFieldServlet extends HttpServlet {
public void init(ServletConfig config)throws ServletException {
super.init(config);
}
//Process the HTTP Post request
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>HiddenFieldServlet" +
"</title></head>");
out.println("<body>");
// Get the hidden inputs and echo them
String user = request.getParameter("name");
String id = request.getParameter("id");
String session = request.getParameter("session");
out.println("<H3>" + user +", Your ID is:</H3><BR>");
out.println(id + "<BR>");
out.println("</body></html>");
out.close();
}
}

When the HTML is loaded, one should only see a Submit button. When the submit button is clicked the form
invoke the servlet and the response as user and id will be returned back to the client browser.

Cookies

Cookies are the mostly used technology for session tracking. Cookie is a key value pair of information, sent by the server
to the browser. This should be saved by the browser in its space in the client computer. Whenever the browser sends a
request to that server it sends the cookie along with it. Then the server can identify the client using the cookie.
In java, following is the source code snippet to create a cookie:

Cookie cookie = new Cookie(―userID‖, ―7456″);

response.addCookie(cookie);

83
Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the users can opt to disable
cookies using their browser preferences. In such case, the browser will not save the cookie at client computer and session
tracking fails.

Example: Form Example to set the cookies for first and last name

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

//Servlet to create cookies for lastname and firstname


// 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
{
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name",
request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name",
request.getParameter("last_name"));

// Set expiry date after 24 Hrs for both the cookies.


firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);

// Add both the cookies in the response header.


response.addCookie( firstName );
response.addCookie( lastName );

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Setting Cookies Example";

out.println( "<html>\n" +
"<head><title>" + title + "</title></head>\n" +
84
"<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>");
}
}

//code to read values of cookies

Cookie[] cookies = request.getCookies();


Cookie cookie;
for(int i=0; i<cookies.length; i++) {
cookie = cookies[i];
out.println("<TR>\n" +
" <TD>" + cookie.getName() + "\n" +
" <TD>" + cookie.getValue());
}

Session tracking API

Session tracking API is built on top of the first four methods. This is in order to help the developer to minimize the
overhead of session tracking. This type of session tracking is provided by the underlying technology. Let‘s take the java
servlet example. Then, the servlet container manages the session tracking task and the user need not do it explicitly using
the java servlets. This is the best of all methods, because all the management and errors related to session tracking will be
taken care of by the container itself.

Every client of the server will be mapped with a javax.servlet.http.HttpSession object. Java servlets can use the session
object to store and retrieve java objects across the session. Session tracking is at the best when it is implemented using
session tracking API. 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.

One would get HttpSession object by calling the public method getSession() of HttpServletRequest, as below:

HttpSession session = request.getSession();

We need to call request.getSession() before we send any document content to the client. Here is a summary of the
important methods available through HttpSession object:

85
S.No. Method & Description

public Object getAttribute(String name)


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

public long getCreationTime()


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

public long getLastAccessedTime()


5 This method returns the last time the client sent a request associated with this session, as the number of
milliseconds since midnight January 1, 1970 GMT.

public int getMaxInactiveInterval()


6 This method returns the maximum time interval, in seconds, that the servlet container will keep this session open
between client accesses.

7 public void invalidate()


This method invalidates this session and unbinds any objects bound to it.

public boolean isNew(


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

10 public void setAttribute(String name, Object value)


This method binds an object to this session, using the name specified.

public void setMaxInactiveInterval(int interval)


11 This method specifies the time, in seconds, between client requests before the servlet container will invalidate this
session.

Session Tracking Example using APIs:

This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a
session. Association of a new session with the request if one does not already exist.

86
// 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());

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();

out.println("<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<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" +
87
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
}
}
Compile above servlet SessionTrack and create appropriate entry in web.xml file. Now running
http://localhost:8080/SessionTrack would display the following result when the servlet would run for the first time:

Welcome to my website

Session Information

Session info value

id 0AE3EC93FF44E3C525B4351B77ABB2D5

Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010

Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010

User ID ABCD

Number of visits 0

Now try to run the same servlet for second time, it would display following result.

Welcome Back to my website

Session Infomation

info type value

id 0AE3EC93FF44E3C525B4351B77ABB2D5

Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010

Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010

User ID ABCD

Number of visits 1

88
Servlet Collaboration

Servlets running together in the same server have several ways to communicate with one another. There are two main
styles of servlet collaboration:

Sharing information

This involves two or more servlets sharing state or resources. For example, a set of servlets managing an online
store could share the store‘s product inventory count or share a database connection. Session tracking is a special
case of sharing information.

Sharing control

This involves two or more servlets sharing control of the request. For example, one servlet could receive the
request but let another servlet handle some or all of the request-handling responsibilities.

Servlet collaboration is all about sharing information among the servlets.

Request Dispatching with RequestDispatcher interface Forward() and Include() methods:

RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet or
jsp. This interface can also be used to include the content of another resource also. A servlet gets a RequestDispatcher
instance using the getRequestDispatcher( ) method on its request object. This method returns a RequestDispatcher that can
dispatch to the component (servlet, JSP, static file, etc.) found at the given URI path:

public RequestDispatcher ServletRequest.getRequestDispatcher(String path)

The provided path may be relative, although it cannot extend outside the current servlet context.

Methods summary:

Method Description
void forward(ServletRequest request, Forwards a request from a servlet to another
ServletResponse response) resource (servlet, JSP file, or HTML file) on the
server.
void include(ServletRequest request, Includes the content of a resource (servlet, JSP
ServletResponse response) page, HTML file) in the response.

89
Example:

Index.html /* Html program to invoke the login servlet */

<form action="Login" method="post">


Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>

Login.java /* Servlet accepts username and password as parameters. If password is ‗servlet‘ it invokes the
second servlet */

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Login extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);

}
}
}

90
WelcomeServlet.java /* Second servlet that adds welcome message to the parameter username */

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class WelcomeServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);
}

Servlet Context

ServletContext is a interface which helps us to communicate with the servlet container. There is only one ServletContext
for the entire web application and the components of the web application can share it. The information in the
ServletContext will be common to all the components. Remember that each servlet will have its own ServletConfig. The
ServetContext is created by the container when the web application is deployed and after that only the context is available
to each servlet in the web application.

The servletContext interface:

ServletContext is one of pre-defined interface available in javax.servlet.*; Object of ServletContext interface is available
one per web application. An object of ServletContext is automatically created by the container when the web application
is deployed. Assume there exist a web application with 2 servlet classes, and they need to get some technical values from
web.xml, in this case ServletContext concept will works great, it means all servlets in the current web application can
access these context values from the web.xml but it‘s not the case in ServletConfig, each and every servlet has its own
servletconfig.

91
Methods summary:

Method Description
ServletContext getContext(String uripath) Returns a ServletContext object that corresponds to a specified
URL on the server.
RequestDispatcher Returns a RequestDispatcher object that acts as a wrapper for
getRequestDispatcher(String path)c the resource located at the given path.
String getServerInfo() Returns the name and version of the servlet container on which the
servlet is running.
String getInitParameter(String parameter) Returns a String containing the value of the named context-wide
initialization parameter, or null if the parameter does not exist.
Enumeration gerInitParameterNames() Returns the names of the context's initialization parameters as an
Enumeration of String objects
Object getAttribute(String name) Returns the servlet container attribute with the given name
Void removeAttribute(String name) Removes the attribute with the given name from the servlet context.

Example:

Index.html /* Html file to invoke servlet onContext while clicking the submit button */

<form action="OnContext" method="post">


Example on ServletContext<br>
<input type="submit" value="Click Here">
</form>

OnContext.java /* Servlet program to handle context parameters */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OnContext extends HttpServlet


{
protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
PrintWriter pw=res.getWriter();
res.setContentType("text/html");

ServletContext context=getServletContext();

String s1=context.getInitParameter("n1");
String s2=context.getInitParameter("n2");

pw.println("n1 value is " +s1+ " and n2 is " +s2);

pw.close();
}
}

92
Web.xml file /* configuration file */

<context-param>
<param-name> n1 </param-name>
<param-value> 100 </param-value>
</context-param>

<context-param>
<param-name> n2 </param-name>
<param-value> 200 </param-value>
</context-param>

<servlet>
<servlet-name>OnContext</servlet-name>
<servlet-class>OnContext</servlet-class>
</servlet>

93
UNIT-V

Introduction to Struts:

The Apache Struts Project was launched in May 2000 by Craig R. McClanahan to provide a standard MVC framework to
the Java community. In July 2001, version 1.0 was released. Struts is an open source framework that extends the Java
Servlet API and employs a Model, View, Controller (MVC) architecture. It enables to create maintainable, extensible, and
flexible web applications based on standard technologies, such as JSP pages, JavaBeans, resource bundles, and XML. In
other words: the framework includes a set of custom tag libraries and their associated Java classes, along with various
utility classes. The most powerful aspect of the Struts framework is its support for creating and processing web-based
forms.

A Web Application Framework:

The Struts Framework is a standard for developing well-architected Web applications. It has the following features:

Open source
Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:
o Model: application state
o View: presentation of data (JSP, HTML)
o Controller: routing of the application flow
Implements the JSP Model 2 Architecture
Stores application routing information and request mapping in a single core file, struts-config.xml

The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the developer. Web
applications differ from conventional websites in that web applications can create a dynamic response. Many websites
deliver only static pages. A web application can interact with databases and business logic engines to customize a
response. Web applications based on Java Server Pages sometimes commingle database code, page design code, and
control flow code. In practice, we find that unless these concerns are separated, larger applications become difficult to
maintain. One way to separate concerns in a software application is to use a Model-View-Controller (MVC) architecture.
The Model represents the business or database code, the View represents the page design code, and the Controller
represents the navigational code. The Struts framework is designed to help developers create web applications that utilize
a MVC architecture.

The framework provides three key components:

A "request" handler provided by the application developer that is mapped to a standard URI.
A "response" handler that transfers control to another resource which completes the response.
A tag library that helps developers create interactive form-based applications with server pages.

Architecture Overview:

94
All incoming requests are intercepted by the Struts servlet controller. The Struts Configuration file struts-config.xml is
used by the controller to determine the routing of the flow. This flow consists of an alternation between two transitions:

A user clicks on a link or submits a form on an HTML or JSP page. The controller receives the request,
From View
looks up the mapping for this request, and forwards it to an action. The action in turn calls a Model layer
to Action
(Business layer) service or function.
From Action After the call to an underlying function or service returns to the action class, the action forwards to a
to View resource in the View layer and a page is displayed in a web browser.

The diagram below describes the flow in more detail:

1. User clicks on a link in an HTML page.


2. Servlet controller receives the request, looks up mapping information in struts-config.xml, and routes to an action.
3. Action makes a call to a Model layer service.
4. Service makes a call to the Data layer (database) and the requested data is returned.
5. Service returns to the action.
6. Action forwards to a View resource (JSP page)
7. Servlet looks up the mapping for the requested resource and forwards to the appropriate JSP page.
8. JSP file is invoked and sent to the browser as HTML.
9. User is presented with a new HTML page in a web browser.

Struts Components

1. The Controller: This receives all incoming requests. Its primary function is the mapping of a request URI to an
action class selecting the proper application module. It's provided by the framework.

95
2. The struts-config.xml File:This file contains all of the routing and configuration information for the Struts
application. This XML file needs to be in the WEB-INF directory of the application.

3. Action Classes: It's the developer's responsibility to create these classes. They act as bridges between user-invoked
URIs and business services. Actions process a request and return an ActionForward object that identifies the next
component to invoke. They're part of the Controller layer, not the Model layer.

4. View Resources: View resources consist of Java Server Pages, HTML pages, JavaScript and Stylesheet files,
Resource bundles, JavaBeans, and Struts JSP tags.

5. ActionForms: These greatly simplify user form validation by capturing user data from the HTTP request. They act
as a "firewall" between forms (Web pages) and the application (actions). These components allow the validation of
user input before proceeding to an Action. If the input is invalid, a page with an error can be displayed.

6. Model Components: The Struts Framework has no built-in support for the Model layer. Struts supports any model
components:

JavaBeans
EJB
CORBA
JDO
any other

Struts-config.xml:

The struts-config.xml configuration file is a link between the View and Model components in the Web Client
but one would not have to touch these settings for many of the projects. The configuration file basically
contains following main elements:

SN Interceptor & Description


struts-config
1
This is the root node of the configuration file.
form-beans
2 This is where you map your ActionForm subclass to a name. You use this name as an alias for your
ActionForm throughout the rest of the struts-config.xml file, and even on your JSP pages.
global forwards
3 This section maps a page on your webapp to a name. You can use this name to refer to the actual page. This
avoids hardcoding URLs on your web pages.
action-mappings
4
This is where you declare form handlers and they are also known as action mappings.
controller
5
This section configures Struts internals and rarely used in practical situations.
plug-in
6
This section tells Struts where to find your properties files, which contain prompts and error messages

96
Following is the sample struts-config.xml file:

<?xml version="1.0" encoding="ISO-8859-1" ?>


<!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.0//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_0.dtd">

<struts-config>

<!-- ========== Form Bean Definitions ============ -->


<form-beans>
<form-bean name="login" type="test.struts.LoginForm" />
</form-beans>

<!-- ========== Global Forward Definitions ========= -->


<global-forwards>
</global-forwards>

<!-- ========== Action Mapping Definitions ======== -->


<action-mappings>
<action
path="/login"
type="test.struts.LoginAction" >

<forward name="valid" path="/jsp/MainMenu.jsp" />


<forward name="invalid" path="/jsp/LoginView.jsp" />
</action>
</action-mappings>

<!-- ========== Controller Definitions ======== -->


<controller
contentType="text/html;charset=UTF-8"
debug="3"
maxFileSize="1.618M"
locale="true"
nocache="true"/>

</struts-config>

Understanding MVC architecture:

Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A
Model View Controller pattern is made up of the following three parts:

Model - The lowest level of the pattern which is responsible for maintaining data.
View - This is responsible for displaying all or a portion of the data to the user.
Controller - Software Code that controls the interactions between the Model and View.

MVC is popular as it isolates the application logic from the user interface layer and supports separation of concerns. Here
the Controller receives all requests for the application and then works with the Model to prepare any data needed by the
View. The View then uses the data prepared by the Controller to generate a final presentable response. The MVC
abstraction can be graphically represented as follows.

97
The model

The model is responsible for managing the data of the application. It responds to the request from the view and it also
responds to instructions from the controller to update itself.

The view

A presentation of data in a particular format, triggered by a controller's decision to present the data. They are script based
templating systems like JSP, ASP, PHP and very easy to integrate with AJAX technology.

The controller

The controller is responsible for responding to user input and performs interactions on the data model objects. The
controller receives the input, it validates the input and then performs the business operation that modifies the state of the
data model.

Struts is a MVC based framework.

Advantages of MVC:

1. Navigation control is centralized(Controller contains the logic to determine the next page)
2. Easy to maintain
3. East to extend
4. Easy to test
5. Better separation of concerns

Disadvantages of MVC:

1. We need to write the controller code self. If we change the controller code then we need to compile the code
and deploy the application.

98
ActionServlet:

java.lang.Object
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
org.apache.struts.action.ActionServlet

ActionServlet provides the "controller" in the Model-View-Controller (MVC) design pattern for web applications that is
commonly known as "Model 2". The controller is responsible for intercepting and translating user input into actions to be
performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of
model operations. The Controller receives the request from the browser, invoke a business operation and coordinating the
view to return to the client. The controller is implemented by a java servlet, this servlet is centralized point of control for
the web application.

The controller is implemented by the ActionServlet class. All incoming requests are mapped to the central controller in
the deployment descriptor as follows.

<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>

All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows.

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
<url-pattern>*.do</url-pattern>

A request URI that matches this pattern will have the following form.

http://www.my_site_name.com/mycontext/actionName.do

The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends
with /* as shown below.

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/do/*</url-pattern>
<url-pattern>*.do</url-pattern>

A request URI that matches this pattern will have the following form.

http://www.my_site_name.com/mycontext/do/action_Name

ActionForm:

java.lang.Object
org.apache.struts.action.ActionForm

99
An ActionForm is a JavaBean optionally associated with one or more ActionMappings. Such a bean will have had its
properties initialized from the corresponding request parameters before the corresponding Action.execute method is
called. When the properties of this bean have been populated, but before the execute method of the Action is called, this
bean's validate method will be called, which gives the bean a chance to verify that the properties submitted by the user are
correct and valid. If this method finds problems, it returns an error messages object that encapsulates those problems, and
the controller servlet will return control to the corresponding input form. Otherwise, the validate method returns null,
indicating that everything is acceptable and the corresponding Action.execute method should be called. This class must be
subclassed in order to be instantiated. Subclasses should provide property getter and setter methods for all of the bean
properties they wish to expose, plus override any of the public or protected methods for which they wish to provide
modified functionality. Because ActionForms are JavaBeans, subclasses should also implement Serializable, as required
by the JavaBean specification. Some containers require that an object meet all JavaBean requirements in order to use the
introspection API upon which ActionForms rely.

Action Form is the bean where all the parameters sent from the from are stored. To create an this bean your class should
extend from ActionForm.

Example:

public class LoginForm extends ActionForm {

//Create variables, setter and getter methods for form submission parameters

private String userName;


private String password;

public String getuserName() {


System.out.println("LoginForm::getuserName()");
return userName;
}
public void setuserName(String user) {
userName = user;
System.out.println("LoginForm::setuserName()");
}

public String getPassword() {


return password;
}
----
----
}

ActionMapping:

An action mapping is a configuration file entry that, in general, associates an action name with an action. An action
mapping can contain a reference to a form bean that the action can use, and can additionally define a list of local forwards
and exceptions that are visible only to this action. The action-mappings section of the struts-config.xml file is by far the
most important one because it is the one that defines the application's workflow: This determines which request is mapped
to which Action subclass and, from there, which possible forwards can be invoked, adding the global-forwards to the list.
Action subclasses represent the processes implemented by the web application. The action-mapping element defines
which input forms generate data, whether the data entered should be validated, and whether the ActionForm bean
representing that data will be found on the session or the request scope.

100
Example:

<action-mappings>

<!— The basic query in the application -->


<action path="/getBookList"
type="book.example.GetBookListAction"
name="bookListForm"
scope="request"
validate="false">
<forward name="success" path="/bookList.jsp"/>
</action>

<!— Detail info on a certain book -->


<action path="/getBookDetail"
type="book.example.GetBookDetailAction"
name="bookForm"
scope="request"
validate="false">
<forward name="success" path="/bookDetail.jsp"/>
</action>

<!— Centralized logon -->


<action path="/logon"
type="book.example.authcontrol.LogonAction"
name="logonForm"
scope="request"
input="/logon.jsp"
className="book.example.SecSensitiveMapping"
validate="true">
<forward name="success" path="/menu.jsp"/>
<set-property name="secExtraInfo" value="public level"/>
<set-property name="authContext" value="bookDB"/>
</action>

...

</action-mappings>

Action classes:

A Struts action is an instance of a subclass of an Action class, which implements a portion of a Web application and
whose perform or execute method returns a forward. An action can perform tasks such as validating a user name and
password or performing a computation. The class org.apache.struts.action.requestProcessor process the request from the
controller. One can subclass the RequestProcessor with own version and modify how the request is processed. Once the
controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to
execute the business operation associated with the requested action. In the Struts framework this helper class is descended
of org.apache.struts.action.Action class. It acts as a bridge between a client-side user action and business operation. The
Action class decouples the client request from the business model. This decoupling allows for more than one-to-one
mapping between the user request and an action. The Action class also can perform other functions such as authorization,
logging before invoking business operation. the Struts Action class contains several methods, but most important method
is the execute() method.

101
public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception;

The execute() method is called by the controller when a request is received from a client. The controller creates an
instance of the Action class if one doesn‘t already exist. The strut framework will create only a single instance of each
Action class in your application.

Action are mapped in the struts configuration file and this configuration is loaded into memory at startup and made
available to the framework at runtime. Each Action element is represented in memory by an instance of the
org.apache.struts.action.ActionMapping class . The ActionMapping object contains a path attribute that is matched against
a portion of the URI of the incoming request.

<action>
path= "/somerequest"
type="com.somepackage.someAction"
scope="request"
name="someForm"
validate="true"
input="somejsp.jsp"
<forward name="Success" path="/action/xys" redirect="true"/>
<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>

Once this is done the controller should determine which view to return to the client. The execute method signature in
Action class has a return type org.apache.struts.action.ActionForward class. The ActionForward class represents a
destination to which the controller may send control once an action has completed. Instead of specifying an actual JSP
page in the code, you can declaratively associate as action forward through out the application. The action forward are
specified in the configuration file.

<action>
path= "/somerequest"
type="com.somepackage.someAction"
scope="request"
name="someForm"
validate="true"
input="somejsp.jsp"
<forward name="Success" path="/action/xys" redirect="true"/>
<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>

The action forward mappings also can be specified in a global section, independent of any specific action mapping.

<global-forwards>
<forward name="Success" path="/action/somejsp.jsp" />
<forward name="Failure" path="/someotherjsp.jsp" />
</global-forwards>

Example:

package strutsdemo.actions;
public class EmployeeAction implements Action {
private String code;
private String name;
102
private String city;
private String salary;
// all getter and setter methods
@Override
public String execute() throws Exception {
System.out.println("Execute method in EmployeeAction1");
return SUCCESS;
}
}

JSP Expression Language:

EL Introduction:

The Expression Language or EL as it is known is used by JSP developers to access and use application data without using
java code. EL was introduced in JSTL 1.0, but now is formally defined in JSP 2.0.

The EL allows page authors to use simple expressions to dynamically access data from JavaBeans components.
For example, the test attribute of the following conditional tag is supplied with an EL expression that
compares 0 with the number of items in the session-scoped bean named cart.

<c:if test="${sessionScope.cart.numberOfItems > 0}">


...
</c:if>

EL allows us to create expressions both (a) arithmetic and (b) logical. Within a JSP EL expression, we can use integers,
floating point numbers, strings, the built-in constants true and false for boolean values, and null.

To summarize, the EL provides a way to use simple expressions to perform the following tasks:

Dynamically read application data stored in JavaBeans components, various data structures, and implicit
objects
Dynamically write data, such as user input into forms, to JavaBeans components
Invoke arbitrary static and public methods
Dynamically perform arithmetic operations

EL Operators:

EL provides the following operators, which can be used in expressions:

Arithmetic: +, - (binary), *, / and div, % and mod, - (unary)


Logical: and, &&, or, ||, not, !
Relational: ==, eq, !=, ne, <, lt, >, gt, <=, ge, >=, le. Comparisons can be made against other values or
against Boolean, string, integer, or floating-point literals.
Empty: The empty operator is a prefix operation that can be used to determine whether a value is null or
empty.
Conditional: A ? B : C. Evaluate B or C, depending on the result of the evaluation of A.

103
The precedence of operators highest to lowest, left to right is as follows:

[] .
() (used to change the precedence of operators)
- (unary) not ! empty
* / div % mod
+ - (binary)
< > <= >= lt gt le ge
== != eq ne
&& and
|| or
? :

Reserved Words:

The following words are reserved for the EL and should not be used as identifiers:

and or not eq

ne lt gt le

ge true false null

instanceof empty div mod

Examples of EL Expressions:

Below table contains example EL expressions and the result of evaluating them.

Example Expressions

EL Expression Result

${1 > (4/2)} false

${4.0 >= 3} true

${100.0 == 100} true

${4 > 3} true

${1.2E4 + 1.4} 12001.4

${3 div 4} 0.75

Example:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
104
<h5>Not Operator</h5>
<c:if test="$!{3>1}" var="b" />
The result of using NOT operator with (3>1) is: ${b}

Result:
Not Operator
The result of using NOT operator with (3>1) is: false

EL Implicit Objects:

Implicit objects are those which are instantiated automatically and are references to objects created by the JSP EL
language. These are provided by default by the JSP container.

Following are the list of implicit objects provided by JSP.

Variables Description
pageScope Collection of all page scope variables
requestScope Collection of all request scope variables
sessionScope Collection of all session scope variables
applicationScope Collection of all application scope variables
param Collection of all request parameter as single string value per parameter
paramValue Collection of all request parameter as string array per parameter
header Collection of all request header values as a single string value per header
headerValues Collection of all request header values as string array per header.
Collection of all request cookie values as javax.servlet.http.Cookie value per
cookie
cookie
Collection of all application intialization parameter as single string value per
intiParam
value
pageContext Instance of javax.servlet.jsp.Pagecontext class to access various request data.

Page Scope:

Variables using this JSP object can be used within the page where it was created.

Request Scope:

Variables using this JSP object can be used from anywhere the request is being served.

Session scope:

Variables using this JSP object can be used from pages belonging to the same session.

Application scope:

Variables using this JSP object can be used from pages across the application.

105
Example:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="Pag" value="Page Value" scope="page" />
<c:set var="Req" value="Request Value" scope="request" />
<c:set var="Ses" value="Session Value" scope="session" />
<c:set var="App" value="Application Value" scope="application" />
<html>
<body>
<b>Page Scope</b> ::<c:out value="${Pag}" /><br>
<b>Request Scope</b> ::<c:out value="${Req}" /><br>
<b>Session Scope</b> ::<c:out value="${Ses}" /><br>
<b>Application Scope</b>::<c:out value="${App}" /><br>
<a href="scope2.jsp">Go nextpage for Session,Application Scope</a>
</body>
</html>

Result
Page Scope ::Page Value
Request Scope ::Request Value
Session Scope ::Session Value
Application Scope::Application Value
Goto to next page to know the Session,Application Scope

PageContext:

The pageContext object gives you access to the pageContext JSP object. Through the pageContext object, you can access
the request object. For example, to access the incoming query string for a request, you can use the expression:

${pageContext.request.queryString}

Param and Header:

The param and paramValues objects give us access to the parameter values normally available through the
request.getParameter and request.getParameterValues methods. The header and headerValues objects give us access to the
header values normally available through the request.getHeader and request.getHeaders methods.

Example:

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


prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %>
<html>
<body>
<form action="implicit1.jsp" method="GET">
NAME:<input type="text" name="nam">
<input type="submit">
</form>
<p><b>NAME</b> : ${param.nam}</p>
<p><b>HEADER</b> : ${header["host"]}</p>
<p><b>USER AGENT</b>:${header["user-agent"]}</p>
</html>

106
Result:
NAME : alex
HEADER : localhost:8080
USER AGENT:Mozilla/12.0 (Windows; U; Windows NT 5.1;
en-US; rv:1.9.0.15)Gecko/2009101601 Firefox/12.0
GTB5

In the above example we have used the implicit variables "param" and "header" to display the name entered, header,
browser details etc.

EL Functions:

Designing Expression Language (EL) function application contains the following steps.

1. Writing a java classes with required functionality.


2. Writing tld file to map java class to the Jsp.
3. Write a taglib directive to make business functionality available to Jsp.
4. Write Expression Language (EL) function call.

1. Writing a Java Class:

Any java class can simply acts as a repository for EL functions. The only requirements of a method that acts as EL
function it should be declared as public & static. Method can take parameters also. No restrictions on return type void
return types also allow.

public class StrMethods {


public static String upper(String s) {
return s.toUpperCase();
}
}

2.Writing tld file: (tag library descriptor)

For Expression Language functions tld file provides mapping between Jsp [where functionality is required] and java
class [where functionality is available].tld file is an xml file. We can configure Expression Language (EL) function by
using function tag in this tld. This tag defines the following four child tags.

1. <description>
2. <name>
By means of this name only we can call EL functionality in the Jsp.
3. <function-class>
It defines fully qualified name of java class name where Expression Language (EL) function is available.
4. <function-signature>
Signature of the method .

Example:

<function>
<name>upper</name>
<function-class>StrMethods</function-class>
<function-signature>java.lang.String upper(java.lang.String)</function-signature>
</function>

107
3.Writing tagLib Directive:

This is to make EL functionality available to the Jsp.


<%@ taglib prefix="myString" uri="StringOperations" %>

4.Invoking EL Functions:

${myString:upper(param.name)}

EL Function Flow:

1. Where Jsp engine encounters EL functions call with prefix and EL function name then it checks for
corresponding taglib directive with matched prefix.
2. From taglib directive Jsp engine identifies uri and checks for tld file with matched uri.
3. From the tld file Jsp engine checks for corresponding class and required method.
4. Jsp engine executes that method and return its result to the Jsp.

JSP Standard Tag Library

JSTL Introduction:

JSTL is the JSP Standard Tag Library. The JSTL came about under JSR-52 of the Java Community Process (JCP). JSR-52
covers the creation of a standard tag library for Java Server Pages and allows this library to be available to all compliant
JSP containers. These tag libraries provide a wide range of custom action functionality that most JSP authors have found
themselves in need of in the past. Having a defined specification for how the functionality is implemented means that a
page author can learn these custom actions once and then use and reuse them on all future products on all application
containers that support the specification. Using the JSTL will not only make our JSPs more readable and maintainable, but
will allow us to concentrate on good design and implementation practices in our pages. Developer can finally take the
‗custom' out of custom action and replace it with ‗standard' .No more creating our own iteration action for the tenth time.
Additionally, Integrated Development Environment (IDE) that supports JSP authoring will now support these standard
actions and can assist the JSP page author in rapid development.

Functional Overview

The JSTL encapsulates common functionality that a typical JSP author would encounter. This set of common
functionality has come about through the input of the various members of the expert group. Since this expert group has a
good cross section of JSP authors and users, the actions provided in the JSTL should suit a wide audience. The JSTL is a
set of custom actions that is based on the JSP 1.2 and Servlet 2.3 specifications. While the JSTL is commonly referred to
as a single tag library, it is actually composed of four separate tag libraries:

Core
XML manipulation
SQL
Internationalization and formatting

These libraries are defined by the Tag Library Descriptor files. Using separate TLDs to expose the tags, the functionality
for each set of actions is apparent and makes more sense. Using separate TLDs also allows each library to have its own
namespace. To sum up for now, the layout of the JSTL is straightforward. The overriding theme throughout the JSTL is
108
simplifying the life of the page author. The page author is the person who builds the JSP pages. There has always been a
need (although not a requirement) that the page authors have some understanding of a programming language (usually
Java)in order to create complex pages. This dilemma is what has hampered the true role separation between the JSP page
author and the Java programmer. Using the tags provided in the JSTL, we are closer to reaching that clean division of
labor. The functional areas in the JSTL help page authors identify what type of functionality they need and where they can
find it.

Core tags:

The JSTL encapsulates the core functionality which is common to many web applications. The JSTL provides a single set
of tags instead of mixing many set of tags. The JSTL have tags for loop statement, If Else statement etc. It removes the
burden of writing long java codes. The prefix for the core library is ‗c‘.

The core groups of tags are the most frequently used JSTL tags. Following is the syntax to include JSTL Core library in
the JSP:

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

There are following Core JSTL Tags:

Tag Description

<c:out > Like <%= ... >, but for expressions.

<c:set > Sets the result of an expression evaluation in a 'scope'

<c:remove > Removes a scoped variable (from a particular scope, if specified).

<c:catch> Catches any Throwable that occurs in its body and optionally exposes it.

<c:if> Simple conditional tag which evalutes its body if the supplied condition is true.

<c:choose> Simple conditional tag that establishes a context for mutually exclusive conditional
operations, marked by <when> and <otherwise>

<c:when> Subtag of <choose> that includes its body if its condition evalutes to 'true'.

<c:otherwise > Subtag of <choose> that follows <when> tags and runs only if all of the prior
conditions evaluated to 'false'.

<c:import> Retrieves an absolute or relative URL and exposes its contents to either the page, a
String in 'var', or a Reader in 'varReader'.

<c:forEach > The basic iteration tag, accepting many different collection types and supporting sub
setting and other functionality .

<c:forTokens> Iterates over tokens, separated by the supplied delimiters.

109
<c:param> Adds a parameter to a containing 'import' tag's URL.

<c:redirect > Redirects to a new URL.

<c:url> Creates a URL with optional query parameters

1. <c : out>

The <c:out> tag displays the result of an expression, similar to the way <%= %> works with a difference that <c:out> tag
lets you use the simpler "." notation to access properties. For example, to access customer.address.street just use tag is
<c:out value="customer.address.street"/>.

The <c:out> tag can automatically escape XML tags so they aren't evaluated as actual tags.

Attribute:

The <c:out> tag has following attributes:

Attribute Description Required Default

value Information to output Yes None

default Fallback information to output No body

escapeXml True if the tag should escape special XML characters No true

Example:

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


<html>
<head>
<title>Simple Calculation by using c: out</title>
</head>
<body bgcolor="#FFFFCC">
<h1>Simple Calculation by using c: out</h1>
<%-- Multiplying the numbers 2 * 3 dynamically --%>
2 * 3 = <c:out value="${2 * 3}" />
</body>
</html>

2. <c : set>

The <c:set> tag is JSTL-friendly version of the setProperty action. The tag is helpful because it evaluates an expression
and uses the results to set a value of a JavaBean or a java.util.Map object.
Attribute:

110
The <c:set> tag has following attributes:

Attribute Description Required Default


value Information to save No body
target Name of the variable whose property should be modified No None
property Property to modify No None
var Name of the variable to store information No None
scope Scope of variable to store information No Page

If target is specified, property must also be specified.

Example:

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


<html>
<head>
<title><c:set> Tag Example</title>
</head>
<body>
<c:set var="salary" scope="session" value="${2000*2}"/>
<c:out value="${salary}"/>
</body>
</html>

This would produce following result:

4000

3. <c : if>

The <c:if> tag evaluates an expression and displays its body content only if the expression evaluates to true.
Attribute:

The <c:if> tag has following attributes:

Attribute Description Required Default


test Condition to evaluate Yes None
var Name of the variable to store the condition's result No None
scope Scope of the variable to store the condition's result No page

Example:

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


<html>
<head>
<title><c:if> Tag Example</title>
</head>
111
<body>
<c:set var="salary" scope="session" value="${2000*2}"/>
<c:if test="${salary > 2000}">
<p>My salary is: <c:out value="${salary}"/><p>
</c:if>
</body>
</html>

This would produce following result:

My salary is: 4000

XML tags

The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents. Following is the syntax to
include JSTL XML library in your JSP. The JSTL XML tag library has custom tags for interacting with XML data. This
includes parsing XML, transforming XML data, and flow control based on XPath expressions.

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

Following is the list of XML JSTL Description


Tags:

Tag
<x:out> Like <%= ... >, but for XPath expressions.

<x:parse> Use to parse XML data specified either via an attribute or in the tag body.

<x:set > Sets a variable to the value of an XPath expression.

<x:if > Evaluates a test XPath expression and if it is true, it processes its body. If the test
condition is false, the body is ignored.

<x:forEach> To loop over nodes in an XML document.

<x:choose> Simple conditional tag that establishes a context for mutually exclusive conditional
operations, marked by <when> and <otherwise>

<x:when > Subtag of <choose> that includes its body if its expression evalutes to 'true'

<x:otherwise > Subtag of <choose> that follows <when> tags and runs only if all of the prior
conditions evaluated to 'false'

<x:transform > Applies an XSL transformation on a XML document

<x:param > Use along with the transform tag to set a parameter in the XSLT stylesheet

Example:

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


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

112
<html>
<head>
<title>JSTL Tags</title>
</head>
<body>
<h3>Books Info:</h3>
<c:set var="xmltext">
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
<book>
<name>Great Mistry</name>
<author>NUHA</author>
<price>2000</price>
</book>
</books>
</c:set>

<x:parse xml="${xmltext}" var="output"/>


<x:set var="fragment" select="$output//book"/>
<b>The price of the second book</b>:
<c:out value="${fragment}" />
</body>
</html>

SQL tags

The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such as Oracle, mySQL, or
Microsoft SQL Server.

Following is the syntax to include JSTL SQL library in the JSP:

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

Following is the list of SQL JSTL Tags:

Tag Description

<sql:setDataSource> Creates a simple DataSource suitable only for prototyping

<sql:query> Executes the SQL query defined in its body or through the sql attribute.

<sql:update> Executes the SQL update defined in its body or through the sql attribute.

<sql:param> Sets a parameter in an SQL statement to the specified value.

<sql:dateParam> Sets a parameter in an SQL statement to the specified java.util.Date value.

<sql:transaction > Provides nested database action elements with a shared Connection, set up to execute all
statements as one transaction.
113
1. <sql:query>

The <sql:query> tag executes an SQL SELECT statement and saves the result in a scoped variable.

Attribute:

The <sql:query> tag has following attributes:

Attribute Description Required Default

sql SQL command to execute (should return a ResultSet) No Body

dataSource Database connection to use (overrides the default) No Default database

maxRows Maximum number of results to store in the variable No Unlimited

startRow Number of the row in the result at which to start recording No 0

var Name of the variable to represent the database No Set default

scope Scope of variable to expose the result from the database No Page

2. <sql:update>

The <sql:update> tag executes an SQL statement that does not return data, for example SQL INSERT, UPDATE, or
DELETE statements.

Attribute:

The <sql:update> tag has following attributes:

Attribute Description Required Default

sql SQL command to execute (should not return a ResultSet) No Body

dataSource Database connection to use (overrides the default) No Default database

var Name of the variable to store the count of affected rows No None

scope Scope of the variable to store the count of affected rows No Page

Example:

To start with basic concept, let us create a simple table Employees table in TEST database and create few records in that
table.

114
Sqltest.jsp

<%@ page import="java.io.*,java.util.*,java.sql.*"%>


<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

<html>
<head>
<title>JSTL sql:query Tag</title>
</head>
<body>

<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"


url="jdbc:mysql://localhost/TEST"
user="root" password="pass123"/>

<sql:update dataSource="${snapshot}" var="count">


INSERT INTO Employees VALUES (104, 2, 'Nuha', 'Ali');
</sql:update>

<sql:query dataSource="${snapshot}" var="result">


SELECT * from Employees;
</sql:query>

<table border="1" width="100%">


<tr>
<th>Emp ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.id}"/></td>
<td><c:out value="${row.first}"/></td>
<td><c:out value="${row.last}"/></td>
<td><c:out value="${row.age}"/></td>
</tr>
</c:forEach>
</table>

</body>
</html>

Now try to access above JSP, which should display the following result:

115
Emp ID First Name Last Name Age

100 Zara Ali 18

101 Mahnaz Fatma 25

102 Zaid Khan 30

103 Sumit Mittal 28

104 Nuha Ali 2

Format tags

The JSTL formatting tags are used to format and display text, the date, the time, and numbers for internationalized Web
sites. Following is the syntax to include formatting library in the JSP:

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

Following is the list of Formatting JSTL Tags:

Tag Description

<fmt:formatNumber> To render numerical value with specific precision or format.

<fmt:parseNumber> Parses the string representation of a number, currency, or percentage.

<fmt:formatDate> Formats a date and/or time using the supplied styles and pattern

<fmt:parseDate> Parses the string representation of a date and/or time

<fmt:bundle> Loads a resource bundle to be used by its tag body.

<fmt:setLocale> Stores the given locale in the locale configuration variable.

<fmt:setBundle> Loads a resource bundle and stores it in the named scoped variable or the bundle
configuration variable.
<fmt:timeZone> Specifies the time zone for any time formatting or parsing actions nested in its body.

<fmt:setTimeZone> Stores the given time zone in the time zone configuration variable

<fmt:message> To display an internationalized message.

<fmt:requestEncoding> Sets the request character encoding

116
1. <fmt : formatNumber>

The <fmt:formatNumber> tag is used to format numbers, percentages, and currencies.

Attribute:

The <fmt:formatNumber> tag has following attributes:

Attribute Description Required Default

value Numeric value to display Yes None

type NUMBER, CURRENCY, or PERCENT No Number

pattern Specify a custom formatting pattern for the output. No None

currencyCode Currency code (for type="currency") No From the default locale

currencySymbol Currency symbol (for type="currency") No From the default locale

groupingUsed Whether to group numbers (TRUE or FALSE) No true

maxIntegerDigits Maximum number of integer digits to print No None

minIntegerDigits Minimum number of integer digits to print No None

maxFractionDigits Maximum number of fractional digits to print No None

minFractionDigits Minimum number of fractional digits to print No None

var Name of the variable to store the formatted number No Print to page

scope Scope of the variable to store the formatted number No page

Example:

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


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

<html>
<head>
<title>JSTL fmt:formatNumber Tag</title>
</head>
<body>
<h3>Number Format:</h3>
<c:set var="balance" value="120000.2309" />
<p>Formatted Number (1): <fmt:formatNumber value="${balance}"
type="currency"/></p>
<p>Formatted Number (2): <fmt:formatNumber type="number"
maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (3): <fmt:formatNumber type="number"
maxFractionDigits="3" value="${balance}" /></p>

117
<p>Formatted Number (4): <fmt:formatNumber type="number"
groupingUsed="false" value="${balance}" /></p>
<p>Formatted Number (5): <fmt:formatNumber type="percent"
maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (6): <fmt:formatNumber type="percent"
minFractionDigits="10" value="${balance}" /></p>
<p>Formatted Number (7): <fmt:formatNumber type="percent"
maxIntegerDigits="3" value="${balance}" /></p>
<p>Formatted Number (8): <fmt:formatNumber type="number"
pattern="###.###E0" value="${balance}" /></p>
<p>Currency in USA :
<fmt:setLocale value="en_US"/>
<fmt:formatNumber value="${balance}" type="currency"/></p>
</body>
</html>

This would produce following result:


Number Format:
Formatted Number (1): £120,000.23
Formatted Number (2): 000.231
Formatted Number (3): 120,000.231
Formatted Number (4): 120000.231
Formatted Number (5): 023%
Formatted Number (6): 12,000,023.0900000000%
Formatted Number (7): 023%
Formatted Number (8): 120E3
Currency in USA : $120,000.23

2. <fmt : formatDate>

The <fmt:formatDate> tag is used to format dates in a variety of ways

Attribute:

The <fmt:formatDate> tag has following attributes:

Attribute Description Required Default

value Date value to display Yes None


type DATE, TIME, or BOTH No date
dateStyle FULL, LONG, MEDIUM, SHORT, or DEFAULT No default
timeStyle FULL, LONG, MEDIUM, SHORT, or DEFAULT No default
pattern Custom formatting pattern No None
timeZone Time zone of the displayed date No Default time zone
var Name of the variable to store the formatted date No Print to page
scope Scope of the variable to store the formatted date No page

118
Example:

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


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

<html>
<head>
<title>JSTL fmt:dateNumber Tag</title>
</head>
<body>
<h3>Number Format:</h3>
<c:set var="now" value="<%=new java.util.Date()%>" />

<p>Formatted Date (1): <fmt:formatDate type="time"


value="${now}" /></p>
<p>Formatted Date (2): <fmt:formatDate type="date"
value="${now}" /></p>
<p>Formatted Date (3): <fmt:formatDate type="both"
value="${now}" /></p>
<p>Formatted Date (4): <fmt:formatDate type="both"
dateStyle="short" timeStyle="short"
value="${now}" /></p>
<p>Formatted Date (5): <fmt:formatDate type="both"
dateStyle="medium" timeStyle="medium"
value="${now}" /></p>
<p>Formatted Date (6): <fmt:formatDate type="both"
dateStyle="long" timeStyle="long"
value="${now}" /></p>
<p>Formatted Date (7): <fmt:formatDate pattern="yyyy-MM-dd"
value="${now}" /></p>

</body>
</html>

This would produce following result:

Date Format:
Formatted Date (1): 14:27:18
Formatted Date (2): 23-Sep-2010
Formatted Date (3): 23-Sep-2010 14:27:18
Formatted Date (4): 23/09/10 14:27
Formatted Date (5): 23-Sep-2010 14:27:18
Formatted Date (6): 23 September 2010 14:27:18 GST
Formatted Date (7): 2010-09-23

119

You might also like