0% found this document useful (0 votes)
360 views65 pages

Javascript: Where Javascript Is Used

Uploaded by

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

Javascript: Where Javascript Is Used

Uploaded by

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

Unit-2

Javascript
JavaScript is an object-based scripting language that is lightweight and cross-platform.
JavaScript is not compiled but translated.

Where JavaScript is used


JavaScript is used to create interactive websites.
It is mainly used for:
o Client-side validation
o Dynamic drop-down menus
o Displaying data and time
o Displaying popup windows and dialog boxes
o Displaying clocks etc.

JavaScript Example
<html>
<body>
<h2>Welcome to JavaScript</h2>
<script>
document.write("Hello JavaScript by JavaScript");
</script>
</body>
</html>

JavaScript
Javascript example is easy to code.
JavaScript provides 3 places to put the JavaScript code:
within body tag, within head tag and external JavaScript file.

<html>
<body>
<script type="text/javascript">
document.write("JavaScript is a simple language for javatpoint learners");
</script>
</body>
</html>

The script tag specifies that we are using JavaScript.


The text/javascript is the content type that provides information to the browser about the data.
The document.write() function is used to display dynamic content through JavaScript.

Places to put JavaScript code


1. Between the body tag of html
2. Between the head tag of html
3. In .js file (external javaScript)

JavaScript Example : code between the body tag


<html>
<body>
<script type="text/javascript">
alert("Hello Javatpoint");
</script>
</body>
</html>
Alert Dialog Box
An alert dialog box is mostly used to give a warning message to the users.
For example, if one input field requires to enter some text but the user does not provide any input, then as a part of
validation, you can use an alert box to give a warning message.
JavaScript Example : code between the head tag
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

External JavaScript file


An external JavaScript file must be saved by .js extension.
message.js
function msg(){
alert("Hello Javatpoint");
}
a.html
<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

JavaScript Comment
Single line Comment
It is represented by double forward slashes (//).
It can be used before and after the statement.
Multi line Comment
/* It is multi line comment.
It will not be displayed */

JavaScript Variable
JavaScript variables are case sensitive, for example x and X are different variables.
Correct JavaScript variables
var x = 10;
var _value="sonoo";
Example of JavaScript variable
<html>
<body>
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
</body>
</html>

JavaScript local variable


A JavaScript local variable is declared inside block or function
<script>
function abc(){
var x=10;//local variable
}
</script>
JavaScript global variable
A JavaScript global variable is accessible from any function.
<script>
var data=200;//gloabal variable
function a(){
document.writeln(data);
}
function b(){
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>
JavaScript Global Variable
A JavaScript global variable is declared outside the function
<html>
<body>
<script>
var value=50;//global variable
function a(){
alert(value);
}
function b(){
alert(value);
}

a();
</script>
</body>
</html>

Declaring JavaScript global variable within function


To declare JavaScript global variables inside function, you need to use window object.
window.value=90;
<html>
<body>
<script>
function m(){
window.value=100;//declaring global variable by window object
}
function n(){
alert(window.value);//accessing global variable from other function
}
m();
n();
</script>
</body>
</html>

Javascript Data Types


JavaScript provides different data types to hold different types of values. There are two types of data types in
JavaScript.
1. Primitive data type
2. Non-primitive (reference) data type
JavaScript is a dynamic type language, means you don't need to specify type of the variable because it is dynamically
used by JavaScript engine.
use var here to specify the data type. It can hold any type of values such as numbers, strings etc.
For example:
var a=40;//holding number
var b="Rahul";//holding string

JavaScript primitive data types


There are five types of primitive data types in JavaScript. They are as follows:
Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

JavaScript non-primitive data types


The non-primitive data types are as follows:
Data Type Description

Object represents instance through which we can access members

Array represents group of similar values

RegExp represents regular expression


JavaScript Operators
JavaScript operators are symbols that are used to perform operations on operands.
For example:
var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.
There are following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands.
Operator Description Example

+ Addition 10+20 = 30

- Subtraction 20-10 = 10

* Multiplication 10*20 = 200

/ Division 20/10 = 2

% Modulus (Remainder) 20%10 = 0

++ Increment var a=10; a++; Now a = 11

-- Decrement var a=10; a--; Now a = 9


JavaScript Comparison Operators
The JavaScript comparison operator compares the two operands. The comparison operators are as follows:
Operator Description Example

== Is equal to 10==20 = false

=== Identical (equal and of same type) 10==20 = false

!= Not equal to 10!=20 = true

!== Not Identical 20!==20 = false

> Greater than 20>10 = true

>= Greater than or equal to 20>=10 = true

< Less than 20<10 = false

<= Less than or equal to 20<=10 = false


JavaScript Bitwise Operators
The bitwise operators perform bitwise operations on operands. The bitwise operators are as follows:
Operator Description Example

& Bitwise AND (10==20 & 20==33) = false

| Bitwise OR (10==20 | 20==33) = false

^ Bitwise XOR (10==20 ^ 20==33) = false

~ Bitwise NOT (~10) = -10

<< Bitwise Left Shift (10<<2) = 40


>> Bitwise Right Shift (10>>2) = 2

>>> Bitwise Right Shift with Zero (10>>>2) = 2


JavaScript Logical Operators
The following operators are known as JavaScript logical operators.
Operator Description Example

&& Logical AND (10==20 && 20==33) = false

|| Logical OR (10==20 || 20==33) = false

! Logical Not !(10==20) = true


JavaScript Assignment Operators
The following operators are known as JavaScript assignment operators.
Operator Description Example

= Assign 10+10 = 20

+= Add and assign var a=10; a+=20; Now a = 30

-= Subtract and assign var a=20; a-=10; Now a = 10

*= Multiply and assign var a=10; a*=20; Now a = 200

/= Divide and assign var a=10; a/=2; Now a = 5

%= Modulus and assign var a=10; a%=2; Now a = 0


JavaScript Special Operators
The following operators are known as JavaScript special operators.
Operator Description

(?:) Conditional Operator returns value based on the condition. It is like if-else.

, Comma Operator allows multiple expressions to be evaluated as single statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.

JavaScript If-else
The JavaScript if-else statement is used to execute the code whether condition is true or false. There are three forms
of if statement in JavaScript.
1. If Statement
2. If else statement
3. if else if statement
JavaScript If statement
<html>
<body>
<script>
var a=20;
if(a>10){
document.write("value of a is greater than 10");
}
</script>
</body>
</html>
JavaScript If...else Statement
<html>
<body>
<script>
var a=20;
if(a%2==0){
document.write("a is even number");
}
else{
document.write("a is odd number");
}
</script>
</body>
</html>

JavaScript If...else if statement


<html>
<body>
<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>
</body>
</html>
JavaScript Switch
The JavaScript switch statement is used to execute one code from multiple expressions.
<html>
<body>
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
document.write(result);
</script>
</body>
</html>
JavaScript Loops
The JavaScript loops are used to iterate the piece of code using for, while, do while or for-in loops
There are four types of loops in JavaScript.
1. for loop
2. while loop
3. do-while loop

JavaScript For loop


The JavaScript for loop iterates the elements for the fixed number of times.
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>
</body>
</html>
JavaScript while loop
The JavaScript while loop iterates the elements for the infinite number of times.
<html>
<body>
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>
</body>
</html>
JavaScript do while loop
do{
code to be executed
}while (condition);
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>
</body>
</html>
JavaScript Functions
JavaScript functions are used to perform operations.
There are mainly two advantages of JavaScript functions.
1. Code reusability: We can call a function several times so it save coding.
2. Less coding: It makes our program compact.
The syntax of declaring function is given below.
function functionName([arg1, arg2, ...argN]){
//code to be executed
}
JavaScript Function Example
<html>
<body>
<script>
function msg(){
alert("hello! this is message");
}
</script>
<input type="button" onclick="msg()" value="call function"/>
</body>
</html>
JavaScript Function Arguments
<html>
<body>
<script>
function getcube(number){
alert(number*number*number);
}
</script>
<form>
<input type="button" value="click" onclick="getcube(4)"/>
</form>
</body>
</html>

Function with Return Value


<html>
<body>
<script>
function getInfo(){
return "hello javatpoint! How r u?";
}
</script>
<script>
document.write(getInfo());
</script>
</body>
</html>
JavaScript Objects
A JavaScript object is an entity having state and behavior (properties and method).
For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language.
Everything is an object in JavaScript.
Creating Objects in JavaScript
There are 3 ways to create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

JavaScript Object by object literal

object={property1:value1,property2:value2.....propertyN:valueN}

<html>
<body>
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
By creating instance of Object
The syntax of creating object directly is given below:
<html>
<body>
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
</body>
</html>
By using an Object constructor
We need to create function with arguments.
Each argument value can be assigned in the current object by using this keyword.
The this keyword refers to the current object.
<html>
<body>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);


</script>
</body>
</html>

JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
JavaScript array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
<html>
<body>
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
</body>
</html>

JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:
var arrayname=new Array();

<html>
<body>
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
JavaScript array constructor (new keyword)
We need to create instance of array by passing arguments in constructor
<html>
<body>
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
</body>
</html>
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
1. By string literal
2. By string object (using new keyword)
By string literal
The string literal is created using double quotes. The syntax of creating string using string literal is given
below:
var stringname="string value";
<html>
<body>
<script>
var str="This is string literal";
document.write(str);
</script>
</body>
</html>
By string object (using new keyword)
The syntax of creating string object using new keyword is given below:
var stringname=new String("string literal");
JavaScript String Methods
Let's see the list of JavaScript string methods with examples.
o charAt(index)
o concat(str)
o indexOf(str)
o lastIndexOf(str)
o toLowerCase()
o toUpperCase()
o slice(beginIndex, endIndex)- returns the parts of string from given beginIndex to endIndex.
o trim()- removes leading and trailing whitespaces from the string.

String charAt(index) Method

<html>
<body>
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
</body>
</html>
String concat(str) Method
<script>
var s1="javascript ";
var s2="concat example";
var s3=s1.concat(s2);
document.write(s3);
</script>
JavaScript Date Object
The JavaScript date object can be used to get year, month and day.
We can display a timer on the webpage by the help of JavaScript date object.
Constructor
You can use 4 variant of Date constructor to create date object.
Date()
Date(milliseconds)
Date(dateString)
Date(year, month, day, hours, minutes, seconds, milliseconds)
JavaScript Date Methods
The important methods of date object are as follows:

Method Description

getFullYear() returns the year in 4 digit e.g. 2015. It is a new method


and suggested than getYear() which is now deprecated.

getMonth() returns the month in 2 digit from 0 to 11. So it is better to


use getMonth()+1 in your code.

getDate() returns the date in 1 or 2 digit from 1 to 31.

getDay() returns the day of week in 1 digit from 0 to 6.


getHours() returns all the elements having the given name value.

getMinutes() returns all the elements having the given class name.

getSeconds() returns all the elements having the given class name.

getMilliseconds() returns all the elements having the given tag name.

The HTML <span> tag is used for grouping and applying styles to inline elements.
To print date/month/year.
<html>
<body>
Current Date : <script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
</script>
</body>
</html>
JavaScript Current Time Example
Let's see the simple example to print current time of system.
Current Time: <span id="txt"></span>
<script>
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script>

Document Object Model


The document object represents the whole html document.
When html document is loaded in the browser, it becomes a document object.
It is the root element that represents the html document.
It has properties and methods.
By the help of document object, we can add dynamic content to our web page.
it is the object of window. So
window.document
Is same as document
Properties of document object
The properties of document object that can be accessed and modified by the document object.

Methods of document object


We can access and change the contents of document by its methods.
The important methods of document object are as follows:

Method Description

write("string") writes the given string


On the document.

writeln("string") writes the given string on the


document with newline character at
The end.

getElementById() returns the element having


The given id Value.

getElementsByName() returns all the elements having


The given name Value.
getElementsByTagName() returns all the elements having
The given tag name.

getElementsByClassName() returns all the elements having the given class


Name.

Accessing field value by document object


Here, we are using document.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.
form1 is the name of the form.
name is the attribute name of the input text.
value is the property, that returns the value of the input text.
<html>
<head>
<title>web page</title>
</head>
<body>
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
</body>
</html>
Javascript- document.getElementById() method
The document.getElementById() method returns the element of specified id.
we have used document.form1.name.value to get the value of the input value.
Instead of this, we can use document.getElementById() method to get value of the input text.
But we need to define id for the input field.
<html>
<head>
<title>web page</title>
</head>
<body>
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
</body>
</html>
Javascript-document.getElementsByName() method
document.getElementsByName() method returns all the element of specified name.
The syntax of the getElementsByName() method is given below:
document.getElementsByName("name")
Example
To count total number of genders

<html>
<head>
<title>web page</title>
</head>
<body>
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total Genders">
</form>

</body>
</html>

Javascript- document.getElementsByTagName() method


The document.getElementsByTagName() method returns all the element of specified tag
name.
The syntax of the getElementsByTagName() method is given below:
document.getElementsByTagName("name")
example, -to count total number of paragraphs used in the document.
<html>
<head>
<title>web page</title>
</head>
<body>
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);

}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by getElementByTagNam
e() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
</body>
</html>
Javascript - innerHTML
The innerHTML property can be used to write the dynamic html on the html document.
It is used mostly in the web pages to generate the dynamic html such as registration form,
comment form, links etc.
Example of innerHTML property
In this example, we are going to create the html form when user clicks on the button.
<html>
<body>
<script type="text/javascript" >
function showcommentform() {
var data="Name:<br><input type='text' name='name'><br>Comment:<br><textarea
rows='5' cols='50'></textarea><br><input type='submit' value='comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
</body>
</html>

Javascript – innerText
The innerText property can be used to write the dynamic text on the html document.
Here, text will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as writing the
validation message, password strength etc.
Example

<html>
<body>
<script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}

</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>
</body>
</html>
The HTML <span> tag is used for grouping and applying styles to inline elements.
There is a difference between the span tag and the div tag.
The span tag is used with inline elements whilst the div tag is used with block-level content.

JavaScript Form Validation


It is important to validate the form submitted by the user because it can have inappropriate
values. So validation is must.
Through JavaScript, we can validate name, password, email, date, mobile number etc fields.
JavaScript form validation example
In this example, we are going to validate the name and password. The name can’t be empty
and password can’t be less than 6 characters long.
Here, we are validating the form on form submit.
<html>
<body>
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}
}
</script>
<body>
<form name="myform" method="post" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="submit">
</form>
</body>
</html>
Definition and Usage-GET & POST attributes in forms
The method attribute specifies how to send form-data (the form-data is sent to the page
specified in the action attribute).
The form-data can be sent as URL variables (with method="get") or as HTTP post
transaction (with method="post").
Notes on GET:
 Appends form-data into the URL in name/value pairs
 The length of a URL is limited (about 3000 characters)
 Never use GET to send sensitive data! (will be visible in the URL)
 Useful for form submissions where a user want to bookmark the result
 GET is better for non-secure data, like query strings in Google
Notes on POST:
 Appends form-data inside the body of the HTTP request (data is not shown is in URL)
 Has no size limitations
 Form submissions with POST cannot be bookmarked
Definition and Usage-of action attribute in form
The action attribute specifies where to send the form-data when a form is submitted.

JavaScript Retype Password Validation


<html>
<head>
<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword){
return true;
}
else{
alert("password must be same!");
return false;
}
}
</script>
</head>
<body>

<form name="f1" onsubmit="return matchpass()">


Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>

</body>
</html>
JavaScript email validation
We can validate the email by the help of JavaScript.
There are many criteria that need to be following to validate the email id such as:
o email id must contain the @ and . character
o There must be at least one character before and after the @.
o There must be at least two characters after . (dot).
<html>
<body>
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n ");
return false;
}
}
</script>
<body>
<form name="myform" method="post" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>

<input type="submit" value="register">


</form>
</body>
</html>

HTML/DOM events for JavaScript


HTML or DOM events are widely used in JavaScript code. JavaScript code is executed with
HTML/DOM events. So before learning JavaScript, let’s have some idea about events.

Events Description

onclick occurs when element is clicked.

ondblclick occurs when element is double-clicked.

onfocus occurs when an element gets focus such


as button, input, textarea etc.

onblur occurs when form looses the focus from


an element.

onsubmit occurs when form is submitted.

onmouseover occurs when mouse is moved over an


element.

onmouseout occurs when mouse is moved out from


an element (after moved over).

onmousedown occurs when mouse button is pressed over


an element.

onmouseup occurs when mouse is released from


an element (after mouse is pressed).

onload occurs when document, object or frameset


is loaded.

onunload occurs when body or frameset is


unloaded.

onscroll occurs when document is scrolled.

onresized occurs when document is resized.

onreset occurs when form is reset.

onkeydown occurs when key is being pressed.

onkeypress occurs when user presses the key.

onkeyup occurs when key is released.

JAVASCRIPT QUESTION BANK PROGRAMS


1)onsubmit Event Attribute:
<!DOCTYPE html>
<html>
<body>

<p>When you submit the form, a function is triggered which alerts some text.</p>

<form action="/action_page.php" onsubmit="myFunction()">


Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

<script>
function myFunction() {
alert("The form was submitted");
}
</script>

</body>
</html>

onload Event Attribute:

<!DOCTYPE html>
<html>
<head>
<script>
function loadImage() {
alert("Image is loaded");
}
</script>
</head>
<body>
<img src="w3javascript.gif" onload="loadImage()" width="100" height="132">

</body>
</html>

2) script to count the number of number of characters entered by user in a textbox and limit it to a particular
number.

HTML:
<input type='text' id='text'/>
JS:
function textLength(value){
var maxLength = 144;
if(value.length > maxLength) return false;
return true;
}

document.getElementById('text').onkeyup = function(){
if(!textLength(this.value)) alert('text is too long!');
}

3) java script to find and print the largest and smallest values among 10 elements of an array.

var counter=0;
var number= new Array;
number.length=9;
var newnumber;
var largest=0;

while (counter <= 10)


{

newnumber=window.prompt("Enter Numbers 1-10 Number:"+counter+".");


number[counter]= parseInt(newnumber);

counter++;
}
largest=Math.max.apply(Math, number);
document.writeln("<h1>Largest number is " +largest+ "</h1>");

4) java script program for simple basic calculator.

<html>
<form name="calculator">
<table border=4>
<tr>
<td>
<input type="text" name="text" size="18">
<br>
</td>
</tr>
<tr>
<td>
<input type="button" value="1" onclick="calculator.text.value += '1'">
<input type="button" value="2" onclick="calculator.text.value += '2'">
<input type="button" value="3" onclick="calculator.text.value += '3'">
<input type="button" value="+" onclick="calculator.text.value += ' + '">
<br>
<input type="button" value="4" onclick="calculator.text.value += '4'">
<input type="button" value="5" onclick="calculator.text.value += '5'">
<input type="button" value="6" onclick="calculator.text.value += '6'">
<input type="button" value="-" onclick="calculator.text.value += ' - '">
<br>
<input type="button" value="7" onclick="calculator.text.value += '7'">
<input type="button" value="8" onclick="calculator.text.value += '8'">
<input type="button" value="9" onclick="calculator.text.value += '9'">
<input type="button" value="*" onclick="calculator.text.value += ' * '">
<br>
<input type="button" value="c" onclick="calculator.text.value = ''">
<input type="button" value="0" onclick="calculator.text.value += '0'">
<input type="button" value="=" onclick="calculator.text.value = eval(calculator.text.value)">
<input type="button" value="/" onclick="calculator.text.value += ' / '">
<br>
</td>
</tr>
</table>
</form>
</html>

5) Write java script program to read a number and print multiplication table in HTML format for the given
number.

<script type='text/javascript'>
var num = prompt("Enter Number", "0") //prompt user to enter the number

var num = parseInt(num); //parse the num to number


var i = 0;

document.write('<table border="1" cellspacing="0">');


for(i=1;i<10;i++) {
document.write("<tr><td>" + num + " x " + i + " = " + num*i + "</td></tr>");
}

document.write("</table>");
</script>

6) java script program to perform the validation process in an application program.


<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
</head>
<body>

<form name="myForm" action="/action_page.php"


onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

</body>
</html>

JavaScript - Errors & Exceptions Handling


Runtime Errors
Runtime errors, also called exceptions, occur during execution (after
compilation/interpretation).
For example, the following line causes a runtime error because here the syntax is correct,
but at runtime, it is trying to call a method that does not exist.
<script type="text/javascript">
<!--
window.printme();
//-->
</script>

The try...catch...finally Statement


The latest versions of JavaScript added exception handling capabilities. JavaScript
implements the try...catch...finally construct as well as the throw operator to handle
exceptions.
You can catch programmer-generated and runtime exceptions, but you
cannot catch JavaScript syntax errors.
Here is the try...catch...finally block syntax −
<script type="text/javascript">
<!--
try {
// Code to run
[break;]
}

catch ( e ) {
// Code to run if an exception occurs
[break;]
}
[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>

The try block must be followed by either exactly one catch block or one finally block (or one
of both).
When an exception occurs in the try block, the exception is placed in e and the catch block
is executed.
The optional finally block executes unconditionally after try/catch.
Example
<html>
<head>
<script type="text/javascript">
<!--
function myFunc()
{
var a = 100;
var b = 0;

try{
if ( b == 0 )
{
throw( "Divide by zero error." );
}

else
{
var c = a / b;
}
}

catch ( e )
{
alert("Error: " + e );
}
}
//-->
</script>

</head>

<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="ClickMe" onclick="myFunc();" />
</form>

</body>
</html>

Input Validation Example


This example examines input.

<html>
<body>

<p>Please input a number between 5 and 10:</p>

<input id="demo" type="text">


<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>

<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script>

</body>
</html>

JavaScript Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
 An HTML web page has finished loading
 An HTML input field was changed
 An HTML button was clicked
Often, when events happen, you may want to do something.
JavaScript lets you execute code when events are detected.
EXAMPLE-
<html>
<body>

<button onclick="document.getElementById('demo').innerHTML=Date()">The time


is?</button>
<p id="demo"></p>

</body>
</html>

EXAMPLE-

<html>
<body>

<button onclick="this.innerHTML=Date()">The time is?</button>

</body>
</html>

Common HTML Events


Here is a list of some common HTML events:
Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an


HTML element

onmouseout The user moves the mouse away from an


HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page


Mouse Events
onmouseover/onmouseout - When the mouse passes over an element

<html>
<body>

<h1 onmouseover="style.color='red'" onmouseout="style.color='black'">Mouse over this


text</h1>

</body>
</html>

onmousedown/onmouseup - When pressing/releasing a mouse button


<html>
<head>
<script>
function myFunction(elmnt, clr) {
elmnt.style.color = clr;
}
</script>
</head>
<body>

<p onmousedown="myFunction(this,'red')" onmouseup="myFunction(this,'green')">


Click the text to change the color. A function, with parameters, is triggered when the mouse
button is pressed down, and again, with other parameters, when the mouse button is
released.
</p>

</body>
</html>

What Is a Regular Expression?


A regular expression is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to describe what you
are searching for.
A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text search and text
replace operations.
Syntax
/pattern/modifiers;
Example explained:
/w3schools/i is a regular expression.
w3schools is a pattern (to be used in a search).
i is a modifier (modifies the search to be case-insensitive).
Using String Methods
In JavaScript, regular expressions are often used with the two string methods: search()
and replace().
The search() method uses an expression to search for a match, and returns the position
of the match.
The replace() method returns a modified string where the pattern is replaced.
Using String search() With a Regular Expression
Example
Use a regular expression to do a case-insensitive search for "w3schools" in a string:
<html>
<body>
<p>Search a string for "w3Schools", and display the position of the match:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Visit W3Schools!";
var n = str.search(/w3Schools/i);
document.getElementById("demo").innerHTML = n;
}
</script>
</body>
</html>
OUTPUT:
Search a string for "w3Schools", and display the position of the match:
6
Regular Expression Modifiers
Modifiers can be used to perform case-insensitive more global searches:
Modifier Description

i Perform case-insensitive matching

g Perform a global match (find all matches rather than


stopping after the first match)

m Perform multiline matching

Regular Expression Patterns


Brackets are used to find a range of characters:
Expression Description

[abc] Find any of the characters between the brackets

[0-9] Find any of the digits between the brackets

(x|y) Find any of the alternatives separated with |


Metacharacters are characters with a special meaning:
Metacharacter Description

\d Find a digit

\s Find a whitespace character

\b Find a match at the beginning or at the end of a word

\uxxxx Find the Unicode character specified by the hexadecimal number xxxx
Quantifiers define quantities:
Quantifier Description

n+ Matches any string that contains at least one n

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

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

Using the RegExp Object


In JavaScript, the RegExp object is a regular expression object with predefined properties
and methods.

Using test()
The test() method is a RegExp expression method.
It searches a string for a pattern, and returns true or false, depending on the result.
The following example searches a string for the character "e":
<html>
<body>

<p>Search for an "e" in the next paragraph:</p>

<p id="p01">The best things in life are free!</p>

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

<p id="demo"></p>

<script>
function myFunction() {
text = document.getElementById("p01").innerHTML;
document.getElementById("demo").innerHTML = /e/.test(text);
}
</script>

</body>
</html>
OUTPUT
True
Using exec()
The exec() method is a RegExp expression method.
It searches a string for a specified pattern, and returns the found text.
If no match is found, it returns null.
The following example searches a string for the character "e":
/e/.exec("The best things in life are free!");
Since there is an "e" in the string, the output of the code above will be:
E

Servlets

Servlet technology is used to create web application

Servlet technology is robust and scalable because of java language.

There are many interfaces and classes in the servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest,
ServletResponse etc.

Servlet is an interface that must be implemented for creating any servlet.


Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any
type of requests.

Servlet is a web component that is deployed on the server to create dynamic web page.
Advantage of Servlet
1. better performance: because it creates a thread for each request not process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so we don't need to worry about memory leak, garbage collection etc.
4. Secure: because it uses java language..
Servlets Architecture
The following diagram shows the position of Servlets in a Web Application.

Servlets Tasks
Servlets perform the following major tasks −
 Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could
also come from an applet or a custom HTTP client program.
 Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and
compression schemes the browser understands, and so forth.
 Process the data and generate the results. This process may require talking to a database, executing an RMI
or CORBA call, invoking a Web service, or computing the response directly.
 Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of
formats, including text (HTML or XML), binary (GIF images), Excel, etc.
 Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients
what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks.
Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification.
Servlets can be created using the javax.servlet and javax.servlet.http packages.
Setting up Java Development Kit

SETTING ENVIRONMENT VARIABLES

Rightclick on mycomputer
Advanced system settings->advanced ->environment variables->system variables

CLASSPATH= C:\Program Files\Java\jdk1.8.0_144\bin;

C:\Program Files\Java\jre1.8.0_144\bin;

C:\Program Files\Apache Software Foundation\Tomcat 7.0\lib\servlet-api.jar;.

JAVA_HOME=C:\Program Files\Java\jdk1.8.0_144;.

PATH=C:\Program Files\Java\jdk1.8.0_144\bin;

Setting up Web Server − Tomcat


 Download latest version of Tomcat from https://tomcat.apache.org/.
 Once you downloaded the installation, unpack the binary distribution into a convenient location. For example
in C:\apache-tomcat-8.0.28 on windows,
 Tomcat can be started by executing the following commands on windows machine −
 %CATALINA_HOME%\bin\startup.bat
 or
 C:\apache-tomcat-8.0.28\bin\startup.bat
 Tomcat can be stopped by executing the following commands on windows machine −
 C:\apache-tomcat-8.0.28\bin\shutdown
Setting Up the CLASSPATH
set CATALINA = C:\apache-tomcat-8.0.28
set CLASSPATH = %CATALINA%\common\lib\servlet-api.jar;%CLASSPATH%
A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the
paths followed by a servlet.
 The servlet is initialized by calling the init() method.
 The servlet calls service() method to process a client's request.
 The servlet is terminated by calling the destroy() method.
 Finally, servlet is garbage collected by the garbage collector of the JVM.
The init() Method
The init method is called only once. It is called only when the servlet is created, and not called for any user requests
afterwards.
The init method definition looks like this −
public void init() throws ServletException {
// Initialization code...
}
The service() Method
The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the
service() method to handle requests coming from the client( browsers) and to write the formatted response back to the
client.
Here is the signature of this method −
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and
it should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled
by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The destroy() Method
The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a
chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform
other such cleanup activities.
public void destroy() {
// Finalization code...
}
Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
 First the HTTP requests coming to the server are delegated to the servlet container.
 The servlet container loads the servlet before invoking the service() method.
 Then the servlet container handles multiple requests by spawning multiple threads, each thread executing the
service() method of a single instance of the servlet.
HTTP Requests
The request sends by the computer to a web server that contains all sorts of potentially interesting information is
known as HTTP requests.
The HTTP client sends the request to the server in the form of request message which includes following information:
o The Request-line
o The analysis of source IP address, proxy and port
o The analysis of destination IP address, protocol, port and host
o The Requested URI (Uniform Resource Identifier)
o The Request method and Content
o The User-Agent header
o The Connection control header
o The Cache control header
The HTTP request method indicates the method to be performed on the resource identified by the Requested URI
(Uniform Resource Identifier). This method is case-sensitive and should be used in uppercase.
The HTTP request methods are:

HTTP Request Description

GET Asks to get the resource at the requested URL.

POST Asks the server to accept the body info attached.

It is like GET request with extra info sent with the


request.

HEAD Asks for only the header part of whatever a GET

would return. Just like GET but with no body.

TRACE Asks for the loopback of the request message,

for testing or troubleshooting.

PUT Says to put the enclosed info (the body) at the

requested URL.

DELETE Says to delete the resource at the requested URL.

OPTIONS Asks for a list of the HTTP methods to which

the thing at the request URL can respond


Get vs. Post
There are many differences between the Get and Post request. Let's see these differences:

GET POST

1) In case of Get request, only limited amount of data can In case of post request,
be sent because data is sent in header.

large amount of data can

be sent because data is sent


in body.

2) Get request is not secured because data is exposed in URL Post request is secured
bar.

because data is not exposed

in URL bar.

3) Get request can be bookmarked. Post request cannot be

bookmarked.

4) Get request is idempotent . It means second request will Post request is non-idempotent
be ignored until response of first request is delivered

5) Get request is more efficient and used more than Post. Post request is less efficient

and used less than get.


Servlet API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are used by the servlet or web container. These
are not specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.
Let's see what the interfaces of javax.servlet package are.

Package javax.servlet

The javax.servlet package contains a number of classes and interfaces that describe and define the contracts between
a servlet class and the runtime environment provided for an instance of such a class by a conforming servlet
container.

Interface Summary
A filter is an object that performs filtering tasks on either the request
Filter to a resource (a servlet or static content), or on the response from a
resource, or both.

A FilterChain is an object provided by the servlet container to the


FilterChain developer giving a view into the invocation chain of a filtered
request for a resource.

A filter configuration object used by a servlet container to pass


FilterConfig
information to a filter during initialization.

Defines an object that receives requests from the client and sends
RequestDispatcher them to any resource (such as a servlet, HTML file, or JSP file) on
the server.

Servlet Defines methods that all servlets must implement.

A servlet configuration object used by a servlet container to pass


ServletConfig
information to a servlet during initialization.

Defines a set of methods that a servlet uses to communicate with its


ServletContext servlet container, for example, to get the MIME type of a file,
dispatch requests, or write to a log file.

Implementations of this interface receive notifications of changes to


ServletContextAttributeListener
the attribute list on the servlet context of a web application.

Implementations of this interface receive notifications about changes


ServletContextListener
to the servlet context of the web application they are part of.

ServletRequest Defines an object to provide client request information to a servlet.


A ServletRequestAttributeListener can be implemented by the
ServletRequestAttributeListener
developer interested in being notified of request attribute changes.

A ServletRequestListener can be implemented by the developer


ServletRequestListener interested in being notified of requests coming in and out of scope in
a web component.

Defines an object to assist a servlet in sending a response to the


ServletResponse
client.

SingleThreadModel Deprecated. As of Java Servlet API 2.4, with no direct replacement.

Class Summary

GenericServlet Defines a generic, protocol-independent servlet.

This is the event class for notifications about changes to the attributes of the
ServletContextAttributeEvent
servlet context of a web application.

This is the event class for notifications about changes to the servlet context of a
ServletContextEvent
web application.

Provides an input stream for reading binary data from a client request, including
ServletInputStream
an efficient readLine method for reading data one line at a time.

ServletOutputStream Provides an output stream for sending binary data to the client.
This is the event class for notifications of changes to the attributes of the servlet
ServletRequestAttributeEvent
request in an application.

ServletRequestEvent Events of this kind indicate lifecycle events for a ServletRequest.

Provides a convenient implementation of the ServletRequest interface that can be


ServletRequestWrapper
subclassed by developers wishing to adapt the request to a Servlet.

Provides a convenient implementation of the ServletResponse interface that can


ServletResponseWrapper
be subclassed by developers wishing to adapt the response from a Servlet.

Exception Summary

ServletException Defines a general exception a servlet can throw when it encounters difficulty.

Defines an exception that a servlet or filter throws to indicate that it is permanently or


UnavailableException
temporarily unavailable.

Package javax.servlet Description

The javax.servlet package contains a number of classes and interfaces that describe and define the contracts between
a servlet class and the runtime environment provided for an instance of such a class by a conforming servlet
container.
Package javax.servlet.http

The javax.servlet.http package contains a number of classes and interfaces that describe and define the contracts
between a servlet class running under the HTTP protocol and the runtime environment provided for an instance of
such a class by a conforming servlet container.

Interface Summary

Extends the ServletRequest interface to provide request information for


HttpServletRequest
HTTP servlets.

Extends the ServletResponse interface to provide HTTP-specific


HttpServletResponse
functionality in sending a response.

Provides a way to identify a user across more than one page request or
HttpSession
visit to a Web site and to store information about that user.

Objects that are bound to a session may listen to container events


HttpSessionActivationListener notifying them that sessions will be passivated and that session will be
activated.

This listener interface can be implemented in order to get notifications


HttpSessionAttributeListener
of changes to the attribute lists of sessions within this web application.

Causes an object to be notified when it is bound to or unbound from a


HttpSessionBindingListener
session.

Deprecated. As of Java(tm) Servlet API 2.1 for security reasons, with


HttpSessionContext
no replacement.

Implementations of this interface are notified of changes to the list of


HttpSessionListener
active sessions in a web application.
Class Summary

Creates a cookie, a small amount of information sent by a servlet to a Web


Cookie
browser, saved by the browser, and later sent back to the server.

Provides an abstract class to be subclassed to create an HTTP servlet suitable for


HttpServlet
a Web site.

Provides a convenient implementation of the HttpServletRequest interface that


HttpServletRequestWrapper
can be subclassed by developers wishing to adapt the request to a Servlet.

Provides a convenient implementation of the HttpServletResponse interface that


HttpServletResponseWrapper
can be subclassed by developers wishing to adapt the response from a Servlet.

Events of this type are either sent to an object that


implements HttpSessionBindingListener when it is bound or unbound from a
HttpSessionBindingEvent session, or to a HttpSessionAttributeListener that has been configured in the
deployment descriptor when any attribute is bound, unbound or replaced in a
session.

This is the class representing event notifications for changes to sessions within a
HttpSessionEvent
web application.

HttpUtils Deprecated. As of Java(tm) Servlet API 2.3.

Package javax.servlet.http Description

The javax.servlet.http package contains a number of classes and interfaces that describe and define the contracts
between a servlet class running under the HTTP protocol and the runtime environment provided for an instance of
such a class by a conforming servlet container.
Servlet Interface
Servlet interface provides common behavior 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.

Methods of Servlet interface


There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of servlet. These are
invoked by the web container.

Method Description

public void init(ServletConfig config) initializes the servlet. It is the life


cycle method of servlet and
invoked by the web container
only once.

public void service(ServletRequest provides response for the


request,ServletResponse response) incoming request. It is invoked
at each request by the web
container.

public void destroy() is invoked only once and


indicates that servlet is being
destroyed.

public ServletConfig getServletConfig() returns the object of ServletConfig.

public String getServletInfo() returns information about


servlet such as writer, copyright,
version etc
Servlets - Examples

Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet interface.

Web application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that
implements the Servlet interface and is specially designed to handle HTTP requests.

Servlets - Cookies Handling

Cookies are text files stored on the client computer and they are kept for various information
tracking purpose. Java Servlets transparently supports HTTP cookies.
There are three steps involved in identifying returning users −
 Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
 Browser stores this information on local machine for future use.
 When next time browser sends any request to web server then it sends those cookies
information to the server and server uses that information to identify the user.
The Anatomy of a Cookie
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie
directly on a browser). A servlet that sets a cookie might send headers that look
something like this −
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT;
path = /; domain = tutorialspoint.com
Connection: close
Content-Type: text/html

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String value) constructs a cookie with a


specified name and value.
Useful Methods of Cookie class
There are given some commonly used methods of the Cookie class.

Method Description

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.


Other methods required for using Cookies
For adding cookie or getting the value from the cookie, we need some methods provided
by other interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is
used to add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used
to return all the cookies from the browser.
Simple example of Servlet Cookies
In this example, we are storing the name of the user in the cookie object and accessing it in
another servlet.
index.html

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


Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

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

public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

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

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

Cookie ck=new Cookie("uname",n);//creating cookie object


response.addCookie(ck);//adding cookie in the response

//creating submit button


out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");

out.close();
}catch(Exception e){System.out.println(e);}
}
}

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

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

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

Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());

out.close();

}catch(Exception e){System.out.println(e);}
}

}
web.xml
<web-app>

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

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

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

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

</web-app>
Output
Session Tracking in Servlets
Session simply means a particular interval of time.
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques.
Each time user requests to the server, server treats the request as the new request. So we
need to maintain the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in
the figure given below:

Session Tracking Techniques


There are four techniques used in Session tracking:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.

How Cookie works


By default, each request is considered as a new request. In cookies technique, we add cookie
with response from the servlet. So cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the
user as the old user.

Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser.
It is removed only if user logout or signout.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Hidden Form Field
In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state
of an user.
In such case, we store the information in the hidden field and get it from another servlet.
This approach is better if we have to submit form in all the pages and we don't want to depend
on the browser.
Let's see the code to store value in hidden field.
<input type="hidden" name="uname" value="Vimal Jaiswal">
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.

Real application of hidden form field


It is widely used in comment form of a website. In such case, we store page id or page name
in the hidden field so that each page can be uniquely identified.

Advantage of Hidden Form Field


1. It will always work whether cookie is disabled or not.
Disadvantage of Hidden Form Field:
1. It is maintained at server side.
2. Extra form submission is required on each pages.
3. Only textual information can be used.
Example of using Hidden Form Field
In this example, we are storing the name of the user in a hidden textfield and getting that
value from another servlet.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response){
try{

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

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

//creating form that have invisible textfield


out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");
out.close();

}catch(Exception e){System.out.println(e);}
}

}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

//Getting the value from the hidden field


String n=request.getParameter("uname");
out.print("Hello "+n);

out.close();
}catch(Exception e){System.out.println(e);}
}
}

URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next
resource. We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign,
a parameter name/value pair is separated from another parameter using the ampersand(&).
When the user clicks the hyperlink, the parameter name/value pairs will be passed to the
server.
From a Servlet, we can use getParameter() method to obtain a parameter value.

Advantage of URL Rewriting


1. It will always work whether cookie is disabled or not (browser independent).
2. Extra form submission is not required on each pages.
Disadvantage of URL Rewriting
1. It will work only with links.
2. It can send Only textual information.
Example of using URL Rewriting
In this example, we are maintaning the state of the user using link. For this purpose, we are
appending the name of the user in the query string and getting the value from the query
string in another page.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response){


try{

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

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

//appending the username in the query string


out.print("<a href='servlet2?uname="+n+"'>visit</a>");

out.close();

}catch(Exception e){System.out.println(e);}
}

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

public class SecondServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


try{

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

//getting value from the query string


String n=request.getParameter("uname");
out.print("Hello "+n);

out.close();

}catch(Exception e){System.out.println(e);}
}
}

JDBC -
Creating JDBC Application
There are following six steps involved in building a JDBC application −
 Import the packages: Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, using import java.sql.* will
suffice.
 Register the JDBC driver: Requires that you initialize a driver so you can open a
communication channel with the database.
 Open a connection: Requires using the DriverManager.getConnection() method to
create a Connection object, which represents a physical connection with the database.
 Execute a query: Requires using an object of type Statement for building and
submitting an SQL statement to the database.
 Extract data from result set: Requires that you use the
appropriate ResultSet.getXXX() method to retrieve the data from the result set.
 Clean up the environment: Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.

Sample Code
Copy and paste the following example in JDBCExample.java, compile and run as follows −
//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");

//STEP 4: Execute a query


System.out.println("Creating table in given database...");
stmt = conn.createStatement();

String sql = "CREATE TABLE REGISTRATION " +


"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";

stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end JDBCExample
Now, let us compile the above example as follows −
C:\>javac JDBCExample.java
C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
Connecting to a selected database...
Connected database successfully...
Creating table in given database...
Created table in given database...
Goodbye!
C:\>
JSP
JSP technology is used to create web application just like Servlet technology.
It can be thought of as an extension to servlet because it provides more functionality than
servlet such as expression language, jstl etc
A JSP page consists of HTML tags and JSP tags.
The jsp pages are easier to maintain than servlet because we can separate designing and
development.
It provides some additional features such as Expression Language, Custom Tag etc.
JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic
content.
This helps developers insert java code in HTML pages by making use of special JSP tags,
most of which start with <% and end with %>.
Advantage of JSP over Servlet
There are many advantages of JSP over servlet. They are as follows:
1) Extension to Servlet
JSP technology is the extension to servlet technology.
We can use all the features of servlet in JSP.
In addition to, we can use implicit objects, predefined tags, expression language and Custom
tags in JSP, that makes JSP development easy.
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic.
In servlet technology, we mix our business logic with the presentation logic.
3) Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.
4) Less code than Servlet
In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the
code. Moreover, we can use EL, implicit objects etc.
Life cycle of a JSP Page
The JSP pages follows these phases:
o Translation of JSP Page
o Compilation of JSP Page
o Classloading (class file is loaded by the classloader)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( jspInit() method is invoked by the container).
o Reqeust processing ( _jspService() method is invoked by the container).
o Destroy ( jspDestroy() method is invoked by the container).
Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify the
servlet classes to the compiler.
If you are running Windows, you need to put the following lines in
your C:\autoexec.bat file.
set CATALINA = C:\apache-tomcat-5.5.29
set CLASSPATH = %CATALINA%\common\lib\jsp-api.jar;%CLASSPATH%
Creating a simple JSP Page
To create the first jsp page, write some html code as given below, and save it by .jsp
extension.
index.jsp
<html>
<body>
<% out.print(2*5); %>
</body>
</html>

How to run a simple JSP Page ?


Follow the following steps to execute this JSP page:
o Start the server
o put the jsp file in a folder and deploy on the server
o visit the browser by the url e.g. http://localhost:8888/myapplication/index.jsp
The JSP API
The JSP API consists of two packages:
1. javax.servlet.jsp
2. javax.servlet.jsp.tagext
javax.servlet.jsp package
The javax.servlet.jsp package has two interfaces and classes.The two interfaces are as
follows:
1. JspPage
2. HttpJspPage
The classes are as follows:
o JspWriter
o PageContext
o JspFactory
o JspEngineInfo
o JspException
o JspError
The JspPage interface
According to the JSP specification, all the generated servlet classes must implement the
JspPage interface. It extends the Servlet interface. It provides two life cycle methods.

Methods of JspPage interface


1. public void jspInit(): It is invoked only once during the life cycle of the JSP when
JSP page is requested firstly. It is used to perform initialization. It is same as the init()
method of Servlet interface.
2. public void jspDestroy(): It is invoked only once during the life cycle of the JSP
before the JSP page is destroyed. It can be used to perform some clean up operation.
The HttpJspPage interface
The HttpJspPage interface provides the one life cycle method of JSP. It extends the JspPage
interface.
Method of HttpJspPage interface:
public void _jspService(): It is invoked each time when request for the JSP page
comes to the container. It is used to process the request. The underscore _ signifies
that you cannot override this method.
JSP Scriptlet tag (Scripting elements)
In JSP, java code can be written inside the jsp page using the scriptlet tag.
JSP Scripting elements
The scripting elements provides the ability to insert java code inside the jsp. There are three
types of scripting elements:
o scriptlet tag
o expression tag
o declaration tag
JSP scriptlet tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
<% java source code %>
Example of JSP scriptlet tag
In this example, we are displaying a welcome message.
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
Example of JSP scriptlet tag that prints the user name
In this example, we have created two files index.html and welcome.jsp.
The index.html file gets the username from the user and the welcome.jsp file prints the
username with the welcome message.
File: index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

File: welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>

JSP expression tag


The code placed within JSP expression tag is written to the output stream of the response.
So you need not write out.print() to write data.
It is mainly used to print the values of variable or method.
Syntax of JSP expression tag
<%= statement %>
Example of JSP expression tag
In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
Example of JSP expression tag that prints current time
To display the current time, we have used the getTime() method of Calendar class. The
getTime() is an instance method of Calendar class, so we have called it after getting the
instance of Calendar class by the getInstance() method.
index.jsp
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
Example of JSP expression tag that prints the user name
In this example, we are printing the username using the expression tag.
The index.html file gets the username and sends the request to the welcome.jsp file, which
displays the username.
File: index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
File: welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>
JSP Declaration Tag
The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.
So it doesn't get memory at each request.
Syntax of JSP declaration tag
The syntax of the declaration tag is as follows:
<%! field or method declaration %>
Example of JSP declaration tag that declares field
In this example of JSP declaration tag, we are declaring the field and printing the value of the
declared field using the jsp expression tag.
index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>

Example of JSP declaration tag that declares method


In this example of JSP declaration tag, we are defining the method which returns the cube of
given number and calling this method from the jsp expression tag. But we can also use jsp
scriptlet tag to call the declared method.
index.jsp
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
JSP Implicit Objects
A list of the 9 implicit objects is given below:

Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable

JSP out implicit object


For writing any data to the buffer, JSP provides an implicit object named out. It is the object
of JspWriter. In case of servlet you need to write:
PrintWriter out=response.getWriter();
But in JSP, you don't need to write this code.

Example of out implicit object


In this example we are simply displaying date and time.
index.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>

JSP request implicit object


The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp
request by the web container.
It can be used to get request information such as parameter, header information, remote
address, server name, server port, content type, character encoding etc.
It can also be used to set, get and remove attributes from the jsp request scope.
Let's see the simple example of request implicit object where we are printing the name of the
user with welcome message.
Example of JSP request implicit object
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>

JSP response implicit object


In JSP, response is an implicit object of type HttpServletResponse. The instance of
HttpServletResponse is created by the web container for each jsp request.
It can be used to add or manipulate response such as redirect response to another resource,
send error etc.
Example of response implicit object
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>

JSTL (JSP Standard Tag Library)


The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.
Advantage of JSTL
1. Fast Developement JSTL provides many tags that simplifies the JSP.
2. Code Reusability We can use the JSTL tags in various pages.
3. No need to use scriptlet tag It avoids the use of scriptlet tag.
JSTL Tags
There JSTL mainly provides 5 types of tags:

Tag Name Description

Core tags The JSTL core tag provide variable support, URL management,
flow control etc. The url for the core tag is
http://java.sun.com/jsp/jstl/core . The prefix of core tag is c.

Function tags The functions tags provide support for string manipulation
and string length. The url for the functions
tags is http://java.sun.com/jsp/jstl/functions and prefix is fn.

Formatting tags The Formatting tags provide support for message formatting,
number and date formatting etc.
The url for the Formatting tags is http://java.sun.com/jsp/jstl/fmt
and prefix is fmt.

XML tags The xml sql tags provide flow control,


transformation etc. The url for the xml tags
is http://java.sun.com/jsp/jstl/xml and prefix is x.
SQL tags The JSTL sql tags provide SQL support.
The url for the sql tags is http://java.sun.com/jsp/jstl/sql
and prefix is sql.

JSTL Core Tags


The JSTL core tag provides variable support, URL management, flow control etc. The syntax
used for including JSTL core library in your JSP is:
1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
JSTL Core Tags List

Tags Description

c:out It display the result of an expression,


similar to
the way <%=...%> tag work.

c:import It Retrives relative or an absolute URL


and display the contents to either a String
in 'var',a Reader in 'varReader' or the page.

c:set It sets the result of an expression under


evaluation in a 'scope' variable.

c:remove It is used for removing the specified scoped


variable from a particular scope.

c:catch It is used for Catches any Throwable exceptions


that occurs in the body.

c:if It is conditional tag used for testing the condition


and display the body content only if
the expression evaluates is true.

c:choose, c:when, c:otherwise It is the simple conditional tag that includes its
body content if the evaluated condition is true.

c:forEach It is the basic iteration tag. It repeats the nested


body content for fixed number of times or
over collection.

c:forTokens It iterates over tokens which is separated by


the supplied delimeters.

c:param It adds a parameter in a containing


'import' tag's URL.

c:redirect It redirects the browser to a new URL and


supports the context-relative URLs.

c:url It creates a URL with optional query parameters.


JSTL Core <c:out> Tag
The <c:out> tag is similar to JSP expression tag, but it can only be used with expression. It
will display the result of an expression, similar to the way < %=...% > work.
The < c:out > tag automatically escape the XML tags. Hence they aren't evaluated as actual
tags.
Let's see the simple example of c:out tag:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Tag Example</title>
</head>
<body>
<c:out value="${'Welcome to java'}"/>
</body>
</html>
Output:
JSTL Function Tags
The JSTL function provides a number of standard functions, most of these functions are
common string manipulation functions. The syntax used for including JSTL function library in
your JSP is:
1. <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
JSTL Function Tags List

JSTL Functions Description

fn:contains() It is used to test if an input string containing the


specified substring in a program.

fn:containsIgnoreCase() It is used to test if an input string contains the


specified substring as a case insensitive way.

fn:endsWith() It is used to test if an input string ends with the


specified suffix.

fn:escapeXml() It escapes the characters that would be interpreted


as XML markup.

fn:indexOf() It returns an index within a string of first occurrence


of a specified substring.

fn:trim() It removes the blank spaces from both the ends of a string.

fn:startsWith() It is used for checking whether the given string is


started with a particular string value.

fn:split() It splits the string into an array of substrings.

fn:toLowerCase() It converts all the characters of a string to lower case.

fn:toUpperCase() It converts all the characters of a string to upper case.

fn:substring() It returns the subset of a string according to the


given start and end position.
fn:substringAfter() It returns the subset of string after a specific substring.

fn:substringBefore() It returns the subset of string before a specific substring.

fn:length() It returns the number of characters inside a string,


or the number of items in a collection.

fn:replace() It replaces all the occurrence of a string with


another string sequence.
STL Formatting tags
The formatting tags provide support for message formatting, number and date formatting
etc. The url for the formatting tags ishttp://java.sun.com/jsp/jstl/fmt and prefix is fmt.
The JSTL formatting tags are used for internationalized web sites to display and format text,
the time, the date and numbers. The syntax used for including JSTL formatting library in your
JSP is:
1. <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>

Formatting Tags Descriptions

fmt:parseNumber It is used to Parses the string representation of a


currency, percentage or number.

fmt:timeZone It specifies a parsing action nested in its body or the


time zone for any time formatting.

fmt:formatNumber It is used to format the numerical value with specific


format or precision.

fmt:parseDate It parses the string representation of a time and date.

fmt:bundle It is used for creating the ResourceBundle objects


which will be used by their tag body.

fmt:setTimeZone It stores the time zone inside a time zone configuration variable.

fmt:setBundle It loads the resource bundle and stores it in a bundle


configuration variable or the named scoped variable.

fmt:message It display an internationalized message.

fmt:formatDate It formats the time and/or date using the supplied


pattern and styles.
JSTL XML tags
The JSTL XML tags are used for providing a JSP-centric way of manipulating and creating XML
documents.
The xml tags provide flow control, transformation etc. The url for the xml tags
is http://java.sun.com/jsp/jstl/xml and prefix is x. The JSTL XML tag library has custom
tags used for interacting with XML data. The syntax used for including JSTL XML tags library
in your JSP is:
1. <%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
Before you proceed further with the examples, you need to copy the two XML and XPath
related libraries into the <Tomcat Installation Directory>\lib:
Xalan.jar: Download this jar file from the link:
1. http://xml.apache.org/xalan-j/index.html
XercesImpl.jar: Download this jar file from the link:
1. http://www.apache.org/dist/xerces/j/
JSTL XML tags List

XML Tags Descriptions

x:out Similar to <%= ... > tag, but for XPath expressions.

x:parse It is used for parse the XML data specified either in


the tag body or an attribute.

x:set It is used to sets a variable to the value of an XPath expression.

x:choose It is a conditional tag that establish a context for mutually


exclusive conditional operations.

x:when It is a subtag of that will include its body if the condition


evaluated be 'true'.

x:otherwise It is subtag of that follows tags and runs only if all the prior
conditions evaluated be 'false'.

x:if It is used for evaluating the test XPath expression and


if it is true, it will processes its body content.

x:transform It is used in a XML document for providing


the XSL(Extensible Stylesheet Language) transformation.

x:param It is used along with the transform tag for setting


the parameter in the XSLT style sheet.

You might also like