0% found this document useful (0 votes)
20 views80 pages

PHP Variable Naming and Data Types Guide

The document outlines the rules for naming variables in PHP, the various data types available including integers, doubles, booleans, strings, arrays, objects, NULL, and resources. It also explains PHP operators such as arithmetic, comparison, logical, assignment, conditional, string, and array operators, along with examples for each type. Additionally, it covers the concept of operator precedence in PHP.

Uploaded by

Bharat Sharma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views80 pages

PHP Variable Naming and Data Types Guide

The document outlines the rules for naming variables in PHP, the various data types available including integers, doubles, booleans, strings, arrays, objects, NULL, and resources. It also explains PHP operators such as arithmetic, comparison, logical, assignment, conditional, string, and array operators, along with examples for each type. Additionally, it covers the concept of operator precedence in PHP.

Uploaded by

Bharat Sharma
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Web Technologies III B.

Tech II Sem (R15)

Variable Naming
Rules for naming a variable is-
Variable names must begin with a letter or underscore character.
A variable name can consist of numbers, letters, underscores but you cannot use characters like
+ , - , % , ( , ) . & , etc
There is no size limit for variables.
PHP - Data Types:
PHP has a total of eight data types which we use to construct our variables:
Integers: are whole numbers, without a decimal point, like 4195.
Doubles: are floating-point numbers, like 3.14159 or 49.1. Scalar types
Booleans: have only two possible values either true or false.
Strings: are sequences of characters, like 'PHP supports string operations.'
Arrays: are named and indexed collections of other values.
Objects: are instances of programmer-defined classes. Compound types
NULL: is a special type that only has one value: NULL.
Resources: are special variables that hold references to resources external Special types
to PHP (such as database connections).
The first four are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the simple
types cannot.
PHP Integers
Integers are primitive data types. They are whole numbe rs, without a decimal point, like 4195.
They are the simplest type. They correspond to simple whole numbers, both positive and
negative {..., -2, -1, 0, 1, 2, ...}.
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal
format is the default, octal integers are specified with a leading 0, and hexadecimals have a
leading 0x.
Ex: $v = 12345;
$var1 = -12345 + 12345;
[Link]
<?php
$var1 = 31; $var2 = 031; $var3 = 0x31;
echo "$var1\n$var2\n$var3"; ?>
Output:
31
25
49
The default notation is the decimal. The script shows these three numbers in decimal. In Java
and C, if an integer value is bigger than the maximum value allowed, integer overflow happens.
PHP works differently. In PHP, the integer becomes a float number. Floating point numbers have
greater boundaries. In 32bit system, an integer value size is four bytes. The maximum integer
value is 2147483647.

Dept. of CSE, MRCET Page | 37


Web Technologies III [Link] II Sem (R15)

[Link]
<?php
$var = PHP_INT_MAX;
echo var_dump($var);
$var++;
echo var_dump($var);
?>
We assign a maximum integer value to the $var variable. We increase the variable by one. And
we compare the contents.
Output:
int(2147483647)
float(2147483648)
As we have mentioned previously, internally, the number becomes a floating point value.
var_dump(): The PHP var_dump() function returns the data type and value.
PHP Doubles or Floating point numbers
Floating point numbers represent real numbers in computing. Real numbers measure continuous
quantities like weight, height or speed. Floating point numbers in PHP can be larger than integers
and they can have a decimal point. The size of a float is platform dependent.
We can use various syntaxes to create floating point values.
<?php The $d variable is assigned a large number,
$a = 1.245; so it is automatically converted to float type.
$b = 1.2e3;
Output:
$c = 2E-10;
float(1.245)
$d = 1264275425335735;
float(1200)
var_dump($a);
float(2.0E-10)
var_dump($b);
float(1264275425340000)
var_dump($c);
This is the output of beside script
var_dump($d);
?>

PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
$x = true; $y = false;
Booleans are often used in conditional testing.
<?php
$male = False;
$r = rand(0, 1);
$male = $r ? True: False;
if ($male) {
echo "We will use name John\n";
} else {
echo "We will use name Victoria\n";
} ?>

Dept. of CSE, MRCET Page | 38


Web Technologies III [Link] II Sem (R15)

The script uses a random integer generator to simulate our case. $r = rand(0, 1);
The rand( ) function returns a random number from the given integer boundaries 0 or 1.
$male = $r? True: False;
We use the ternary operator to set a $male variable. The variable is based on the random $r
value. If $r equals to 1, the $male variable is set to True. If $r equals to 0, the $male variable
is set to False.
PHP Strings
String is a data type representing textual data in computer programs. Probably the single most
important data type in programming.
<?php
$a = "PHP ";
$b = 'PERL';
echo $a . $b; ?>
Output: PHP PERL
We can use single quotes and double quotes to create string literals.
The script outputs two strings to the console. The \n is a special sequence, a new line.
The escape-sequence replace ments are −
\n is replaced by the newline character
\r is replaced by the carriage-return character
\t is replaced by the tab character
\$ is replaced by the dollar sign itself ($)
\" is replaced by a single double-quote (")
\\ is replaced by a single backslash (\)
The Concatenation Operator
There is only one string operator in PHP.
The concatenation operator ( . ) is used to put two string values together. To concatenate two
string variables together, use the concatenation operator:
<?php
$txt1="Hello Kalpana!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?> O/P: Hello Kalpana! What a nice day!
Search for a Specific Text within a String
The PHP strpos() function searches for a specific text within a string. If a match is found,
the function returns the characte r position of the first match. If no match is found, it will
return FALSE. The example below searches for the text "world" in the string "Hello world!":
Example
<?php
echo strpos("Hello world!", "world");
?> output: 6
Tip: The first character position in a string is 0 (not 1).
Replace Text within a String
The PHP str_replace() function replaces some characters with some other characters in a
string. The example below replaces the text "world" with "Dolly":

Dept. of CSE, MRCET Page | 39


Web Technologies III [Link] II Sem (R15)

Example
<?php
echo str_replace("world", "Kalpana", "Hello world!");
?> Output: Hello Kalpana!
The strlen() function:
The strlen() function is used to return the length of a string. Let's find the length of a string:
Eg: <?php
echo strlen("Hello world!"); ?> The output of the code above will be: 12
PHP Array
Array is a complex data type which handles a collection of elements. Each of the elements
can be accessed by an index. An array stores multiple values in one single variable. In the
following example $cars is an array. The PHP var_dump() function returns the data type and
value:
Example
<?php
$cars = array("Volvo","BMW","Toyota");
print_r($cars);
var_dump($cars);
?>
The array keyword is used to create a collection of elements. In our case we have names.
The print_r function prints human readable information about a variable to the console.
O/P: Array ( [0] => Volvo [1] => BMW [2] => Toyota )
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
PHP Object
An object is a data type which stores data and information on how to process that data. In
PHP, an object must be explicitly declared. First we must declare a class of object. For this,
we use the class keyword. A class is a structure that can contain properties and methods:
Example
<?php
class Car {
function Car() {
$this->model = "VW";
} }
$herbie = new Car(); // create an object
echo $herbie->model; // show object properties
?>
Output: VW
PHP NULL
NULL is a special data type that only has one value: NULL. To give a variable the NULL
value, simply assign it like this −
Ex: $my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case insensitive;
you could just as well have typed −
$my_var = null;
A variable that has been assigned NULL has the following properties −
It evaluates to FALSE in a Boolean context.
It returns FALSE when tested with IsSet() function.

Dept. of CSE, MRCET Page | 40


Web Technologies III [Link] II Sem (R15)

Tip: If a variable is created without a value, it is automatically assigned a value of NULL.


Variables can also be emptied by setting the value to NULL:
Example1
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>
PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to
functions and resources external to PHP. A common example of using the resource data type
is a database call. Resources are handlers to opened files, database connections or image
canvas areas. We will not talk about the resource type here, since it is an advanced topic.
constant() function
As indicated by the name, this function will return the value of the constant. This is useful
when you want to retrieve value of a constant, but you do not know its name, i.e. It is stored
in a variable or returned by a [Link]() example

<?php
define("MINSIZE", 50);
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Output: 50 50
Only scalar data (boolean, integer, float and string) can be contained in constants.
PHP - Operators:
What is Operator?
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called
operands and + is called operator. PHP language supports following type of operators.

Arithmetic Operators:
There are following arithmetic operators supported by PHP language:
Assume variable A holds 10 and variable B holds 20 then:
Ope rator 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 $B % $A will give 0
division
** Exponentiation ($x to the $y'th power) $A ** $B

Dept. of CSE, MRCET Page | 41


Web Technologies III [Link] II Sem (R15)

Incre ment/Decrement operators


Ope rator Description Example
++ Increment operator, increases integer value by one $A++ - 11 / ++$A
-- Decrement operator, decreases integer value by one $A-- will give 9 / --$A
Comparison Operators:
There are following comparison operators supported by PHP language Assume variable A
holds 10 and variable B holds 20 then:
Ope rator Description Example
== Checks if the value of two operands are equal or not ($A==$B) is not true.
=== Identical(Returns true if $A is equal to $B, and they $A === $B
are of the same type)
!= Checks if the values of two operands are equal or not, ($A != $B) is true.
if values are not equal then condition becomes true.
<> Returns true if $x is not equal to $y $A <> $B
!== Not identical (Returns true if $A is not equal to $B, or $A !== $B
they are not of the same type)
> Checks if the value of left operand is greater than 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 (A < B) is
true. Than the value of right operand, if yes then
condition becomes true.
>= Checks if the value of left operand is greater than or ($A >= $B) is not true.
equal to the value of right operand, if yes then returns
true.
<= Checks if the value of left operand is less than or equal ($A <= $B) is true.
to the value of right operand, if yes then condition
becomes true.
Logical Operators:
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
Ope rator Description Example
and (or) Called Logical AND operator. If both the operands ($A and $B) is true.
&& are true then then condition becomes true. ($A && $B) is true.
or (or) || Called Logical OR Operator. If any of the two ($A or $B) is true.
operands are non zero then then condition becomes ($A || $B) is true.
true.
! Called Logical NOT Operator. Use to reverses the !( $A && $B) is false.
logical state of its operand. If a condition is true
then Logical NOT operator will make false.
Assignment Ope rators:
There are following assignment operators supported by PHP language:
Operator Description Example
= Simple assignment operator, Assigns values from right $C = $A + $B
side operands to left side operand

Dept. of CSE, MRCET Page | 42


Web Technologies III [Link] II Sem (R15)

+= Add AND assignment operator, It adds right operand $C += $A is equivalent


to the left operand and assign the result to left operand to $C = $C + $A
-= Subtract AND assignment operator, It subtracts right $C -= $A is equivalent
operand from the left operand and assign the result to to $C = $C - $A
left operand
*= Multiply AND assignment operator, It multiplies right $C *= $A is equivalent
operand with the left operand and assign the result to to $C = $C * $A
left operand
/= Divide AND assignment operator, It divides left $C /= $A is equivalent
operand with the right operand and assign the result to to $C = $C / $A
left operand
%= Modulus AND assignment operator, It takes modulus $C %= $A is
using two operands and assign the result to left equivalent to
operand $C = $C % $A
Conditional Ope rator
There is one more 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
PHP String Operators
PHP has two operators that are specially designed for strings.
Operator Description Example
. Concatenation $txt1 . $txt2 (Concatenation of $txt1 and $txt2)
.= Concatenation assignment $txt1 .= $txt2 (Appends $txt2 to $txt1)

PHP Array Operators


The PHP array operators are used to compare arrays.
Operator Description Example
+ Union $x + $y (Union of $x and $y)
== Equality $x == $y (Returns true if $x and $y have the same key/value pairs)
=== Identity $x === $y (Returns true if $x and $y have the same key/value
pairs in the same order and of the same types)
!= or <> Inequality $x != $y or $x <> $y Returns true if $x is not equal to $y
!== Non-identity $x !== $y (Returns true if $x is not identical to $y)
Precedence of PHP Operators
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7. Ans:13
Here operators with the highest precedence appear at the top of the table; those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.

Dept. of CSE, MRCET Page | 43


Web Technologies III [Link] II Sem (R15)

Category Ope rator Associativity


Unary ! ++ -- Right to left
Multiplicative */% Left to right
Additive +- Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditio nal ?: Right to left
Assignment = += -= *= /= % = Right to left

Ex:<!DOCTYPE html> <!DOCTYPE html> <!DOCTYPE html>


<html> <html> <html>
<body> <body> <body>
<?php <?php <?php
$x = 10; $x = 100; $x = 100;
$y = 6; $y = 50; $y = 50;
echo $x + $y; var_dump($x > $y); // if ($x == 100 xor $y == 80) {
?> returns true because $x is echo "Hello world!";
</body> greater than $ y }
</html> ?> ?>
O/P: 16 O/P: bool(true) O/P: Hello world!

PHP -DecisionMaking
The if, elseif ...else and switch statements are used to take decision based on the different
condition. You can use conditional statements in your code to make your decisions. PHP
supports following three decision making statements –
if...else statement − use this statement if you want to
execute a set of code when a condition is true and another
if the condition is not true
elseif statement − is used with the if...else statement to
execute a set of code if one of the several condition is true
switch statement − is used if you want to select one of
many blocks of code to be executed, use the Switch
statement. The switch statement is used to avoid long
blocks of if..elseif..else code.

Syntax EX: <html>


if (condition) <body>
code to be executed if condition is true; <?php
else $d=date("D");
code to be executed if condition is false; if ($d=="Fri")
echo "Have a nice weekend!";
Example else
The following example will output "Have a echo "Have a nice day!";
nice weekend!" if the current day is Friday, ?>
Otherwise, it will output "Have a nice day!": </body> </html>

Dept. of CSE, MRCET Page | 44


Web Technologies III [Link] II Sem (R15)

The If...Else Statement


If you want to execute some code if a condition is true and another code if a condition is
false, use the if....else statement.
The elseif Statement
If you want to execute some code if one of the several conditions is true use the elseif
statement
Syntax EX: <html>
if (condition) <body>
code to be executed if condition is true; <?php
elseif (condition) $d=date("D");
code to be executed if condition is true; if ($d=="Fri")
else echo "Have a nice weekend!";
code to be executed if condition is false; elseif ($d=="Sun")
Example echo "Have a nice Sunday!";
The following example will output "Have a else
nice weekend!" if the current day is Friday, echo "Have a nice day!";
and "Have a nice Sunday!" if the current day ?>
is Sunday. Otherwise, it will output "Have a </body>
nice day!" </html>

The Switch Statement


If you want to select one of many blocks of code to be executed, use the Switch statement.
The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax Example
switch (expression) The switch statement works in an unusual
{ way. First it evaluates given expression
case label1: then seeks a lable to match the resulting
code to be executed if expression = label1; value. If a matching value is found then the
break; code associated with the matching label
case label2: will be executed or if none of the lable
code to be executed if expression = label2; matches then statement will execute any
break; specified default code.
default:
code to be executed
if expression is different
from both label1 and label2;
}

PHP -LoopTypes
Loops in PHP are used to execute the same block of code a specified number of times. PHP
supports following four loop types.
for − loops through a block of code a specified number of times.
while − loops through a block of code if and as long as a specified condition is true.
do...while − loops through a block of code once, and then repeats the loop as long as a
special condition is true.

Dept. of CSE, MRCET Page | 45


Web Technologies III [Link] II Sem (R15)

foreach − loops through a block of code for each element in an array.


We will discuss about continue and break keywords used to control the loops execution.
The for loop statement
The for statement is used when you know how many times you want to execute a statement
or a block of statements.
Syntax
for (initialization; condition; increment)
{
code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop iterations. A
variable may be declared here for this purpose and it is traditional to name it $i.
Example
The following example makes five iterations and changes the assigned value of two
variables on each pass
` of the loop −
<html> <body>
<?php
$a = 0;
$b = 0;
for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
echo ("At the end of the loop a=$a and b=$b" );
?> </body> </html>
This will produce the following result –
At the end of the loop a=50 and b=25
The while loopstatement
The while statement will execute a block of code if and as long as a test expression is true. If
the test expression is true then the code block will be executed. After the code has executed
the test expression will again be evaluated and the loop will continue until the test expression is
found to be false.
Syntax
while (condition)
{
code to be executed;
}
Example
This example decrements a variable value on each iteration of
the loop and the counter increments until it reaches 10 when
the evaluation is false and the loop ends.
<html>
<body>
<?php
$i = 0;

Dept. of CSE, MRCET Page | 46


Web Technologies III [Link] II Sem (R15)

$num = 50;
while( $i < 10)
{
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?> </body> </html>
This will produce the following result –
Loop stopped at i = 10 and num = 40

The do...while loop statement


The do...while statement will execute a block of code at least once. It then will repeat the
loop as long as a condition is true.
Syntax
do
{
code to be executed;
}while (condition);

Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 10 −
<html> }while( $i < 10 );
<body> echo ("Loop stopped at i = $i" );
<?php ?>
$i = 0; $num = 0; </body>
do{ </html>
$i++;
O/P: Loop stopped at i = 10
The foreach loop statement <html>
The foreach statement is used to loop <body>
through arrays. For each pass the value of <?php
the current array element is assigned to $array = array( 1, 2, 3, 4, 5);
$value and the array pointer is moved by foreach( $array as $value )
one and in the next pass next element will be {
processed. echo "Value is $value <br />";
Syntax }
foreach (array as value) ?>
{ </body> </html>
code to be executed; This will produce the following result −
} Value is 1
Example Value is 2
Try out beside example to list out the values Value is 3
of an array. Value is 4
Value is 5

Dept. of CSE, MRCET Page | 47


Web Technologies III [Link] II Sem (R15)

The break statement


The PHP break keyword is used to terminate the execution of a loop prematurely.
The break statement is situated inside the statement block. If gives you full control and
whenever you want to exit from the loop you can come out. After coming out of a loop
immediate statement to the loop will be executed.
Example
In the following example condition test becomes true
when the counter value reaches 3 and loop terminates.
<?php
$i = 0;
while( $i < 10) {
$i++;
if( $i == 3 )break; }
echo ("Loop stopped at i = $i" );
?> O/P: Loop stopped at i=3
The continue statement
The PHP continue keyword is used to halt the current iteration of
a loop but it does not terminate the loop. Just like the break statement
the continue statement is situated inside the statement block containing
the code that the loop executes, preceded by a conditional test. For the
pass encountering continue statement, rest of the loop code is skipped
and next pass starts.
Example
In the following example loop prints the value of array but for which condition becomes true
it just skip the code and next value is printed.
<html>
<body>
<?php
$nos = array( 1, 2, 3, 4, 5);
foreach( $nos as $value )
{
if( $value == 3 ) This will produce the following result −
continue; Value is 1
echo "Value is $value <br />"; Value is 2
} Value is 4
?> Value is 5
</body>
</html>

PHP – Functions
PHP functions are similar to other programming languages. A function is a piece of code
which takes one more input in the form of parameter and does some processing and returns a
value. You already have seen many functions like fopen() and fread() etc. They are built- in
functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you –
Creating a PHP Function
Calling a PHP Function

Dept. of CSE, MRCET Page | 48


Web Technologies III [Link] II Sem (R15)

In fact you hardly need to create your own PHP function because there are already more
than 1000 of built- in library functions created for different area and you just need to call
them according to your requirement.
Creating PHP Function
It‘s very easy to create your own PHP function. Suppose you want to create a PHP function
which will simply write a simple message on your browser when you will call it. Following
example creates a function called writeMessage() and then calls it just after creating it.

<html> <head> echo "Have a nice time Kalpana!";


<title>Writing PHP Function</title> } /* Calling a PHP Function */
</head> writeMessage();
<body> ?>
<?php </body>
/* Defining a PHP Function */ </html>
function writeMessage() Output: Have a nice time Kalpana!
{
PHP Functions with Parameters
PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters you‘re like. These parameters work like variables inside your function.
Following example takes two integer parameters and add them together and then print them.

<html>
<head> <title>Writing PHP Function with Parameters</title> </head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?> </body> </html>
Output: Sum of the two numbers is : 30

Passing Arguments by Reference


It is possible to pass arguments to functions by reference. This means that a reference to the
variable is manipulated by the function rather than a copy of the variable's value. Any
changes made to an argument in these cases will change the value of the original variable.
You can pass an argument by reference by adding an ampersand to the variable name in
either the function call or the function definition.

<html>
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num)
{

Dept. of CSE, MRCET Page | 49


Web Technologies III [Link] II Sem (R15)

$num += 5;
}
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
Output: Original Value is 10
Original Value is 16
PHP Functions returning value
A function can return a value using the return statement in conjunction with a value or
object. return stops the execution of the function and sends the value back to the calling
code. You can return more than one value from a function using return array(1,2,3,4).
<html> <head> <title>Writing PHP Function which returns value</title> </head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
return $sum;
}
$return_value = addFunction(10, 20);
echo "Returned value from the function : $return_value";
?> </body> </html>
Output: Returned value from the function : 30
Setting Default Values for Function Parameters
You can set a parameter to have a default value if the function's caller doesn't pass it.
Following function prints NULL in case use does not pass any value to this function.
<html> <head> <title>Writing PHP Function which returns value</title> </head>
<body>
<?php
function printMe($param = NULL)
{
print $param;
}
printMe("This is test");
printMe();
?>
</body> </html>
Output: This is test

Dept. of CSE, MRCET Page | 50


Web Technologies III [Link] II Sem (R15)

Dynamic Function Calls


It is possible to assign function names as strings to variables and then treat these variables
exactly as you would the function name itself.

<html> <html>
<head> <head>
<title>Dynamic Function Calls</title> <title>Dynamic Function Calls</title>
</head> </head>
<body> <body>
<?php <?php
function sayHello() function add($x,$y)
{ {
echo "Hello<br />"; echo "addition=" . ($x+$y);
} }
$function_holder = "sayHello"; $function_holder = "add";
$function_holder(); $function_holder(20,30);
?> </body> </html> ?> </body> </html>
Output: Hello Output: addition=50
PHP Default Argument Value
The following example shows how to use a default parameter. If we call the function
setHeight() without arguments it takes the default value as argument:
Example
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight \t";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
O/P: 350 50 135 80

PHP -WebConcepts andReading data from WEB


Identifying Browser & Platform
PHP creates some useful environme nt variables that can be seen in the [Link] page
that was used to setup the PHP environment. One of the environment variables set by PHP
is HTTP_USER_AGENT which identifies the user's browser and operating system.
Using HTML Form with name validation in PHP: [Link]

<?php
if( $_POST["name"] || $_POST["age"] )
{
if (preg_match("/[^A- Za-z'-]/",$_POST['name'] ))
{
die ("invalid name and name should be alpha"); }
echo "Welcome ". $_POST['name']. "<br />";

Dept. of CSE, MRCET Page | 51


Web Technologies III [Link] II Sem (R15)

echo "You are ". $_POST['age']. " years old.";


exit();
} ?>
<html>
<body>
<form action="<?php $_PHP_SELF ?>" method="POST">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form> </body> </html>

The PHP default variable $_PHP_SELF is used for the PHP script name and when yo u
click "submit" button then same PHP script will be called and will produce following result
The method = "POST" is used to post user data to the server script.
PHP Forms and User Input:
The PHP $_GET and $_POST variables are used to retrieve information from forms, like
user input.
PHP- GET & POST Methods
There are two ways the browser client can send information to the web server.
The GET Method
The POST Method
Before the browser sends the information, it encodes it using a scheme called URL
encoding or URL Parameters. In this scheme, name/value pairs are joined with equal signs
and different pairs are separated by the ampersand.
name1=value1&name2=value2&name3=value3

The GET Method


The GET method sends the encoded user information appended to the page request. The
page and the encoded information are separated by the ?character.
[Link]

The GET method produces a long string that appears in your server logs, in the browser's
Location: box.
The GET method is restricted to send upto 1024 characters only.
Never use GET method if you have password or other sensitive information to be sent to
the server.
GET can't be used to send binary data, like images or word documents, to the server.
The PHP provides $_GET associative array to access all the sent information using GET
method.
<?php
if( $_GET["name"] || $_GET["age"] )
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?> <html> <body>

Dept. of CSE, MRCET Page | 52


Web Technologies III [Link] II Sem (R15)

<form action="<?php $_PHP_SELF ?>" method="GET">


Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form> </body> </html>
The POST Method
The POST method transfers information via HTTP heade rs or HTTP Parameters. The
information is encoded as described in case of GET method and put into a header called
QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure.
The PHP provides $_POST associative array to access all the sent information using POST
method.
PHP Form Handling
Example : The example below contains an HTML form with two input fields and a submit
button:
<html>
<body>
<form action="we [Link]" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>
When a user fills out the form above and click on the submit button, the form data is sent
to a PHP file, called "[Link]": its looks like this:
<html> <body>
Welcome <?php echo $_POST["fname"]; ?>!
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html> Output: Welcome Kalpana! You are 29 years old.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.

PHP -File Uploading


A PHP script can be used with a HTML form to allow users to upload files to the server.
Initially files are uploaded into a temporary directory and then relocated to a target
destination by a PHP script.
Information in the [Link] page describes the temporary directory that is used for file
uploads as upload_tmp_dir and the maximum permitted size of files that can be uploaded
is stated as upload_max_filesize. These parameters are set into PHP configuration
file [Link]

Dept. of CSE, MRCET Page | 53


Web Technologies III [Link] II Sem (R15)

The process of uploading a file follows these steps −


The user opens the page containing a HTML form featuring a text files, a browse button
and a submit button.
The user clicks the browse button and selects a file to upload from the local PC.
The full path to the selected file appears in the text filed then the user clicks the submit
button.
The selected file is sent to the temporary directory on the server.
The PHP script that was specified as the form handler in the form's action attr ibute checks
that the file has arrived and then copies the file into an intended directory.
The PHP script confirms the success to the user.
As usual when writing files it is necessary for both temporary and final locations to have
permissions set that enable file writing. If either is set to be read-only then process will fail.
An uploaded file could be a text file or image file or any document.
Creating an upload form
The following HTML code below creates an up loader form. This form is having method
attribute set to post and enctype attribute is set to multipart/form-data
There is one global PHP variable called $_FILES. This variable is an associate double
dimension array and keeps all the information related to uploaded file. So if the value
assigned to the input's name attribute in uploading form was file, then PHP would create
following five variables –
$_FILES['file']['tmp_name'] the uploaded file in the temporary dir on the web server.
$_FILES['file']['name'] − the actual name of the uploaded file.
$_FILES['file']['size'] − the size in bytes of the uploaded file.
$_FILES['file']['type'] − the MIME type of the uploaded file.
$_FILES['file']['error'] − the error code associated with this file upload.
Example: Below example should allow upload images and gives back result as uploaded
file information.
<?php <ul>
if(isset($_FILES['image'])) <li>Sent file: <?php echo
{ $_FILES['image']['name']; ?>
$file_name = <li>File size: <?php echo
$_FILES['image']['name']; $_FILES['image']['size']; ?>
$file_size =$_FILES['image']['size']; <li>File type: <?php echo
$file_type=$_FILES['image']['type']; $_FILES['image']['type'] ?>
} </ul>
?> <img src=" <?php echo
<html> <body> $_FILES['image']['name']; ?>"
<form action="" method="POST" height="200" width="200" />
enctype="multipart/form-data"> </form>
<input type="file" name="image" /> </body>
<input type="submit"/> </html

Dept. of CSE, MRCET Page | 54


Web Technologies III [Link] II Sem (R15)

PHP -Cookies
Cookies are text files stored on the client computer and they are kept of use tracking purpose.
PHP transparently supports HTTP cookies.
There are three steps involved in identifying returning users −
Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
Setting Cookies with PHP
PHP provided setcookie() function to set a cookie. This function requires upto six
arguments and should be called before <html> tag. For each cookie this function has to be
called separately.

setcookie(name, value, expire, path, domain, security);

Here is the detail of all the arguments −


Name − This sets the name of the cookie and is stored in an environment variable
called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
Value − This sets the value of the named variable and is the content that you actually
want to store.
Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
After this time cookie will become inaccessible. If this parameter is not set then
cookie will automatically expire when the Web Browser is closed.
Path − This specifies the directories for which the cookie is valid. A single forward
slash character permits the cookie to be valid for all directories.
Domain − This can be used to specify the domain name in very large domains and
must contain at least two periods to be valid. All cookies are only valid for the host
and domain which created them.
Security − This can be set to 1 to specify that the cookie should only be sent by
secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent
by regular HTTP.
Following example will create two cookies name and age these cookies will be expired after
one hour.
<?php
setcookie("name", "KALPANA", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>
<head> <title>Setting Cookies with PHP</title> </head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>

Accessing Cookies withPHP


PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in
above example.

Dept. of CSE, MRCET Page | 55


Web Technologies III [Link] II Sem (R15)

<html>
<head> <title>Accessing Cookies with PHP</title> </head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
?>
</body> </html>

You can use isset() function to check if a cookie is set or not.


<html> <head> <title>Accessing Cookies with PHP</title> </head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body> </html>

Deleting Cookie with PHP


Officially, to delete a cookie you should call setcookie() with the name argument only but
this does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired –
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head> <title>Deleting Cookies with PHP</title> </head>
<body>
<?php echo "Deleted Cookies" ?>
</body> </html>

PHP - Session
When you work with an application, you open it, do some changes, and then you close it.
This is much like a Session.
Session ID is stored as a cookie on the client box or passed along through URL's.
The values are actually stored at the server and are accessed via the session id from your
cookie. On the client side the session ID expires when connection is broken.
Session variables solve this problem by storing user information to be used across multiple
pages (e.g. username, favorite color, etc). By default, session variables last until the user
closes the browser.
Session variable values are stored in the 'superglobal' associative array '$_SESSION'

Dept. of CSE, MRCET Page | 56


Web Technologies III [Link] II Sem (R15)

Start a PHP Session


A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.
demo_session1.php Modify a PHP Session Variable
<?php To change a session variable, just overwrite
// Start the session it:
session_start();
?> <?php
<html> session_start();
<body> ?>
<?php <html>
// Set session variables <?php
$_SESSION["favcolor"] = "green"; $_SESSION["favcolor"] = "yellow";
$_SESSION["favanimal"] = "cat"; print_r($_SESSION); ?> </html>
echo "Session variables are set.";
?>
</body> </html>
Get PHP Session Variable Values
Next, we create another page called "de mo_session2.php". From this page, we will access
the session information we set on the first page ("demo_session1.php").
Notice that session variables are not passed individually to each new page, instead they are
retrieved from the session we open at the beginning of each page (session_start()).
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body> </html>
Destroy a PHP Session
To remove all global session variables and destroy the session, use session_unset() and
session_destroy():
Example
<?php
session_start();
?>
<html>
<body>
<?php
session_unset(); // remove all session variables
session_destroy(); // destroy the session
?> </body> </html>

Dept. of CSE, MRCET Page | 57


Web Technologies III [Link] II Sem (R15)

Difference between a session and a cookie


The main difference between a session and a cookie is that session data is stored on the
server, whereas cookies store data in the visitor's browser.
Sessions are more secure than cookies as it is stored in server. Cookie can be turn off from
browser.
Sessions Cookies
1 Sessions are server-side files that contain user Cookies are client-side files that contain
information user information
2 Session Max life time is 1440 Seconds(24 We have to set cookie max life time
Minutes) as defined in [Link] file manually with php code with setcookie
in [Link] on line 1604 you can find function.
; [Link] maxlifetime setcookie("email", 'test@[Link]',
session.gc_maxlifetime = 1440 time()+3600); /* expire in 1 hour */
You can edit this value if you need custom Expire time : I hour after current time
session life.
3 In php $_SESSION super global variable is used In php $_COOKIE super global
to manage session. variable is used to manage cookie.
4 Before using $_SESSION, you have to write You don't need to start Cookie as It is
session_start(); In that way session will start stored in your local machine.
5 You can store as much data as you like within in Official MAX Cookie size is 4KB
sessions.(default is 128MB.) memory_limit=
128M
[Link] line 479 ;[Link] limit
6 Session is dependent on COOKIE. Because when you start session with session_start() then
SESSIONID named key will be set in COOKIE with Unique Identifier Value for your
system.
7 session_destroy(); is used to "Destroys all data There is no function named
registered to a session", and if you want to unset unsetcookie()
some key's of SESSION then use unset() time()-3600);//expire before 1hour
function. In that way you unset cookie(Set cookie
unset($_SESSION["key1"], in previous time)
$_SESSION["key2"])
8 Session ends when user closes his browser. Cookie ends depends on the life time
you set for it.
9 A session is a group of information on the server Cookies are used to identify sessions.
that is associated with the cookie information.
Write a Program to create simple Login and Logout example using sessions.
[Link]
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<form method="post" action="[Link]">
User Id: <input type="text" name="uid"><br>

Dept. of CSE, MRCET Page | 58


Web Technologies III [Link] II Sem (R15)

Password: <input type="password" name="pw"><br>


<input type="submit" value="Login">
</form>
</body>
</html>
[Link]
<?php
$uid = $_POST['uid'];
$pw = $_POST['pw'];
if($uid == 'arun' and $pw == 'arun123')
{
session_start();
$_SESSION['sid']=session_id();
header("location:[Link]");
}
?>
[Link]
<?php
session_start();
if($_SESSION['sid']==session_id())
{
echo "Welcome to you<br>";
echo "<a href='[Link]'>Logout</a>";
}
else
{
header("location:[Link]");
}
?>
[Link]
<?php
echo "Logged out scuccessfully";
session_start();
session_destroy();
setcookie(PHPSESSID,session_id(),time()-1);
?>

Dept. of CSE, MRCET Page | 59


Web Technologies III [Link] II Sem (R15)

XML - XML stands for Extensible Mark-up Language, developed by W3C in 1996. It is a
text-based mark-up language derived from Standard Generalized Mark-up Language
(SGML). XML 1.0 was officially adopted as a W3C recommendation in 1998. XML was
designed to carry data, not to display data. XML is designed to be self-descriptive. XML is a
subset of SGML that can define your own tags. A Meta Language and tags describe the
content. XML Supports CSS, XSL, DOM. XML does not qualify to be a programming
language as it does not performs any computation or algorithms. It is usually stored in a
simple text file and is processed by special software that is capable of interpreting XML.
The Difference between XML and HTML
1. HTML is about displaying information, where asXML is about carrying information. In
other words, XML was created to structure, store, and transport information. HTML was
designed to display the data.
2. Using XML, we can create own tags where as in HTML it is not possible instead it offers
several built in tags.
3. XML is platform independent neutral and language independent.
4. XML tags and attribute names are case-sensitive where as in HTML it is not.
5. XML attribute values must be single or double quoted where as in HTML it is not
compulsory.
6. XML elements must be properly nested.
7. All XML elements must have a closing tag.

Well Formed XML Documents


A "Well Forme d" XML document must have the following correct XML syntax:
- XML documents must have a root element
- XML elements must have a closing tag(start tag must have matching end tag).
- XML tags are case sensitive
- XML elements must be properly nested Ex:<one><two>Hello</two></one>
- XML attribute values must be quoted
XML with correct syntax is "Well Formed" XML. XML validated against a DTD is "Valid"
XML.
What is Markup?
XML is a markup language that defines set of rules for encoding documents in a format that
is both human-readable and machine-readable.
Example for XML Document
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!—xml declaration-->
<note>
<to>MRCET</to>
<from>MRGI</from>
<heading>KALPANA</heading>
<body>Hello, world! </body>
</note>
Xml document begins with XML declaration statement: <? xml version="1.0"
encoding="ISO-8859-1"?> .
The next line describes the root element of the document: <note>.

Dept. of CSE, MRCET Page | 60


Web Technologies III [Link] II Sem (R15)

This element is "the parent" of all other elements.


The next 4 lines describe 4child elements of the root: to, from, heading, and body. And
finally the last line defines the end of the root element : < /note>.
The XML declaration has no closing tag i.e. </?xml>
The default standalone value is set to no. Setting it to yes tells the processor there are no
external declarations (DTD) required for parsing the document. The file name extension
used for xml program is .xml.
Valid XML document
If an XML document is well- formed and has an associated Document Type Declaration
(DTD), then it is said to be a valid XML document. We will study more about DTD in the
chapter XML - DTDs.
XML DTD
Document Type Definition purpose is to define the structure of an XML document. It defines
the structure with a list of defined elements in the xml document. Using DTD we can specify
the various elements types, attributes and their relationship with one another. Basically DTD
is used to specify the set of rules for structuring data in any XML file.
Why use a DTD?
XML provides an application independent way of sharing data. With a DTD, independent
groups of people can agree to use a common DTD for interchanging data. Your application
can use a standard DTD to verify that data that you receive from the outside world is valid.
You can also use a DTD to verify your own data.
DTD - XML building blocks
Various building blocks of XML are-
1. Elements: The basic entity is element. The elements are used for defining the tags. The
elements typically consist of opening and closing tag. Mostly only one element is used to
define a single tag.
Syntax1: <!ELEMENT element- name (element-content)>
Syntax 2: <!ELEMENT element- name (#CDATA)>
#CDATA means the element contains character data that is not supposed to be parsed by a
parser. or
Syntax 3: <!ELEMENT element- name (#PCDATA)>
#PCDATA means that the element contains data that IS going to be parsed by a parser. or
Syntax 4: <!ELEMENT element- name (ANY)>
The keyword ANY declares an element with any content.
Example:
<!ELEMENT note (#PCDATA)>
Ele ments with children (sequences)
Elements with one or more children are defined with the name of the children elements inside
the parentheses:
<!ELEMENT parent-name (child-element- name)> EX:<!ELEMENT student (id)>
<!ELEMENT id (#PCDATA)> or
<!ELEMENT element-name (child-element-name, child-element-name,.....)>
Example: <!ELEMENT note (to,from,heading,body)>

When children are declared in a sequence separated by commas, the children must appear in
the same sequence in the document. In a full declaration, the children must also be declared,
and the children can also have children. The full declaration of the note document will be:

Dept. of CSE, MRCET Page | 61


Web Technologies III [Link] II Sem (R15)

<!ELEM ENT note (to,fro m,heading,body)>


<!ELEM ENT to (# CDATA)>
<!ELEM ENT fro m (# CDATA)>
<!ELEM ENT heading (#CDATA)>
<!ELEM ENT body (# CDATA)>

2. Tags
Tags are used to markup elements. A starting tag like <element_name> mark up the
beginning of an element, and an ending tag like </element_name> mark up the end of an
element.
Examples:
A body element: <body>body text in between</body>.
A message element: <message>some message in betwee n</message>
3. Attribute: The attributes are generally used to specify the values of the element. These
are specified within the double quotes. Ex: <flag type=‖true‖>
4. Entities
Entities as variables used to define common text. Entity references are references to entities.
Most of you will known the HTML entity reference: "&nbsp;" that is used to insert an extra
space in an HTML document. Entities are expanded when a document is parsed by an XML
parser.
The following entities are predefined in XML:
&lt; (<), &gt;(>), &amp;(&), &quot;(") and &apos;(').
5. CDATA: It stands for character data. CDATA is text that will NOT be parsed by a
parser. Tags inside the text will NOT be treated as markup and entities will not be expanded.
6. PCDATA: It stands for Parsed Character Data(i.e., text). Any parsed character data should
not contain the markup characters. The markup characters are < or > or &. If we want to use
these characters then make use of &lt; , &gt; or &amp;. Think of character data as the text
found between the start tag and the end tag of an XML element. PCDATA is text that will be
parsed by a parser. Tags inside the text will be treated as markup and entities will be
expanded.
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
Where PCDATA refers parsed character data. In the above xml document the elements to,
from, heading, body carries some text, so that, these elements are declared to carry text in
DTD file.
This definition file is stored with .dtd extension.
DTD identifier is an identifier for the document type definition, which may be the path to a
file on the system or URL to a file on the internet. If the DTD is pointing to external path, it
is called External Subset.
The square brackets [ ] enclose an optional list of entity declarations called Internal Subset.

Dept. of CSE, MRCET Page | 62


Web Technologies III [Link] II Sem (R15)

Types of DTD:
1. Internal DTD
2. External DTD
1. Inte rnal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML files. To
refer it as internal DTD, standalone attribute in XML declaration must be set to yes. This
means, the declaration works independent of external source.
Syntax:
The syntax of internal DTD is as shown:
<!DOCTYPE root-element [element-declarations]>
Where root-element is the name of root element and element-declarations is where you
declare the elements.
Example:
Following is a simple example of internal DTD:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Kalpana</name>
<company>MRCET</company>
<phone>(040) 123-4567</phone>
</address>
Let us go through the above code:
Start Declaration- Begin the XML declaration with following statement <?xml version="1.0"
encoding="UTF-8" standalone="yes" ?>
DTD- Immediately after the XML header, the document type declaration follows, commonly
referred to as the DOCTYPE:
<!DOCTYPE address [
The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. The
DOCTYPE informs the parser that a DTD is associated with this XML document.
DTD Body- The DOCTYPE declaration is followed by body of the DTD, where you declare
elements, attributes, entities, and notations:
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone_no (#PCDATA)>
Several elements are declared here that make up the vocabulary of the <name> document.
<!ELEMENT name (#PCDATA)> defines the element name to be of type "#PCDATA".
Here #PCDATA means parse-able text data. End Declaration - Finally, the declaration
section of the DTD is closed using a closing bracket and a closing angle bracket (]>). This
effectively ends the definition, and thereafter, the XML document follows immediately.

Dept. of CSE, MRCET Page | 63


Web Technologies III [Link] II Sem (R15)

Rules
 The document type declaration must appear at the start of the document (preceded only by
the XML header) — it is not permitted anywhere else within the document.
 Similar to the DOCTYPE declaration, the element declarations must start with an
exclamation mark.
 The Name in the document type declaration must match the element type of the root
element.
External DTD
In external DTD elements are declared outside the XML file. They are accessed by
specifying the system attributes which may be either the legal .dtd file or a va lid URL. To
refer it as external DTD, standalone attribute in the XML declaration must be set as no. This
means, declaration includes information from the external source.
Syntax Following is the syntax for external DTD:
<!DOCTYPE root-element SYSTEM "file-name">
where file- name is the file with .dtd extension.
Example The following example shows external DTD usage:
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE address SYSTEM "[Link]">
<address>
<name>Kalpana</name>
<company>MRCET</company>
<phone>(040) 123-4567</phone>
</address>
The content of the DTD file [Link] are as shown:
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
Types
You can refer to an external DTD by using either system identifiers or public identifiers.

SYSTEM IDENTIFIERS
A system identifier enables you to specify the location of an external file containing DTD
declarations. Syntax is as follows:
<!DOCTYPE name SYSTEM "[Link]" [...]>
As you can see, it contains keyword SYSTEM and a URI reference pointing to the location of
the document.
PUBLIC IDENTIFIERS
Public identifiers provide a mechanism to locate DTD resources and are written as below:
<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN">
As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public
identifiers are used to identify an entry in a catalog. Public identifiers can follow any format;
however, a commonly used format is called Formal Public Identifiers, or FPIs.

Dept. of CSE, MRCET Page | 64


Web Technologies III [Link] II Sem (R15)

XML Schemas
XML Schema is commonly known as XML Schema Definition (XSD). It is used to
describe and validate the structure and the content of XML data. XML schema defines the
elements, attributes and data types. Schema element supports Namespaces. It is similar to
a database schema that describes the data in a database. XSD extension is “.xsd”.
This can be used as an alternative to XML DTD. The XML schema became the W#C
recommendation in 2001.
XML schema defines elements, attributes, element having child elements, order of child
elements. It also defines fixed and default values of elements and attributes.
XML schema also allows the developer to us data types.

Syntax :You need to declare a schema in your XML document as follows:


<xs:schema xmlns:xs="[Link]
Example : [Link]
The following example shows how to use schema:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="[Link]
<xs:element name="contact">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
<xs:element name="phone" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
The basic idea behind XML Schemas is that they describe the legitimate format that an XML
document can take.
XML Document: [Link]
<?xml version="1.0" encoding="UTF-8"?>
<contact xmlns:xsi=[Link] instance
xsi:noNamespaceSchemaLocation=”[Link]”>
<name>KALPANA</name>
<company>04024056789</company>
<phone>9876543210</phone>
</contact>
Limitations of DTD:
There is no built- in data type in DTDs.
No new data type can be created in DTDs.
The use of cardinality (no. of occurrences) in DTDs is limited.
Namespaces are not supported.
DTDs provide very limited support for modularity and reuse.
We cannot put any restrictions on text content.
Defaults for elements cannot be specified.
DTDs are written in a non-XML format and are difficult to validate.

Dept. of CSE, MRCET Page | 65


Web Technologies III [Link] II Sem (R15)

Strengths of Sche ma:


XML schemas provide much greater specificity than DTDs.
They supports large number of built- in-data types.
They are namespace-aware.
They are extensible to future additions.
They support the uniqueness.
It is easier to define data facets (restrictions on data).

SCHEMA STRUCTURE
The Schema Element
<xs: schema xmlns: xs="[Link]
Element definitions
As we saw in the chapter XML - Elements, elements are the building blocks of XML
document. An element can be defined within an XSD as follows:
<xs:element name="x" type="y"/>
Data types:
These can be used to specify the type of data stored in an Element.
String (xs:string)
Date (xs:date or xs:time)
Numeric (xs:integer or xs:decimal)
Boolean (xs:boolean)
EX: [Link]
<?xml version=‖1.0‖ encoading=‖UTF-8‖?>
<xs:schema xmlns:xs=[Link]
<xs:element name="sname‖ type=‖xs:string"/>
/* <xs:element name="dob” type=”xs:date"/>
<xs:element name="dobtime” type=”xs:time"/>
<xs:element name="marks” type=”xs:integer"/>
<xs:element name="avg” type=”xs:decimal"/>
<xs:element name="flag” type=”xs:boolean"/> */
</xs:schema>
[Link]:
<?xml version=‖1.0‖ encoading=‖UTF-8‖?>
<sname xmlns:xsi="[Link]
xsi:noNamespaceSchemaLocation="[Link]">
Kalpana /*yyyy-mm-dd 23:14:34 600 92.5 true/false */
</sname>
Definition Types
You can define XML schema elements in following ways:
Simple Type - Simple type element is used only in the context of the text. Some of
predefined simple types are: xs:integer, xs:boolean, xs:string, xs:date. For example:
<xs:element name="phone_number" type="xs:int" />
<phone>9876543210</phone>

Dept. of CSE, MRCET Page | 66


Web Technologies III [Link] II Sem (R15)

Default and Fixed Values for Simple Elements


In the following example the default value is "red":
<xs:element name="color" type="xs:string" default="red"/>
In the following example the fixed value is "red":
<xs:element name="color" type="xs:string" fixed="red"/>

Complex Type - A complex type is a container for other element definitions. This allows
you to specify which child elements an element can contain and to provide some structure
within your XML documents. For example:
<xs:element name="Address">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
<xs:element name="phone" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
In the above example, Address element consists of child elements. This is a container for
other <xs:element> definitions, that allows to build a simple hierarchy of elements in the
XML document.
Global Types - With global type, you can define a single type in your document, which can
be used by all other references. For example, suppose you want to generalize the person and
company for different addresses of the company. In such case, you can define a general type
as below:
<xs:element name="AddressType">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
Now let us use this type in our example as below:
<xs:element name="Address1">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType " />
<xs:element name="phone1" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="Address2">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType " />
<xs:element name="phone2" type="xs:int" />
</xs:sequence> </xs:complexType> </xs:element>

Dept. of CSE, MRCET Page | 67


Web Technologies III [Link] II Sem (R15)

Instead of having to define the name and the company twice (once for Address1 and once for
Address2), we now have a single definition. This makes maintenance simpler, i.e., if you
decide to add "Postcode" elements to the address, you need to add them at just one place.
Attributes
Simple elements cannot have attributes. If an element has attributes, it is considered to be of a
complex type. But the attribute itself is always declared as a simple type. Attributes in XSD
provide extra information within an element. Attributes have name and type property as
shown below:
<xs:attribute name="x" type="y"/>
Ex: <lastname lang="EN">Smith</lastname>
<xs:attribute name="lang" type="xs:string"/>
Default and Fixed Values for Attributes
<xs:attribute name="lang" type="xs:string" default="EN"/>
<xs:attribute name="lang" type="xs:string" fixed="EN"/>
Optional and Required Attributes
Attributes are optional by default. To specify that the attribute is required, use the "use"
attribute:
<xs:attribute name="lang" type="xs:string" use="required"/>
Restrictions on Content
When an XML element or attribute has a data type defined, it puts restrictions on the
element's or attribute's content. If an XML element is of type "xs:date" and contains a string
like "Hello World", the element will not validate.
Restrictions on Values:
The value of age cannot be lower than 0 or greater than 120:
<xs:element name="age">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxInclusive value="120"/>
</xs:restriction>
</xs:simpleType> </xs:element>
Restrictions on a Set of Values
The example below defines an element called "car" with a restriction. The only acceptable
values are: Audi, Golf, BMW:
<xs:element name="car">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Audi"/>
<xs:enumeration value="Golf"/>
<xs:enumeration value="BMW"/>
</xs:restriction>
</xs:simpleType>
</xs:element>

Dept. of CSE, MRCET Page | 68


Web Technologies III [Link] II Sem (R15)

Restrictions on Length
To limit the length of a value in an element, we would use the length, maxLength, and
minLength constraints. The value must be exactly eight characters:
<xs:element name="password">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:length value="8"/> [<xs:minLength value="5"/> <xs:maxLength value="8"/>]
</xs:restriction> </xs:simpleType> </xs:element>

XSD Indicators
We can control HOW elements are to be used in documents with indicators.
Indicators: There are seven indicators
Orde r indicators:
All
Choice
Sequence
Occurrence indicators:
maxOccurs
minOccurs
Group indicators:
Group name
attributeGroup name
Order Indicators
Order indicators are used to define the order of the elements.
All Indicator
The <all> indicator specifies that the child elements can appear in any order, and that each
child element must occur only once:
<xs:element name="person">
<xs:complexType>
<xs:all>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:all>
</xs:complexType>
</xs:element>
Note: When using the <all> indicator you can set the <minOccurs> indicator to 0 or 1 and the
<maxOccurs> indicator can only be set to 1 (the <minOccurs> and <maxOccurs> are
described later).
Choice Indicator
The <choice> indicator specifies that either one child element or another can occur:
<xs:element name="person">
<xs:complexType>
<xs:choice>
<xs:element name="employee" type="employee"/>
<xs:element name="member" type="member"/>
</xs:choice> </xs:complexType> </xs:element>

Dept. of CSE, MRCET Page | 69


Web Technologies III [Link] II Sem (R15)

Sequence Indicator
The <sequence> indicator specifies that the child elements must appear in a specific order:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence> </xs:complexType> </xs:element>
Occurrence Indicators
Occurrence indicators are used to define how often an element can occur.
Note: For all "Order" and "Group" indicators (any, all, choice, sequence, group name, and group
reference) the default value for maxOccurs and minOccurs is 1.
maxOccurs Indicator
The <maxOccurs> indicator specifies the maximum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" maxOccurs="10"/>
</xs:sequence>
</xs:complexType>
</xs:element>

minOccurs Indicator
The <minOccurs> indicator specifies the minimum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" maxOccurs="10" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Tip: To allow an element to appear an unlimited number of times, use the
maxOccurs="unbounded" statement:
EX: An XML file called "[Link]":
<?xml version="1.0" encoding="UTF-8"?>
<persons xmlns:xsi="[Link] instance"
xsi:noNamespaceSchemaLocation="[Link]">
<person>
<full_name>KALPANA</full_name>
<child_name>mrcet</child_name>
</person>
<person>
<full_name>Tove Refsnes</full_name>
<child_name>Hege</child_name>
<child_name>Stale</child_name>

Dept. of CSE, MRCET Page | 70


Web Technologies III [Link] II Sem (R15)

<child_name>Jim</child_name>
<child_name>Borge</child_name>
</person>
<person>
<full_name>Stale Refsnes</full_name>
</person>
</persons>
The XML file above contains a root element named "persons". Inside this root element we
have defined three "person" elements. Each "person" element must contain a "full_name"
element and it can contain up to five "child_name" elements.
Here is the schema file "[Link]":
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs=[Link]
elementFormDefault="qualified">
<xs:element name="persons">
<xs:complexType>
<xs:sequence>
<xs:element name="person" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" minOccurs="0" maxOccurs="5"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Group Indicators: Group indicators are used to define related sets of elements.
Ele ment Groups
Element groups are defined with the group declaration, like this:
<xs:group name="groupname">
...
</xs:group>
You must define an all, choice, or sequence element inside the group declaration. The
following example defines a group named "persongroup", that defines a group of elements
that must occur in an exact sequence:
<xs:group name="persongroup">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="birthday" type="xs:date"/>
</xs:sequence>
</xs:group>

Dept. of CSE, MRCET Page | 71


Web Technologies III [Link] II Sem (R15)

After you have defined a group, you can reference it in another definition, like this:
<xs:element name="person" type="personinfo"/>
<xs:complexType name="personinfo">
<xs:sequence>
<xs:group ref="pe rsongroup"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>

Attribute Groups
Attribute groups are defined with the attributeGroup declaration, like this:
<xs:attributeGroup name="groupname">
...
</xs:attributeGroup>
The following example defines an attribute group named "personattrgroup":
<xs:attributeGroup name="personattrgroup">
<xs:attribute name="firstname" type="xs:string"/>
<xs:attribute name="lastname" type="xs:string"/>
<xs:attribute name="birthday" type="xs:date"/>
</xs:attributeGroup>
After you have defined an attribute group, you can reference it in another definition, like this:
<xs:element name="person">
<xs:complexType>
<xs:attributeGroup ref="personattrgroup"/> </xs:complexType> </xs:element>

Example Program: "[Link]"


<?xml version="1.0" encoding="UTF-8"?>
<shiporder orderid="889923"
xmlns:xsi=[Link] instance
xsi:noNamespaceSchemaLocation="[Link]">
<orderperson>John Smith</orderperson>
<shipto>
<name>Ola Nordmann</name>
<address>Langgt 23</address>
<city>4000 Stavanger</city>
<country>Norway</country>
</shipto>
<item>
<title>Empire Burlesque</title>
<note>Special Edition</note>
<quantity>1</quantity>
<price>10.90</price>
</item>
<item>
<title>Hide your heart</title> <quantity>1</quantity>
<price>9.90</price> </item>
</shiporder>

Dept. of CSE, MRCET Page | 72


Web Technologies III [Link] II Sem (R15)

Create an XML Sche ma "[Link] d":


<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="[Link]
<xs:element name="shiporde r">
<xs:complexType>
<xs:sequence>
<xs:element name="orderperson" type="xs:string"/>
<xs:element name="s hipto">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="ite m" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
<xs:element name="note" type="xs:string" minOccurs="0"/>
<xs:element name="quantity" type="xs:positiveInteger"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
<xs:attribute name="orderid" type="xs:string" use="re quired"/>
</xs:complexType>
</xs:element>
</xs:schema>

XML DTD vs XML Schema


The schema has more advantages over DTD. A DTD can have two types of data in it, namely
the CDATA and the PCDATA. The CDATA is not parsed by the parser whereas the
PCDATA is parsed. In a schema you can have primitive data types and custom data types
like you have used in programming.
Schema vs. DTD
• XML Schemas are extensible to future additions
• XML Schemas are richerand more powerful than DTDs
• XMLSchemas are written in XML
• XMLSchemas support data types
• XMLSchemas support namespaces
XML Parsers
An XML parser converts an XML document into an XML DOM object - which can then be
manipulated with a JavaScript.

Dept. of CSE, MRCET Page | 73


Web Technologies III [Link] II Sem (R15)

Two types of XML parsers:


 Validating Parser
• It requires document type declaration
• It generates error if document does not
o Conform with DTD and
o Meet XML validity constraints
 Non-validating Parser
• It checks well- formedness for xml document
• It can ignore external DTD

What is XML Parser?


XML Parser provides way how to access or modify data present in an XML document. Java
provides multiple options to parse XML document. Following are various types of parsers
which are commonly used to parse XML documents.
Types of parsers:
Dom Parser - Parses the document by loading the complete contents of the document and
creating its complete hiearchical tree in memory.
SAX Parser - Parses the document on event based triggers. Does not load the complete
document into the memory.
JDOM Parser - Parses the document in similar fashion to DOM parser but in more easier
way.
StAX Parser - Parses the document in similar fashion to SAX parser but in more efficient
way.
XPath Parser - Parses the XML based on expression and is used extensively in
conjuction with XSLT.
DOM4J Parser - A java library to parse XML, XPath and XSLT using Java Collections
Framework , provides support for DOM, SAX and JAXP.

DOM-Document Object Model


The Document Object Model protocol converts an XML document into a collection of
objects in your program. XML documents have a hierarchy of informational units called
nodes; this hierarchy allows a developer to navigate through the tree looking for specific
information. Because it is based on a hierarchy of information, the DOM is said to be tree
based. DOM is a way of describing those nodes and the relationships between them.

You can then manipulate the object model in any way that makes sense. This mechanism is
also known as the "random access" protocol, because you can visit any part of the data at any
time. You can then modify the data, remove it, or insert new data.

The XML DOM, on the other hand, also provides an API that allows a developer to add, edit,
move, or remove nodes in the tree at any point in order to create an application. A DOM
parser creates a tree structure in memory from the input document and then waits for requests
from client. A DOM parser always serves the client application with the entire document no
matter how much is actually needed by the client. With DOM parser, method calls in client
application have to be explicit and forms a kind of chained method calls.
Document Object Model is for defining the standard for accessing and manipulating XML
documents. XML DOM is used for

Dept. of CSE, MRCET Page | 74


Web Technologies III [Link] II Sem (R15)

Loading the xml document


Accessing the xml document
Deleting the elements of xml document
Changing the elements of xml document
According to the DOM, everything in an XML document is a node. It considers
The entire document is a document node
Every XML element is an element node
The text in the XML elements are text nodes
Every attribute is an attribute node
Comments are comment nodes

The W3C DOM specification is divided into three major parts:


DOM Core- This portion defines the basic set of interfaces and objects for any structured
documents.
XML DOM- This part specifies the standard set of objects and interfaces for XML
documents only.
HTML DOM- This part specifies the objects and interfaces for HTML documents only.
DOM Levels
Level 1 Core: W3C Recommendation, October 1998
 It has feature for primitive navigation and manipulation of XML trees
 other Level 1 features are: All HTML features
Level 2 Core: W3C Recommendation, November 2000
 It adds Namespace support and minor new features
 other Level 2 features are: Events, Views, Style, Traversal and Range
Level 3 Core: W3C Working Draft, April 2002
 It supports: Schemas, XPath, XSL, XSLT
We can access and parse the XML document in two ways:
 Parsingusing DOM (tree based)
 Parsing using SAX (Event based)
Parsing the XML doc. using DOM methods and properties are called as tree based approach
whereas using SAX (Simple Api for Xml) methods and properties are called as event based
approach.
Steps to Using DOM Parser
Let‘s note down some broad steps involved in using a DOM parser for parsing any XML file
in java.

Dept. of CSE, MRCET Page | 75


Web Technologies III [Link] II Sem (R15)

DOM based XML Parsing:(tree based)


JAXP is a tool, stands for Java Api for Xml Processing, used for accessing and manipulating
xml document in a tree based manner.
The following DOM javaClasses are necessary to process the XML document:
DocumentBuilderFactory class creates the instance of DocumentBuilder.
DocumentBuilder produces a Document (a DOM) that conforms to the DOM specification.
The following methods and properties are necessary to process the XML document:
Property Meaning
nodeName Finding the name of the node
nodeValue Obtaining value of the node
parentNode To get parnet node
childNodes Obtain child nodes
Attributes For getting the attributes values
Method Meaning
getElementByTagName(name) To access the element by specifying its name
appendChild(node) To insert a child node
removeChild(node) To remove existing child node

#document

BODY
<html>
<body>
HTML <h1>Heading 1</h1>
lastChild
parentNode

<p>Paragraph.</p>
firstChild

HEAD
<h2>Heading 2</h2>
<p>Paragraph.</p>
BODY </body>
</html> nextSibling nextSibling nextSibling
H1
#text
H1 P H2 P
previousSibling previousSibling previousSibling
parentNode

parentNode

parentNode

parentNode
P
firstChild

firstChild

firstChild

firstChild
lastChild

lastChild

lastChild

lastChild
#text

H2
#text

P #text #text #text #text


#text

DOM Document Object


 There are 12 types of nodes in a DOM Document object

1. Document node 7. EntityReference node


2. Element node 8. Entity node
3. Text node 9. Comment node
4. Attribute node 10. DocumentType node
5. Processing instruction node 11. DocumentFragment node
6. CDATA Section node 12. Notation node

Dept. of CSE, MRCET Page | 76


Web Technologies III [Link] II Sem (R15)

Examples for Document method


<html>
<head>
<title>Change the Background</title>
</head>
<body>
<script language = "JavaScript">
function background()
{ var color = [Link];
[Link]=color; }
</script>
<form name="bg">
Type the Color Name:<input type="text" name="color" size="20">
<br>
Click the Submit Button to change this Background color as your Color.
<br>
<input type="button" value="Submit" onClick='background()'>
</form>
</body>
</html>
DOM NODE Methods
Method Name Description

appendChild Appends a child node.


cloneNode Duplicates the node.
getAttributes Returns the node‘s attributes.
getChildNodes Returns the node‘s child nodes.
getNodeName Returns the node‘s name.
getNodeType Returns the node‘s type (e.g., element, attribute,
text, etc.).
getNodeValue Returns the node‘s value.
getParentNode Returns the node‘s parent.
hasChildNodes Returns true if the node has child nodes.
removeChild Removes a child node from the node.
replaceChild Replaces a child node with another node.
setNodeValue Sets the node‘s value.
insertBefore Appends a child node in front of a child node.

DOM Advantages & Disadvantages


ADVANTAGES
- Robust API for the DOM tree
- Relatively simple to modify the data structure and extract data
- It is good when random access to widely separated parts of a document is required
- It supports both read and write operations
-
Disadvantages
- Stores the entire document in memory, It is memory inefficient
- As Dom was written for any language, method naming conventions don‘t follow
standard java programming conventions

Dept. of CSE, MRCET Page | 77


Web Technologies III [Link] II Sem (R15)

DOM or SAX
DOM
- Suitable for small documents
- Easily modify document
- Memory intensive;Load the complete XML document
SAX
- Suitable for large documents; saves significant amounts of memory
- Only traverse document once, start to end
- Event driven
- Limited standard functions.
-
Loading an XML file:[Link]
<html> <body>
<script type=‖text/javascript‖>
try
{
xmlDocument=new ActiveXObject(―[Link]‖);
}
catch(e)
{
try {
xmlDocument=[Link]("","",null);
}
catch(e){alert([Link])}
}
try
{
[Link]=false;
[Link](―[Link]‖);
[Link](―XML document student is loaded‖);
}
catch(e){alert([Link])}
</script>
</body> </html>
[Link]:
<?xml version=‖1.0‖?>
< faculty >
<eno>30</eno>
<personal_inf>
<name>Kalpana</name>
<address>Hyd</address>
<phone>9959967192</phone>
</personal_inf>
<dept>CSE</dept>
<col>MRCET</col>
<group>MRGI</group>
</faculty>
OUTPUT: XML document student is loaded
ActiveXObject: It creates empty xml document object.

Dept. of CSE, MRCET Page | 78


Web Technologies III [Link] II Sem (R15)

Use separate function for Loading an XML document: [Link]


<html> <head>
<script type=‖text/javascript‖>
Function My_function(doc_file)
{
try
{
xmlDocument=new ActiveXObject(―[Link]‖);
}
catch(e)
{
try
{
xmlDocument=[Link]("","",null);
}
catch(e){alert([Link])}
}
try
{
[Link]=false;
[Link](―[Link]‖);
return(xmlDocument);
}
catch(e){alert([Link])}
return(null);
}
</script>
</head>
<body>
<script type=‖text/javascript‖>
xmlDoc=‖My_function(―[Link]‖);
[Link](―XML document student is loaded‖);
</script>
</body> </html>
OUTPUT: XML document student is loaded
Use of properties and methods: [Link]
<html> <head>
<script type=‖text/javascript‖ src=‖my_function_file.js‖></script>
</head> <body>
<script type=‖text/javascript‖>
xmlDocument=My_function(“[Link]”);
[Link](―XML document faculty is loaded and content of this file is:‖);
[Link](―<br>‖);
[Link](―ENO:‖+
[Link](―eno‖)[0].childNodes[0].nodeValue);
[Link](―<br>‖);
[Link](―Name:‖+
[Link](―name‖)[0].childNodes[0].nodeValue);

Dept. of CSE, MRCET Page | 79


Web Technologies III [Link] II Sem (R15)

[Link](―<br>‖);
[Link](―ADDRESS:‖+
[Link](―address‖)[0].childNodes[0].nodeValue);
[Link](―<br>‖);
[Link](―PHONE:‖+
[Link](―phone‖)[0].childNodes[0].nodeValue);
[Link](―<br>‖);
[Link](―DEPARTMENT:‖+
[Link](―dept‖)[0].childNodes[0].nodeValue);
[Link](―<br>‖);
[Link](―COLLEGE:‖+
[Link](―col‖)[0].childNodes[0].nodeValue);
[Link](―<br>‖);
[Link](―GROUP:‖+
[Link](―group‖)[0].childNodes[0].nodeValue);
</script>
</body>
</html>
OUTPUT:
XML document faculty is loaded and content of this file is
ENO: 30
NAME: Kalpana
ADDRESS: Hyd
PHONE: 9959967192
DEPARTMENT: CSE
COLLEGE: MRCET
GROUP: MRGI
We can access any XML element using the index value: [Link]
<html> <head>
<script type=‖text/javascript‖ src=‖my_function_file.js‖></script>
</head> <body>
<script type=‖text/javascript‖>
xmlDoc=My_function(“[Link]”);
value=xmlDoc. getElementsByTagName(―name‖);
[Link](―value[0].childNodes[0].nodeValue‖);
</script></body></html>
OUTPUT: Kalpana
XHTML: eXtensible Hypertext Markup Language
Hypertext is simply a piece of text that works as a link. Markup language is a language of
writing layout information within documents. The XHTML recommended by W3C. Basically
an XHTML document is a plain text file and it is very much similar to HTML. It contains rich
text, means text with tags. The extension to this program should b either html or htm. These
programs can be opened in some web browsers and the corresponding web page can be viewed.

Dept. of CSE, MRCET Page | 80


Web Technologies III [Link] II Sem (R15)

HTML Vs XHTML
HTML XHTML
1. The HTML tags are case insensitive. 1. The XHTML tags are case sensitive.
EX: <BoDy>---------</body> EX: <body>---------</body>
2. We can omit the closing tags sometimes. 2. For every tag there must be a closing tag.
EX: <h1>---------</h1> or <h1------------/>
3. The attribute values not always 3. The attribute values are must be quoted.
necessary to quote.
4. In HTML there are some implicit 4. In XHTML the attribute values must be
attribute values. specified explicitly.
5. In HTML even if we do not follow the 5. In XHTML the nesting rules must be
nesting rules strictly it does not cause much strictly followed. These nesting rules are-
difference. - A form element cannot contain another form
element.
-an anchor element does not contain another
form element
-List element cannot be nested in the list
element
-If there are two nested elements then the
inner element must be enclosed first before
closing the outer element
-Text element cannot be directly nested in
form element

The relationship between SGML, XML, HTML and XHTML is as given below

Standard structure: DOCTYPE, html, head and body


The doctype is specified by the DTD. The XHTML syntax rules are specified by the file
[Link] [Link] are 3 types of DTDs.
1. XHTML 1.0 Strict: clean markup code
2. XHTML 1.0 Transitional: Use some html features in the existing XHTML document.
3. XHTML 1.0 Frameset: Use of Frames in an XHTML document.
EX:
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN"
"[Link]
<html xmlns="[Link]
<head>
<title>Sample XHTML Document</title>
</head>
<body bgcolor=‖#FF0000‖>
<basefont face=‖arial‖ size=‖14‖ color=‖white‖>

Dept. of CSE, MRCET Page | 81


Web Technologies III [Link] II Sem (R15)

<h1>MRCET</h1>
<h2>MRCET</h2>
<h3>MRCET</h3>
<h4> KALPANA </h4>
<h5> KALPANA </h5>
<h6>KALPANA</h6>
<p><center> XHTML syntax rules are specified by the file [Link] file. </center></p>
<div align="right"> <b>XHTML standards for eXtensible Hypertext Markup Language.</b>
XHTML syntax rules are specified by the file [Link] file.</div>
<pre> <b>XHTML standards for <i>eXtensible Hypertext Markup Language.</i></b>
XHTML syntax rules are specified by the file [Link] file.</pre>
</basefont>
</body>
</html>

DOM in JAVA
DOM interfaces
The DOM defines several Java interfaces. Here are the most common interfaces:
Node - The base datatype of the DOM.
Ele ment - The vast majority of the objects you'll deal with are Elements.
Attr Represents an attribute of an element.
Text The actual content of an Element or Attr.
Document Represents the entire XML document. A Document object is often
referred to as a DOM tree.
Common DOM methods
When you are working with the DOM, there are several methods you'll use often:
[Link] ntEleme nt() - Returns the root element of the document.
[Link]() - Returns the first child of a given Node.
[Link]() - Returns the last child of a given Node.
[Link]() - These methods return the next sibling of a given Node.
[Link]() - These methods return the previous sibling of a given
Node.
[Link](attrName) - For a given Node, returns the attribute with the
requested name.
Steps to Using DOM
Following are the steps used while parsing a document using DOM Parser.
Import XML-related packages.
Create a DocumentBuilder
Create a Document from a file or stream
Extract the root element
Examine attributes
Examine sub-elements

Dept. of CSE, MRCET Page | 82


Web Technologies III [Link] II Sem (R15)

DOM
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class parsing_DOMDemo
{
public static void main(String[] args)
{
try
{
[Link](―enter the name of XML document‖);
BufferedReader input=new Bufferedreader(new InputStreamReader([Link]));
String file_name=[Link]();
File fp=new File(file_name);
if([Link]())
{
try
{
DocumentBuilderFactory Factory_obj= [Link]();
DocumentBuilder builder=Factory_obj.newDocumentBuilder();
InputSource ip_src=new InputSource(file_name);
Document doc=[Link](ip_src);
[Link](―file_name+‖is well- formed.‖);
}
catch (Exception e)
{
[Link](file_name+‖is not well- formed.‖);
[Link](1);
} }
else
{
[Link](―file not found:‖+file_name);
} }
catch(IOException ex)
{
[Link]();
}
} }

SAX:
SAX (the Simple API for XML) is an event-based parser for xml documents. Unlike a
DOM parser, a SAX parser creates no parse tree. SAX is a streaming interface for XML,
which means that applications using SAX receive event notifications about the XML
document being processed an element, and attribute, at a time in sequential order starting at
the top of the document, and ending with the closing of the ROOT element.
Reads an XML document from top to bottom, recognizing the tokens that make up a
well- formed XML document

Dept. of CSE, MRCET Page | 83


Web Technologies III [Link] II Sem (R15)

Tokens are processed in the same order that they appear in the document
Reports the application program the nature of tokens that the parser has encountered
as they occur
The application program provides an "event" handler that must be registered with the
parser
As the tokens are identified, callback methods in the handler are invoked with the
relevant information
When to use?
You should use a SAX parser when:
You can process the XML document in a linear fashion from the top down
The document is not deeply nested
You are processing a very large XML document whose DOM tree would consume
too much [Link] DOM implementations use ten bytes of memory to
represent one byte of XML
The problem to be solved involves only part of the XML document
Data is available as soon as it is seen by the parser, so SAX works well for an XML
document that arrives over a stream
Disadvantages of SAX
We have no random access to an XML document since it is processed in a forward-
only manner
If you need to keep track of data the parser has seen or change the order of items, you
must write the code and store the data on your own
The data is broken into pieces and clients never have all the information as a whole
unless they create their own data structure
The kinds of events are:
The start of the document is encountered
The end of the document is encountered
The start tag of an element is encountered
The end tag of an element is encountered
Character data is encountered
A processing instruction is encountered
Scanning the XML file from start to end, each event invokes a corresponding callback method
that the programmer writes.

SAX packages
[Link]: Describing the main classes needed for parsing 
[Link]: Describing few interfaces for parsing
SAX classes
SAXParser Defines the API that wraps an XMLReader implementation class
SAXParserFactory Defines a factory API that enables applications to configure and
obtain a SAX based parser to parse XML documents
ContentHandler Receive notification of the logical content of a document.

Dept. of CSE, MRCET Page | 84


Web Technologies III [Link] II Sem (R15)

DTDHandler Receive notification of basic DTD-related events.


EntityResolver Basic interface for resolving entities.
ErrorHandler Basic interface for SAX error handlers.
DefaultHandler Default base class for SAX event handlers.
SAX parser methods
StartDocument() and endDocument() – methods called at the start and end of an XML
document.
StartElement() and endElement() – methods called at the start and end of a document
element.
Characters() – method called with the text contents in between the start and end tags of
an XML document element.
ContentHandler Interface
This interface specifies the callback methods that the SAX parser uses to notify an
application program of the components of the XML document that it has seen.
void startDocument() - Called at the beginning of a document.
void endDocument() - Called at the end of a document.
void startElement(String uri, String localName, String qName, Attributes atts) -
Called at the beginning of an element.
void endElement(String uri, String localName,String qName) - Called at the end
of an element.
void characte rs(char[] ch, int start, int length) - Called when character data is
encountered.
void ignorableWhitespace( char[] ch, int start, int length) - Called when a DTD is
present and ignorable whitespace is encountered.
void processingInstruction(String target, String data) - Called when a processing
instruction is recognized.
void setDocumentLocator(Locator locator)) - Provides a Locator that can be used
to identify positions in the document.
void skippedEntity(String name) - Called when an unresolved entity is
encountered.
void startPrefixMapping(String prefix, String uri) - Called when a new
namespace mapping is defined.
void endPrefixMapping(String prefix) - Called when a namespace definition ends
its scope.
Attributes Interface
This interface specifies methods for processing the attributes connected to an element.
int getLength() - Returns number of attributes, etc.
SAX simple API for XML
import [Link].*;
import [Link];
import [Link];
public class parsing_SAXDemo
{
public static void main(String[] args) throws IOException
{

Dept. of CSE, MRCET Page | 85


Web Technologies III [Link] II Sem (R15)

try {
[Link](―enter the name of XML document‖);
BufferedReader input=new Bufferedreader(new InputStreamReader([Link]));
String file_name=[Link]();
File fp=new File(file_name);
if([Link]())
{
try
{
XMLReader reader=[Link]();
[Link](file_name);
[Link](―file_name+‖is well- formed.‖);
}
catch (Exception e)
{
[Link](file_name+‖is not well- formed.‖);
[Link](1);
}
}
else
{
[Link](―file not found:‖+file_name);
}
}
catch(IOException ex){[Link]();}
} }

Differences between DOM and SAX


DOM SAX
Stores the entire XML document into memory Parses node by node
before processing
Occupies more memory Doesn‘t store the XML in memory
We can insert or delete nodes We can‘t insert or delete a node
DOM is a tree model parser SAX is an event based parser
Document Object Model (DOM) API SAX is a Simple API for XML
Preserves comments Doesn‘t preserve comments
DOM is slower than SAX, heavy weight. SAX generally runs a little faster than DOM,
light weight.
Traverse in any direction. Top to bottom traversing is done in this
approach
Random Access Serial Access
Packages required to import Packages required to import
import [Link].*; import [Link].*;
import [Link] mentBuilder; import [Link].*;
import [Link] mentBuilderFactory;
import [Link];

Dept. of CSE, MRCET Page | 86


Web Technologies III [Link] II Sem (R15)

UNIT III

Web Servers and Servlets

Web Servers:

Web servers are computers that deliver (serves up) Web pages. Every Web server has an IP
address and possibly a domain name. For example, if you enter the URL
[Link] in your browser, this sends a request to the Web server whose
domain name is [Link]. The server then fetches the page named [Link] and sends it to your
browser.

Any computer can be turned into a Web server by installing server software and connecting the
machine to the Internet. There are many Web server software applications, including public domain
software and commercial packages.

Install TOMCAT web server and APACHE.


While installation, we assign port number 8080 to APACHE. Make sure that these ports are
available i.e., no other process is using this port.
DESCRIPTION:
Set the JAVA_HOME Variable
You must set the JAVA_HOME environment variable to tell Tomcat where to find Java.
Failing to properly set this variable prevents Tomcat from handling JSP pages. This variable
should list the base JDK installation directory, not the bin subdirectory. On Windows XP,
you could also go to the Start menu, select Control Panel, choose System, click on the
Advanced tab, press the Environment Variables button at the bottom, and enter the
JAVA_HOME variable and value directly as:
Name: JAVA_HOME
Value: C:\jdk
Set the CLASSPATH
Since servlets and JSP are not part of the Java 2 platform, standard edition, you have to
identify the servlet classes to the compiler. The server already knows about the servlet
classes, but the compiler (i.e., javac) you use for development probably doesn't. So, if you
don't set your CLASSPATH, attempts to compile servlets, tag libraries, or other classes that
use the servlet and JSP APIs will fail with error messages about unknown classes.

Name: JAVA_HOME
Value: install_dir/common/lib/[Link]
Turn on Servlet Reloading
The next step is to tell Tomcat to check the modification dates of the class files of requested
servlets and reload ones that have changed since they were loaded into the server's memory.
This slightly degrades performance in deployment situations, so is turned off by default.
However, if you fail to turn it on for your development server, you'll have to restart the server
every time you recompile a servlet that has already been loaded into the server's memory.

Dept. of CSE, MRCET Page | 87


Web Technologies III [Link] II Sem (R15)

RESULT: Thus TOMCAT web server was installed successfully.

Access the developed static web pages for books web site, using these servers by putting the
web pages developed in week-1 and week-2 in the document root.

Dept. of CSE, MRCET Page | 88


Web Technologies III [Link] II Sem (R15)

RESULT: These pages are accessed using the TOMCAT web server successfully.

INTRODUCTION TO SERVLETS
Servlets:
• Servlets are server side programs that run on a Web or Application server and act as a
middle layer between a requests coming from a Web browser and databases or
applications on the server.
• Using Servlets, you can collect input from users through web page forms, present records
from a database or another source, and create web pages dynamically.
• Servlets don‘t fork new process for each request, instead a new thread is created.
• Servlets are loaded and ready for each request.
• The same servlet can handle many requests simultaneously.

Web Container: It is web server that supports servlet execution. Individual Servlets
are registered with a container. Tomcat is a popular servlet and JSP container.

Dept. of CSE, MRCET Page | 89


Web Technologies III [Link] II Sem (R15)

Servlet Architecture:

ServletsTasks:
Servlets perform the following major tasks:
Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.
Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
Process the data and generate the results. This process may require talking to a database,
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel,
etc.
Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.

Life Cycle of Servlet

Life Cycle

Dept. of CSE, MRCET Page | 90


Web Technologies III [Link] II Sem (R15)

Steps:
The sequence in which the Web containe r calls the life cycle methods of a servlet is:

1. The Web container loads the servlet class and creates one or more instances of the
servlet class.
2. The Web container invokes init() method of the servlet instance during initialization of
the servlet. The init() method is invoked only once in the servlet life cycle.
3. The Web container invokes the service() method to allow a servlet to process a client
request.
4. The service() method processes the request and returns the response back to the Web
container.
5. The servlet then waits to receive and process subsequent requests as explained in steps
3 and 4.
6. The Web container calls the destroy() method before removing the servlet instance
from the service. The destroy() method is also invoked only once in a servlet life cycle.

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.
The servlet is normally created when a user first invokes a URL corresponding to the
servlet.
When a user invokes a servlet, a single instance of each servlet gets created, with each
user request resulting in a new thread that is handed off to doGet or doPost as appropriate.
The init() method simply creates or loads some data that will be used throughout the life
of the servlet.
publicvoidinit()throwsServletException{
// Initialization code...
}

The service() method :


The service() method is the main method to perform the actual task.
The servlet container (i.e. web server) calls the service() method to handle requests
coming from the client( browsers) and to write the formatted response back to the client.

Dept. of CSE, MRCET Page | 91


Web Technologies III [Link] II Sem (R15)

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.
publicvoid service(ServletRequest request,
ServletResponse response)
throwsServletException,IOException{
}
The doGet() Method
The doGet() method processes client request, which is sent by the client, using the
HTTP GET method.
To handle client requests that are received using GET method, we need to override
the doGet() method in the servlet class.
In the doGet() method, we can retrieve the client information of the
HttpServletRequest object. We can use the HttpServletResponse object to send the
response back to the client.
publicvoiddoGet(HttpServletRequest request,
HttpServletResponse response)
throwsServletException,IOException{
// Servlet code
}
The doPost() Method:
The doPost() method handles requests in a servlet, which is sent by the client, using the
HTTP POST method.
For example, if a client is entering registration data in an HTML form, the data can be
sent using the POST method.
Unlike the GET method, the POST request sends the data as part of the HTTP request
body. As a result, the data sent does not appear as a p art of URL.
To handle requests in a servlet that is sent using the POST method, we need to override
the doPost() method. In the doPost() method, we can process the request and send the
response back to the client.
publicvoiddoPost(HttpServletRequest request,
HttpServletResponse response)
throwsServletException,IOException{
// Servlet code
}
The destroy() method :
The destroy() method is called only once at the end of the life cycle of a servlet.
This method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection.
publicvoid destroy()
{
// Finalization code...
}

Dept. of CSE, MRCET Page | 92


Web Technologies III [Link] II Sem (R15)

import [Link].*;
import [Link].*;
import [Link].*;

public class HelloWorld extends HttpServlet {


private String message;
public void init() throws ServletException {
// Do required initialization
message = "Hello KALPANA";
}
public void doGet(HttpServletRequestrequest,HttpServletResponse response)
throwsServletException, IOException {
// Set response content type
[Link]("text/html");
// Actual logic goes here.
PrintWriter out = [Link]();
[Link]("<h1>" + message + "</h1>");
}
public void destroy() {
// do nothing.
}
}

Deploying a Servlet- Steps:


1. Download and install the Java Software Development kit(SDK).
2. Download a server(Tomcat).
3. Configure the server
- After installation Tomcat folder will contain ―Start Tomcat‖ and ―Stop Tomcat‖
shortcuts.
- The JAVA_HOME environment variable should be set so that Tomcat can find JDK
JAVA_HOME = c:\jdk1.5
4. Setup deployment environment

Tomcat Directory Structure


- To set up a new application, add a directory under the we bappsdirectory and create a
subdirectory called WEB-INF.
- WEB-INF needs to contain [Link] (servlet configuration file)
- After WEB-INF dir is created, create a subdirectory classesunder [Link] classes will
go under this directory.

Dept. of CSE, MRCET Page | 93


Web Technologies III [Link] II Sem (R15)

5. Creating ServletDemoServlet
There are three different ways to create a servlet.
a. By implementing Servlet interface
b. By extending GenericServlet class
c. By extending HttpServlet class
6. Compile Servlet and save the class file in classes folder.
7. Create a Deployment Descriptor
- The deployme nt descriptor is an xml file, from which Web Container gets the
information about the servlet to be invoked.
- The web container uses the Parser to get the information from the [Link] file.
- Add a servlet entry and a servlet- mapping entry for each servlet for Tomcat to run.
Add entries after <web-app> tag inside [Link]
<web-app>
<servlet>
<servlet-name>Demo</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Demo</servlet-name>
<url-patte rn>/welcome</url-pattern>
</servlet-mapping>
</web-app>
8. Start Tomcat server
9. Open browser and type [Link]

Dept. of CSE, MRCET Page | 94


Web Technologies III [Link] II Sem (R15)

Servlet API
Servlet API consists of two important packages that encapsulates all the important classes
and interface, namely :
1. [Link]
2. [Link]

1. [Link]
Inte rfaces
1. Servlet – Declares life cycle methods for a servlet.
2. ServletConfig – To get initialization parameters
3. ServletContext- To log events and access information
4. ServletRequest- To read data from a client request
5. ServletResponse – To write data from client response
Classes
1. GenericServlet – Implements Servlet and ServletConfig
2. ServletInputStream – Provides an input stream for reading client requests.
3. ServletOutputStream - Provides an output stream for writing
responses to a client.
4. ServletException – Indicates servlet error occurred.
5. UnavailableException - Indicates servlet is unavailable

Servlet Interface

Servlet interface provides common behaviour to all the servlets.


Servlet interface needs to be implemented for creating any servlet (either directly or
indirectly).
It provides 3 life cycle methods that are used to initialize the servlet, to service the
requests, and to destroy the servlet and 2 non-life cycle methods.

Dept. of CSE, MRCET Page | 95


Web Technologies III [Link] II Sem (R15)

Method Description
public void init(ServletConfigconfig) initializes the servlet. It is the life cycle
method of servlet and invoked by the web
container only once.
public void provides response for the incoming request.
service(ServletRequestrequest,ServletResponse It is invoked at each request by the web
response) container.
public void destroy() is invoked only once and indicates that
servlet is being destroyed.
public ServletConfiggetServletConfig() returns the object of ServletConfig.
public String getServletInfo() returns information about servlet such as
writer, copyright, version etc.

import [Link].*;
import [Link].*;
public class First implements Servlet{
ServletConfig config=null;
public void init(ServletConfig config){
[Link]=config;
[Link]("servlet is initialized");
}
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
[Link]("text/html");
PrintWriter out=[Link]();
[Link]("<html><body>");
[Link]("<b>hello KALPANA</b>");
[Link]("</body></html>");
}
public void destroy(){
[Link]("servlet is destroyed");
}
public ServletConfig getServletConfig(){
return config;
}
public String getServletInfo(){
return "copyright 2007-1010";
}
}

ServletConfig interface
• When the Web Container initializes a servlet, it creates a ServletConfig object for the
servlet.

• ServletConfig object is used to pass information to a servlet during initialization by getting


configuration information from we [Link](Deployment Descriptor).

Dept. of CSE, MRCET Page | 96


Web Technologies III [Link] II Sem (R15)

Methods
• getInitParameter(String name): returns a String value initialized parameter
• getInitParameterNames(): returns the names of the servlet's initialization parameters as an
Enumeration of String objects
• getServletContext(): returns a reference to the ServletContext
• getServletName(): returns the name of the servlet instance

ServletContext Interface

• For every Web application a Se rvletContext object is created by the web container.
• ServletContext object is used to get configuration information from Deployme nt
Descriptor([Link]) which will be available to any servlet.

Methods :
• getAttribute(String name) - returns the container attribute with the given name
• getInitParameter(String name) - returns parameter value for the specified parameter name
• getInitParameterNames() - returns the names of the context's initialization parameters as
an Enumeration of String objects
• setAttribute(String name,Objectobj) - set an object with the given attribute name in the
application scope
• removeAttribute(String name) - removes the attribute with the specified name from the
application context

Servlet RequestInterface

• True job of a Servlet is to handle client request.


• Servlet API provides two important interfaces [Link] to
encapsulate client request.
• Implementation of these interfaces provides important information about client request to
a servlet.

Methods
• getAttribute(String name), removeAttribute(String name), setAttribute(String name,
Object o), getAttributeName() – used to store and retrieve an attribute from request.
• getParameter(String name) - returns value of parameter by name
• getParameterNames() - returns an enumeration of all parameter names
• 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

Servlet ResponseInterface
• Servlet API provides ServletResponseto assist in sending response to client.

Methods
• getWriter()- returns a PrintWriter object that can send character text to the client.
• setContentType(String type)- sets the content type of the response being sent to the client
before sending the respond.

Dept. of CSE, MRCET Page | 97


Web Technologies III [Link] II Sem (R15)

GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces.
It provides the implementation of all the methods of these interfaces except the service
method.
GenericServlet class can handle any type of request so it is protocol- independent.
You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method .

Methods

public void init(Se rvletConfigconfig) is used to initialize the servlet.


public abstract void service(ServletRequest request, ServletResponse
response) provides service for the incoming request. It is invoked at each time when user
requests for a servlet.
public void destroy() is invoked only once throughout the life cycle and indicates that
servlet is being destroyed.
publicServletConfiggetServletConfig() returns the object of ServletConfig.
public String getServletInfo() returns information about servlet such as writer, copyright,
version etc.
public void init() it is a convenient method for the servlet programmers, now there is no
need to call [Link](config)
publicServletContextgetServletContext() returns the object of ServletContext.
public String getInitParameter(String name) returns the parameter value for the given
parameter name.
public Enumeration getInitParameterNames() returns all the parameters defined in the
we [Link] file.
public String getServletName() returns the name of the servlet object.
public void log(String msg) writes the given message in the servlet log file.
public void log(String msg,Throwable t) writes the explanatory message in the servlet
log file and a stack trace.

ServletInputStream Class
It provides stream to read binary data such as image etc. from the request object. It is an
abstract class.
The getInputStream() method of ServletRequest interface returns the instance of
ServletInputStream class
intreadLine(byte[] b, int off, intlen) it reads the input stream.

ServletOutputStream Class
It provides a stream to write binary data into the response. It is an abstract class.
The getOutputStream() method of Se rvletResponse interface returns the instance of
ServletOutputStream class.
ServletOutputStream class provides print() and println() methods that are overloaded.

ServletException and UnavailableException


ServletException is a general exception that the servlet container will catch and log. The
cause can be anything.

Dept. of CSE, MRCET Page | 98


Web Technologies III [Link] II Sem (R15)

The exception contains a root cause exception.


Defines an exception that a servlet or filter throws to indicate that it is permanently or
temporarily unavailable.
When a servlet or filter is permanently unavailable, something is wrong with it, and it
cannot handle requests until some action is taken. For example, a servlet might be
configured incorrectly, or a filter's state may be corrupted.

2. [Link]
Inte rfaces

1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
Classes
1. HttpServlet
[Link]

HTTPServletRequest and HTTPServletResponse

HTTPServletRequestExtends the ServletRequest interface to provide request information


for HTTP servlets.
The servlet container creates an HttpServletRequest object and passes it as an argument to
the servlet's service methods (doGet, doPost, etc).
It Contains all the client's request information.
The HttpServletRequest breaks a request down into parsed elements, such as request URI,
query arguments and headers. Various get methods allow you to access different parts of
the request.

1. requestURI – URL sent by browser

2. Parameters -
The HttpServletRequest provides methods for accessing parameters of a request. The
methods getParameter(), getParameterValues()and getParameterNames() are offered
as ways to access the arguments.

Dept. of CSE, MRCET Page | 99


Web Technologies III [Link] II Sem (R15)

3. Attributes –
The request object defines a method called getAttribute(). The servlet interface
provides this as a way to include extra information about the request that is not covered
by any of the other HttpServletRequest methods.
4. ServletInputStream –
The ServletInputStream is an InputStream that allows your servlets to read all of the
request‘s input following the headers.

HTTPServletResponseExtends the ServletResponse interface and can perform these tasks


1. Set Response Codes –
The response code for a request is a numeric value that represents the status of the
response. For example, 200 represents a successful response, 404 represents a file not
found.
2. Set Headers –
Headers for the response can be set by calling setHeader, specifying the name and value
of the header to be set.
3. Send Redirects –
The sendRedirect method is used to issue a redirect to the browser, causing the browser
to issue a request to the specified URL. The URL passed to sendRedirect must be an
absolute URL—it must include protocol, machine, full path, and so on.
4. Set ServletOutputStream –
The ServletOutputStream is obtained by calling getOutputStream on the
HttpServletResponse. It is a subclass of OutputStream that contains a number of
convenient print and println [Link] written to the ServletOutputStream goes
straight back to the browser.

HTTPSession
HttpSession object is used to store entire session with a specific client.
We can store, retrieve and remove attribute from HttpSession object.
Any servlet can have access to HttpSession object throughout the getSession() method of
the HttpServletRequest object.

HTTPServlet
HttpServlet is extends from GenericServlet and does not override init, destroy and other
methods.
It implements the service () method which is abstract method in GenericServlet.
A subclass of HttpServlet must override at least one method, usually one of these:
o doGet(), if the servlet supports HTTP GET requests
o doPost(), for HTTP POST requests
o doPut(), for HTTP PUT requests
o doDelete(), for HTTP DELETE requests
o Init() and destroy(), to manage resources that are held for the life of the servlet
o getServletInfo(), which the servlet uses to provide information about itself

Dept. of CSE, MRCET Page | 100


Web Technologies III [Link] II Sem (R15)

Cookie
A cookie is a small piece of information that is persisted between the multiple client
requests.
[Link] class provides the functionality of using cookies. It provides a
lot of useful methods for cookies.
public void addCookie(Cookie ck):method of HttpServletResponse interface is used to
add cookie in response object.
public Cookie[] getCookies():method of HttpServletRequest interface is used to return all
the cookies from the browser.
Reading Servlet Parameters(or) Handling HTTPRequest and HTTPResponse
The parameters are the way in which a client or user can send information to the Http
Server.
The HTTPSe rvletRequest interface includes methods that allow you to read the names
and values of parameters that are included in a client request.
The HttpServletResponse Interface provides functionality for sending response to client.
The browser uses two methods to pass this information to web server. These methods are
GET Method and POST Method.
GET method:
The GET method sends the encoded user information appended to the page request.
The page and the encoded information are separated by the ? character as follows:
[Link]
The GET method is the defualt method to pass information from browser to web server.
Never use the GET method if you have password or other sensitive information to pass to
the server.
The GET method has size limtation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable.
Servlet handles this type of requests using doGet() method.
POST method:
A generally more reliable method of passing information to a backend program is the
POST method.
This message comes to the backend program in the form of the standard input which you
can parse and use for your processing.
Servlet handles this type of requests using doPost() method.

Reading Form Datausing Servlet:


Servlets handles form data parsing automatically using the following methods depending on
the situation:
getParameter(): You call [Link]() method to get the value of a form
parameter.
getParameterValues(): Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
getParameterNames(): Call this method if you want a complete list of all parameters in
the current request.

Dept. of CSE, MRCET Page | 101


Web Technologies III [Link] II Sem (R15)

Sending Data to Client:


Obtain a PrintWriter object HTTPServletResponse that can send character text to the client.
PrintWriterpw = [Link]();
[Link](―Hello world‖);

POST method example


Let us consider [Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class HelloForm extends HTTPServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException{
PrintWriter pw = [Link]();
[Link]("<html><body>");
[Link]("Name: "+[Link]("first_name")+
― ―+[Link]("last_name"));
[Link]("</body></html>");
[Link]();
}
}
Compile [Link] as follows: $javac [Link]
Compilation would produce [Link] file.
Next you would have to copy this class file in
<Tomcat- installation-directory>/webapps/ROOT/WEB-INF/classes
Create following entries in we [Link] file located in
<Tomcat- installation-directory>/webapps/ROOT/WEB-INF/

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

<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet- mapping>

Now create a HTML page [Link] put it in


<Tomcat- installation-directory>/webapps/ROOT directory
html>
<body>
<formaction="HelloForm"method="GET">
First Name: <inputtype="text"name="first_name"><br/>
Last Name: <inputtype="text"name="last_name"/></br>
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>

Dept. of CSE, MRCET Page | 102


Web Technologies III [Link] II Sem (R15)

When you access [Link] then output of the above form.

First Name: Kalpana


Last Name: Mrcet

Submit
Start Tomcat Server and open browser.
Now enter firstname and lastname, Click Submit
It will generate result

Name: KalpanaMrcet

Reading Initialization Parameters


1. Using Servlet Config:
An object of ServletConfig is created by the web container for each servlet. This object
can be used to get configuration information from [Link] file.
If the configuration information is modified from the [Link] file, we don't need to
change the servlet. So it is easier to manage the web application if any specific content is
modified from time to time.
Methods
• getInitParameter(String name): returns a String value initialized parameter
• getInitParameterNames(): returns the names of the servlet's initialization parameters as an
Enumeration of String objects
• getServletContext(): returns a reference to the ServletContext
• getServletName(): returns the name of the servlet instance
Syntax to provide the initialization parameter for a servlet
The init-param sub-element of servlet is used to specify the initialization parameter
for a servlet.
<web-app>
<servlet>
......
<init-param>
<param-name>email</param-name>
<param-value>kalpana@[Link]</param-value>
</init-param>
......
</servlet>
</web-app>
Retrieve ServletConfig
ServletConfigsc = getServletConfig();
[Link]([Link]("email"));

Dept. of CSE, MRCET Page | 103


Web Technologies III [Link] II Sem (R15)

Ex: we [Link]
<web-app>
servlet>
<servlet-name>TestInitParam</servlet-name>
<servlet-class>TestInitParam</servlet-class>
<init-param>
<param-name>email</param-name>
<param-value>kalpana@[Link]</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>TestInitParam</servlet-name>
<url-pattern>/TestInitParam</url-pattern>
</servlet- mapping>
</web-app>

[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class TestInitParam extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
ServletConfigsc=getServletConfig();
[Link]("<html><body>");
[Link]("<b>"+[Link]("email")+"</b>");
[Link]("</body></html>");
[Link]();
}
}
It will generate result

kalpana@[Link]

2. Using ServletContext
An object of ServletContext is created by the web container at time of deploying the
project.
This object can be used to get configuration information from [Link] file.
There is only one ServletContext object per web application.
If any information is shared to many servlet, it is better to provide it from the [Link] file
using the <context-param> element.

Dept. of CSE, MRCET Page | 104


Web Technologies III [Link] II Sem (R15)

Advantage
Easy to maintain if any information is shared to all the servlet, it is better to make it
available for all the servlet.
We provide this information from the [Link] file, so if the information is changed, we
don't need to modify the servlet. Thus it removes maintenance problem.

Uses
1. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the [Link]
file.
3. The ServletContext object can be used to set, get or remove attribute from the [Link]
file.
4. The ServletContext object can be used to provide inter-application communication.

Methods:
getAttribute(String name) - returns the container attribute with the given name
getInitParameter(String name) - returns parameter value for the specified parameter name
getInitParameterNames() - returns the names of the context's initialization parameters as
an Enumeration of String objects
setAttribute(String name,Objectobj) - set an object with the given attribute name in the
application scope
removeAttribute(String name) - removes the attribute with the specified name from the
application context
Retrieve ServletContext
ServletContextapp = getServletContext();
OR
ServletContextapp = getServletConfig().getServletContext();

Ex: we [Link]
<web-app>
<context-param>
<param-name>driverName</param-name>
<param-value>[Link]</param-value>
</context-param>

<servlet>
<servlet-name>TestServletContext</servlet- name>
<servlet-class>TestServletContext</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>TestServletContext</servlet- name>
<url-pattern>/TestServletContext</url-pattern>
</servlet- mapping>
</web-app>

Dept. of CSE, MRCET Page | 105


Web Technologies III [Link] II Sem (R15)

[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class TestServletContext extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
PrintWriter out = [Link]();
ServletContextsc = getServletContext();
[Link]([Link]("driverName"));
}
}

It will generate result

[Link]

Context Init parameters Servlet Init parameter


Available to all servlets and JSPs that are part Available to only servlet for which the
of web <init-param> was configured

Context Init parameters are initialized within Initialized within the <servlet> for each
the <web-app> not within a specific servlet.
specific <servlet> elements
ServletContext object is used to get Context ServletConfig object is used to get Servlet
Init parameters Init parameters

Only one ServletContext object for entire web Each servlet has its own ServletConfig
app object

Session Tracking
• Session simply means a particular interval of time.
• Session Tracking is a way to maintain state (data) of an user.
• Http protocol is a stateless, each request is considered as the new request, so we need to
maintain state using session tracking techniques.
• Each time user requests to the server, server treats the request as the new request. So we
need to maintain the state of an user to recognize to particular user.

Dept. of CSE, MRCET Page | 106


Web Technologies III [Link] II Sem (R15)

• We use session tracking to recognize the user It is used to recognize the particular user.
• Session Tracking Techniques
– Cookies
– Hidden Form Field
– URL Rewriting
– HttpSession

Cookies
Cookies are text files stored on the client computer and they are kept for various
information tracking purpose
There are three steps involved in identifying returning users:
o Server script sends a set of cookies to the browser in response header.
o Browser stores this information on local machine for future use.
o When next time browser sends any request to web server then it sends those cookies
information to the server in request header and server uses that information to identify the
user.
Cookies are created using Cookie class present in Servlet API.
For adding cookie or getting the value from the cookie, we need some methods provided
by other interfaces. They are:
a. public void addCookie(Cookie ck):method of HttpServletResponse interface is used
to add cookie in response object.
b. public Cookie[] getCookies():method of HttpServletRequest interface is used to return
all the cookies from the browser.

Dept. of CSE, MRCET Page | 107


Web Technologies III [Link] II Sem (R15)

Disadvantage of Cookies
• It will not work if cookie is disabled from the browser.
• Only textual information can be set in Cookie object.

Methods
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

public String getName() Returns the name of the cookie. The name cannot
be changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.

Create Cookie
Cookie ck=ne w Cookie("user","kalpana ");//creating cookie object
[Link](ck);//adding cookie in the response

Delete Cookie
It is mainly used to logout or signout the user.
Cookie ck=ne w Cookie("user","");//deleting value of cookie
[Link](0);//changing the maximum age to 0 seconds
[Link](ck);//adding cookie in the response

Get Cookies
Cookie ck[]=[Link]();
for(int i=0;i<[Link];i++)
[Link]("<br>"+ck[i].getName()+" "+ck[i].getValue());

//printing name and value of cookie

Sending the Cookie into the HTTP response headers:


We use [Link] to add cookies in the HTTP response header as follows:
[Link](cookie);

Ex: List and [Link]


import [Link].*;
import [Link].*;
import [Link].*;
public class ListandAddCookieextends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html");
PrintWriter out = [Link]();
Cookie cookie = null;
[Link]("<html><body>"+
"<form method='get' action='/mrcet/CookieLab'>"+
"Name:<input type='text' name='user' /><br/>"+

Dept. of CSE, MRCET Page | 108


Web Technologies III [Link] II Sem (R15)

"Password:<input type='text' name='pass' ><br/>"+


"<input type='submit' value='submit'>"+
"</form>");

String name = [Link]("user");


String pass = [Link]("pass");

if(![Link]("") || ![Link]("")) {
Cookie ck = new Cookie(name,pass);
[Link](ck);
}

Cookie[] cookies = [Link]();


if( cookies != null ){
[Link]("<h2> Found Cookies Name and Value</h2>");
for (inti = 0; i<[Link]; i++){
cookie = cookies[i];
[Link]("Cookie Name : " + [Link]() + ", ");
[Link]("Cookie Value: " + [Link]()+" <br/>");
}
}
[Link]("</body></html>");
}
}
we [Link]
<web-app>
<servlet>
<servlet-name>ListandAddCookie</servlet-name>
<servlet-class>ListandAddCookie</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListandAddCookie</servlet-name>
<url-pattern>/ListandAddCookie</url-pattern>
</servlet- mapping>
</web-app>

Session
• HttpSession Interface 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.
• Web container creates a session id for each user. The container uses this id to identify the
particular 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.

Dept. of CSE, MRCET Page | 109


Web Technologies III [Link] II Sem (R15)

Get the HttpSession object

The HttpServletRequest interface provides two methods to get the object of HttpSession:
1. publicHttpSessiongetSession():Returns the current session associated with this
request, or if the request does not have a session, creates one.
2. publicHttpSessiongetSession(boolean create):Returns the current HttpSession
associated with this request or, if there is no current session and create is true, returns
a new session.

Destroy Session
[Link]();

Set/Get data in session


[Link](name,value);
[Link](name);

Methods
1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1,
1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Steps
• On client's first request, the Web Container generates a unique session ID and gives it
back to the client with response. This is a temporary session created by web container.
• The client sends back the session ID with each request. Making it easier for the web
container to identify where the request is coming from.
• The Web Container uses this ID, finds the matching session with the ID and associates
the session with the request.

Dept. of CSE, MRCET Page | 110


Web Technologies III [Link] II Sem (R15)

Ex: [Link]
import [Link].*;
[Link].*;
[Link].*;

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 = [Link](true);

String title = "Welcome to my website";


String userID = "";
Integer visitCount = new Integer(0);

if ([Link]())
{
userID = "Kalpana";
[Link]("UserId", "Kalpana");
}
else {
visitCount = (Integer)[Link]("visitCount");
visitCount = visitCount + 1;
userID = (String)[Link]("UserId");
}
[Link]("visitCount", visitCount);

[Link]("text/html");
PrintWriter out = [Link]();

[Link]("<html>" +
"<body>" +
"<h1>Session Infomation</h1>" +
"<table border='1'>" +
"<tr><th>Session info</th><th>value</th></tr>" +
"<tr><td>id</td><td>" + [Link]() + "</td></tr>" +
"<tr><td>User ID</td<td>" + userID + ―</td></tr>" +
"<tr><td>Number of visits</td><td>" + visitCount + "</td></tr>" +
"</table></body></html>");
}
}

Dept. of CSE, MRCET Page | 111


Web Technologies III [Link] II Sem (R15)

we [Link]
<web-app>
<servlet>
<servlet-name>SessionTrack</servlet-name>
<servlet-class>SessionTrack</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionTrack</servlet-name>
<url-pattern>/SessionTrack</url-pattern>
</servlet- mapping>
</web-app>

Output:

Dept. of CSE, MRCET Page | 112


Web Technologies III [Link] II Sem (R15)

UNIT IV
JAVA SERVER PAGES

Introduction to JSP: The Problem with Servlet. The Anatomy of a JSP Page, JSP Processing. JSP
Application Design with MVC Setting Up and JSP Environment, JSP Declarations, Directives,
Expressions, Code Snipplets, implement objects, Requests, Using Cookies and Session for Session
The Servlet technology and JavaServer Pages (JSP) are the two main technologies for
developing java Web applications. When first introduced by Sun Microsystems in 1996, the
Servlet technology was considered superior to the reigning Common Gateway Interface
(CGI) because servlets stay in memory after they service the first requests. Subsequent
requests for the same servlet do not require instantiation of the servlet‘s class therefore
enabling better response time.

Servlets are Java classes that implement the [Link] interface. They are
compiled and deployed in the web server. The problem with servlets is that you embed
HTML in Java code. If you want to modify the cosmetic look of the page or you want to
modify the structure of the page, you have to change code. Generally speaking, this
is left to the better hands (and brains) of a web page designer and not to a Java developer.

PrintWriter pw = [Link]();
[Link]("<html><head><title>Testing</title></head>"); [Link]("<body
bgcolor=\"# ffdddd\"> ");
As seen from the example above this method presents several difficulties to the web
developer:
1. The code for a servlet becomes difficult to understand for the programmer.
2. The HTML content of such a page is difficult if not impossible for a web designer to
understand or design.
3. This is hard to program and even small changes in the presentation, such as the page‘s
background color, will require the servlet to be recompiled. Any changes in the
HTML content require the rebuilding of the whole servlet.
4. It's hard to take advantage of web-page development tools when designing the
application interface. If such tools are used to develop the web page layout, the
generated HTML must then be manually embedded into the servlet code, a process
which is time consuming, error prone, and extremely boring.
5. In many Java servlet-based applications, processing the request and generating the
response are both handled by a single servlet class.
6. The servlet contains request processing and business logic (implemented by methods ),
and also generates the response HTML code, are embedded directly in the servlet code.
JSP solves these problems by giving a way to include java code into an HTML page using
scriptlets. This way the HTML code remains intact and easily accessible to web designers,
but the page can sill perform its task.

In late 1999, Sun Microsystems added a new element to the collection of Enterprise Java
tools: JavaServer Pages (JSP). JavaServer Pages are built on top of Java servlets and
designed to increase the efficiency in which programmers, and even nonprogrammers, can
create web content.

Dept. of CSE, MRCET Page | 113


Web Technologies III [Link] II Sem (R15)

Instead of embedding HTML in the code, you place all static HTML in a JSP page, just as in
a regular web page, and add a few JSP elements to generate the dynamic parts of the page.
The request processing can remain the domain of the servlet, and the business logic can be
handled by JavaBeans and EJB components.

A JSP page is handled differently compared to a servlet by the web server. When a servlet is
deployed into a web server in compiled (bytecode) form, then a JSP page is deployed in its
original, human-readable form.
When a user requests the specific page, the web server compiles the page into a servlet and
from there on handles it as a standard servlet.
This accounts for a small delay, when a JSP page is first requested, but any subsequent
requests benefit from the same speed effects that are associated with servlets.
The Problem with Servlet
• Servlets are difficult to code which are overcome in JSP. Other way, we can say, JSP is
almost a replacement of Servlets, (by large, the better word is extension of Servlets),
where coding decreases more than half.
• In Servlets, both static code and dynamic code are put together. In JSP, they are
separated. For example,In Servlets:
[Link](―Hello Mr.‖ + str + ‖ you are great man‖);
where str is the name of the client which changes for each client and is known as dynamic
content. The strings, ―Hello Mr.‖ and ―you are great man‖ are static content which is the
same irrespective of client. In Servlets, in println(), both are put together.
• In JSP, the static content and dynamic content is separated. Static content is written in
HTML and dynamic content in JSP. As much of the response comprises of static content
(nearly 70%) only, the JSP file more looks as a HTML file.
• Programmer inserts, here and there, chunks of JSP code in a running HTML developed
by Designer. As much of the response delivered to cleint by server comprises of static
content (nearly 70%), the JSP file more looks like a HTML file. Other way we can say,
JSP is nothting but Java in HTML (servlets are HTML
• in Java); java code embedded in HTML.
• When the roles of Designer and Programmer are nicely separated, the product
development becomes cleaner and fast. Cost of developing Web site becomes cheaper as
Designers are much paid less than Programmers, especially should be thought in the
present competitive world.
• Both presentation layer and business logic layer put together in Servlets. In JSP, they can
be separated with the usage of JavaBeans.
• The objects of PrintWriter, ServletConfig, ServletContext, HttpSession and
RequestDispatcher etc. are created by the Programmer in Servlets and used. But in JSP,
they are builtin and are known as "implicit objects". That is, in JSP, Programmer never
creates these objects and straightaway use them as they are implicitly created and given
by JSP container. This decreases lot of coding.
• JSP can easily be integrated with JavaBeans.
• JSP is much used in frameworks like Sturts etc.
• With JSP, Programmer can build custom tags that can be called in JavaBeans directly.
Servlets do not have this advantage. Reusability increases with tag libraries and JavaBean
etc.
• Writing alias name in <url-pattern> tag of [Link] is optional in JSP but mandatory in
Servlets.
• A Servlet is simply a Java class with extension .java written in normal Java code.
• A Servlet is a Java class. It is written like a normal Java. JSP is comes with some
elements that are easy to write.

Dept. of CSE, MRCET Page | 114


Web Technologies III [Link] II Sem (R15)

• JSP needs no compilation by the Programmer. Programmer deploys directly a JSP


source code file in server where as incase of Servlets, the Programmer compiles
manually a Servlet file and deploys a .class file in server.
• JSP is so easy even a Web Designer can put small interactive code (not knowing much
of Java) in static Web pages.
• First time when JSP is called it is compiled to a Servlet. Subsequent calls to the same
JSP will call the same compiled servlet (instead of converting the JSP to servlet),
Ofcourse, the JSP code would have not modified. This increases performance.

Anatomy of JSP

JSP Processing
Once you have a JSP capable web-server or application server, you need to know the
following information about it:
• Where to place the files
• How to access the files from your browser (with an http: prefix, not as file:)

You should be able to create a simple file, such as


<HTML>
<BODY>
Hello, world
</BODY> </HTML>
Know where to place this file and how to see it in your browser with an http:// prefix.
Since this step is different for each web-server, you would need to see the web-server
documentation to find out how this is done. Once you have completed this step, proceed to
the next.

Dept. of CSE, MRCET Page | 115


Web Technologies III [Link] II Sem (R15)

Your first JSP


JSP simply puts Java inside HTML pages. You can take any existing HTML page and change
its extension to ".jsp" instead of ".html". In fact, this is the perfect exercise for your first JSP.
Take the HTML file you used in the previous exercise. Change its extension from ".html" to
".jsp". Now load the new file, with the ".jsp" extension, in your browser.
You will see the same output, but it will take longer! But only the first time. If you
reload it again, it will load normally.
What is happening behind the scenes is that your JSP is being turned into a Java file,
compiled and loaded. This compilation only happens once, so after the first load, the file
doesn't take long to load anymore. (But everytime you change the JSP file, it will be re-
compiled again.)

Of course, it is not very useful to just write HTML pages with a .jsp e xtension! We now
proceed to see what makes JSP so useful
Adding dynamic content via expressions
As we saw in the previous section, any HTML file can be turned into a JSP file by changing
its extension to .jsp. Of course, what makes JSP useful is the ability to embed Java. Put the
following text in a file with .jsp extension (let us call it [Link]), place it in your JSP
directory, and view it in a browser.

<HTML>
<BODY>
Hello! The time is now <%= new [Link]() %>
</BODY>
</HTML>
Notice that each time you reload the page in the browser, it comes up with the current time.
The character sequences
<%= and %> enclose Java expressions, which are evaluated at run time.

This is what makes it possible to use JSP to generate dyamic HTML pages that change in
response to user actions or vary from user to user.

Explain about JSP Elements


In this lesson we will learn about the various elements available in JSP with suitable
examples. In JSP elements can be dividedinto 4 different types.
These are:
1. Expressions
We can use this tag to output any data on the generated page. These data are automatically
converted to string and printed on the output stream.
Syntax of JSP Expressions are: <%="Any thing" %>

JSP Expressions start with Syntax of JSP Scriptles are with <%= and ends with %>.
Between these this you can put anything and that will convert to the String and that will be
displayed.
Example: <%="Hello World!" %> Above code will display 'Hello World!'

Dept. of CSE, MRCET Page | 116

You might also like