Professional Documents
Culture Documents
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.
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:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Output:
This condition is true
5.Array:
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.
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
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:
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)
);
Creating 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.
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
Increment/Decrement operators
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:
Assignment Operators:
There are following assignment operators supported by PHP language:
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.
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 ~.
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
The preg_match_all() function will tell you how many matches were found for a pattern in a string.
Example
The preg_replace() function will replace all of the matches of the pattern in a string with another
string.
Example
Modifier Description
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)
Expression Description
[abc] Find one character from the options between the brackets
[^abc] Find any character NOT between the brackets
Metacharacters
Metacharacter Description
| Find a match for any one of the patterns separated by | as in: cat|dog|fish
\d Find a digit
\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
Quantifier Description
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
?>
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>
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>
<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
<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.
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.
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:
OUTPUT:
6. Elaborate Connecting to Database( My SQL as Reference)?
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
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);
?>
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>
<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>
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);
?>
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
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
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
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
hello
// Change directory
chdir("images");
Result:
/home/php
/home/php/images
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.
Syntax
chroot(directory)
directory- Required. Specifies the new current directory
<?php
// Change root directory
chroot("/path/to/chroot/");
Result:
/
PHP closedir() Function
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
Both handle and path properties have three methods: read(), rewind(), and close()
Syntax
dir(directory, context)
<?php
$d = dir(getcwd());
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
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/";
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)
Result:
filename: cat.gif
filename: dog.gif
filename: horse.gif
PHP rewinddir() Function
Syntax
rewinddir(dir)
Open a directory, list its files, reset directory handle, list its files once again, then close:
<?php
$dir = "/images/";
Result:
filename: cat.gif
filename: dog.gif
filename: horse.gif
filename: cat.gif
filename: dog.gif
filename: horse.gif
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.
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.
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>
<garden>
<plants category = "flowers" />
<plants category = "shrubs">
</plants>
</garden>
Example
Following is a simple example of internal DTD −
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 −
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 −
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.
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>
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>
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:
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.
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.
Applets are executed on client side. Servlets are executed on server side.
Life cycle of Applets init(), stop(), paint(), Lifecycle of servlets are:- init( ), service( ),
start(), destroy(). and destroy( ).
APPLETS SERVLETS
Applets utilize more network bandwidth as it Servlets are executed on the servers and
executes on the client machine. hence require less bandwidth.
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
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:
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.
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.
ServletConfig interface
When the Web Container initializes a servlet, it creates a ServletConfig object for the servlet.
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
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.
Methods
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.
Interfaces
HttpServletRequest
HttpServletResponse
HttpSession
Classes
1.HttpServlet 2.Cookie
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.
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.
<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>
< 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>
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"));
}
}
sun.jdbc.JdbcOdbcDriver
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
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
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).
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.
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.
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());
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();
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);
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:
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 :
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";
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?
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
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>
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.
Parsing of JSP
Turning JSP into servlet
Compiling the servlet
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.
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.
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
Ans: The jsp directives are messages that tells the web container how to translate a JSP page into the
correspondingservlet.
page directive
include directive
taglib 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:
The web container in such a case, will generate the servlet as:
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.
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).
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.
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>
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>
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>
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
<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>
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.
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 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.
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 −
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"
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
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.
id 0AE3EC93FF44E3C525B4351B77ABB2D5
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
User ID ABCD
Number of visits 1
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:\>
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>
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).
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:
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
<script>
function abc(){
var x=10;//local variable
}
</script>
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:
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.
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?
5 Marks
JavaScript in <body>
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.
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
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.
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).
Function Invocation:
The code inside the function will execute when "something" invokes (calls) the function:
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:
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.
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
No Proper
. ty
1 length
Example:
<html>
<head>
<script>
function
goBack() {
window.history
.back()
}
</script>
</head>
<body>
<input type="button" value="Back" onclick="goBack()">
</body>
</html>