You are on page 1of 133

UNIT-1

2 MARKS
1.What is PHP?
Ans: PHP is an acronym for "PHP: Hypertext Preprocessor"
PHP is a widely-used, open source scripting language
PHP scripts are executed on the server
PHP is free to download and use
PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
PHP is compatible with almost all servers used today (Apache, IIS, etc.)
PHP supports a wide range of databases.
PHP is easy to learn and runs efficiently on the server side.

2.What are the characteristics and advantages of PHP?


Ans: Five important characteristics make PHP's practical nature possible −
Simplicity
Efficiency
Security
Flexibility
Familiarity
Advantages of PHP:
Easy and Simple to Learn. PHP is considered one of the easiest scripting languages.
Extremely Flexible. PHP is highly flexible whether it is during an ongoing project or after completing
the project.
Easy Integration and Compatibility. ...
Efficient Performance. ...
Cost Efficient. ...
Gives Web Developer More Control.

3.What are the Rules for Declaring a Variable?


Ans: Rules for declaring PHP variable:
A variable must start with a dollar ($) sign, followed by the variable name.
It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
A variable name must start with a letter or underscore (_) character.
A PHP variable name cannot contain spaces.
One thing to be kept in mind that the variable name cannot start with a number or special symbols.
PHP variables are case-sensitive, so $name and $NAME both are treated as different variable.

4.What is Local Variable?


Ans: The variables that are declared within a function are called local variables for that function.
These local variables have their scope only in that particular function in which they are declared. This
means that these variables cannot be accessed outside the function, as they have local scope.
A variable declaration outside the function with the same name is completely different from the
variable declared inside the function. Let's understand the local variables with the help of an example:
<?php
function local_var()
{
$num = 45; //local variable
echo "Local variable declared inside the function is: ". $num;
}
local_var();
?>
Output:

Local variable declared inside the function is: 45


5.What is Global Variable?
Ans: The global variables are the variables that are declared outside the function. These variables can
be accessed anywhere in the program. To access the global variable within a function, use the
GLOBAL keyword before the variable. However, these variables can be directly accessed or used
outside the function without any keyword. Therefore there is no need to use any keyword to access a
global variable outside the function.
Let's understand the global variables with the help of an example:
<?php
$name = "Web Technology"; //Global Variable
function global_var()
{
global $name;
echo "Variable inside the function: ". $name;
echo "</br>";
}
global_var();
echo "Variable outside the function: ". $name;
?>
Output:
Variable inside the function: Web Technology
Variable outside the function: Web Technology

3 MARKS
1.What are the Different Data Types in PHP?
Ans: Variables can store data of different types, and different data types can do different things.
PHP supports the following data types:
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource

1.String:

A string is a non-numeric data type. It holds letters or any alphabets, numbers, and even special
characters.String values must be enclosed either within single quotes or in double quotes. But both
are treated differently. To clarify this, see the example below:
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>

Output:
Hello world!
Hello world!
2.Integer
An integer data type is a non-decimal number between -2,147,483,648 and 2,147,483,647.
Rules for integers:
An integer must have at least one digit
An integer must not have a decimal point
An integer can be either positive or negative
Integers can be specified in: decimal (base 10), hexadecimal (base 16), octal (base 8), or binary (base
2) notation
In the following example $x is an integer. The PHP var_dump() function returns the data type and
value:
<?php
$x = 100;
var_dump($x);
?>

Output:
Int(100)

3.Float:

A float (floating point number) is a number with a decimal point or a number in exponential form.
In the following example $x is a float. The PHP var_dump() function returns the data type and value:
<?php
$x = 3.123;
var_dump($x);
?>
Output:
float(3.123)

4.Boolean:

A Boolean represents two possible states: TRUE or FALSE.


$x = true;
$y = false;
Booleans are often used in conditional testing.
Booleans are the simplest data type works like switch. It holds only two values: TRUE (1) or FALSE
(0). It is often used with conditional statements. If the condition is correct, it returns TRUE otherwise
FALSE.

<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Output:
This condition is true

5.Array:

An array is a compound data type.


It can store multiple values of same data type in a single variable.
<?php
$bikes = array ("Royal Enfield", "Yamaha", "KTM");
var_dump($bikes); //the var_dump() function returns the datatype and values
echo "</br>";
echo "Array Element1: $bikes[0] </br>";
echo "Array Element2: $bikes[1] </br>";
echo "Array Element3: $bikes[2] </br>";
?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3) "KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM

6.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:
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>

Output:
Bike Model: Royal Enfield

7.NULL

Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
Variables can also be emptied by setting the value to NULL
<?php
$x = "Hello world!";
$x = null;
var_dump($x);
?>

Output:
NULL

8.Resource:
Resources in PHP are not an exact data type. These are basically used to store references to some
function call or to external PHP resources. For example, consider a database call. This is an external
resource.

2.Explain Arrays in PHP?

Ans: PHP Arrays


A PHP array is a variable that stores more than one piece of related data in a single variable.

Advantage of PHP Array


Less Code: We don't need to define multiple variables.
Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
Sorting: We can sort the elements of array.

PHP Array Types


There are 3 types of array in PHP.
Indexed Array
Associative Array
Multidimensional Array

PHP Indexed Array


PHP index is represented by number which starts from 0. We can store number, string and object in
the PHP array. All PHP array elements are assigned to an index number by default.
There are two ways to define indexed array:
1st way:
$season=array("summer","winter","spring","autumn");
2nd way:
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";

Example
File: array1.php
<?php
$season=array("summer","winter","spring","autumn");
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn
File: array2.php
<?php
$season[0]="summer";
$season[1]="winter";
$season[2]="spring";
$season[3]="autumn";
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";
?>
Output:
Season are: summer, winter, spring and autumn

PHP Associative Array


We can associate name with each array elements in PHP using => symbol.
There are two ways to define associative array:
1st way:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
2nd way:
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";

Example
File: arrayassociative1.php
<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>

Output:

Sonoo salary: 350000

John salary: 450000

Kartik salary: 200000


File: arrayassociative2.php
<?php
$salary["Sonoo"]="350000";
$salary["John"]="450000";
$salary["Kartik"]="200000";
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";
echo "John salary: ".$salary["John"]."<br/>";
echo "Kartik salary: ".$salary["Kartik"]."<br/>";
?>
Output:

Sonoo salary: 350000

John salary: 450000

Kartik salary: 200000

PHP Multidimensional Array

PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in an
array. PHP multidimensional array can be represented in the form of matrix which is represented by
row * column.

Definition
$emp = array
(
array(1,"sonoo",400000),
array(2,"john",500000),
array(3,"rahul",300000)
);

3.Explain Strings in PHP?


Ans: Strings can be seen as a stream of characters. For example, ‘h’ is a character and ‘helloworld’ is
a string. Every thing inside quotes , single (‘ ‘) and double (” “) in PHP is treated as a string.

Creating Strings

There are two ways of creating strings in PHP:


Single-quote strings: This type of strings does not processes special characters inside quotes.
<?php
// single-quote strings
$first = 'Welcome to PHP strings ';
echo $first;
?>
Output:
Welcome to PHP strings

The above program compiles correctly. We have created a string ‘'Welcome to PHP strings’ and
stored it in variable and printing it using echo statement.

2.Double-quote strings : Unlike single-quote strings, double-quote strings in PHP is capable of


processing special characters.
<?php
// double-quote strings
echo "Welcome to PHP world \n";
$first = "PHP world";
echo "Welcome to $first";
?>
Output:
Welcome to PHP world
Welcome to PHP world

PHP treats everything inside double quotes(” “) as Strings


Strings within single quote ignores the special characters but double-quoted strings recognize the
special characters and treat them differently.

Example:
<?php
$name = "sam";
echo "The name is $name \n";
echo 'The name is $name';

?>
Output:
The name is sam
The name is $name
The Important and frequently used special characters that are used with double-quoted strings are
explained below:
The character beginning with a backslash(“\”) are treated as escape sequences and are replaced with
special characters. Here are few important escape sequences.
“\n” is replaced by a new line
“\t” is replaced by a tab space
“\$” is replaced by a dollar sign
“\r” is replaced by a carriage return
“\\” is replaced by a backslash
“\”” is replaced by a double quote
“\'” is replaced by a single quote
The string starting with a dollar sign(“$”) are treated as variables and are replaced with the content of
the variables.
Built-in String functions
Built-in functions in PHP are some existing library functions which can be used directly in our
programs making an appropriate call to them. Below are some important built-in string functions that
we use in our daily and regular programs:
1.strlen() function: This function is used to find the length of a string. This function accepts the string
as argument and return the length or number of characters in the string.
Example:

<?php
echo strlen("Hello World!");
?>
Output:
12
2.strrev() function: This function is used to reverse a string. This function accepts a string as
argument and returns its reversed string.
Example:
<?php
echo strrev("Hello!");

?>
Output:
!olleH

3.str_replace() function: This function takes three strings as arguments. The third argument is the
original string and the first argument is replaced by the second one. In other words we can say that it
replaces all occurrences of the first argument in the original string by second argument.
Example:
<?php
echo str_replace("There", "World", "Hello There!"), "\n";

?>
Output:
Hello World!

4.strpos() function: This function takes two string arguments and if the second string is present in
the first one, it will return the starting position of the string otherwise returns FALSE. Example:

<?php
echo strpos("Hello World!", "World"), "\n";
?>

Output:
7
5. trim() function: This function allows us to remove whitespaces or strings from both sides of a
string. Example:

<?php
echo trim("Hello World!", "Hed!");

?>
Output:
llo Worl

4.what are Operators?


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

Operator Description Example


+ Adds two operands $A + $B will give 30
- Subtracts second operand from the first $A - $B will give -10
* Multiply both operands $A *$B will give 200
/ Divide numerator by denumerator $B / $A will give 2
% Modulus Operator and remainder of after a integ $B % $A will give 0
division n er
** Exponentiation ($x to the $y’th power) $A ** $B

Increment/Decrement operators

Operato Description Example


r
++ 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:
Operato Description Example
r
== 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:

Operator Description Example


and Called Logical AND operator. If both the operands ($A and $B) is true.
(o are true then then condition becomes true. ($A && $B) is true.
r) &&
Or (or) || Called Logical OR Operator. If any of the two ($A or $B) is true. ($A
operands are non zero then then condition becomes || $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 Operators:
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
+= 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 left to $C = $C - $A
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 operand $C /= $A is equivalent
with the right operand and assign the result to left operand to $C = $C / $A

%= 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 Operator
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 X : val Y
? value Otherwise ue

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.
Category Operator 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
Conditional ?: 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!
5 MARKS
1.Explain Expressions in PHP?
Ans: Expressions are the most important building blocks of PHP. In PHP, almost anything you write
is an expression. The simplest yet most accurate way to define an expression is "anything that has a
value".

A regular expression is a sequence of characters that forms a search pattern. When you search for data
in a text, you can use this search pattern to describe what you are searching for.

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

Regular expressions can be used to perform all types of text search and text replace operations.
Syntax

In PHP, regular expressions are strings composed of delimiters, a pattern and optional modifiers.
$exp = "/hello/i";
In the example above, / is the delimiter, hello is the pattern that is being searched for, and i is
a modifier that makes the search case-insensitive.

The delimiter can be any character that is not a letter, number, backslash or space. The most common
delimiter is the forward slash (/), but when your pattern contains forward slashes it is convenient to
choose other delimiters such as # or ~.

Regular Expression Functions

PHP provides a variety of functions that allow you to use regular expressions.
The preg_match(), preg_match_all() and preg_replace() functions are some of the most commonly
used ones:

Function Description

preg_match() Returns 1 if the pattern was found in the string and 0 if not

preg_match_all() Returns the number of times the pattern was found in the string, which may
also be 0

preg_replace() Returns a new string where matched patterns have been replaced with another
string

Using preg_match()

The preg_match() function will tell you whether a string contains matches of a pattern.
Example

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


<?php
$str = "hello worls";
$pattern = "/hello/i";
echo preg_match($pattern, $str); // Outputs 1
?>
Using preg_match_all()

The preg_match_all() function will tell you how many matches were found for a pattern in a string.
Example

Use a regular expression to do a case-insensitive count of the number of occurrences of "ain" in a


string:
<?php
$str = "The rain in SPAIN falls mainly on the plains.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str); // Outputs 4
?>
Using preg_replace()

The preg_replace() function will replace all of the matches of the pattern in a string with another
string.
Example

Use a case-insensitive regular expression to replace Microsoft with W3Schools in a string:


<?php
$str = "Visit Microsoft!";
$pattern = "/microsoft/i";
echo preg_replace($pattern, "google", $str); // Outputs "Visit google!"
?>
Regular Expression Modifiers

Modifiers can change how a search is performed.

Modifier Description

i Performs a case-insensitive search

m Performs a multiline search (patterns that search for the beginning or end of a
string will match the beginning or end of each line)

u Enables correct matching of UTF-8 encoded patterns

Regular Expression Patterns

Brackets are used to find a range of characters:

Expression Description

[abc] Find one character from the options between the brackets
[^abc] Find any character NOT between the brackets

[0-9] Find one character from the range 0 to 9

Metacharacters

Metacharacters are characters with a special meaning:

Metacharacter Description

| Find a match for any one of the patterns separated by | as in: cat|dog|fish

. Find just one instance of any character

^ Finds a match as the beginning of a string as in: ^Hello

$ Finds a match at the end of the string as in: World$

\d Find a digit

\s Find a whitespace character

\b Find a match at the beginning of a word like this: \bWORD, or at the end of a
word like this: WORD\b

\uxxxx Find the Unicode character specified by the hexadecimal number xxxx

Quantifiers

Quantifiers define quantities:

Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n

n? Matches any string that contains zero or one occurrences of n


n{x} Matches any string that contains a sequence of X n's

n{x,y} Matches any string that contains a sequence of X to Y n's

n{x,} Matches any string that contains a sequence of at least X n's

Grouping

You can use parentheses ( ) to apply quantifiers to entire patterns. They also can be used to select
parts of the pattern to be used as a match.
Example

Use grouping to search for the word "banana" by looking for ba followed by two instances of na:
<?php
$str = "Apples and bananas.";
$pattern = "/ba(na){2}/i";
echo preg_match($pattern, $str); // Outputs 1
?>

2.Explain Control Structures in PHP?


Ans: 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!"; else
Example
echo "Have a nice day!";
The following example will output "Have a ?>
nice weekend!" if the current day is Friday, </body> </html>
Otherwise, it will output "Have a nice day!":
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!"; elseif
code to be executed if condition is false; ($d=="Sun")
Example echo "Have a nice Sunday!"; else
The following example will output "Have a echo "Have a nice day!";
nice weekend!" if the current day is Friday, ?>
and "Have a nice Sunday!" if the current day </body>
is Sunday. Otherwise, it will output "Have a </html>
nice day!"

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 The switch statement works in an unusual
switch (expression) way. First it evaluates given expression
{ then seeks a lable to match the resulting
case label1: value. If a matching value is found then the
code to be executed if expression = label1; code associated with the matching label
break; 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; default: specified default code.
code to be executed
if expression is different from both label1 and
label2;
}

PHP -Loop Types


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.
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 loop statement
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
willwhile
again(condition)
be evaluated and the loop will continue until the test expression is found to be false.
Syntax
{
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>
result –
The do...while loopstatement
The do...while statement will execute a block of code at least once. It then will repeat thePage | long
loop as
as a condition is true. 46
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>
<body>
<?php
$i = 0; $num = 0; do{
$i++;
}while( $i < 10 );
echo ("Loop stopped at i = $i" );
?>
</body>
</html>

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); foreach( $array
$value and the array pointer is moved by one as $value )
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
Value is 2
Example
Value is 3
Try out beside example to list out the values
Value is 4
of an array.
Value is 5

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
3.Explain Functions in PHP?

Ans: 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 –

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

<html> <head>

<title>Writing PHP Function</title>


</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage()
{
echo "Have a nice time Kalpana!";
} /* Calling a PHP Function */
writeMessage();
?>
It‘s very easy to create your own PHP function. Suppose you want to create a PHP function which
</body></html>
will simply write a simple message on your browser when you will call it. Following example creates
Output: Have a nice time Kalpana!
a function called writeMessage() and then calls it just after creating it.
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;
Output:echo
Sum"Sum
of theoftwo
thenumbers
two numbers
is : 30is : $sum";
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)
{
$num += 5;
}
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );
echo "O riginal Value is $orignum<br />";
addSix( $orignum );
echo "O riginal Value is $orignum<br />";
?>
</body>
</html>
Output: Original Value is 10
PHP Functions returning value
A function canOriginal
return Value
a valueisusing
16 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;
}
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

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

4. How to Read Data from Web Form Controls like Text boxes, Radio Buttons,Lists Etc?
Ans: When we develop a website or a web application, we often have to create forms to take input
from users, like a Login form or a Registration form.
Creating a form on the webpage is accomplished using HTML, while PHP serves as a transport for
those values from the webpage to the server and then in further processing those values.
PHP provides two superglobals $_GET and $_POST for collecting form-data for processing.
HTML Form:

<html>
<body>
<form action="welcome.php" method="get">
<p>Name: <input type="text" name="name"><br></p>
<p>Password: <input type="password" name="pswd"><br></p>
<P>Gender:
<input type="radio" name="gender" value="male">male
<input type="radio" name="gender" value="female">female<br>
</p>
<p><input type="submit" name="submit" value="login"><br><p>
<p><input type="reset" name="reset" value="reset page"><br><p>
</form>
</body>
</html>

In the code above, we have used the <form> tag to create an HTML form, with input fields for Name
and Email along with submit button to submit the form-data.
In the <form> tag, we have two attributes, action and method, do you know what they are for?

action: Using this attribute, we can specify the name of the file which will collect and handle the form-
data. In the example above, we have provided name of a Php file.

method: This attribute specify the means of sending the form-data, whether it will be submitted
via POST method or GET method.

PHP Form Handling with POST or GET


If we specify the form method to be POST, then the form-data is sent to the server using the HTTP
POST method.
If we specify the form method to be GET, then the form-data is sent to the server using the HTTP
GET method.
Below, we have the code, to access the form-data in the Php file specified in the action attribute of
our HTML form, this time using the GET superglobal.
PHP Script:
<html>
<body bgcolor="#76D7C4">
<center>
<b><i> welcome,
<?php
echo $_GET["name"];
?>
<br>
Your password is
<?php
echo $_GET["pswd"];
?>
<br>
Gender:
<?php
echo $_GET["gender"];
?>
</i></b>
</center>
</body>
</html>

The first step to process the form-data is to fetch the data using POST or GET superglobals, once you
have the data, you can do anything with it, display it on your webpage, save the data into database,
perform validations etc.

PHP - GET & POST Methods


There are two ways the browser client can send information to the web server.
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.
http://www.sampletest.com/index.htm?name1=value1&name2=value2

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
The POST Method
The POST method transfers information via HTTP headers 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.

Below is the HTML Form page and a PHP Form Handling page
OUTPUT:

5.Explain Handling File Uploads ?


Ans: 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 phpinfo.php 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 php.ini
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.

OUTPUT:
6. Elaborate Connecting to Database( My SQL as Reference)?

Ans: MySQL Database


MySQL is a fast, easy-to-use RDBMS being used for many small and big businesses. MySQL is
developed, marketed and supported by MySQL AB, which is a Swedish company. MySQL is
becoming so popular because of many good reasons −
MySQL is released under an open-source license. So you have nothing to pay to use it.
MySQL is a very powerful program in its own right. It handles a large subset of the functionality of
the most expensive and powerful database packages.
MySQL uses a standard form of the well-known SQL data language.
MySQL works on many operating systems and with many languages including PHP, PERL, C, C++,
JAVA, etc.
MySQL works very quickly and works well even with large data sets.
MySQL is very friendly to PHP, the most appreciated language for web development.
MySQL works very well in combination of various programming languages like PERL, C, C++,
JAVA and PHP. Out of these languages, PHP is the most popular one because of its web application
development capabilities.
PHP provides various functions to access the MySQL database and to manipulate the data records
inside the MySQL database. You would require to call the PHP functions in the same way you call
any other PHP function.
Sr.No. Parameter & Description

1 server
Optional − The host name running the database server. If not specified, then the default
value will be localhost:3306.

2 user
Optional − The username accessing the database. If not specified, then the default will
be the name of the user that owns the server process.

3
passwd
Optional − The password of the user accessing the database. If not specified, then the
default will be an empty password.

4 new_link
Optional − If a second call is made to mysql_connect() with the same arguments, no new
connection will be established; instead, the identifier of the already opened connection
will be returned.

5 client_flags
Optional − A combination of the following constants −
MYSQL_CLIENT_SSL − Use SSL encryption.
MYSQL_CLIENT_COMPRESS − Use compression protocol.
MYSQL_CLIENT_IGNORE_SPACE − Allow space after function names.
MYSQL_CLIENT_INTERACTIVE − Allow interactive timeout seconds of inactivity
before closing the connection.
MySQL Connection Using PHP Script
PHP provides mysql_connect() function to open a database connection. This function takes five
parameters and returns a MySQL link identifier on success or FALSE on failure.
Syntax

connection mysql_connect(server,user,passwd,new_link,client_flag);

You can disconnect from the MySQL database anytime using another PHP function mysql_close().
This function takes a single parameter, which is a connection returned by
the mysql_connect() function.
Syntax

bool mysql_close ( resource $link_identifier );


If a resource is not specified, then the last opened database is closed. This function returns true if it
closes the connection successfully otherwise it returns false.
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
$conn= mysqli_connect($hostname, $username, $password);
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
echo 'Connected to Database successfully';
mysqli_close($conn);
?>

Create a Database using PHP Script


PHP uses mysql_query function to create or delete a MySQL database. This function takes two
parameters and returns TRUE on success or FALSE on failure.
Syntax

bool mysql_query( sql, connection );


Sr.No. Parameter & Description

1 sql
Required - SQL query to create or delete a MySQL database

2 connection
Optional - if not specified, then the last opened connection by mysql_connect will be used.
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected to database successfully<br/>';
$sql = 'CREATE DATABASE STUDENT';

if(mysqli_query( $conn,$sql))
{
echo "Database student created successfully.";
}
else
{
echo "Sorry, database creation failed ".mysqli_error($conn);
}
mysqli_close($conn);
?>

Creating Tables Using PHP Script


To create new table in any existing database you would need to use PHP function mysql_query().
You will pass its second argument with a proper SQL command to create a table.
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'university';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn)
{
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';

$sql = "create table student(id INT AUTO_INCREMENT,name VARCHAR(20) NOT NULL,


marks INT NOT NULL,primary key (id))";
if(mysqli_query($conn, $sql))
{
echo "Table student created successfully";
}else
{
echo "Could not create table: ". mysqli_error($conn);
}
mysqli_close($conn);
?>

Inserting Data Using a PHP Script


You can use the same SQL INSERT INTO command into the PHP function mysql_query() to insert
data into a MySQL table.
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'student';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
$sql = 'INSERT INTO students(name,marks) VALUES ("sonu", 100)';
$sql = 'INSERT INTO students(name,marks) VALUES ("Rani", 90)';
if(mysqli_query($conn, $sql))
{
echo "Record inserted successfully";
}
else{
echo "Could not insert record: ". mysqli_error($conn);
}
mysqli_close($conn);
?>

Fetching Data Using a PHP Script


Use the same SQL SELECT command into a PHP function mysql_query(). This function is used to
execute the SQL command and then later another PHP function mysql_fetch_array() can be used to
fetch all the selected data. This function returns the row as an associative array, a numeric array, or
both. This function returns FALSE if there are no more rows.
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$dbname = 'mydatabase';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
$sql = 'SELECT * FROM student';
$retval=mysqli_query($conn, $sql);
if(mysqli_num_rows($retval) > 0){
while($row = mysqli_fetch_assoc($retval)){
echo "id :{$row['id']} <br> ".
"name : {$row['name']} <br> ".
"marks : {$row['marks']} <br> ";
} //end of while
}else{
echo "0 results";
}
mysqli_close($conn);
?>

7. Explain Handling Session and Cookies?


Ans:
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", "SAM", 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 with PHP


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.

<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'
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
<?php
// Start the session
session_start();
?>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body> </html>
Modify a PHP Session Variable
To change a session variable, just overwrite
it:
<?php
session_start();
?>
<html>
<?php
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION); ?> </html>
Get PHP Session Variable Values
Next, we create another page called "demo_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>

8. Difference between a session and a cookie

Ans: 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
information contain user information
2 Session Max life time is 1440 Seconds(24 We have to set cookie max life time
Minutes) as defined in php.ini file manually with php code with setcookie
in php.ini on line 1604 you can find function.
; http://php.net/session.gc- maxlifetime setcookie("email",
session.gc_maxlifetime = 1440 'test@example.com', time()+3600); /*
You can edit this value if you need custom expire in 1 hour */ Expire time : I hour
session life. after current time
3 In php $_SESSION super global variable is In php $_COOKIE super global
used 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
php.ini line 479 ;http://php.net/memory- 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
unset($_SESSION["key1"], cookie 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.

login.php
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<form method="post" action="checklogin.php">
User Id: <input type="text" name="uid"><br>
Password: <input type="password" name="pw"><br>
<input type="submit" value="Login">
</form>
</body>
</html>
checklogin.php
<?php
$uid = $_POST['uid'];
$pw = $_POST['pw'];
if($uid == 'arun' and $pw == 'arun123')
{
session_start();
$_SESSION['sid']=session_id();
header("location:securepage.php");
}
?>
securepage.php
<?php
session_start();
if($_SESSION['sid']==session_id())
{
echo "Welcome to you<br>";
echo "<a href='logout.php'>Logout</a>";
}
else
{
header("location:login.php");
}
?>
logout.php
<?php
echo "Logged out scuccessfully";
session_start();
session_destroy();
setcookie(PHPSESSID,session_id(),time()-1);
?>

9.Explain File Operations like Opening,Closing,Reading,Writing, Appending,Deleting etc. on


Text and Binary Files?
Ans:When a program is terminated, the entire data is lost. Storing in a file will preserve your data
even if the program terminates.
Types of Files
When dealing with files, there are two types of files you should know about:
Text files
Binary files
Text files
Text files are the normal .txt files. You can easily create text files using any simple text editors such
as Notepad.
When you open those files, you'll see all the contents within the file as plain text. You can easily edit
or delete the contents.
They take minimum effort to maintain, are easily readable, and provide the least security and takes
bigger storage space.
Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold a higher amount of data, are not readable easily, and provides better security than text
files.

PHP Open File


PHP fopen() function is used to open file or URL and returns resource. The fopen() function accepts
two arguments: $filename and $mode. The $filename represents the file to be opended and $mode
represents the file mode for example read-only, read-write, write-only etc.
Syntax
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $conte
xt ]] )

PHP Open File Example


<?php
$handle = fopen("c:\\folder\\file.txt", "r");
?>
PHP Read File
PHP provides various functions to read data from file. There are different functions that allow you to
read all file data, read data line by line and read data character by character.

The available PHP file read functions are given below.


fread()
fgets()
fgetc()

PHP Read File - fread()


The PHP fread() function is used to read data of the file. It requires two arguments: file resource and
file size.

Syntax
string fread (resource $handle , int $length )
$handle represents file pointer that is created by fopen() function.
$length represents length of byte to be read.

Example
<?php
$filename = "c:\\file1.txt";
$fp = fopen($filename, "r");//open file in read mode
$contents = fread($fp, filesize($filename));//read file
echo "<pre>$contents</pre>";//printing data of file
fclose($fp);//close file
?>
Output

this is first line

this is another line

this is third line

PHP Read File - fgets()


The PHP fgets() function is used to read single line from the file.

Syntax
string fgets ( resource $handle [, int $length ] )

Example
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
echo fgets($fp);
fclose($fp);
?>
Output

this is first line

PHP Read File - fgetc()


The PHP fgetc() function is used to read single character from the file. To get all data using fgetc()
function, use !feof() function inside the while loop.

Syntax
string fgetc ( resource $handle )

Example
<?php
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>
Output

this is first line this is another line this is third line


PHP Write File
PHP fwrite() and fputs() functions are used to write data into file. To write data into file, you need to
use w, r+, w+, x, x+, c or c+ mode.

PHP Write File - fwrite()


The PHP fwrite() function is used to write content of the string into file.
Syntax
int fwrite ( resource $handle , string $string [, int $length ] )

Example
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'welcome ');
fwrite($fp, 'to php file write');
fclose($fp);
echo "File written successfully";
?>

Output: data.txt

PHP Overwriting File


If you run the above code again, it will erase the previous data of the file and writes the new data.
Let's see the code that writes only new data into data.txt file.
<?php
$fp = fopen('data.txt', 'w');//opens file in write-only mode
fwrite($fp, 'hello');
fclose($fp);
echo "File written successfully";
?>
Output: data.txt

hello

PHP Append to File


If we use a mode, it will not erase the data of the file. It will write the data at the end of the file.
Append data into file by using a or a+ mode in fopen() function

PHP Append to File - fwrite()


The PHP fwrite() function is used to write and append data into file.
Example
<?php
$fp = fopen('data.txt', 'a');//opens file in append mode
fwrite($fp, ' this is additional text ');
fwrite($fp, 'appending data');
fclose($fp);
echo "File appended successfully";
?>
Output: data.txt
PHP Delete File
In PHP, we can delete any file using unlink() function. The unlink() function accepts one argument
only: file name. It is similar to UNIX C unlink() function.
PHP unlink() generates E_WARNING level error if file is not deleted. It returns TRUE if file is
deleted successfully otherwise FALSE.
Syntax
bool unlink ( string $filename [, resource $context ] )
$filename represents the name of the file to be deleted.

PHP Delete File Example


<?php
$status=unlink('data.txt');
if($status){
echo "File deleted successfully";
}else{
echo "Sorry!";
}
?>
Output

File deleted successfully

10. Explain Listing Directories?


Ans: The directory functions allow you to retrieve information about directories and their contents.
The PHP directory functions are part of the PHP core. No installation is required to use these
functions.
PHP Directory Functions
Function Description

chdir() Changes the current directory

chroot() Changes the root directory

closedir() Closes a directory handle

dir() Returns an instance of the Directory class

getcwd() Returns the current working directory

opendir() Opens a directory handle

readdir() Returns an entry from a directory handle

rewinddir() Resets a directory handle

scandir() Returns an array of files and directories of a specified directory

PHP chdir() Function

The chdir() function changes the current directory.


Syntax
chdir(directory)
directory- Required. Specifies the new current directory
Change the current directory:
<?php
// Get current directory
echo getcwd() . "<br>";

// Change directory
chdir("images");

// Get current directory


echo getcwd();
?>

Result:
/home/php
/home/php/images

PHP chroot() Function

The chroot() function changes the root directory of the current process to directory, and changes the
current working directory to "/".

This function requires root privileges, and is only available to GNU and BSD systems, and only when
using the CLI, CGI or Embed SAPI.

This function is not implemented on Windows platforms.

Syntax
chroot(directory)
directory- Required. Specifies the new current directory

<?php
// Change root directory
chroot("/path/to/chroot/");

// Get current directory


echo getcwd();
?>

Result:
/
PHP closedir() Function

The closedir() function closes a directory handle.


Syntax
closedir(dir)

dir Optional. Specifies the directory handle resource previously opened with opendir(). If this
parameter is not specified, the last link opened by opendir() is assumed
PHP dir() Function

The dir() function returns an instance of the Directory class. This function is used to read a directory,
which includes the following:
The given directory is opened

The two properties handle and path of dir() are available

Both handle and path properties have three methods: read(), rewind(), and close()
Syntax
dir(directory, context)
<?php
$d = dir(getcwd());

echo "Handle: " . $d->handle . "<br>";


echo "Path: " . $d->path . "<br>";

while (($file = $d->read()) !== false){


echo "filename: " . $file . "<br>";
}
$d->close();
?>

Result:
Handle: Resource id #2
Path: /etc/php
filename: .
filename: ..
filename: ajax.gif
filename: books.xml
filename: cdcatalog.xml
filename: cd_catalog.xml
filename: default.asp
filename: demo_array.asp
filename: demo_array.htm

PHP getcwd() Function

The getcwd() function returns the current working directory.

Get the current working directory:


<?php
echo getcwd();
?>

Result:
/home/php
PHP opendir() Function
The opendir() function opens a directory handle.
Syntax
opendir(path, context)
Open a directory, read its contents, then close:
<?php
$dir = "/images/";

// Open a directory, and read its contents


if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
?>

Result:
filename: cat.gif
filename: dog.gif
filename: horse.gif
PHP readdir() Function
The readdir() function returns the name of the next entry in a directory.
Syntax
readdir(dir)

List all entries in the images directory, then close:


<?php
$dir = "/images/";

// Open a directory, and read its contents


if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
?>

Result:
filename: cat.gif
filename: dog.gif
filename: horse.gif
PHP rewinddir() Function

The rewinddir() function resets the directory handle created by opendir().

Syntax
rewinddir(dir)
Open a directory, list its files, reset directory handle, list its files once again, then close:
<?php
$dir = "/images/";

// Open a directory, and read its contents


if (is_dir($dir)){
if ($dh = opendir($dir)){
// List files in images directory
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
rewinddir();
// List once again files in images directory
while (($file = readdir($dh)) !== false){
echo "filename:" . $file . "<br>";
}
closedir($dh);
}
}
?>

Result:
filename: cat.gif
filename: dog.gif
filename: horse.gif
filename: cat.gif
filename: dog.gif
filename: horse.gif

PHP scandir() Function


The scandir() function returns an array of files and directories of the specified directory.
Syntax
scandir(directory, order, context)

List files and directories inside the images directory:


<?php
$dir = "/images/";
// Sort in ascending order - this is default
$a = scandir($dir);
// Sort in descending order
$b = scandir($dir,1);
print_r($a);
print_r($b);
?>

Result:
Array
(
[0] => .
[1] => ..
[2] => cat.gif
[3] => dog.gif
[4] => horse.gif
[5] => myimages
)
Array
(
[0] => myimages
[1] => horse.gif
[2] => dog.gif
[3] => cat.gif
[4] => ..
[5] => .
UNIT-2
2 MARKS
1.What is Xml?

Ans: 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 wasdesigned 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.

2. Difference between XML and HTML ?

Ans:
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.
XML is platform independent neutral and language independent.
XML tags and attribute names are case-sensitive where as in HTML it is not.
XML attribute values must be single or double quoted where as in HTML it is not
compulsory.
XML elements must be properly nested.
All XML elements must have a closing tag.

3. What is Well Formed XML Documents ?

Ans:A "Well Formed" 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.

4.What is Markup?

Ans: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>ABC</to>
<from>XYZ </from>
<heading>WEB PAGE</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>.
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>

3 MARKS
1.Define XML tags,?
Ans:
XML tags form the foundation of XML. They define the scope of an element in XML. They can also
be used to insert comments, declare settings required for parsing the environment, and to insert special
instructions.

Start Tag
The beginning of every non-empty XML element is marked by a start-tag. Following is an example
of start-tag −

<address>

End Tag
Every element that has a start tag should end with an end-tag. Following is an example of end-tag −

</address>

Empty Tag
The text that appears between start-tag and end-tag is called content. An element which has no content
is termed as empty. An empty element can be represented in two ways as follows −
A start-tag immediately followed by an end-tag as shown below −
<hr></hr>
A complete empty-element tag is as shown below
<hr />
XML Tags Rules
Following are the rules that need to be followed to use XML tags −
Rule 1
XML tags are case-sensitive. Following line of code is an example of wrong syntax </Address>,
because of the case difference in two tags, which is treated as erroneous syntax in XML.
<address>This is wrong syntax</Address>
Following code shows a correct way, where we use the same case to name the start and the end tag.
<address>This is correct syntax</address>
Rule 2
XML tags must be closed in an appropriate order, i.e., an XML tag opened inside another element
must be closed before the outer element is closed. For example −
<outer_element>
<internal_element>
This tag is closed before the outer_element
</internal_element>
</outer_element>

2.Explain XML ELEMENTS?


Ans: XML elements can be defined as building blocks of an XML. Elements can behave as containers
to hold text, elements, attributes, media objects or all of these.
Each XML document contains one or more elements, the scope of which are either delimited by start
and end tags, or for empty elements, by an empty-element tag.
Syntax
Following is the syntax to write an XML element −
<element-name attribute1 attribute2>
....content
</element-name>
where,
element-name is the name of the element. The name its case in the start and end tags must match.
attribute1, attribute2 are attributes of the element separated by white spaces. An attribute defines a
property of the element. It associates a name with a value, which is a string of characters. An attribute
is written as −
name = "value"
name is followed by an = sign and a string value inside double(" ") or single(' ') quotes.
Empty Element
An empty element (element with no content) has following syntax −
<name attribute1 attribute2.../>
Following is an example of an XML document using various XML element −
<?xml version = "1.0"?>
<contact-info>
<address category = "residence">
<name>Sam</name>
<company>micro.com</company>
<phone>(011) 123-4567</phone>
</address>
</contact-info>

XML Elements Rules


Following rules are required to be followed for XML elements −
An element name can contain any alphanumeric characters. The only punctuation mark allowed in
names are the hyphen (-), under-score (_) and period (.).
Names are case sensitive. For example, Address, address, and ADDRESS are different names.
Start and end tags of an element must be identical.
An element, which is a container, can contain text or elements as seen in the above example.

3.Explain XML ATTRIBUTE?


Ans: Attributes are part of XML elements. An element can have multiple unique attributes. Attribute
gives more information about XML elements. To be more precise, they define properties of elements.
An XML attribute is always a name-value pair.
Syntax
An XML attribute has the following syntax −
<element-name attribute1 attribute2 >
....content..
< /element-name>
where attribute1 and attribute2 has the following form −
name = "value"
value has to be in double (" ") or single (' ') quotes. Here, attribute1 and attribute2 are unique attribute
labels.

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


<!DOCTYPE garden [
<!ELEMENT garden (plants)*>
<!ELEMENT plants (#PCDATA)>
<!ATTLIST plants category CDATA #REQUIRED>
]>

<garden>
<plants category = "flowers" />
<plants category = "shrubs">
</plants>
</garden>

Element Attribute Rules


Following are the rules that need to be followed for attributes −
An attribute name must not appear more than once in the same start-tag or empty-element tag.
An attribute must be declared in the Document Type Definition (DTD) using an Attribute-List
Declaration.
Attribute values must not contain direct or indirect entity references to external entities.
The replacement text of any entity referred to directly or indirectly in an attribute value must not
contain a less than sign (<)

4.Explain Document Type Definition?


Ans: The XML Document Type Declaration, commonly known as DTD, is a way to describe XML
language precisely. DTDs check vocabulary and validity of the structure of XML documents against
grammatical rules of appropriate XML language.
An XML DTD can be either specified inside the document, or it can be kept in a separate document
and then liked separately.
Syntax
Basic syntax of a DTD is as follows −
<!DOCTYPE element DTD identifier
[
declaration1
declaration2
........
]>
In the above syntax,
The DTD starts with <!DOCTYPE delimiter.
An element tells the parser to parse the document from the specified root element.
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.
Internal 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 an external source.
Syntax
Following is the syntax of internal DTD −
<!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>Sam</name>
<company>MICRO</company>
<phone>(011) 123-4567</phone>
</address>
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 valid 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 "address.dtd">
<address>
<name>Sam</name>
<company>MICRO</company>
<phone>(011) 123-4567</phone>
</address>

The content of the DTD file address.dtd is as shown −

<!ELEMENT address (name,company,phone)>


<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>

5.Explain XML SCHEMA ?


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.
Syntax
Declare a schema in XML document as follows −
Example
The following example shows how to use schema −
<?xml version = "1.0" encoding = "UTF-8"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
<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.

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"/>
Definition Types
Defining XML schema elements in the following ways −
Simple Type
Simple type element is used only in the context of the text. Some of the predefined simple types are:
xs:integer, xs:boolean, xs:string, xs:date. For example −
<xs:element name = "phone_number" type = "xs:int" />
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.

6. Explain Document Object Model?


Ans: An XML document is always descriptive. The tree structure is often referred to as XML Tree
and plays an important role to describe any XML document easily.
The tree structure contains root (parent) elements, child elements and so on. By using tree structure,
you can get to know all succeeding branches and sub-branches starting from the root. The parsing
starts at the root, then moves down the first branch to an element, take the first branch from there, and
so on to the leaf nodes.
Example
Following example demonstrates simple XML tree structure −

<?xml version = "1.0"?>


<Company>
<Employee>
<FirstName>Tanmay</FirstName>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
<Email>tanmaypatil@xyz.com</Email>
<Address>
<City>Bangalore</City>
<State>Karnataka</State>
<Zip>560212</Zip>
</Address>
</Employee>
</Company>
Following tree structure represents the above XML document −

XML Trees Structure

In the above diagram, there is a root element named as <company>. Inside that, there is one more
element <Employee>. Inside the employee element, there are five branches named <FirstName>,
<LastName>, <ContactNo>, <Email>, and <Address>. Inside the <Address> element, there are three
sub-branches, named <City> <State> and <Zip>.
The Document Object Model (DOM) is the foundation of XML. XML documents have a hierarchy
of informational units called nodes; DOM is a way of describing those nodes and the relationships
between them.
A DOM document is a collection of nodes or pieces of information organized in a hierarchy. 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.
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.
4 MARKS
1.Explain XHTML ?
Ans: XHTML stands for EXtensible HyperText Markup Language. It is the next step in the evolution
of the internet. The XHTML 1.0 is the first document type in the XHTML family.

XHTML is almost identical to HTML 4.01 with only few differences. This is a cleaner and stricter
version of HTML 4.01. If you already know HTML, then you need to give little attention to learn this
latest version of HTML.

XHTML was developed by World Wide Web Consortium (W3C) to help web developers make the
transition from HTML to XML. By migrating to XHTML today, web developers can enter the XML
world with all of its benefits, while still remaining confident in the backward and future compatibility
of the content.
Benefits of XHTML:
XHTML documents are XML conforming as they are readily viewed, edited, and validated with
standard XML tools.
XHTML documents can be written to operate better than they did before in existing browsers as well
as in new browsers.
XHTML documents can utilize applications such as scripts and applets that rely upon either the
HTML Document Object Model or the XML Document Object Model.
XHTML gives you a more consistent, well-structured format so that your webpages can be easily
parsed and processed by present and future web browsers.
You can easily maintain, edit, convert and format your document in the long run.
Since XHTML is an official standard of the W3C, your website becomes more compatible with many
browsers and it is rendered more accurately.
XHTML combines strength of HTML and XML. Also, XHTML pages can be rendered by all XML
enabled browsers.

XHTML syntax is very similar to HTML syntax and almost all the valid HTML elements are valid in
XHTML as well. But when you write an XHTML document, you need to pay a bit extra attention to
make your HTML document compliant to XHTML.

Here are the important points to remember while writing a new XHTML document or converting
existing HTML document into XHTML document −

Write a DOCTYPE declaration at the start of the XHTML document.


Write all XHTML tags and attributes in lower case only.
Close all XHTML tags properly.
Nest all the tags properly.
Quote all the attribute values.
Forbid Attribute minimization.
Replace the name attribute with the id attribute.
Deprecate the language attribute of the script tag.

2. Explain DOCTYPE Declaration ?


Ans: All XHTML documents must have a DOCTYPE declaration at the start. There are three types
of DOCTYPE declarations, which are discussed in detail in XHTML Doctypes chapter. Here is an
example of using DOCTYPE −
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Case Sensitivity
XHTML is case sensitive markup language. All the XHTML tags and attributes need to be written in
lower case only.
<!-- This is invalid in XHTML -->
<A Href="/xhtml/xhtml_tutorial.html">XHTML Tutorial</A>
<!-- Correct XHTML way of writing this is as follows -->
<a href="/xhtml/xhtml_tutorial.html">XHTML Tutorial</a>
In the example, Href and anchor tag A are not in lower case, so it is incorrect.

Closing the Tags


Each and every XHTML tag should have an equivalent closing tag, even empty elements should also
have closing tags. Here is an example showing valid and invalid ways of using tags −

<!-- This is invalid in XHTML -->


<p>This paragraph is not written according to XHTML syntax.

<!-- This is also invalid in XHTML -->


<img src="/images/xhtml.gif" >
The following syntax shows the correct way of writing above tags in XHTML. Difference is that, here
we have closed both the tags properly.
<!-- This is valid in XHTML -->
<p>This paragraph is not written according to XHTML syntax.</p>
<!-- This is also valid now -->
<img src="/images/xhtml.gif" />
Attribute Quotes
All the values of XHTML attributes must be quoted. Otherwise, your XHTML document is assumed
as an invalid document. Here is the example showing syntax −
<!-- This is invalid in XHTML -->
<img src="/images/xhtml.gif" width=250 height=50 />
<!-- Correct XHTML way of writing this is as follows -->
<img src="/images/xhtml.gif" width="250" height="50" />
Attribute Minimization
XHTML does not allow attribute minimization. It means you need to explicitly state the attribute and
its value. The following example shows the difference −
<!-- This is invalid in XHTML -->
<option selected>

<!-- Correct XHTML way of writing this is as follows -->


<option selected="selected">
The following example shows you a minimum content of an XHTML 1.0 document −
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/TR/xhtml1" xml:lang="en" lang="en">
<head>
<title>Every document must have a title</title>
</head>
<body>
...your content goes here...
</body>
</html>

3.Explain DOM and SAX ?

Ans: An XML parser is a software library or package that provides interfaces for client applications
to work with an XML document. The XML Parser is designed to read the XML and create a way for
programs to use XML.

XML parser validates the document and check that the document is well formatted.

Types of XML Parsers


These are the two main types of XML Parsers:
DOM
SAX
DOM (Document Object Model)
A DOM document is an object which contains all the information of an XML document. It is
composed like a tree structure. The DOM Parser implements a DOM API. This API is very simple to
use.
Features of DOM Parser
A DOM Parser creates an internal structure in memory which is a DOM document object and the
client applications get information of the original XML document by invoking methods on this
document object.
DOM Parser has a tree based structure.
Advantages
It supports both read and write operations and the API is very simple to use.
It is preferred when random access to widely separated parts of a document is
required.
Disadvantages
1) It is memory inefficient. (consumes more memory because the whole XML document needs to
loaded into memory).
It is comparatively slower than other parsers.
SAX (Simple API for XML)
A SAX Parser implements SAX API. This API is an event based API and less intuitive.
Features of SAX Parser
It does not create any internal structure.
Clients does not know what methods to call, they just overrides the methods of the API and place his
own code inside method.
It is an event based parser, it works like an event handler in Java.
Advantages
It is simple and memory efficient.
It is very fast and works for huge documents.
Disadvantages
It is event-based so its API is less intuitive.
Clients never know the full information because the data is broken into pieces.

4.Explain DOM and SAX Parsers in java with Example?

Ans: A DOM XML parser read below XML file and print out each elements one by one.
File : file.xml
<?xml version="1.0"?>
<company>
<staff>
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff>
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
</company>

File : ReadXMLFile.java – A Java class to read above XML file.


import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
File fXmlFile = new File("c:\\file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("-----------------------");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
System.out.println("First Name : " +
getTagValue("firstname", eElement));
System.out.println("Last Name : " + getTagValue("lastname", eElement));
System.out.println("Nick Name : " + getTagValue("nickname", eElement));
System.out.println("Salary : " + getTagValue("salary", eElement));
}}
} catch (Exception e) {
e.printStackTrace();
}}
private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}}
2. Result
Root element :company
-----------------------
First Name : yong
Last Name : mook kim
Nick Name : mkyong
Salary : 100000
First Name : low
Last Name : yin fong
Nick Name : fong fong
Salary : 200000

Each parser works differently with DOM parser, it either loads any XML document into memory or
creates any object representation of the XML document. Instead, the SAX parser uses callback
function (org.xml.sax.helpers.DefaultHandler) to informs clients of the XML document structure
XML file
Create a simple XML file.
<?xml version="1.0"?>
<company>
<staff>
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff>
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
</company>

5.Difference between DOM and SAX XML Parser?


Ans: DOM parser loads whole XML document in memory while SAX only loads a small part of the
XML file in memory.
DOM parser is faster than SAX because it loads whole XML document in memory.
Since DOM loads whole document in memory so it is memory dependent and is not suitable for large
XML files. Whereas SAX is event based and loads only a part of XML file in memory so it is suitable
for large XML files.
DOM parser works on Document Object Model while SAX is an event based XML parser. In DOM,
there are no events triggered while parsing. The entire XML is parsed and a DOM tree is generated.
DOM can insert or delete nodes. SAX is read only.
Backward and forward search is possible in DOM parser and you can query tags of whole
document. So navigation is easier in DOM.
SAX reads document from top to bottom, so backward navigation is not possible.
Java file
Use SAX parser to parse the XML file.
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class ReadXMLFile {
public static void main(String argv[]) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
DefaultHandler handler = new DefaultHandler() {
boolean bfname = false;
boolean blname = false;
boolean bnname = false;
boolean bsalary = false;
public void startElement(String uri, String localName,String qName,
Attributes attributes) throws SAXException {
System.out.println("Start Element :" + qName);
if (qName.equalsIgnoreCase("FIRSTNAME")) {
bfname = true;
}
if (qName.equalsIgnoreCase("LASTNAME")) {
blname = true;
}
if (qName.equalsIgnoreCase("NICKNAME")) {
bnname = true;
}
if (qName.equalsIgnoreCase("SALARY")) {
bsalary = true;
}
}
public void endElement(String uri, String localName, String qName) throws SAXException {
System.out.println("End Element :" + qName);
}
public void characters(char ch[], int start, int length) throws SAXException {
if (bfname) {
System.out.println("First Name : " + new String(ch, start, length));
bfname = false;
}
if (blname) {
System.out.println("Last Name : " + new String(ch, start, length));
blname = false;
}
if (bnname) {
System.out.println("Nick Name : " + new String(ch, start, length));
bnname = false;
}
if (bsalary) {
System.out.println("Salary : " + new String(ch, start, length));
bsalary = false;
}
}
};
saxParser.parse("c:\\file.xml", handler);
}catch (Exception e) {
e.printStackTrace();
}
}
}
Result
Start Element :company
Start Element :staff
Start Element :firstname
First Name : yong
End Element :firstname
Start Element :lastname
Last Name : mook kim
End Element :lastname
Start Element :nickname
Nick Name : mkyong
End Element :nickname
Start Element :salary
Salary : 100000
End Element :salary
End Element :staff
Start Element :staff
Start Element :firstname
First Name : low
End Element :firstname
Start Element :lastname
Last Name : yin fong
End Element :lastname
Start Element :nickname
Nick Name : fong fong
End Element :nickname
Start Element :salary
Salary : 200000
End Element :salary
End Element :staff
End Element :company

SAX Parser is faster and uses less memory than DOM parser
UNIT -3
2 MARKS
1.What are Servlets?

Ans: Servlets are the Java programs that runs on the Java-enabled web server or application server.
They are used to handle the request obtained from the web server, process the request, produce the
response, then send response back to the web server.
Properties of Servlets :
Servlets work on the server-side.
Servlets are capable of handling complex requests obtained from web server.

Execution of Servlets :
Execution of Servlets involves six basic steps:
The clients send the request to the web server.
The web server receives the request.
The web server passes the request to the corresponding servlet.
The servlet processes the request and generates the response in the form of output.
The servlet sends the response back to the web server.
The web server sends the response back to the client and the client browser displays it on the screen.
Servlet Architecture
The following diagram shows the servlet architecture:

Need For Server-Side Extensions

The server-side extensions are nothing but the technologies that are used to create dynamic Web
pages. Actually, to provide the facility of dynamic Web pages, Web pages need a container or Web
server. To meet this requirement, independent Web server providers offer some proprietary solutions
in the form of APIs(Application Programming Interface).
These APIs allow us to build programs that can run with a Web server. In this case , Java Servlet is
also one of the component APIs of Java Platform Enterprise Edition which sets standards for creating
dynamic Web applications in Java.

2.Explain CGI?
Ans:CGI is actually an external application which is written by using any of the programming
languages likeC or C++ and this is responsible for processing client requests and generating dynamic
content.
In CGI application, when a client makes a request to access dynamic Web pages, the Web server
performs the following operations :
It first locates the requested web page i.e the required CGI application using URL.
It then creates a new process to service the client’s request.
Invokes the CGI application within the process and passes the request information to the server.
Collects the response from CGI application.

Destroys the process, prepares the HTTP response and sends it to the client.

So, in CGI server has to create and destroy the process for every request. It’s easy to understand that
this approach is applicable for handling few clients but as the number of clients increases, the
workload on the server increases and so the time taken to process requests increases.

3.Difference Between Servlet and CGI?

SERVLET CGI(COMMON GATEWAY INTERFACE)

Servlets are portable and efficient. CGI is not portable

In Servlets, sharing of data is possible. In CGI, sharing of data is not possible.

Servlets can directly communicate with the web CGI cannot directly communicate with the web
server. server.

Servlets are less expensive than CGI. CGI are more expensive than Servlets.

Servlets can handle the cookies. CGI cannot handle the cookies.

4.Difference between Applets and Servlets?


APPLETS SERVLETS

A Java applet is a small application which is A servlet is a Java programming language


written in Java and delivered to users in the class used to extend the capabilities of a
form of bytecode. server.

Applets are executed on client side. Servlets are executed on server side.

Applets are used to provide interactive


features to web applications that cannot be Servlets are the Java counterpart to other
provided by HTML alone like capture mouse dynamic Web content technologies such as
input etc. PHP and ASP.NET.

Life cycle of Applets init(), stop(), paint(), Lifecycle of servlets are:- init( ), service( ),
start(), destroy(). and destroy( ).
APPLETS SERVLETS

Packages available in servlets are:- import


Packages available in Applets are :- import javax.servlet.*; and import
java.applet.*; and import java.awt.*. java.servlet.http.*;

Applets use user interface classes like AWT


and Swing. No User interface required.

Applets are more prone to risk as it is on the


client machine. Servlets are under the server security.

Applets utilize more network bandwidth as it Servlets are executed on the servers and
executes on the client machine. hence require less bandwidth.

It accepts input from browser and generates


Requires java compatible browser for response in the form of HTML Page,
execution. Javascript Object, Applets etc.

5.Explain Life Cycle of a Servlet?


Ans: The entire life cycle of a Servlet is managed by the Servlet container which uses
the javax.servlet.Servlet interface to understand the Servlet object and manage it. So, before creating
a Servlet object, let’s first understand the life cycle of the Servlet object which is actually
understanding how the Servlet container manages the Servlet object.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four stages,
Loading a Servlet.
Initializing the Servlet.
Request handling.
Destroying the Servlet.
Let’s look at each of these stages in details:
Loading a Servlet: The first stage of the Servlet lifecycle involves loading and initializing the Servlet
by the Servlet container. The Web container or Servlet Container can load the Servlet at either of the
following two stages :
Initializing the context, on configuring the Servlet with a zero or positive integer value.
If the Servlet is not preceding stage, it may delay the loading process until the Web container
determines that this Servlet is needed to service a request.
The Servlet container performs two operations in this stage :
Loading : Loads the Servlet class.
Instantiation : Creates an instance of the Servlet. To create a new instance of the Servlet, the
container uses the no-argument constructor.
Initializing a Servlet: After the Servlet is instantiated successfully, the Servlet container initializes the
instantiated Servlet object. The container initializes the Servlet object by invoking
the Servlet.init(ServletConfig) method which accepts ServletConfig object reference as parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method only once, immediately after
the Servlet.init(ServletConfig) object is instantiated successfully. This method is used to initialize the
resources, such as JDBC datasource.

Now, if the Servlet fails to initialize, then it informs the Servlet container by throwing
the ServletException or UnavailableException.
Handling request: After initialization, the Servlet instance is ready to serve the client requests. The
Servlet container performs the following operations when the Servlet instance is located to service a
request :
It creates the ServletRequest and ServletResponse objects. In this case, if this is a HTTP
request, then the Web container creates HttpServletRequest and HttpServletResponse objects
which are subtypes of the ServletRequest and ServletResponse objects respectively.
After creating the request and response objects it invokes the Servlet.service(ServletRequest,
ServletResponse) method by passing the request and response objects.
The service() method while processing the request may throw
the ServletException or UnavailableException or IOException.
Destroying a Servlet: When a Servlet container decides to destroy the Servlet, it performs the
following operations,
It allows all the threads currently running in the service method of the Servlet instance to
complete their jobs and get released.
After currently running threads have completed their jobs, the Servlet container calls
the destroy() method on the Servlet instance.
After the destroy() method is executed, the Servlet container releases all the references of this Servlet
instance so that it becomes eligible for garbage collection.

3 MARkS

1.Explain Servlet Life Cycle Methods?

Ans: There are three life cycle methods of a Servlet :


init()
service()
destroy()

Let’s look at each of these methods in details:


1.init() method: The Servlet.init() method is called by the Servlet container to indicate that this Servlet
instance is instantiated successfully and is about to put into service.
//init() method

public class MyServlet implements Servlet{


public void init(ServletConfig config) throws ServletException {
//initialization code
}
//rest of code
}
service() method: The service() method of the Servlet is invoked to inform the Servlet about the client
requests.
This method uses ServletRequest object to collect the data requested by the client.
This method uses ServletResponse object to generate the output content.
// service() method

public class MyServlet implements Servlet{


public void service(ServletRequest res, ServletResponse res)
throws ServletException, IOException {

// request handling code


}
// rest of code
}
3.destroy() method: The destroy() method runs only once during the lifetime of a Servlet and signals
the end of the Servlet instance.
//destroy() method
public void destroy()
As soon as the destroy() method is activated, the Servlet container releases the Servlet instance.
2. Compare GET vs. POST ?

3.Explain Deploying a Servlet?


Ans:To create a Servlet application the following steps required.These steps are common for all the
Web server. Apache Tomcat is an open source web server for testing servlets and JSP technology
The steps are as follows:
Create a directory structure
Create a Servlet
Compile the Servlet
Create a deployment descriptor
Start the server and deploy the project
Access the servlet

1.Create a directory structures

The directory structure defines that where to put the different types of files so that web container
may get the information and respond to the client.

The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's see
the directory structure that must be followed to create the servlet.

As you can see that the servlet class file must be in the classes folder. The web.xml file must be under
the WEB-INF folder.
2.Create a Servlet
There are three ways to create the servlet.
By implementing the Servlet interface
By inheriting the GenericServlet class
By inheriting the HttpServlet class
The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests suc
doGet(), doPost, doHead() etc.

DemoServlet.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
//writing html in the stream
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
pw.close();//closing the stream
}}
3)Compile the servlet
For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files:

Jar file Server

servlet-api.jar Apache Tomcat

Two ways to load the jar file


set classpath
paste the jar file in JRE/lib/ext folder
Put the java file in any folder. After compiling the java file, paste the class file of servlet in WEB-
INF/classes directory.
4)Create the deployment descriptor (web.xml file)
The deployment descriptor is an xml file, from which Web Container gets the information about the
servet to be invoked.
The web container uses the Parser to get the information from the web.xml file. There are many xml
parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here is given some necessary elements to run the simple
servlet program.

web.xml file
<web-app>
<servlet>
<servlet-name>Example</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Example </servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Description of the elements of web.xml file
<web-app> represents the whole application.
<servlet> is sub element of <web-app> and represents the servlet.
<servlet-name> is sub element of <servlet> represents the name of the servlet.
<servlet-class> is sub element of <servlet> represents the class of the servlet.
<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet.

5)Start the Server and deploy the project


To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin directory.
6) How to access the servlet
Open browser and write http://hostname:portno/contextroot/urlpatternofservlet. For example:
http://localhost:9999/DemoServlet/welcome
4. Explain Interfaces of javax.servlet in Servlet API ?
Ans:Servlet API consists of two important packages that encapsulates all the important classes and
interface, namely :
javax.servlet
javax.servlet.http
javax.servlet

Interfaces
Servlet – Declares life cycle methods for a servlet.
ServletConfig – To get initialization parameters
ServletContext- To log events and access information
ServletRequest- To read data from a client request
ServletResponse – To write data from client response

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.
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,ServletRespons It is invoked at each request by the web
e container.
response)
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 java.io.*; import javax.servlet.*;


public class First implements Servlet{ ServletConfig config=null;
public void init(ServletConfig config){ this.config=config; System.out.println("servlet is
initialized");
}
public void service(ServletRequest req,ServletResponse res) throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter(); out.print("<html><body>"); out.print("<b>hello KALPANA</b>");
out.print("</body></html>");
}
public void destroy(){
System.out.println("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 b.xml(Deployment Descriptor).
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 ServletContext object is created by the web container.
ServletContext object is used to get configuration information from Deployment
Descriptor(web.xml) 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 javax.servlet.ServletRequest 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.

5.Explain Classes of javax.servlet in Servlet API ?


Ans: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(ServletConfigconfig) 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
super.init(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 b.xml 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 ServletResponse 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.
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
’tate may be corrupted.
5 MARKS
1.Explain javax.servlet.http in Servlet API ?
Ans:
javax.servlet.http

Interfaces

HttpServletRequest
HttpServletResponse
HttpSession
Classes
1.HttpServlet 2.Cookie

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.
requestURI – URL sent by browser

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


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.
Set Headers –
Headers for the response can be set by calling setHeader, specifying the name and value of the header
to be set.
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.
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 methods.Data
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:
doGet(), if the servlet supports HTTP GET requests
doPost(), for HTTP POST requests
doPut(), for HTTP PUT requests
doDelete(), for HTTP DELETE requests
Init() and destroy(), to manage resources that are held for the life of the servlet
getServletInfo(), which the servlet uses to provide information about itself

Cookie
A cookie is a small piece of information that is persisted between the multiple client requests.
javax.servlet.http.Cookie 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.

2. Explain Reading Servlet parameters ?


Ans: The parameters are the way in which a client or user can send information to the Http Server.
The HTTPServletRequest 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:
http://www.test.com/hello?key1=value1&key2=value2
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 Data using Servlet:
Servlets handles form data parsing automatically using the following methods depending on the
situation:
getParameter(): You call request.getParameter() method to get the value of a form parameter.
getParameterValues(): Call this method if the parameter appears more than once and returns
multiple values, for example checkbox.
getParameterNames(): Call this method if you want a complete list of all parameters in the current
request.
Now create a HTML page Hello.htmland 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>
Sending Data to Client:
Obtain a PrintWriter object HTTPServletResponse that can send character text to the client.
PrintWriterpw = response.getWriter(); pw.println(―Hello world‖);
POST method example
Let us consider HelloForm.java
import java.io.*; import java.util.*;
import javax.servlet.http.*;
public class HelloForm extends HTTPServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException{
PrintWriter pw = response.getWriter(); pw.print("<html><body>");
pw.print("Name: "+request.getParameter("first_name") +request.getParameter("last_name"));
pw.print("</body></html>");
pw.close();
}
}
Compile HelloForm.java as follows: $javac HelloForm.java Compilation would produce
HelloForm.class file.
Next you would have to copy this class file in
<Tomcat- installation-directory>/webapps/ROOT/WEB-INF/classes Create following entries in
web.xml file located in
<Tomcat- installation-directory>/webapps/ROOT/WEB-INF/

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

Now create a HTML page Hello.htmland 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>

When you access http://localhost:8080/Hello.html, then output of the above form.


First Name: Last Name:
Kalpana
chawla
Submit
Start Tomcat Server and open browser.
Now enter firstname and lastname, Click Submit It will generate result
Name: Kalpanachawla

3. Explain Reading Initialization parameters?


Ans: 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 web.xml file.
If the configuration information is modified from the web.xml 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@gamil.com</param-value>
</init-param>
......
</servlet>
</web-app>
Retrieve ServletConfig
ServletConfigsc = getServletConfig(); out.println(sc.getInitParameter("email"));

Ex: we b.xml
<web-app>
servlet>
<servlet-name>TestInitParam</servlet-name>
<servlet-class>TestInitParam</servlet-class>
<init-param>
<param-name>email</param-name>
<param-value>kalpana@gmail.com</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>TestInitParam</servlet-name>
<url-pattern>/TestInitParam</url-pattern>
</servlet- mapping>
</web-app>
TestInitParam.java import java.io.*; import javax.servlet.*;
import javax.servlet.http.*;
public class TestInitParam extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter();
ServletConfigsc=getServletConfig();
out.print("<html><body>"); out.print("<b>"+sc.getInitParameter("email")+"</b>");
out.print("</body></html>");
out.close();
}
}
It will generate result

kalpana@gmail.com

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 web.xml 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 web.xml file using the
<context-param> element.

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 web.xml file, so if the information is changed, we don't need
to modify the servlet. Thus it removes maintenance problem.

Uses
The object of ServletContext provides an interface between the container and servlet.
The ServletContext object can be used to get configuration information from the web.xml file.
The ServletContext object can be used to set, get or remove attribute from the web.xml file.
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 b.xml
<web-app>
<context-param>
<param-name>driverName</param-name>
<param-value>sun.jdbc.JdbcOdbcDriver</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>
TestServletContext.java
import java.io.*; import javax.servlet.*;
import javax.servlet.http.*;
public class TestServletContext extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException { response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter(); ServletContextsc = getServletContext();
out.println(sc.getInitParameter("driverName"));
}
}

It will generate result

sun.jdbc.JdbcOdbcDriver

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

4. Explain Handling Http Request & Responses


Ans: HTTP REQUEST
An HTTP client sends an HTTP request to a server in the form of a request message which includes
following format:
A Request-line
Zero or more header (General|Request|Entity) fields followed by CRLF
An empty line (i.e., a line with nothing preceding the CRLF)
indicating the end of the header fields
Optionally a message-body

The following sections explain each of the entities used in an HTTP request message.

Request-Line
The Request-Line begins with a method token, followed by the Request-URI and the protocol version,
and ending with CRLF. The elements are separated by space SP characters.
Request-Line = Method SP Request-URI SP HTTP-Version CRLF

Request Method
The request method indicates the method to be performed on the resource identified by the
given Request-URI. The method is case-sensitive and should always be mentioned in uppercase. The
following table lists all the supported methods in HTTP/1.1.
S.N. Method and Description

1 GET
The GET method is used to retrieve information from the given server using a given URI.
Requests using GET should only retrieve data and should have no other effect on the data.

2 HEAD
Same as GET, but it transfers the status line and the header section only.

3 POST
A POST request is used to send data to the server, for example, customer information, file
upload, etc. using HTML forms.

4 PUT
Replaces all the current representations of the target resource with the uploaded content.

5 DELETE
Removes all the current representations of the target resource given by URI.

6 CONNECT
Establishes a tunnel to the server identified by a given URI.

7 OPTIONS
Describe the communication options for the target resource.

8 TRACE
Performs a message loop back test along with the path to the target resource.

Request-URI
The Request-URI is a Uniform Resource Identifier and identifies the resource upon which to apply
the request. Following are the most commonly used forms to specify an URI:
Request-URI = "*" | absoluteURI | abs_path | authority

S.N. Method and Description


1 The asterisk * is used when an HTTP request does not apply to a particular resource, but
to the server itself, and is only allowed when the method used does not necessarily apply
to a resource. For example:
OPTIONS * HTTP/1.1

2 The absoluteURI is used when an HTTP request is being made to a proxy. The proxy is
requested to forward the request or service from a valid cache, and return the response.
For example:
GET http://www.w3.org/pub/WWW/TheProject.html HTTP/1.1

3 The most common form of Request-URI is that used to identify a resource on an origin
server or gateway. For example, a client wishing to retrieve a resource directly from the
origin server would create a TCP connection to port 80 of the host "www.w3.org" and
send the following lines:
GET /pub/WWW/TheProject.html HTTP/1.1
Host: www.w3.org
Note that the absolute path cannot be empty; if none is present in the original URI, it
MUST be given as "/" (the server root).

Request Header Fields.


The request-header fields allow the client to pass additional information about the request, and about
the client itself, to the server. These fields act as request modifiers.Here is a list of some important
Request-header fields that can be used based on the requirement:
Accept-Charset
Accept-Encoding
Accept-Language
Authorization
Expect
From
Host
If-Match
If-Modified-Since
If-None-Match
If-Range
If-Unmodified-Since
Max-Forwards
Proxy-Authorization
Range
Referer
TE
User-Agent
HTTP RESPONSE:
After receiving and interpreting a request message, a server responds with an HTTP response
message:
A Status-line
Zero or more header (General|Response|Entity) fields followed by CRLF
An empty line (i.e., a line with nothing preceding the CRLF)
indicating the end of the header fields
Optionally a message-body
The following sections explain each of the entities used in an HTTP response message.

Message Status-Line
A Status-Line consists of the protocol version followed by a numeric status code and its associated
textual phrase. The elements are separated by space SP characters.
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF

HTTP Version
A server supporting HTTP version 1.1 will return the following version information:
HTTP-Version = HTTP/1.1

Status Code
The Status-Code element is a 3-digit integer where first digit of the Status-Code defines the class of
response and the last two digits do not have any categorization role. There are 5 values for the first
digit:
S.N. Code and Description

1 1xx: Informational
It means the request was received and the process is continuing.

2 2xx: Success
It means the action was successfully received, understood, and accepted.

3 3xx: Redirection
It means further action must be taken in order to complete the request.

4 4xx: Client Error


It means the request contains incorrect syntax or cannot be fulfilled.

5 5xx: Server Error


It means the server failed to fulfill an apparently valid request.

HTTP status codes are extensible and HTTP applications are not required to understand the meaning
of all registered status codes. A list of all the status codes has been given in a separate chapter for
your reference.

Response Header Fields


The response-header fields allow the server to pass additional information about the response which
cannot be placed in the Status- Line. These header fields give information about the server and about
further access to the resource identified by the Request-URI.
Accept-Ranges
Age
ETag
Location
Proxy-Authenticate
Retry-After
Server
Vary
WWW-Authenticate

5. Explain Cookies and Sessions?


Ans: 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.

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:
Server script sends a set of cookies to the browser in response header.
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 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:
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.

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=new Cookie("user","kalpana ");//creating cookie object response.addCookie(ck);//adding
cookie in the response

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

Get Cookies
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++)
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());

//printing name and value of cookie

Sending the Cookie into the HTTP response headers:


We use response.addCookie to add cookies in the HTTP response header as follows:
response.addCookie(cookie);

Ex: List and AddCookie.java


import java.io.*; import javax.servlet.*;
import javax.servlet.http.*;
public class ListandAddCookieextends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html"); PrintWriter out = response.getWriter(); Cookie cookie = null;
out.println("<html><body>"+
"<form method='get' action='/mrcet/CookieLab'>"+ "Name:<input type='text' name='user' /><br/>"+
"Password:<input type='text' name='pass' ><br/>"+ "<input type='submit' value='submit'>"+
"</form>");

String name = request.getParameter("user"); String pass = request.getParameter("pass");

if(!pass.equals("") || !name.equals("")) { Cookie ck = new Cookie(name,pass);


response.addCookie(ck);
}

Cookie[] cookies = request.getCookies(); if( cookies != null ){


out.println("<h2> Found Cookies Name and Value</h2>"); for (inti = 0; i<cookies.length; i++){
cookie = cookies[i];
out.print("Cookie Name : " + cookie.getName() + ", "); out.print("Cookie Value: " +
cookie.getValue()+" <br/>");
}
}
out.println("</body></html>");
}
}

web.xml
<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.
Get the HttpSession object

The HttpServletRequest interface provides two methods to get the object of HttpSession:
publicHttpSessiongetSession():Returns the current session associated with this request, or if the
request does not have a session, creates one.
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
session.invalidate();

Set/Get data in session


session.setAttribute(name,value); session.getAttribute(name);

Methods
public String getId():Returns a string containing the unique identifier value.
public long getCreationTime():Returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
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.
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.

Ex: SessionTrack.java
import java.io.*; importjavax.servlet.*; importjavax.servlet.http.*;
public class SessionTrack extends HttpServlet { public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Create a session object if it is already not created.
HttpSession session = request.getSession(true);

String title = "Welcome to my website"; String userID = "";


Integer visitCount = new Integer(0);

if (session.isNew())
{
userID = "Kalpana"; session.setAttribute("UserId", "Kalpana");
}
else {
visitCount = (Integer)session.getAttribute("visitCount"); visitCount = visitCount + 1;
userID = (String)session.getAttribute("UserId");
}
session.setAttribute("visitCount", visitCount);
response.setContentType("text/html"); PrintWriter out = response.getWriter();
out.println("<html>" +
"<body>" +
"<h1>Session Infomation</h1>" + "<table border='1'>" +
"<tr><th>Session info</th><th>value</th></tr>" + "<tr><td>id</td><td>" + session.getId() +
"</td></tr>" + "<tr><td>User ID</td<td>" + userID + ―</td></tr>" + "<tr><td>Number of
visits</td><td>" + visitCount + "</td></tr>" + "</table></body></html>");
}}
web.xml
<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:

6. Explain Connecting to a database using JDBC.

Ans: JDBC is an acronym for Java Database Connectivity. It’s an advancement for ODBC ( Open
Database Connectivity ). JDBC is an standard API specification developed in order to move data from
frontend to backend. This API consists of classes and interfaces written in Java. It basically acts as an
interface (not the one we use in Java) or channel between your Java program and databases i.e it
establishes a link between the two so that a programmer could send data from Java code and store it in
the database for future use.
Steps for connectivity between Java program and database
Loading the Driver
To begin with, you first need load the driver or register it before using it in the program . Registration
is to be done once in your program. You can register a driver in one of two ways mentioned below :
Class.forName() : Here we load the driver’s class file into memory at the runtime. No need of using
new or creation of object .The following example uses Class.forName() to load the Oracle driver –
Class.forName(“oracle.jdbc.driver.OracleDriver”);
DriverManager.registerDriver(): DriverManager is a Java inbuilt class with a static member
register. Here we call the constructor of the driver class at compile time . The following example uses
DriverManager.registerDriver()to register the Oracle driver –
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver())
Create the connections
After loading the driver, establish connections using :

Connection con = DriverManager.getConnection(url,user,password)


user – username from which your sql command prompt can be accessed.
password – password from which your sql command prompt can be accessed.
con: is a reference to Connection interface.
url : Uniform Resource Locator. It can be created as follows:
String url = “ jdbc:oracle:thin:@localhost:1521:xe”
Where oracle is the database used, thin is the driver used , @localhost is the IP Address where database
is stored, 1521 is the port number and xe is the service provider. All 3 parameters above are of String
type and are to be declared by programmer before calling the function. Use of this can be referred from
final code.
Create a statement
Once a connection is established you can interact with the database. The JDBCStatement,
CallableStatement, and PreparedStatement interfaces define the methods that enable you to send SQL
commands and receive data from your database.
Use of JDBC Statement is as follows:
Statement st = con.createStatement();
Here, con is a reference to Connection interface used in previous step .
Execute the query
Now comes the most important part i.e executing the query. Query here is an SQL Query . Now we
know we can have multiple types of queries. Some of them are as follows:
Query for updating / inserting table in a database.
Query for retrieving data .
The executeQuery() method of Statement interface is used to execute queries of retrieving values from
the database. This method returns the object of ResultSet that can be used to get all the records of a
table.
The executeUpdate(sql query) method ofStatement interface is used to execute queries of
updating/inserting .
Example:
int m = st.executeUpdate(sql);
if (m==1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
Here sql is sql query of the type String
5.Close the connections
So finally we have sent the data to the specified location and now we are at the verge of completion of
our task .
By closing connection, objects of Statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
Example :
con. End Element :salary
End Element :staff
Start Element :staff
Start Element :firstname
First Name : low
Last Name : yin fong
Start Element :nickname
Nick Name : fong fong
End Element :nickname
Start Element :salary
Salary : 200000
End Element :salary
End Element :staff
End Element :company

SAX Parser is faster and uses less memory than DOM parser

close();
Implementation
importjava.sql.*;
importjava.util.*;
class Main
{
public static void main(String a[])
{
//Creating the connection
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "system";
String pass = "12345";

//Entering the data


Scanner k = new Scanner(System.in);
System.out.println("enter name");
String name = k.next();
System.out.println("enter roll no");
int roll = k.nextInt();
System.out.println("enter class");
String cls = k.next();
//Inserting data using SQL query
String sql = "insert into student1 values('"+name+"',"+roll+",'"+cls+"')";
Connection con=null;
try
{
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());

//Reference to connection interface


con = DriverManager.getConnection(url,user,pass);

Statement st = con.createStatement();
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println("inserted successfully : "+sql);
else
System.out.println("insertion failed");
con.close();
}
catch(Exception ex)
{
System.err.println(ex);
}
}
}
Output –

UNIT 4
2 Marks
1.Define Features of JSP?

Ans: Features of JSP


Coding in JSP is easy :- As it is just adding JAVA code to HTML/XML.
Reduction in the length of Code :- In JSP we use action tags, custom tags etc.
Connection to Database is easier :-It is easier to connect website to database and allows to read or
write data easily to the database.
Make Interactive websites :- In this we can create dynamic web pages which helps user to interact
in realtime environment.
Portable, Powerful, flexible and easy to maintain :- as these are browser and server independent.
2.Explain Advantages and Disadvantages of JSP?

Ans: Advantages of using JSP


It does not require advanced knowledge of JAVA
It is capable of handling exceptions
Easy to use and learn
It can tags which are easy to use and understand
Implicit objects are there which reduces the length of code
It is suitable for both JAVA and non JAVA programmer

Disadvantages of using JSP


Difficult to debug for errors.
First time access leads to wastage of time
It’s output is HTML which lacks features.

3. Explain Scriptlets?

Ans: Scriptlets are blocks of Java code that get translated and placed in the _jspService() method.
Scriptlets start with <% and end with %>.
The following code snippet shows an example of using a scriplet
<%
if (true) {
out.println("true");
} else {
out.println("false");
}
%>.
4.Explain Directives in JSP?
Ans:
The jsp directives are messages that tells the web container how to translate a JSP page into the
correspondingservlet.
There are three types of directives:
page directive
include directive
taglib directive

Syntax for JSP Directive:


<%@ directive attribute="value" %>
5.Explain Expressions in JSP?

Ans: The code placed within JSP expression tag is written to the output stream of the response. So
you need not writeout.print() to write data. It is mainly used to print the values of variable or method.
Syntax of JSP expression Tag:
<%= statement %>
Example:
In this example of jsp expression tag, we are simply displaying a welcome message.

<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
3 MARKS
1.Expain JSP with and Example?
Ans: JSP is a server side technology that does all the processing at server. It is used for creating
dynamic web applications, using java as programming language.
Basically, any html file can be converted to JSP file by just changing the file extension from “.html”
to “.jsp”, itwould run just fine. What differentiates JSP from HTML is the ability to use java code inside
HTML. In JSP, youcan embed Java code in HTML using JSP tags. for e.g. run the code below, every
time you run this, it would display the current time. That is what makes this code dynamic.
It stands for Java Server Pages.
It is a server side technology.
It is used for creating web application.
It is used to create dynamic web content.
In this JSP tags are used to insert JAVA code into HTML pages.
It is an advanced version of Servlet Technology.
It is a Web based technology helps us to create dynamic and platform independent web pages.
In this, Java code can be inserted in HTML/ XML pages or both.
JSP is first converted into servlet by JSP container before processing the client’s request.
<%-- JSP comment --%>
<HTML>
<HEAD>
<TITLE>MESSAGE</TITLE>
</HEAD>
<BODY>
<%out.print("Hello, Sample JSP code");%>
</BODY>
</HTML>

2.Explain the Anatomy of a JSP Page?


Ans: The Anatomy of a JSP Page
A JSP page is simply a regular web page with JSP elements for generating the parts of the page that
differ for each request, as shown below
Everything in the page that is not a JSP element is called template text . Template text can really be
any text: HTML, WML, XML, or even plain text. Since HTML is by far the most common web page
language in use today, most of the descriptions and examples in this book are HTML-based, but keep
in mind that JSP has no dependency on HTML; it can be used with any markup language. Template
text is always passed straight through to the browser.

When a JSP page request is processed, the template text and the dynamic content generated by the
JSP elements aremerged, and the result is sent as the response to the browser.
Syntactic Elements
Syntactic elements are anything within a JSP page that need to be translated prior to compilation and
are recognized by the translator via a standard sets of characters that mark the beginning an end of the
syntactic element. Syntactic elements come in three flavours, these being:

Directives - Directive elements give the translator instructions on how a JSP page should be translated
into a servlet.
Scripting - Scripting elements incorporate code into a JSP page and can be either Java based or use
the Expression Language (EL).
Actions - Action elements incorporate code into a JSP page to perform some type of operation and
can be 'standard' actions that come as part of the container package or 'custom actions
Directives Overview
Directives are input into a JSP page using the directive start tag, followed by the directive name and
any directive attributes and terminated with the directive end tag. In total there are six directives in the
jsp specification these being page, include, taglib, tag, attribute and variable.
The following code shows examples of page directives, the whitespace after the @ symbol is optional
but aids readability. The comma symbol is used to delimit attributes.
LIFE CYCLE OF JSP:
3.Explain the Life Cycle of JSP?
Ans:JSP Life Cycle is defined as translation of JSP Page into servlet as a JSP Page needs to be
converted into servletfirst in order to process the service requests. The Life Cycle starts with the
creation of JSP and ends with the disintegration of that.

When the browser asks for a JSP, JSP engine first checks whether it needs to compile the page. If the
JSP is lastcompiled or the recent modification is done in JSP, then the JSP engine compiles the page.

Compilation process of JSP page involves three steps:

Parsing of JSP
Turning JSP into servlet
Compiling the servlet

JSP Lifecycle is depicted in the below diagram.

Following steps explain the JSP life cycle:

Translation of JSP page


Compilation of JSP page(Compilation of JSP page into _jsp.java)
Classloading (_jsp.java is converted to class file _jsp.class)
Instantiation(Object of generated servlet is created)
Initialisation(_jspinit() method is invoked by container)
Request Processing(_jspservice() method is invoked by the container)
Destroy (_jspDestroy() method invoked by the container)
4.Explain JSP PROCESSING/JSP ARCHITECTURE:
The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP container is
responsible for intercepting requests for JSP pages.Use of Apache which has built-in JSP container
to support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and other services a
JSP needs.It knows how to understand the special elements that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web application.

JSP Processing
The following steps explain how the web server creates the Webpage using JSP −
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine.
Thisis done by using the URL or JSP page which ends with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion
is very simple in which all template text is converted to println( ) statements and all JSP elements are
converted to Java code. This code implements the corresponding dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original request to a
servletengine.
A part of the web server called the servlet engine loads the Servlet class and executes it. During
execution,the servlet produces an output in HTML format. The output is furthur passed on to the web
server by theservlet engine inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML content.
Finally, the web browser handles the dynamically-generated HTML page inside the HTTP response
exactly as if it were a static page.
All the above mentioned steps can be seen in the following diagram −
Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and whether the
modification date on the JSP is older than the servlet. If the JSP is older than its generated servlet, the
JSP container assumes that the JSP hasn't changed and that the generated servlet still matches the
JSP's contents. This makes the process more efficient than with the other scripting languages (such as
PHP) and therefore faster.

So in a way, a JSP page is really just another way to write a servlet without having to be a Java
programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular servlet.

5.Explain Declarations in JSP?


Ans: Declaration tag is a block of java code for declaring class wide variables, methods and classes.
Whatever placedinside these tags gets initialized during JSP initialization phase and has class scope.
JSP container keeps this codeoutside of the service method (_jspService()) to make them class level
variables and methods.

As we know that variables can be initialized using scriptlet too but those declaration being
placed inside
_jspService() method which doesn’t make them class wide declarations. On the other side,
declaration tag can be used for defining class level variables, methods and classes.

Syntax of declaration tag:

<%! Declaration %>

In this example we have declared two variables inside declaration tag and displayed them on
clientusing expression tag.
<html>
<head>
<title>Declaration tag Example1</title>
</head>
<body>
<%! String name="Chaitanya"; %>
<%! int age=27; %>
<%= "Name is: "+ name %><br>
<%= "AGE: "+ age %>
</body>
</html>

Output:
5 MARKS

1.Explain Directives in JSP?

Ans: The jsp directives are messages that tells the web container how to translate a JSP page into the
correspondingservlet.

There are three types of directives:

page directive
include directive
taglib directive

Syntax for JSP Directive:


<%@ directive attribute="value" %>
JSP Page Directive:
The page directive defines attributes that apply to an entire JSP page.
Syntax for JSP Page Directive:
• <%@ p import
• contentType
• extends
• info
• buffer
• language
• isELIgnored
• isThreadSafe
• autoFlush
• session
• pageEncoding
• errorPage
• isErrorPage
age attribute="value" %>Attributes of JSP Page Directive:

import:
The import attribute is used to import class,interface or all the members of a package.It is similar to
importkeyword in java class or interface.
Example:
<html>
<body>
<%@ page import="java.util.Date" %>Today is: <%= new Date() %>
</body>
</html>

Content Type
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP
response.The default value is "text/html;charset=ISO-8859-1".
Example:

<html>
<body>
<%@ page contentType=application/msword %> Today is: <%= new java.util.Date() %>
</body>
</html>

extends:
The extends attribute defines the parent class that will be inherited by the generated servlet.It is rarely
used.
info:
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo()method of Servlet interface.

Example:
<html>
<body>
<%@ page info="composed by me" %>Today is: <%= new java.util.Date() %>
</body>
</html>
The web container will create a method getServletInfo() in the resulting servlet.For example:
public String getServletInfo()
{
return "composed by me ";
}

buffer:
The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.The
default sizeof the buffer is 8Kb.
Example:

<html>
<body>
<%@ page buffer="16kb" %>
Today is: <%= new java.util.Date() %>
</body>
</html>
language:
The language attribute specifies the scripting language used in the JSP page. The default value is
"java".
isELIgnored:
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value
is false i.e.Expression Language is enabled by default. We see Expression Language later.
<%@ page isELIgnored="true" %>//Now EL will be ignored
isThreadSafe:

Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP page, you can use
isThreadSafe attribute of page directive.The value of isThreadSafe value is true.If you make it false,
the web container will serialize the multiple requests, i.e. it will wait until the JSP finishes responding
to a request beforepassing another request to it.If you make the value of isThreadSafe attribute like:

<%@ page isThreadSafe="false" %>

The web container in such a case, will generate the servlet as:

public class SimplePage_jsp extends HttpJspBase


implements SingleThreadModel{
.......
}
errorPage:

The errorPage attribute is used to define the error page, if exception occurs in the current page, it will be
redirectedto the error page.
Example:
/index.jsp
<html>
<body>
<%@ page errorPage="myerrorpage.jsp" %>
<%= 100/0 %>
</body>
</html>

isErrorPage:
The isErrorPage attribute is used to declare that the current page is the error page.

Example:
<html>
<body>
<%@ page isErrorPage="true" %> Sorry an exception occured!<br/> The exception is: <%=
exception %>
</body>
</html>
Session:

Generally while building a user interactive JSP application, we make sure to give access to the user
to get holdof his/her personal data till the session is active. Consider an example of logging in into
your bank account, wecan access all of your data till we signout (or session expires). In order to
maintain session for a page the session attribute should be true.

This attribute is to handle HTTP sessions for JSP pages. It can have two values: true or false. Default
value for session attribute is true, which means if you do not mention this attribute, server may assume
that HTTP sessionis required for this page.

Default value for this attribute: true

Syntax of session attribute:


<%@ page session="value"%>
here value is either true OR false
Examples of session:
<%@ page session="true"%>
The above code would allow a page to have session implicit objects.
<%@ page session="false"%>
If this code is specified in a JSP page, it means session objects will not be available for that page.
Hence sessioncannot be maintained for that page.
autoflush:
If it is true it means the buffer should be flushed whenever it is full. false will throw an exception
when bufferoverflows.
Default value: True
Syntax of autoFlush:
<%@ page autoFlush="value"%>
value can be true or false.

Example of autoFlush attribute:

Buffer will be flushed out when it is full –

<%@ page autoFlush="true"%>


It will throw an exception when buffer is full due to overflow condition

<%@ page autoFlush="true"%>

pageEncoding:
pageEncoding is used to read correctly the file data characters available on OS file system
by JSP. If pageEncoding attribute is ignored by the Programmer, sometimes, it may
lead problems with Cyrillic and Chinese characters especially with PHP language.

A file may contain only text. Even still, it is after all, a sequence bytes. It should be informed to JSP
in what format the data is to be read from the file. It is denoted by pageEncoding where we write the
name of the charset(character set).

2.Explain JSP Directive?


Ans:Include Directive:
The include directive is used to include the contents of any resource it may be jsp file, html file or
text file. The include directive includes the original content of the included resource at page translation
time (the jsp page is translated only once so it will be better to include static resource).

Advantage of Include directive:


Code Reusability
Syntax of include directive:
<%@ include file="resourceName" %>
Example:
In this example, we are including the content of the header.html file. To run this example you must
create anheader.html file.
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>

JSP Taglib Directive:

The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag
Library Descriptor) file to define the tags. In the custom tag section we will use this tag so it will be
better to learn it in custom tag.

<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Example:
In this example, we are using our tag named currentDate. To use this tag we must specify the taglib
directive sothe container may get information about the tag.
<html>
<body>
<%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
<mytag:currentDate/>
</body>
</html>
Expressions in JSP
The code placed within JSP expression tag is written to the output stream of the response. So you
need not writeout.print() to write data. It is mainly used to print the values of variable or method.
Syntax of JSP expression Tag:
<%= statement %>Example:
In this example of jsp expression tag, we are simply displaying a welcome message.

<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>

Example of JSP expression Tag that prints current time:

To display the current time, we have used the getTime() method of Calendar class. The getTime() is
an instancemethod of Calendar class, so we have called it after getting the instance of Calendar class
by the getInstance() method.

index.jsp

<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>

Example of JSP expression Tag that prints user name:


In this example, we are printing the username using the expression tag. The index.html file gets the
usernameand sends the request to the welcome.jsp file, which displays the username.

index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html> Welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>

3.Explain Code Snippets?


Ans: JSP pages have ability to place fragments of java code directly in a jsp page. These Fragments
are known as codeSnippets or Scriptlet, and they simplified java developer’s transition in to web-
application developers. A scriptletcan contain any legal java code and must follow the syntactical rules
for java code and individual statements mustbe terminated by a semicolon.
Code Snippets are enclosed within the <% start tag and the %> end tag. Scriptlet allow HTML and
java code tobe freely intermixed, which can be useful for looping over data structures.
A scriptlet can contain any number of JAVA language statements, variable or method declarations,
orexpressions that are valid in the page scripting language.
Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple
and first
example for JSP
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
OUTPUT:
4. Explain JSP Scripting Elements?
The elements of JSP have been described below −
Scriptlet:
A scriptlet can contain any number of JAVA language statements, variable or method declarations,
orexpressions that are valid in the page scripting language.
Following is the syntax of Scriptlet −
<% code fragment %>
You can write the XML equivalent of the above syntax as follows −
<jsp:scriptlet> code fragment
</jsp:scriptlet>
Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple
and firstexample for JSP
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>

NOTE − Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and your environment
is setup as per environment setup tutorial.
Let us keep the above code in JSP file hello.jsp and put this file in C:\apache-
tomcat7.0.2\webapps\ROOT directory. Browse through the same using URL
http://localhost:8080/hello.jsp.The above code will generate the following result

Following example shows a JSP Expression −

<html>
<head><title>A Comment Test</title></head>

<body>
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
</body>
</html>
The above code will generate the following result −Today's date: 11-Sep-2010 21:24:25
JSP Comments
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful
when youwant to hide or "comment out", a part of your JSP page.
Following is the syntax of the JSP comments −
<%-- This is JSP comment --%>
Following example shows the JSP Comments −
<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>

4.Explain Implicit Objects?


Ans: JSP implicit objects are created during the translation phase of JSP to the servlet.
These objects can be directly used in scriplets that goes in the service method.
They are created by the container automatically, and they can be accessed using objects.
The Implicit Objects in JSP are the Java objects that the JSP Container makes available to the
developers in each page and the developer can call them directly without being explicitly declared. JSP
Implicit Objects are also called pre-defined variables.
Following table lists out the nine Implicit Objects that JSP supports −

S.No. Object & Description

1 request
This is the HttpServletRequest object associated with the request.

2
response
This is the HttpServletResponse object associated with the response to the client.

3 out
This is the PrintWriter object used to send output to the client.

4 session
This is the HttpSession object associated with the request.

5 application
This is the ServletContext object associated with the application context.
6 config
This is the ServletConfig object associated with the page.

7 pageContext
This encapsulates use of server-specific features like higher performance JspWriters.

8 page
This is simply a synonym for this, and is used to call the methods defined by the translated
servlet class.

9 Exception
The Exception object allows the exception data to be accessed by designated JSP.

The request Object

The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a


client requests apage the JSP engine creates a new object to represent that request.
The request object provides methods to get the HTTP header information including form data, cookies,
HTTP methods etc.

The response Object

The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the


server creates the request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP headers. Through
this object the JSP programmer can add new cookies or date stamps, HTTP status codes, etc.
The Out Object:

S.No. Method & Description

1 out.print(dataType dt)
Print a data type value

out.println(dataType dt)
2
Print a data type value then terminate the line with new line character.

out.flush()
3
Flush the stream.

The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send
content in a response.
The session Object

The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same
way that session objects behave under Java Servlets.
The session object is used to track client session between client requests.

The application Object

The application object is direct wrapper around the ServletContext object for the generated Servlet
and in reality an instance of a javax.servlet.ServletContext object.
This object is a representation of the JSP page through its entire lifecycle. This object is created when
the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy()
method.

The config Object

The config object is an instantiation of javax.servlet.ServletConfig and is a direct


wrapper around the ServletConfig object for the generated servlet.
This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters
such as the paths or file locations etc.
The following config method is the only one you might ever use, and its usage is trivial −
config.getServletName();
The pageContext Object

The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext


object is used torepresent the entire JSP page.
This object is intended as a means to access information about the page while avoiding most of the
implementation details.

The page Object

This object is an actual reference to the instance of the page. It can be thought of as an object that
represents the entireJSP page.
The page object is really a direct synonym for the this object.
The exception Object

The exception object is a wrapper containing the exception thrown from the previous page. It is
typically used togenerate an appropriate response to the error condition.
5.Explain Using Beans in JSP Pages

Ans: A JavaBean is a specially constructed Java class written in the Java and coded according to the
JavaBeans APIspecifications.
Following are the unique characteristics that distinguish a JavaBean from other Java classes −
It provides a default, no-argument constructor.
It should be serializable and that which can implement the Serializable interface.
It may have a number of properties which can be read or written.
It may have a number of "getter" and "setter" methods for the properties.
JavaBeans Properties

A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute
can be ofany Java data type, including the classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties are accessed
throughtwo methods in the JavaBean's implementation class −

S.No Method & Description


.

getPropertyName()
1
For example, if property name is firstName, your method name would be
getFirstName() toread that property. This method is called accessor.

setPropertyName()
2
For example, if property name is firstName, your method name would be
setFirstName() towrite that property. This method is called mutator.

A read-only attribute will have only a getPropertyName() method, and a write-only attribute will
have onlya setPropertyName() method.
JavaBeans Example
Consider a student class with few properties −
package com.tutorialspoint;
public class StudentsBean implements
java.io.Serializable {private String firstName
= null;
private String lastName = null;
private int age = 0;
public StudentsBean() {
}
public String getFirstName(){return firstName;
}
public String getLastName(){return lastName;
}
public int getAge(){return age;
}
public void setFirstName(String firstName){this.firstName = firstName;
}
public void setLastName(String lastName){this.lastName = lastName;
}
public void setAge(Integer age){this.age = age;
}}
Accessing JavaBeans

The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a scripting
variablethat can be accessed by both scripting elements and other custom tags used in the JSP. The
full syntax for the useBean tag is as follows −
<jsp:useBean id = "bean's name" scope = "bean's scope" typeSpec/>
Here values for the scope attribute can be a page, request, session or application based on your
requirement. The value of the id attribute may be any value as a long as it is a unique name among
other useBean declarations in the same JSP.
Following example shows how to use the useBean action -
<html>
<head>
<title>useBean Example</title>
</head>
<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>
You will receive the following result − −
The date/time is Thu Sep 30 11:18:11 GST 2010Accessing JavaBeans Properties
Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to access the get
methods andthe <jsp:setProperty/> action to access the set methods. Here is the full syntax −
<jsp:useBean id = "id" class = "bean's class" scope = "bean's scope"

<jsp:setProperty name = "bean's id" property =


"property name"value = "value"/>
<jsp:getProperty name = "bean's id" property = "property name"/>
<jsp:setProperty name = "bean's id" property =
"property name"value = "value"/>
<jsp:getProperty name = "bean's id" property = "property name"/>
The name attribute references the id of a JavaBean previously introduced to the JSP by the useBean
action. Theproperty attribute is the name of the get or the set methods that should be invoked.
Following example shows how to access the data using the above syntax −
<html>
<head>
<title>get and set properties Example</title>
</head>
<body>
<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>
<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>
<jsp:setProperty name = "students" property = "age" value = "10"/>
</jsp:useBean>
<p>Student First Name:
<jsp:getProperty name = "students" property = "firstName"/>
</p>
<p>Student Last Name:
<jsp:getProperty name = "students" property = "lastName"/>
</p>
<p>Student Age:
<jsp:getProperty name = "students" property = "age"/>
</p>
</body>
</html>

Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the following
result willbe displayed −
Student First Name: ZaraStudent Last Name: Ali Student Age: 10

6.Explain Using Cookies and session for session tracking


Ans: Cookies
A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests
from theclient they can be recognized using the received cookie.
This may not be an effective way as the browser at times does not support a cookie. It is not
recommended touse this procedure to maintain the sessions.
Hidden Form Fields
A web server can send a hidden HTML form field along with a unique session ID as follows −
<input type = "hidden" name = "sessionid" value = "12345">
This entry means that, when the form is submitted, the specified name and value are automatically
included in the GET or the POST data. Each time the web browser sends the request back, the
session_id value can be usedto keep the track of different web browsers.
This can be an effective way of keeping track of the session but clicking on a regular (<A HREF...>)
hypertextlink does not result in a form submission, so hidden form fields also cannot support general
session tracking.
URL Rewriting
You can append some extra data at the end of each URL. This data identifies the session; the server can
associatethat session identifier with the data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is
attached as sessionid = 12345 which can be accessed at the web server to identify the client.
URL rewriting is a better way to maintain sessions and works for the browsers when they don't support
cookies.The drawback here is that you will have to generate every URL dynamically to assign a
session ID though pageis a simple static HTML page.

The session Object

Apart from the above mentioned options, JSP makes use of the servlet provided HttpSession Interface.
This interface provides a way to identify a user across.

a one page request or


visit to a website or
store information about that user
By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each
new clientautomatically. Disabling session tracking requires explicitly turning it off by setting the
page directive session attribute to false as follows −
<%@ page session = "false" %>
The JSP engine exposes the HttpSession object to the JSP author through the implicit session
object. Since session object is already provided to the JSP programmer, the programmer can
immediately begin storing and retrieving data from the object without any initialization or
getSession().
Here is a summary of important methods available through the session object −

S.No Method & Description


.

1 public Object getAttribute(String name)


This method returns the object bound with the specified name in this session, or null
if no object isbound under the name.

public Enumeration getAttributeNames()


2
This method returns an Enumeration of String objects containing the names of all the
objects boundto this session.

public long getCreationTime()


3
This method returns the time when this session was created, measured in
milliseconds sincemidnight January 1, 1970 GMT.

4 public String getId()


This method returns a string containing the unique identifier assigned to this session.

public long getLastAccessedTime()


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

public int getMaxInactiveInterval()


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

7 public void invalidate()


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

public boolean isNew()


8
This method returns true if the client does not yet know about the session or if the
client choosesnot to join the session.

9 public void removeAttribute(String name)


This method removes the object bound with the specified name from this session.

10 public void setAttribute(String name, Object value)


This method binds an object to this session, using the name specified.
public void setMaxInactiveInterval(int interval)
11
This method specifies the time, in seconds, between client requests before the servlet
container willinvalidate this session.

Session Tracking Example


This example describes how to use the HttpSession object to find out the creation time and the last-
accessedtime for a session. We would associate a new session with the request if one does not already
exist.
<%@ page import = "java.io.*,java.util.*" %>
<%
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this Webpage.
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");String userIDKey = new String("userID");
String userID = new String("ABCD");
// Check if this is new comer on your Webpage.if (session.isNew() ){
title = "Welcome to my website"; session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer)session.getAttribute(visitCountKey);visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);session.setAttribute(visitCountKey, visitCount);
%>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
<table border = "1" align = "center">
<tr bgcolor = "#949494">
<th>Session info</th>
<th>Value</th>
</tr>
<tr>
<td>id</td>
<td><% out.print( session.getId()); %></td>
</tr>
<tr>
<td>Creation Time</td>
<td><% out.print(createTime); %></td>
</tr>
<tr>
<td>Time of Last Access</td>
<td><% out.print(lastAccessTime); %></td>
</tr>
<tr>
<td>User ID</td>
<td><% out.print(userID); %></td>
</tr>
<tr>
<td>Number of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</html>
Now put the above code in main.jsp and try to access http://localhost:8080/main.jsp. Once you run
the URL,you will receive the following result −
Welcome to my websiteSession Information
Session info value

id 0AE3EC93FF44E3C525B4351B77ABB2D5

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

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

User ID ABCD

Number of visits 0

Now try to run the same JSP for the second time, you will receive the following result.
Welcome Back to my websiteSession Information
info type value

id 0AE3EC93FF44E3C525B4351B77ABB2D5

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

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

User ID ABCD
Number of visits 1

Deleting Session Data


When you are done with a user's session data, you have several options −
Remove a particular attribute − You can call the public void removeAttribute(String name)
methodto delete the value associated with the a particular key.
Delete the whole session − You can call the public void invalidate() method to discard an entire
session.
Setting Session timeout − You can call the public void setMaxInactiveInterval(int interval) method
toset the timeout for a session individually.
Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of
theWeb server and invalidate all sessions belonging to all the users.
web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you
canconfigure the session time out in web.xml file as follows.
<session-config>
<session-timeout>15</session-timeout>
</session-config>
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in
seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( )
returns 900.

7.Explain Connecting to database in JSP.


The database is used for storing various types of data which are huge and has storing capacity in
gigabytes. JSPcan connect with such databases to create and manage the records.

Create Table

In MYSQL database, we can create a table in the database with any MYSQL client.

Here we are using PHPMyadminclient, and there we have an option "new" to create a new table using
belowscreenshot.

In this, we have to provide table name as guru_test, and we will create two fields'emp_id and
emp_name.Emp_id is having datatype as int
Emp_name is having datatype as varchar
Another option is by using command prompt and changes to MYSQL directory:

C:\>

C:\>cd Program Files\MY SQL\binC:\>Program Files\MySql\bin>


We can login to database as follows:

C:\Program Files\MYSQL\bin>mysql –u gururoot –pEnter Password: *******

JSP Operations: Insert, Update, Delete, Select

Using JSP, we can do multiple operations into the database. We can insert the records, and also, we
can deletethe records which are not required. If any record needs to be edited, then we can do using
an update. The Selectoperation will help to fetch the records which are required.

Select

The Select operation is used to select the records from the table.

Example:

In this example, we are going to learn about the select operation of fetching records from guru_test
table whichwas created in the above section.
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Database JSP1</title>
</head>
<body>14.
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/GuruTest"
user="gururoot" password="guru"/>18.
<sql:query dataSource="${snapshot}" var="result">
SELECT * from guru_test;
</sql:query>22.
<table>
<tr>
<th>Guru ID</th>
<th>Name</th>27.
</tr>
<c:forEach var="row" items="${result.rows}">
<tr>
<td><c:out value="${row.emp_id}"/></td>
<td><c:out value="${row.emp_name}"/></td>33.
</tr>
</c:forEach>
</table>37.
</body>
</html>
Explanation of the code:

Code Line 1: Here we are importing io, uti and SQL libraries of java.

Code Line 3: Here we are importing core library of JSTL and giving its prefix as gurucore which will
help toget output.

Code Line 4: Here we are importing SQL library of jstl and giving its prefix as gurusql which will
help to dothe SQL operations.

Code Line 15-17: Here using gurusql, we are connecting data source by naming variable as "guru"
and driveras a JDBC driver. Also adding username and password with "gururoot" and "guru".

Code Line 19-21: Here we are using SQL query of the select query.

Code Line 31-32: We are printing the output for emp id and emp name, which are fetched from the
results ofthe query and using foreach loop we print the output.
When you execute the above code, we will get the output as below;
Output:
Here both the records will be fetched from the database1 guru emp1
2 guru emp2
Insert
Insert operator is used to insert the records into the database.
Example:
In this example, we are going to learn about inserting the records in the table guru_test
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="gurucore"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="gurusql"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Database JSP1</title>
</head>
<body>14.
<gurusql:setDataSource var="guru" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/GuruTest"
user="gururoot" password="guru"/>18.
<gurusql:update dataSource="${guru}" var="guruvar">
INSERT INTO guru_test VALUES (3, 'emp emp3');
</gurusql:update>
</body>
</html>

Explanation of the code:

Code Line 19-20: Here we are inserting records into the table guru_test of GuruTestdatabase.The
recordsinserted are: empID - 3 and empname - emp emp3.These records will be inserted in the table
When you execute the code, the records are inserted into the table as guru_test ,with value 3 and emp
emp3.
Note: Here we are not showing the output as we are just inserting the record in the table. We can get
the recordusing select query as 'select * from guru_test'. If the record was inserted then, we would get
the value as 3 and emp3.If the record is not inserted then, 3 will not be seen in records in the table.
Delete
This is delete operation where we delete the records from the table guru_test.
Example:
Here we will delete query to delete the record from the table guru_test. The record which has to be
deleted hasto be set in variable "guruid", and the corresponding record is deleted from the database.
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="gurucore"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="gurusql"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Database JSP1</title>
</head>
<body>14.
<gurusql:setDataSource var="guru" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/GuruTest"
user="gururoot" password="guru"/>
<gurucore:set var="guruid" value="3"/>
<gurusql:update dataSource="${guru}" var="guruvar">
DELETE FROM guru_test WHERE emp_id = ?
<gurusql:param value="${guruid}" />
</gurusql:update>23.
24.
25.
</body>
</html>
Code Line 18: We are setting a variable guruid whose value is 3, which has to be deleted from the
database. This is always a primary key of the table. In this case, the primary key is the emp_id.

Code Line 19-22: Here we are using a delete query which is setting a parameter in the where
clause.Hereparameter is guruid which is set in code line 18. The corresponding record is deleted.
Output:
When you execute the above code, the record with emp_id as 3 is deleted.
Update
The update is used to edit the records in the table.
Example:
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="gurucore"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="gurusql"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Database JSP1</title>
</head>
<body>
<gurusql:setDataSource var="guru" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/GuruTest"
user="gururoot" password="guru"/>
<gurucore:set var="guruid" value="2"/>
<gurusql:update dataSource="${guru}" var="guruvar">
UPDATE guru_test SET emp_name='emp guru99'
<gurusql:param value="${guruid}" />
</gurusql:update>
</body>
</html>
UNIT-5
2 Marks
1.Define JavaScript?
Ans: JavaScript is used in millions of Web pages to improve the design, validate forms, and much
more. JavaScript was developed by Netscape and is the most popular scripting language on the internet.
JavaScript is a script basedprogramming language that supports the development of both client and
server components of Web based applications. The process of reading the HTML file and identifying
the elements contained in the file is referredas parsing.
When a script is encountered during parsing, the browser executes the script before continuing with
further parsing. The script can perform action, such as generating HTML code that affects the display
of the browser window.
2.Explain the Characteristics of JavaScript?
Ans: Characteristic features of JavaScript are listed as follows:
JavaScript was designed to add interactivity to HTML pages
JavaScript is a scripting language - a scripting language is a lightweight programming language
A JavaScript is lines of executable computer code
A JavaScript is usually embedded directly in HTML pages. JavaScript can put dynamic
text into anHTML page
JavaScript is an interpreted language (means that scripts execute without preliminary
compilation)
Everyone can use JavaScript without purchasing a license
3. Explain Variables in JavaScript?

A JavaScript variable is simply a name of storage location. There are two types of variables in JavaScript
:local variable and global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.


After first letter we can use digits (0 to 9), for example value1.
JavaScript variables are case sensitive, for example x and X are different variables.

Variable declaration and assignment;


Variables in JavaScript are declared by specifying the name of the variable storage to create prefixed
withthe token var.
var x = 10;
var _value="hello ";

4.Explain JavaScript Data Types?


JavaScript provides different data types to hold different types of values. There are two types of data
typesin JavaScript.
Primitive data type
Non-primitive (reference) data type

JavaScript is a dynamic type language, means you don't need to specify type of the variable because it
isdynamically used by JavaScript engine.
var is used to specify the data type. It can hold any type of values such as numbers, strings etc.
For example:
var a=100;//holding
number var
b="Sam";//holding
string
5.Explain Event Handlers?
Ans: JavaScript's interaction with HTML is handled through events that occur when the user or
the browsermanipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event.
Otherexamples include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close
windows,messages to be displayed to users, data to be validated, and virtually any other type of
response imaginable.

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

Things that should be done every time a page loads


Things that should be done when the page is closed
Action that should be performed when a user clicks a button
Content that should be verified when a user inputs data

3 MARKS
1.Explain Scope of the variables?
Ans: The Scope of the Variable is the region of the program in
which it is defined.JavaScript variables have two scopes:
Local Variables
Global Variables

JavaScript Local Variables:


A JavaScript local variable is declared inside block or function. It is accessible within the function or
block only.
Example:

<script>
function abc(){
var x=10;//local variable
}
</script>

JavaScript Global Variables:


A JavaScript global variable is accessible from any function.
A variable i.e. declared outside the function or declared with window object is known as global variable.
Example with output:
2. Explain Data Validation?

Ans: Data validation is the process of ensuring that user input is clean,
correct, and useful.Typical validation tasks are:
has the user filled in all required fields?
has the user entered a valid date?
has the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many
different ways.Server side validation is performed by a web server, after input
has been sent to the server.Client side validation is performed by a web browser,
before input is sent to a web server.
Automatic Form validation:
HTML form validation can be performed automatically by the browser
If a form field (fname) is empty, the required attribute prevents this form from being submitted:

3. Explain any three Events in Event Handlers?


Ans: Onclick Event Type:
This is the most frequently used event type which occurs when a user clicks the left button of his
mouse. Youcan put your validation, warning etc., against this event type.
OnSubmit Event Type:
onsubmit is an event that occurs when you try to submit a form. You can put your form validation
against thisevent type.
Example
The following example shows how to use onsubmit. Here we are calling a validate() function before
submitting a form data to the webserver. If validate() function returns true, the form will be submitted,
otherwise it will notsubmit the data.
onmouseover and onmouseout:
These two event types will help you create nice effects with images or even with text as well. The
onmouseover event triggers when you bring your mouse over any element and the onmouseout
triggers when you move your mouse out from that element.

4.Explain Document Object Model?

Ans:The document object represents the whole html document.

When html document is loaded in the browser, it becomes a document object. It is the root element that
representsthe html document. It has properties and methods. By the help of document object, we can
add dynamic contentto our web page.

DOM is the object of window. So window.document is same as document

According to W3C - "The W3C Document Object Model (DOM) is a platform and language-neutral
interface that allows programs and scripts to dynamically access and update the content, structure,
and style of a document."
Let's see the properties of document object that can be accessed and modified by the document.
5.Explain Operators in JavaScript?

Ans: JavaScript Arithmetic Operators:


Arithmetic operators are used to perform arithmetic on numbers:

JavaScript Assignment Operators:


Assignment operators assign values to JavaScript variables.
JavaScript Comparision Operators:

JavaScript Logical Operators:

JavaScript Type Operators:

JavaScript Bitwise Operators:

Bit operators work on 32 bits numbers.


Any numeric operand in the operation is converted into a 32 bit number. The result is converted
back to aJavaScript number.

5 Marks

1.Explain Embedding JavaScript in HTML?


Ans: JavaScript statement can be included in HTML document by enclosing the statement between
container element
<SCRIPT>.
<SCRIPT> element has the following attributes
LANGUAGE attribute is set to JavaScript to identify the script being JavaScript.
<SCRIPT LANGUAGE="JavaScript">
or it can be written as
<SCRIPT TYPE="text/javascript">
In HTML, JavaScript code must be inserted between <script> and
</script> tags.Example with Output:
JavaScript in <head> or <body>
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
JavaScript in <head>

A JavaScript function is placed in the <head> section of an


HTML page.The function is invoked (called) when a button
is clicked:
Example with Output:

JavaScript in <body>

A JavaScript function is placed in the <body> section of an


HTML page.The function is invoked (called) when a button is
clicked:
Example with Output:
External JavaScript

We can create external JavaScript file and embed it in many html page.

It provides code re usability because single JavaScript file can be used in several html pages.

An external JavaScript file must be saved by .js extension. It is recommended to embed all
JavaScriptfiles into a single file. It increases the speed of the webpage.

2.Explain about JavaScript Language?

Ans: JavaScript is a dynamic computer programming language. It is lightweight and most commonly
used as a part of web pages, whose implementations allow client-side script to interact with the user and
make dynamic pages.It is an interpreted programming language with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly
because of theexcitement being generated by Java. JavaScript made its first appearance in Netscape
2.0 in 1995 with the name LiveScript. The general-purpose core of the language has been embedded
in Netscape, Internet Explorer,and other web browsers.

Client-side JavaScript is the most common form of the language. The script should be included in or
referencedby an HTML document for the code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs that interact with the
user, controlthe browser, and dynamically create HTML content.
The JavaScript client-side mechanism provides many advantages over traditional CGI server-side
scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address
in a form field.
The JavaScript code is executed when the user submits the form, and only if all the entries are valid,
they wouldbe submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation, and other
actions thatthe user initiates explicitly or implicitly.
Advantages of JavaScript

The merits of using JavaScript are −


Less server interaction − You can validate user input before sending the page off to the server.
Thissaves server traffic, which means less load on your server.
Immediate feedback to the visitors − They don't have to wait for a page reload to see if they
haveforgotten to enter something.
Increased interactivity − You can create interfaces that react when the user hovers over them
with amouse or activates them via the keyboard.
Richer interfaces − You can use JavaScript to include such items as drag-and-drop components
andsliders to give a Rich Interface to your site visitors.

Limitations/Disadvantages of JavaScript

We cannot treat JavaScript as a full-fledged programming language. It lacks the following important
features :
Client-side JavaScript does not allow the reading or writing of files. This has been kept for
securityreason.
JavaScript cannot be used for networking applications because there is no such support available.
JavaScript doesn't have any multi-threading or multiprocessor capabilities.
JavaScript is a lightweight, interpreted programming language that allows you to build interactivity
into otherwise static HTML pages.

3.Explain JavaScript Functions?

Ans: A JavaScript function is a block of code designed to perform


a particular task. A JavaScript function is executed when
"something" invokes it (calls it).
JavaScript Function Syntax:

A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().Function names can contain letters, digits, underscores, and dollar signs (same rules
as variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3)


{
// code to be executed
}
Function parameters are listed inside the parentheses () in the function
definition.Function arguments are the values received by the function
when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.

Example with Output:

Function Invocation:

The code inside the function will execute when "something" invokes (calls) the function:

When an event occurs (when a user clicks a button)


When it is invoked (called) from JavaScript code
Automatically (self invoked)

Function With Return Values:

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the code after
the invokingstatement.

Functions often compute a return value. The return value is "returned" back to the "caller":

Example:

Calculate the product of two numbers, and return the result:\


JavaScript Function Object:

In JavaScript, the purpose of Function constructor is to create a new Function object. It executes the
code globally. However, if we call the constructor directly, a function is created dynamically but in
an unsecured way.

Syntax:
new Function ([arg1[, arg2[, argn]],] functionBody)
Parameter:
arg1, arg2, ............, argn - It represents the argument used by function.

functionBody - It represents the function definition.

JavaScript Function Methods:

Advantages of JavaScript Functions:

There are mainly two advantages of JavaScript functions.

Code reusability: We can call a function several times so it save coding.


Less coding: It makes our program compact. We don’t need to write many lines of code each time
to perform a common task.
Examples of JavaScript
Function Object: 1.To display
the sum of given numbers.

4. Explain Form validation?

Ans: HTML form validation can be done by JavaScript.

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

It is important to validate the form submitted by the user because it can have inappropriate values. So,
validationis must to authenticate user.

JavaScript provides facility to validate the form on the client-side so data processing will be faster
than server- side validation. Most of the web developers prefer JavaScript form validation.

Through JavaScript, we can validate name, password, email, date, mobile numbers and more fields.

Form validation normally used to occur at the server, after the client had entered all the necessary
data and thenpressed the Submit button. If the data entered by a client was incorrect or was simply
missing, the server wouldhave to send all the data back to the client and request that the form be
resubmitted with correct information. This was really a lengthy process which used to put a lot of
burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to the
web server. Form validation generally performs two functions.
Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are
filledin. It would require just a loop through each field in the form and check for data.
Data Format Validation − Secondly, the data that is entered must be checked for correct form and
value.Your code must include appropriate logic to test correctness of data.
Data Validation:

Data validation is the process of ensuring that user input is clean, correct,
and useful.Typical validation tasks are:
has the user filled in all required fields?
has the user entered a valid date?
has the user entered text in a numeric field?

Most often, the purpose of data validation is to ensure correct user input.

Validation can be defined by many different methods, and deployed in many different ways. Server side
validation is performed by a web server, after input has been sent to the server. Client side validation
is performed by a web browser, b Automatic Form validation:
HTML form validation can be performed automatically by the browser
If a form field (fname) is empty, the required attribute prevents this form from being submitted:
efore input is sent to a web server.
5.Explain Browser Object Model?
Ans: The Browser Object Model (BOM) is used to interact with the browser.
The default object of browser is window means you can call all the functions of window by
specifying windowor directly.
Example:
window.alert("hel
lo World "); is
same as
alert("hello World");
We can use a lot of properties (other objects) defined underneath the window object like
document, history,screen, navigator, location, innerHeight, innerWidth
Window Object
The window object represents a window in browser. An object of window is created
automatically by thebrowser.
Window is the object of browser, it is not the object of javascript. The javascript objects are string,
array, dateetc.
Methods of window object

Example of alert() in javascript:


Example of confirm () in javascript:

Example of prompt() in javascript:


Example of open() in javascript:

Example of settimeout() in javascript:


JavaScript History Object:
The JavaScript history object represents an array of URLs visited by the user. By using this
object,you can load previous, forward or any particular page.
The history object is the window property, so it can be accessed by:
window.history or history
Property of JavaScript history
object

No Proper
. ty
1 length

Methods of JavaScript history object:


There are only 3 methods of history object.

No. Method Description


1 forward() loads the next page.

2 back() loads the previous page.

3 go() loads the given page number.

Window History Forward:


The history.forward() method loads the next URL in the
history list. This is the same as clicking the Forward
button in the browser.
Example:
<html>
<head>
<script>
function
goForward() {
window.history.for
ward()
}
</script>
</head>
<body>
<input type="button" value="Forward" onclick="goForward()">
</body>
</html>
Window History Back:
The history.back() method loads the previous URL in the
history list.This is the same as clicking the Back button in
the browser.

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

JavaScript Navigator Object:


The JavaScript navigator object is used for browser detection. It can be used to get
browserinformation such as appName, appCodeName, userAgent etc.
The navigator object is the window property, so it can be accessed by:
window.navigator or navigator
Property of JavaScript navigator
object:
There are many properties of navigator object that returns information of the browser.
JavaScript Screen Object:
The JavaScript screen object holds information of browser screen. It can be used to display
screenwidth, height, colorDepth, pixelDepth etc.
The navigator object is the window property, so it can be accessed by:
Window.screen or screen.
Property of JavaScript Screen Object:
There are many properties of screen object that returns information of the browser.
2.To display the power of provided value.

You might also like