0% found this document useful (0 votes)
199 views64 pages

WT Sem 3-2

The document provides explanations and examples of various PHP concepts including: 1. Data types in PHP like integers, floats, strings, booleans. PHP is loosely typed and determines types based on value attributes. 2. String functions like length, word count, search, replace. Arrays can store multiple values in a variable. Indexed and associative arrays are created with examples. 3. User-defined functions are created with the function keyword. Functions can accept arguments and return values. Default arguments are demonstrated. Control structures like if/else statements allow different code execution based on conditions.

Uploaded by

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

WT Sem 3-2

The document provides explanations and examples of various PHP concepts including: 1. Data types in PHP like integers, floats, strings, booleans. PHP is loosely typed and determines types based on value attributes. 2. String functions like length, word count, search, replace. Arrays can store multiple values in a variable. Indexed and associative arrays are created with examples. 3. User-defined functions are created with the function keyword. Functions can accept arguments and return values. Default arguments are demonstrated. Control structures like if/else statements allow different code execution based on conditions.

Uploaded by

Navilash Reds
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Unit-1

1. Explain about variables and data types in PHP?


2. Explain arrays, Strings, expressions in PHP with examples?
3. Explain about Functions and control structures in PHP with examples?
4. Explain Form Validation in PHP with example?
5. Explain about Handling sessions and cookies with examples?
6. Explain File handling operations in PHP briefly?

Answers
1. PHP Data Types
A Data type is the classification of data into a category according to its attributes;
● Alphanumeric characters are classified as strings
● Whole numbers are classified integers
● Numbers with decimal points are classified as floating points.
● True or false values are classified as Boolean.

PHP is a loosely typed language; it does not have explicit defined data types. PHP
determines the data types by analyzing the attributes of data supplied.

PHP implicitly supports the following data types


● Integer – whole numbers e.g. -3, 0, 69. The maximum value of an integer is platform-
dependent. On a 32 bit machine, it’s usually around 2 billion. 64 bit machines usually
have larger values.
● The constant PHP_INT_MAX is used to determine the maximum value
● Floating point number – decimal numbers e.g. 3.14. they are also known as double or
real numbers. The maximum value of a float is platform-dependent. Floating point
numbers are larger than integers.
● Character string – e.g. Hello World
● Boolean - e.g. True or False
==================================================================
2. ​Strings
A string is a sequence of characters, like "Hello world!".
PHP String Functions
In this chapter we will look at some commonly used functions to manipulate strings.

Get The Length of a String


The PHP strlen() function returns the length of a string.
The example below returns the length of the string "Hello world!":
Example
<?php
echo strlen("Hello world!"); // outputs 12

1
?>
The output of the code above will be: 12.

Count The Number of Words in a String


The PHP str_word_count() function counts the number of words in a string:
Example
<?php
echo str_word_count("Hello world!"); // outputs 2
?>
The output of the code above will be: 2.

Reverse a String
The PHP strrev() function reverses a string:
Example
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
The output of the code above will be: !dlrow olleH.

Search For a Specific Text Within a String


The PHP strpos() function searches for a specific text within a string.
If a match is found, the function returns the character position of the first match. If no
match is found, it will return FALSE.
The example below searches for the text "world" in the string "Hello world!":
Example
<?php
echo strpos("Hello world!", "world"); // outputs 6
?>
The output of the code above will be: 6.
Tip: The first character position in a string is 0 (not 1).

Replace Text Within a String


The PHP str_replace() function replaces some characters with some other characters in
a string.
The example below replaces the text "world" with "Dolly":
Example
<?php
echo str_replace("world", "Dolly", "Hello world!"); // outputs Hello Dolly!
?>
The output of the code above will be: Hello Dolly!

Arrays

2
An array stores multiple values in one single variable:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
$cars1 = "Volvo";
$cars2 = "BMW";
$cars3 = "Toyota";

However, what if you want to loop through the cars and find a specific one? And what
if you had not 3 cars, but 300?
The solution is to create an array!

An array can hold many values under a single name, and you can access the values by
referring to an index number.

Create an Array in PHP


In PHP, the array() function is used to create an array: array();
In PHP, there are three types of arrays:
1. Indexed arrays - Arrays with a numeric index
2. Associative arrays - Arrays with named keys
3. Multidimensional arrays - Arrays containing one or more arrays
PHP Indexed Arrays
There are two ways to create indexed arrays:
The index can be assigned automatically (index always starts at 0), like this:
$cars = array("Volvo", "BMW", "Toyota");
or the index can be assigned manually:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The following example creates an indexed array named $cars, assigns three elements to it,
and then prints a text containing the array values:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>

3
Get The Length of an Array ​- The count() Function
The count() function is used to return the length (the number of elements) of an array:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
?>
Loop Through an Indexed Array
To loop through and print all the values of an indexed array, you could use a for loop,
like this:
Example
<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x < $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
PHP Associative Arrays
Associative arrays are arrays that use named keys that you assign to them.
There are two ways to create an associative array:
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
or:
$age['Peter'] = "35";
$age['Ben'] = "37";
$age['Joe'] = "43";

The named keys can then be used in a script:


Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
echo "Peter is " . $age['Peter'] . " years old.";
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use
a foreach loop, like this:
Example
<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
foreach($age as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";

4
}
?>

==================================================================
3.
Functions
The real power of PHP comes from its functions; it has more than 1000 built-in functions.
PHP User Defined Functions
Besides the built-in PHP functions, we can create our own functions.
● A function is a block of statements that can be used repeatedly in a program.
● A function will not execute immediately when a page loads.
● A function will be executed by a call to the function.
● Create a User Defined Function in PHP
A user-defined function declaration starts with the word function:
Syntax
function functionName() {
code to be executed;
}
Note: A function name can start with a letter or underscore (not a number).
Tip: Give the function a name that reflects what the function does!

Function names are NOT case-sensitive.

In the example below, we create a function named "writeMsg()". The opening curly
brace ( { ) indicates the beginning of the function code and the closing curly brace ( } )
indicates the end of the function. The function outputs "Hello world!". To call the
function, just write its name:
Example
<?php
function writeMsg() {
echo "Hello world!";
}
writeMsg(); // call the function
?>
PHP Function Arguments
Information can be passed to functions through arguments. An argument is just like a
variable.
Arguments are specified after the function name, inside the parentheses. You can add as
many arguments as you want, just separate them with a comma.
The following example has a function with one argument ($fname). When the familyName()
function is called, we also pass along a name (e.g. Jani), and the name is used inside the
function, which outputs several different first names, but an equal last name:

5
Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
familyName("Jani");
familyName("Hege");
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
?>
The following example has a function with two arguments ($fname and $year):
Example
<?php
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
?>
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 <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
PHP Functions - Returning values
To let a function return a value, use the return statement:
Example
<?php
function sum($x, $y) {
$z = $x + $y;
return $z;
}

6
echo "5 + 10 = " . sum(5, 10) . "<br>";
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>

PHP Conditional Statements


Very often when you write code, you want to perform different actions for different
conditions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
1. if statement - executes some code if one condition is true
2. if...else statement - executes some code if a condition is true and another code if that
condition is false
3. if...elseif....else statement - executes different codes for more than two conditions
4. switch statement - selects one of many blocks of code to be executed
PHP - The if Statement
The if statement executes some code if one condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less
than 20:
Example
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>

PHP - The if...else Statement


The if....else statement executes some code if a condition is true and another code if
that condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20,
and "Have a good night!" otherwise:
Example

7
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>

PHP - The if...elseif....else Statement


The if....elseif...else statement executes different codes for more than two conditions.
Syntax
if (condition) {
code to be executed if this condition is true;
} elseif (condition) {
code to be executed if this condition is true;
} else {
code to be executed if all conditions are false;
}
The example below will output "Have a good morning!" if the current time is less than
10, and "Have a good day!" if the current time is less than 20. Otherwise it will output
"Have a good night!":

Example
<?php
$t = date("H");
if ($t < "10") {
echo "Have a good morning!";
} elseif ($t < "20") {
echo "Have a good day!";
} else {
echo "Have a good night!";
}
?>
PHP - The switch Statement
The switch statement will be explained in the next chapter.
The switch statement is used to perform different actions based on different conditions. Use
the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;

8
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each
case in the structure. If there is a match, the block of code associated with that case is
executed. Use break to prevent the code from running into the next case automatically.
The default statement is used if no match is found.
Example
<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
PHP while loops execute a block of code while the specified condition is true.
==================================================================
4. Validate Form Data With PHP
The first thing we will do is to pass all variables through PHP's htmlspecialchars() function.
When we use the htmlspecialchars() function; then if a user tries to submit the following in a
text field:
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code, like this:

9
&lt;script&gt;location.href('http://www.hacked.com')&lt;/script&gt;

The code is now safe to be displayed on a page or inside an e-mail.

We will also do two more things when the user submits the form:
● Strip unnecessary characters (extra space, tab, newline) from the user input data (with
the PHP trim() function)
● Remove backslashes (\) from the user input data (with the PHP stripslashes()
function)
● The next step is to create a function that will do all the checking for us (which is much
more convenient than writing the same code over and over again). We will name the
function test_input().
● Now, we can check each $_POST variable with the test_input() function, and the
script looks like this:

Example
<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Notice that at the start of the script, we check whether the form has been submitted using
$_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form
has been submitted - and it should be validated. If it has not been submitted, skip the
validation and display a blank form.
==================================================================
5. ​Cookies
A cookie is often used to identify a user. A cookie is a small file that the server embeds on
the user's computer. Each time the same computer requests a page with a browser, it will send
the cookie too. With PHP, you can both create and retrieve cookie values.

10
Create Cookies With PHP
A cookie is created with the setcookie() function.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);

Only the name parameter is required. All other parameters are optional.

PHP Create/Retrieve a Cookie


The following example creates a cookie named "user" with the value "John Doe". The cookie
will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire
website (otherwise, select the directory you prefer). We then retrieve the value of the cookie
"user" (using the global variable $_COOKIE).
We also use the isset()function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the cookie, and
automatically decoded when received (to prevent URL encoding, use setrawcookie() instead).

Modify a Cookie Value


To modify a cookie, just set (again) the cookie using the setcookie() function:
Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";

11
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>

Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>

Check if Cookies are Enabled


The following example creates a small script that checks whether cookies are enabled. First,
try to create a test cookie with the setcookie() function, then count the $_COOKIE array
variable:
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {

12
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>

Sessions
A session is a way to store information (in variables) to be used across multiple pages. Unlike
a cookie, the information is not stored on the users computer.

When you work with an application, you open it, do some changes, and then you close it.
This is much like a Session. The computer knows who you are. It knows when you start the
application and when you end. But on the internet there is one problem: the web server does
not know who you are or what you do, because the HTTP address doesn't maintain state.

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. So; Session variables hold information about one single user, and are
available to all pages in one application.
Tip: If you need a permanent storage, you may want to store the data in a database.

Start a PHP Session


A session is started with the session_start() function.
Session variables are set with the PHP global variable: $_SESSION.

Now, let's create a new page called "demo_session1.php". In this page, we start a new PHP
session and set some session variables:
Example
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";

13
echo "Session variables are set.";
?>
</body>
</html>
Note: The session_start() function must be the very first thing in your document. Before any
HTML tags.

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()). Also notice that all session
variable values are stored in the global $_SESSION variable:
Example
<?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>
Another way to show all the session variable values for a user session is to run the following
code:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>

14
Most sessions set a user-key on the user's computer that looks something like this:
765487cf34ert8dede5a562e4f3a7e12. Then, when a session is opened on another page, it
scans the computer for a user-key. If there is a match, it accesses that session, if not, it starts a
new session.

Modify a PHP Session Variable


To change a session variable, just overwrite it:
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>
</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();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
// destroy the session
session_destroy();
?>
</body>
</html>

==================================================================

15
6. File Handling
File handling is an important part of any web application. You often need to open and process
a file for different tasks.

PHP Manipulating Files


PHP has several functions for creating, reading, uploading, and editing files.
When you are manipulating files you must be very careful. You can do a lot of damage if you
do something wrong. Common errors are: editing the wrong file, filling a hard-drive with
garbage data, and deleting the content of a file by accident.

PHP readfile() Function


The readfile() function reads a file and writes it to the output buffer.

Assume we have a text file called "webdictionary.txt", stored on the server, that looks
like this:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
The PHP code to read the file and write it to the output buffer is as follows (the readfile()
function returns the number of bytes read on success):
Example
<?php
echo readfile("webdictionary.txt");
?>

File Open/Read/Close
PHP Open File - fopen()
A better method to open files is with the fopen() function. This function gives you more
options than the readfile() function.
We will use the text file, "webdictionary.txt", during the lessons:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hypertext Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language

16
The first parameter of fopen() contains the name of the file to be opened and the second
parameter specifies in which mode the file should be opened. The following example also
generates a message if the fopen() function is unable to open the specified file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("webdictionary.txt"));
fclose($myfile);
?>
Tip: The fread() and the fclose() functions will be explained below.

The file may be opened in one of the following modes:


Description
1. r ​Open a file for read only. File pointer starts at the beginning of the file
2. w​ Open a file for write only. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file
3. a​ Open a file for write only. The existing data in file is preserved. File pointer starts at
the end of the file. Creates a new file if the file doesn't exist
4. x ​Creates a new file for write only. Returns FALSE and an error if file already exists
5. r+​ Open a file for read/write. File pointer starts at the beginning of the file
6. w+​ ​Open a file for read/write. Erases the contents of the file or creates a new file if it
doesn't exist. File pointer starts at the beginning of the file
7. a+​ Open a file for read/write. The existing data in file is preserved. File pointer starts
at the end of the file. Creates a new file if the file doesn't exist
8. x+ ​Creates a new file for read/write. Returns FALSE and an error if file already exists

PHP Read File - fread()


The fread() function reads from an open file.

The first parameter of fread() contains the name of the file to read from and the second
parameter specifies the maximum number of bytes to read.
The following PHP code reads the "webdictionary.txt" file to the end:
fread($myfile,filesize("webdictionary.txt"));

PHP Close File - fclose()


The fclose() function is used to close an open file.
It's a good programming practice to close all files after you have finished with them. You
don't want an open file running around on your server taking up resources! The fclose()
requires the name of the file (or a variable that holds the filename) we want to close:
<?php
$myfile = fopen("webdictionary.txt", "r");
// some code to be executed....

17
fclose($myfile);
?>

PHP Read Single Line - fgets()


The fgets() function is used to read a single line from a file.
The example below outputs the first line of the "webdictionary.txt" file:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
echo fgets($myfile);
fclose($myfile);
?>
Note: After a call to the fgets() function, the file pointer has moved to the next line.

PHP Check End-Of-File - feof()


The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length. The example below
reads the "webdictionary.txt" file line by line, until end-of-file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
echo fgets($myfile) . "<br>";
}
fclose($myfile);
?>

PHP Read Single Character - fgetc()


The fgetc() function is used to read a single character from a file.
The example below reads the "webdictionary.txt" file character by character, until end of-
file is reached:
Example
<?php
$myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// Output one character until end-of-file
while(!feof($myfile)) {
echo fgetc($myfile);
}
fclose($myfile);
?>

18
PHP Create File - fopen()
The fopen() function is also used to create a file. Maybe a little confusing, but in PHP, a file
is created using the same function used to open files. If you use fopen() on a file that does not
exist, it will create it, given that the file is opened for writing (w) or appending (a).

The example below creates a new file called "testfile.txt". The file will be created in the
same directory where the PHP code resides:
Example
$myfile = fopen("testfile.txt", "w")

PHP File Permissions


If you are having errors when trying to get this code to run, check that you have granted your
PHP file access to write information to the hard drive.

PHP Write to File - fwrite()


The fwrite() function is used to write to a file.
The first parameter of fwrite() contains the name of the file to write to and the second
parameter is the string to be written. The example below writes a couple of names into a new
file called "newfile.txt":
Example
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
Notice that we wrote to the file "newfile.txt" twice. Each time we wrote to the file we sent the
string $txt that first contained "John Doe" and second contained "Jane Doe". After we
finished writing, we closed the file using the fclose() function. If we open the "newfile.txt"
file it would look like this:
John Doe
Jane Doe

PHP Overwriting
Now that "newfile.txt" contains some data we can show what happens when we open
an existing file for writing. All the existing data will be ERASED and we start with an
empty file.
In the example below we open our existing file "newfile.txt", and write some new data
into it:
Example

19
<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "Mickey Mouse\n";
fwrite($myfile, $txt);
$txt = "Minnie Mouse\n";
fwrite($myfile, $txt);
fclose($myfile);
?>
File Upload
With PHP, it is easy to upload files to the server. However, with ease comes danger, so
always be careful when allowing file uploads!
==================================================================

20
Unit-2
1. Create a DTD for User login page and wrote an XML document for the above DTD.
2. Create an XML Schema and XML document for User login page.
3. Write an XSLT program for book store application.
4. Differentiate DOM and SAX parsers.
5. Explain about DTD with example?
6. Explain about XML Schema with example?

Note: ​Text highlighted in yellow is optional.


Answers
1.
DTD for User Login Page
<!DOCTYPE note
[
<!ELEMENT Login (email, password)>
<!ELEMENT Email (#PCDATA)>
<!ELEMENT Password (#PCDATA)>
]>

XML Document for above DTD


<?xml version="1.0" encoding="utf-8" ?>
<login>
<email>​[email protected]​</email>
<password>mypassword</password>
</login>
==================================================================
2. ​employee.xsd
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.javatpoint.com"
xmlns="http://www.javatpoint.com"
elementFormDefault="qualified">

<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="username" type="xs:string"/>
<xs:element name="password" type="xs:string"/>
<xs:element name="email" type="xs:string"/>
</xs:sequence>
</xs:complexType>

21
</xs:element>
</xs:schema>

employee.xml
<?xml version="1.0"?>
<employee
xmlns="http://www.javatpoint.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.javatpoint.com employee.xsd">

<username>vimal</username>
<password>jaiswal</password>
<email>[email protected]</email>
</employee>
==================================================================
3. PROGRAM:
bookstore.xml
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="bookstore.xsl"?>

<bookstore>
<book>
<title>Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book>
<title>Harry Potter</title>
<author>J K. Rowling</author>
<year>2005<you/year>
<price>29.99</price>
</book>
<book>
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
bookstore.xsl
<xsl:stylesheet version="1.0” xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

22
<xsl:template match="/">
<html>
<body>
<h2> My Books collection</h2>
<table border="1">
<tr bgcolor="red">
<th align="left">title</th>
<th align="left">author</th>
</tr>
<xsl:for-each select="bookstore/book">
<tr>
<td><xsl:value-of select="title"/></td>
<xsl:choose>
<xsl:when test="price &gt; 30">
<td bgcolor="yellow"><xsl:value-of select="author"/></td>
</xsl:when>
<xsl:when test="price &gt; 10">
<td bgcolor="lightgreen"><xsl:value-of select="author"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="author"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

==================================================================
4.
DOM SAX

Both SAX and DOM are used to parse the XML document. Both has advantages and
disadvantages and can be used in our programming depending on the situation.

DOM stands for Document Object Model SAX stands for Simple API for XML Parsing

good for smaller size good to choose for larger size of file.

23
Stores the entire XML document into Parses node by node
memory before processing

Occupies more memory Doesn’t store the XML in memory

We can insert or delete nodes We can't insert or delete a node

Traverse in any direction. Top to bottom traversing

DOM is a tree model parser SAX is an event based parser

import javax.xml.parsers.*; import javax.xml.parsers.*;


import org.w3c.dom.*; import org.xml.sax.*;
import org.xml.sax.helpers.*;

preserves comments doesn’t preserve comments

SAX generally runs a little faster than SAX generally runs a little faster than DOM
DOM

If we need to find a node and doesn’t need to insert or delete we can go with SAX itself
otherwise DOM provided we have more memory.
==================================================================
5. ​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.

24
● 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>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
Let us go through the above code −

Start Declaration − Begin the XML declaration with the following statement.

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


DTD − Immediately after the XML header, the document type declaration follows,
commonly referred to as the DOCTYPE −

25
<!DOCTYPE address [
The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. The
DOCTYPE informs the parser that a DTD is associated with this XML document.

DTD Body − The DOCTYPE declaration is followed by body of the DTD, where you declare
elements, attributes, entities, and notations.

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


<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone_no (#PCDATA)>
Several elements are declared here that make up the vocabulary of the <name> document.
<!ELEMENT name (#PCDATA)> defines the element name to be of type "#PCDATA".
Here #PCDATA means parse-able text data.

End Declaration − Finally, the declaration section of the DTD is closed using a closing
bracket and a closing angle bracket (]>). This effectively ends the definition, and thereafter,
the XML document follows immediately.

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 −

26
<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</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)>
==================================================================
6. 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
You need to declare a schema in your 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.

27
Elements
As we saw in the XML - Elements chapter, 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
You can define XML schema elements in the following ways −

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


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

3. Global Types
With the global type, you can define a single type in your document, which can be used by all
other references. For example, suppose you want to generalize the person and company for
different addresses of the company. In such case, you can define a general type as follows −

<xs:element name = "AddressType">


<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
</xs:sequence>

28
</xs:complexType>
</xs:element>
Now let us use this type in our example as follows −

<xs:element name = "Address1">


<xs:complexType>
<xs:sequence>
<xs:element name = "address" type = "AddressType" />
<xs:element name = "phone1" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:element name = "Address2">


<xs:complexType>
<xs:sequence>
<xs:element name = "address" type = "AddressType" />
<xs:element name = "phone2" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>

Instead of having to define the name and the company twice (once for Address1 and once for
Address2), we now have a single definition. This makes maintenance simpler, i.e., if you
decide to add "Postcode" elements to the address, you need to add them at just one place.
==================================================================

29
Unit-3
1.​ Define a servlet? Explain life cycle of a servlet. Illustrate with an example program.

2.​ ​Write a Program to read servlet parameters.

3.​ ​Write a Program for cookies (Both reading and writing)

4.​ ​Explain about Javax.servlet and Javax.servlet.http packages.

5.​ ​Explain about cookies with example?

6.​ ​Explain about session tracking with example?

Answers
1. Servlet:
Servlets are java programs that run on web or application servers, servlets are also called
server side programs i.e the code of the program executes at server side, acting as a middle
layer between request coming from Web browsers or other HTTP clients and databases or
applications on the HTTP server. A servlet container uses a Java Virtual Machine to run
servlet code as requested by a web server. A servlet dynamically loaded module that services
requests from Web server. It runs entirely inside the Java Virtual Machine.

LIFE CYCLE OF JAVA SERVLET


The servlet cycle has three methods these init () for initialization of the resources, service()
handles zero or more requests and the destroy() method is invoked at end of servlet life it
releases all resources which were allocated previously.
init()
The init() method is where the servlets life begins. It is called by the server immediately after
the servlet is instantiated. The database connection, opening a file, or a network connection
may be established through it. The init method is not called again for each request. The
servlet is normally created when a user first invokes a URL corresponding to servlet.

public void init (ServletConfig config) throws ServletException

The following are the task performed while implementing init() method
1. Reading initialization parameters using ServletConfig object
2. Initializing a database driver
3. Opening a database connection
4. Initialization of objects
service()
The service method handles all requests sent by a client. Each time the server receive a
request for a servlet, the server spawns a new thread and calls service method. The service
method checks the request type GET, POST, PUT, DELETE etc. For, every request to the
servlet, its service method is called. Two objects ServletRequest and ServletResponse are
passed as argument to it.

30
public void service(ServletRequest request, ServletResponse response ) throws
ServletException, IOException
destroy()
This method signifies the end of a servlet life. The resources that are previously allocated are
destroyed. The method is invoked by server administrator or programmatically by servlet
itself.

public void destroy()

A server loads and initializes the servlet


The servlet handles zero or more client request
The server removes the servlet
==================================================================
2. Reading Servlet Parameters :
The ServletRequest class includes methods that allow you to read the names and values of
parameters that are included in a client request. We will develop a servlet that illustrates their
use.
The example contains two files.
A Web page is defined in sum.html and a servlet is defined in Add.java

sum.html:
<html>
<body>
<form name="Form1" method="post" action="Add">
<table>
<tr>
<td><B>Enter First Number</td>
<td><input type=textbox name="Enter First Number" size="25"
value=""></td>
</tr>

31
<tr>
<td><B>Enter Second Number</td>
<td><input type=textbox name="Enter Second Number" size="25"
value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</form>
</body>
</html>
Add.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Add extends HttpServlet
{
public void doPost (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Get printwriter.
response.getContentType("text/html");
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
int sum=0;
while(e.hasMoreElements())
{
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
sum+=Integer.parseInt(pvalue);
pw.println(pvalue);
}
pw.println("Sum = "+sum);
pw.close();
}
}

32
==================================================================
3. ​HelloForm.java
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloForm extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

​// Create cookies for first and last names.


Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));

​// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);

​ // Add both the cookies in the response header.


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

​// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Setting Cookies Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head>
<title>" + title + "</title>
</head>\n" +

33
"<body>\n" +
"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>
</html>"
);
}
}
Web.html
<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
==================================================================
4.
Servlet API
Servlet API consists of two important packages that encapsulates all the important classes
and interface, namely :
● ​javax.servlet
● ​javax.servlet.http

Some Important Classes and Interfaces of javax.servlet

INTERFACES CLASSES

Servlet ServletInputStream

34
ServletContext ServletOutputStream

ServletConfig ServletRequestWrapper

ServletRequest ServletResponseWrapper

ServletResponse ServletRequestEvent

ServletContextListener ServletContextEvent

RequestDispatcher ServletRequestAttributeEvent

SingleThreadModel ServletContextAttributeEvent

Filter ServletException

FilterConfig UnavailableException

FilterChain GenericServlet

ServletRequestListener

Some Important Classes and Interface of javax.servlet.http

CLASSES INTERFACES

HttpServlet HttpServletRequest

HttpServletResponse HttpSessionAttributeListener

HttpSession HttpSessionListener

Cookie HttpSessionEvent

==================================================================
5. COOKIES
Cookies are small text files that are used to maintain the different session when a user online
for shopping different items from same web store. Cookies are send by the web server to the

35
client browser. The browser later return unchanged when visit the same web page again.
Once the web server receives cookie information the servlet program processes the cookie
information and recognizes it as a new user or already visited user. Cookies are therefore, a
accepted method used by the web server for session tracking. Since the enable web servers to
store and retrieve data from the client side. Cookies let a user to log in automatically. Cookies
can be used to remember user preferences

Example
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

36
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>
==================================================================
6. Session Tracking:
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the
client opens a separate connection to the Web server and the server automatically does not
keep any record of previous client request.
Still there are following three ways to maintain session between web client and web server −

37
Cookies
A web server can assign a unique session ID as a cookie to each web client and for
subsequent requests from the client they can be recognized using the recieved cookie.

This may not be an effective way because many time browser does not support a cookie, so I
would not recommend to use this procedure to maintain the sessions.
Hidden Form Fields
A web server can send a hidden HTML form field along with a unique session ID as follows
<input type = "hidden" name = "sessionid" value = "12345">
This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or POST data. Each time when web browser sends request
back, then session_id value can be used to keep the track of different web browsers.

This could be an effective way of keeping track of the session but clicking on a regular (<A
HREF...>) hypertext link does not result in a form submission, so hidden form fields also
cannot support general session tracking.
URL Rewriting
You can append some extra data on the end of each URL that identifies the session, and the
server can associate that session identifier with data it has stored about that session.

For example, with http://tutorialspoint.com/file.htm;sessionid = 12345, the session identifier


is attached as sessionid = 12345 which can be accessed at the web server to identify the
client.

URL rewriting is a better way to maintain sessions and it works even when browsers don't
support cookies. The drawback of URL rewriting is that you would have to generate every
URL dynamically to assign a session ID, even in case of a simple static HTML page.
The HttpSession Object
Apart from the above mentioned three ways, servlet provides HttpSession Interface which
provides a way to identify a user across more than one page request or visit to a Web site and
to store information about that user.

The servlet container uses this interface to create a session between an HTTP client and an
HTTP server. The session persists for a specified time period, across more than one
connection or page request from the user.

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

HttpSession session = request.getSession();

//SESSION TRACKING USING SERVLET

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

public class SessionServletDemo extends HttpServlet


{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
HttpSession session=request.getSession();
String heading;
Integer c=(Integer)session.getAttribute("c");
if(c==null)
{
c=new Integer(0);
heading="WELCOME YOU ARE ACCESSING THE PAGE FOR THE FIRST
TIME";
}
else
{
heading="WELCOME ONCE AGAIN!";
c=new Integer(c.intValue()+1);
}
session.setAttribute("c",c);
pw.println("<html>");
pw.println("<head>");
pw.println("<title>");
pw.println("SESSION DEMO USING PHP");
pw.println("</title>");
pw.println("</head>");
pw.println("<body>");
pw.println("<h1>" +heading);
pw.println("<h2>THE NUMBER OF PREVIOUS ACCESS=" +c);
pw.println("</body>");
pw.println("</html>");
pw.close();
}//doGet
}//Session Servlet Demo
==================================================================

39
Unit-4
1. Explain about Anatomy of JSP page
2. Write about JSP processing. Explain the components of JSP page?
3. Explain About implicit objects.
4. Differentiate JSP and Servlet and Explain JSP by taking suitable example?
5. Develop a JSP with a Bean in the application scope?
6. Explain cookies and session tracking of JSP by taking suitable examples?

Answers
1. Anatomy of JSP page:
● It is simply a regular web page with JSP elements.
● Everything in the page that is not a JSP element is called template text.
● This can be any text :- HTML, XML, WML or even plain text.
● When a JSP page request is processed, the template text and dynamic content
generated by the JSP elements are merged.

==================================================================
2. JSP processing
The following steps explain how the web server creates the Webpage using JSP −
1. 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

40
JSP engine. This is done by using the URL or JSP page which ends with .jsp instead
of .html.
2. 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.
3. The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
4. 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 the servlet engine inside an HTTP response.
5. The web server forwards the HTTP response to your browser in terms of static HTML
content.
6. 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 −

JSP Components
In this section we will discuss about the elements of JSP.

Structure of JSP Page:​ JSPs are comprised of standard HTML tags and JSP tags. The
structure of JavaServer pages are simple and easily handled by the servlet engine. In addition
to HTML ,you can categorize JSPs as following -
● Directives
● Declarations
● Scriptlets
● Comments
● Expressions
Directives :

41
A directives tag always appears at the top of your JSP file. It is global definition sent to the
JSP engine. Directives contain special processing instructions for the web container. You can
import packages, define error handling pages or the session information of the JSP page.
Directives are defined by using <%@ and %> tags.

Syntax -​ <%@ directive attribute="value" %>

Declarations :
This tag is used for defining the functions and variables to be used in the JSP. This element of
JSPs contains the java variables and methods which you can call in expression block of JSP
page. Declarations are defined by using <%! and %> tags. Whatever you declare within these
tags will be visible to the rest of the page.

Syntax ​- <%! declaration(s) %>

Scriptlets:
In this tag we can insert any amount of valid java code and these codes are placed in
_jspService method by the JSP engine. Scriptlets can be used anywhere in the page. Scriptlets
are defined by using <% and %> tags.

Syntax -​ <% Scriptlets%>

Comments :
Comments help in understanding what is actually code doing. JSPs provides two types of
comments for putting comment in your page. First type of comment is for output comment
which is appeared in the output stream on the browser. It is written by using the <!-- and -->
tags.

Syntax - ​ <!-- comment text -->


Second type of comment is not delivered to the browser. It is written by using the <%-- and
--%> tags.
Syntax -​ <%-- comment text --%>

Expressions :
Expressions in JSPs is used to output any data on the generated page. These data are
automatically converted to string and printed on the output stream. It is an instruction to the
web container for executing the code with in the expression and replace it with the resultant
output content. For writing expression in JSP, you can use <%= and %> tags.

Syntax - ​<%= expression %>


==================================================================
3. Implicit Objects

42
These Objects 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 −

The request Object


The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time
a client requests a page 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

43
The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to
send content in a response. The initial JspWriter object is instantiated differently depending
on whether the page is buffered or not. Buffering can be easily turned off by using the
buffered = 'false' attribute of the page directive.
The JspWriter object contains most of the same methods as the java.io.PrintWriter class.
However, JspWriter has some additional methods designed to deal with buffering. Unlike the
PrintWriter object, JspWriter throws IOExceptions.

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.
By adding an attribute to application, you can ensure that all JSP files that make up your web
application have access to it.

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();
This returns the servlet name, which is the string contained in the <servletname> element
defined in the WEB-INF\web.xml file.

The pageContext Object


The pageContext object is an instance of a javax.servlet.jsp.PageContextobject. The
pageContext object is used to represent the entire JSP page.
This object is intended as a means to access information about the page while avoiding most
of the implementation details.
This object stores references to the request and response objects for each request. The
application, config, session, and out objects are derived by accessing attributes of this object.
The pageContext object also contains information about the directives issued to the JSP page,
including the buffering information, the errorPageURL, and page scope.

44
The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE,
SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes. It also
supports more than 40 methods, about half of which are inherited from the
javax.servlet.jsp.JspContext class.
One of the important methods is removeAttribute. This method accepts either one or two
arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute
from all scopes, while the following code only removes it from the page scope −
pageContext.removeAttribute("attrName", PAGE_SCOPE);

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 entire JSP 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 to generate an appropriate response to the error condition.
==================================================================
4.

JSP:
● It stands for Java Server Pages.

45
● 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 pages are more advantageous than Servlet:


1. They are easy to maintain.
2. No recompilation or redeployment is required.
3. JSP has access to entire API of JAVA .
4. JSP are extended version of Servlet.

Example of Hello World


We will make one .html file and .jsp file
demo.jsp
<html>
<head>
<title>Hello World - JSP tutorial</title>
</head>
<body>
<%= "Hello World!" %>
</body>
</html>

==================================================================
5. 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() {
}

46
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 variable that 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 − −

47
The date/time is Thu Sep 30 11:18:11 GST 2010

Accessing JavaBeans Properties


Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to access the
get methods and the <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:useBean>
The name attribute references the id of a JavaBean previously introduced to the JSP by the
useBean action. The property 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"/>

48
</p>

</body>
</html>
Let us make the StudentsBean.class available in CLASSPATH. Access the above JSP. the
following result will be displayed −

Student First Name: Zara


Student Last Name: Ali
Student Age: 10

==================================================================
6. Cookies in JSP:
Cookies are text files stored on the client computer and they are kept for various information
tracking purposes. JSP transparently supports HTTP cookies using underlying servlet
technology.

There are three steps involved in identifying and returning users −


1. Server script sends a set of cookies to the browser. For example, name, age, or
identification number, etc.
2. Browser stores this information on the local machine for future use.
3. When the next time the browser sends any request to the web server then it sends
those cookies information to the server and server uses that information to identify the
user or may be for some other purpose as well.
Example:
<%
​ // Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));

​// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);

​// Add both the cookies in the response header.


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

<html>
<head>
<title>Setting Cookies</title>

49
</head>
<body>
<center>
<h1>Setting Cookies</h1>
</center>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>

Session Tracking JSP:


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

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

50
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>
</table>

51
</body>
</html>

==================================================================

52
Unit-5
1. Write a JavaScript program to check whether the given number is palindrome or not.
Show the result in an alert () dialog box.
2. Write a web page which prompts the user for six items of input ,stores this in an array
and display it using join (). Display the data in a sorted order.
3. Write a JavaScript program to handle mouse events.
4. Define javascript? Justify how javascript is Object oriented?
5. Write javascript function which will find the L.C.M. and G.C.D. of two numbers?
6. Explain about Document Object Model with example?
7. Write a program for form validation with example?
8. Explain about simple AJAX Application?

Answers
1.
<html>
<head>
<script type=text/javascript>
function Palindrome()
{
var rem, temp, final = 0;
var number = Number(document.getElementById("N").value);
temp = number;
while(number>0)
{
rem = number%10;
number = parseInt(number/10);
final = final*10+rem;
}
if(final==temp)
{
window.alert("The inputted number is Palindrome");
}
else
{
window.alert("The inputted number is not palindrome");
}
}
</script>
</head>
<body>
<br>

53
<h1>Whether a number is Palindrome or not</h1>
Enter The Number :<input type="text" name="n" id = "N"/><br>
<center><button onClick="Palindrome()">CHECK</button>
</body>
</html>
==================================================================
2.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
var x = 0;
var array = Array();
function add_element_to_array() {
array[x] = document.getElementById("text1").value;
alert("Element: " + array[x] + " Added at index " + x);
x++;
document.getElementById("text1").value = "";
}

function display_array() {
array.sort();
var e = "<hr/>";
for (var y=0; y<array.length; y++) {
e +=array[y] + " ";
}
document.getElementById("Result").innerHTML = e;
}
</script>
</head>
<body>
<input type="text" id="text1"></input>
<input type="button" id="button1" value="Add" onclick="add_element_to_array();">
</input>
<input type="button" id="button2" value="Display" onclick="display_array();">
</input>
document.getElementById("Result").innerHTML = e;
</body>
</html>
==================================================================

54
3.
i. onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of
his mouse. You can put your validation, warning etc., against this event type.

Example
Try the following example.

<html>
<head>
<script type = "text/javascript">
function sayHello() {
alert("Hello World")
}
</script>
</head>

<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
Output

ii. onsubmit Event Type


onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.

Example
The following example shows how to use onsubmit. Here we are calling a validate() function
before submitting a form data to the web server. If validate() function returns true, the form
will be submitted, otherwise it will not submit the data.

Try the following example.

<html>
<head>

55
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>

<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>

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

Example:
<html>
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>

<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">

56
<h2> This is inside the division </h2>
</div>
</body>
</html>
Output

==================================================================
4. Javascript (JS)​ is a scripting languages, primarily used on the Web. It is used to enhance
HTML pages and is commonly found embedded in HTML code. JavaScript is an interpreted
language. Thus, it doesn't need to be compiled. JavaScript renders web pages in an interactive
and dynamic fashion. This allowing the pages to react to events, exhibit special effects,
accept variable text, validate data, create cookies, detect a user’s browser, etc.

Object-oriented​ (OO) languages usually are recognized through their use of classes for
creating various objects which have the equivalent properties and methods. It is to be noted
that, ECMA-Script has no concept of classes, and hence objects are different than in
class-based languages.
ECMA-262 describes and classifies an object as an "​unordered collection of dissimilar
properties each of them having a primitive value, object, or function.​" Firmly speaking, this
means that an object is an array of all values in no specific order. Each property and/or
method is recognized by a name which is mapped to a value. For this reason, it thinks of
ECMA-Script objects as hash tables i.e., nothing more than a combination of name-value
pairs where the value may be data or a function. In this chapter, you will learn about
JavaScript Object oriented concepts.

The simplest way to create a custom object is to create a new instance of Object and add
properties and methods to it, as in the example mentioned below:

var person = new Object();


person.name = "Karlos";
person.age = 23;
person.job = "Network Engineer";
person.say_Name = function(){
alert (this.name);
};
This example creates an object called the person that has three properties which are: name,
age, and job and one method (say_Name()). The say_Name() method is used to display the
value of this.name, which resolves to person.name.

57
The previous example can be rewritten using literal object notation as follows:

var person = {
name: "Karlos",
age: 23,
job: "Network Engineer",
say_Name: function(){
alert(this.name);
}
};
The person object in the above example is equivalent to the person object in the prior
example mentioned earlier, with all those same properties and methods added. These
properties are all created with certain characteristics that define their behavior in JavaScript.

Since JavaScript is an object-oriented programming language and so a programming


language can be called object-oriented when it provides programmers with at least four basic
capabilities to develop:

1. Encapsulation​: It is the capability for storing related information, whether data or


methods mutually in a single object.
2. Aggregation​: It is the ability to store one object inside another.
3. Inheritance​: A class can depend upon another class or number of classes and inherit
their variables and methods for some specific use.
4. Polymorphism​: It is the potential of the concept of OOP for writing one function or
method which works in a variety of different ways.
Objects are composed of attributes, and when an attribute contains a function, it is considered
to be a method of the object else the attribute is considered a property.

Object properties can be any of the three basic data types or any of the abstract data types.
Object properties​ are variables which are used within the object's methods, but as well can
be globally visible variables which are used throughout the page.

The syntax for including any property to an object is:

Obj_Name . obj_Property = property_Value;


==================================================================
5.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>LCM & GCD of two numbers</title>

58
<script type=text/javascript>
function lcm_two_numbers(x, y) {
if ((typeof x !== 'number') || (typeof y !== 'number'))
return false;
return (!x || !y) ? 0 : Math.abs((x * y) / gcd_two_numbers(x, y));
}

function gcd_two_numbers(x, y) {
x = Math.abs(x);
y = Math.abs(y);
while(y) {
var t = y;
y = x % y;
x = t;
}
return x;
}

function gcd_lcm() {
a=Number(document.getElementById("a_input").value);
b=Number(document.getElementById("b_input").value);
console.log(lcm_two_numbers(a,b));
console.log(gcd_two_numbers(a,b));
}
</script>
</head>
<body>
Enter any Number: <input id="a_input">
Enter any Number: <input id="b_input">
<button onclick="gcd_lcm()">Find</button></br></br>
</body>
</html>
==================================================================
6. ​Every web page resides inside a browser window which can be considered as an object.

A Document object represents the HTML document that is displayed in that window. The
Document object has various properties that refer to other objects which allow access to and
modification of document content.

The way a document content is accessed and modified is called the ​Document Object
Model​, or DOM. The Objects are organized in a hierarchy. This hierarchical structure applies
to the organization of objects in a Web document.

59
JavaScript can access all the elements in a webpage making use of Document Object Model
(DOM). In fact, the web browser creates a DOM of the webpage when the page is loaded.
The DOM model is created as a tree of objects like this:

Using DOM, JavaScript can perform multiple tasks. It can create new elements and attributes,
change the existing elements and attributes and even remove existing elements and attributes.
JavaScript can also react to existing events and create new events in the page.

getElementById, innerHTML Example


1. getElementById: To access elements and attributes whose id is set.
2. innerHTML: To access the content of an element.

Example:
<html>
<head>
<title>DOM!!!</title>
</head>
<body>
<h1 id="one">Welcome</h1>
<p>This is the welcome message.</p>
<h2>Technology</h2>
<p>This is the technology section.</p>
<script type="text/javascript">
var text = document.getElementById("one").innerHTML;
alert("The first heading is " + text);
</script>
</body>
</html>
==================================================================

60
7.
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
//-->
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 )) {
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}

function validate() {
if( document.myForm.Name.value == "" ) {
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" || isNaN(
document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 ) {

alert( "Please provide a zip in the format #####." );


document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" ) {
alert( "Please provide your country!" );
return false;

61
}
return( true );
}
</script>
</head>

<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit = "return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
==================================================================

62
8. ​Ajax is the method of using JavaScript to send the client data on the server and then
retrieve it without refreshing the complete page. We can us the XMLHttpRequest object to
perform a GET or POST and then retrieve the server response without page refresh.

Simple Ajax Example


In this tutorial we are going to develop a very simple Ajax Example. This simple Ajax
example code will help you in understanding the core concept of Ajax.
In this tutorial we are developing a simple Ajax example application that sends the user name
on the server without refreshing the page.
It also process the server response and then display the response text on the same page.
This application is using the XMLHttpRequest object for making a call to the server side
script.
We are using PHP script to process the request.

<html>
<head>
<title>Simple Ajax Example</title>
<script language="Javascript">

function postRequest(strURL) {
var xmlHttp;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
var xmlHttp = new XMLHttpRequest();
}else if (window.ActiveXObject) { // IE
var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.open('POST', strURL, true);
xmlHttp.setRequestHeader
('Content-Type', 'application/x-www-form-urlencoded');
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
updatepage(xmlHttp.responseText);
}

63
}
xmlHttp.send(strURL);
}

function updatepage(str){
document.getElementById("result").innerHTML =
"<font color='red' size='5'>" + str + "</font>";;
}

function SayHello(){
var usr=window.document.f1.username.value;
var rnd = Math.random();
var url="sayhello.php?id="+rnd +"&usr="+usr;
postRequest(url);
}
</script>
</head>
<body>
<h1 align="center">Simple Ajax Example</h1>
<p align="center">Enter your name and then press "Say Hello Button"</p>
<form name="f1">
<p align="center">
Enter your name:
<input type="text" name="username" id="username">
<input value="Say Hello" type="button" onclick='JavaScript:SayHello()'
name="showdate">
</p>
<div id="result" align="center"></div>
</form>
<div id=result></div>
</body>
</html>
==================================================================

64

You might also like