Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 71

JAVA SCRIPT: AN INTRODUCTION TO JAVASCRIPT

Here to begin with a “Hello World!” JavaScript program. There’s just one
problem:JavaScript itself has no statement for performing output. Instead, the
JavaScript language specification leaves it up to browsers to supply output (and input)
methods.
 alert(), to write a JavaScript “Hello World!” program
window.alert("Hello World!");

 We can execute this program by referencing a file containing it from a script


element within an HTML document.
 For example, if the JavaScript code given is placed within a file named
JSHelloWorld.js in the same directory as the HTML document of Fig 4.1, then
loading this document into a browser will cause the code to be executed.
 If this document is loaded into Mozilla 1.4, then the pop-up window shown in
Figure 4.2 will appear.
 The browser window will be unresponsive until this alert box is dismissed,
either by clicking the OK button or by closing the window .
 The client area of the browser window itself will be completely empty after
the alert box is dismissed.
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>
JSHelloWorld.html
</title>
<script type="text/javascript" src="JSHelloWorld.js">
</script>
</head>
<body>
</body>
</html>
Fig 2.1 HTML document that loads and executes the JavaScript program in file
JSHelloWorld.js.

Fig 2.2 Alert box generated by a JavaScript statement.


 As with output, there is no input statement in JavaScript itself. Again, though,
most browsers implement a prompt() method that can be called as illustrated
by the following code:
var inString = window.prompt("Enter JavaScript code to be tested:","");
 This pops up a window that displays the value of its first string argument and
also provides a text box in which a user can enter information and that initially
contains the string given by the second argument .
 The value returned by the prompt() method is the string entered by the user,
assuming that the user clicks OK after entering the user, assuming that the user
clicks OK after entering the string.

Definition of Web-application

A web-application is an application program that is usually stored on a remote server,


and users can access it through the use of Software known as web-browser.

The Flow of the Web Application

Let's understand how the flow of the typical web application looks like.

1. In general, a user sends a request to the web-server using web browsers such
as Google Chrome, Microsoft Edge, Firefox, etc over the internet.
2. Then, the request is forwarded to the appropriate web application server by
the web-server.
3. Web application server performs the requested operations/ tasks
like processing the database, querying the databases; produces the result
of the requested data.
4. The obtained result is sent to the web-server by the web application server
along with the requested data/information or processed data.
5. The web server responds to the user with the requested or processed
data/information and provides the result to the user's screen .

Benefits of a web application

Let see some of the significant benefits offered by a web application:

o Any typical web application can run or accessible on any operating system
such as the Windows, Mac, Linux as long as the browser is compatible.
o A web application is usually not required to install in the hard drive of the
computer system, thus it eliminates all the issues related to the space
limitation.
o All the users are able to access the same version of the web application, which
eliminates all compatibility issues.
o It also reduces software piracy in subscription-based web applications, for
example, SAAS (or Software as a service).

Disadvantages of the Web Applications

As we all know, there are two sides of anything; if something has some advantages, it
may also have limitations/ disadvantages. Consider the following disadvantages of the
web applications.

o Internet connection is necessary to access any web application, and without an


internet connection, anyone can't use any of the web applications. It is very
typical to get an internet connection in our modern cities, still rural area
internet connectivity not so well.
o Several people in business believe that their data on the cloud environment is
no that secure and likes to stick with old methods; they even don't want to use
new methods.

o As we all know that many users like to use different web browsers according
to their needs and choices. So while creating a web application, you must
remember that your application must support several web browsers, including
new and old versions of browsers.
.

In Javascript, popup boxes are used to display the message or notification to the
user. There are three types of pop-up boxes in JavaScript namely Alert
Box, Confirm Box and Prompt Box.
Alert Box: It is used when a warning message is needed to be produced. When the
alert box is displayed to the user, the user needs to press ok and proceed.
Syntax:
alert("your Alert here")
Prompt Box: It is a type of pop up box which is used to get the user input for
further use. After entering the required details user have to click ok to proceed next
stage else by pressing the cancel button user returns the null value.
Syntax:
prompt("your Prompt here")
Confirm Box: It is a type of pop-up box that is used to get authorization or
permission from the user. The user has to press the ok or cancel button to proceed.
Syntax:
confirm("your query here")

Control Statements in JS

Control statements are intended to allow users to write scripts which determine which
lines of code get evaluated and how many times they get evaluated. Control
statements are classified into two types: conditional statements and loop statements.

Types of Control Statements in JS


There are basically two types of control statements in Javascript. Namely, Conditional
Statements and Iterative Statements (in simple words, Loops).
 Conditional Statements: These are the ones which make a decision. There is an
expression that gets passed, and then the conditional statement decides on it. It is
either YES or NO.
 Iterative Statements (Loop): This is a type of statement which keeps repeating
itself till a condition is satisfied. In simple words, if we have an expression, until
and unless it gets satisfied, the statement will keep repeating itself.
Conditional Statements
If Statment
As the name suggests, we use the If Statement if we want to check for a specific
condition. When we are using the IF condition, the inner code block gets executed
only when the given condition is satisfied.
Syntax:
if (condition_is_given_here) {
//If the condition is met, the code block will get executed.
}
If-Else Statement
The If-Else Statement is an extended version of the If statement. We use this one
when we want to check a condition we want and another one if the evaluation turns
out otherwise.
Syntax:
if (condition_is_given_here) {
//If the condition is met, this code block will get executed.
}
else {
/*If the condition is not met and turns out to be false, this code block will get
executed. */
}
As we can see, the first block of code gets executed when the condition in IF-ELSE is
satisfied. The second block of code gets executed when the condition does not get
satisfied.
Switch Statement
A switch statement is similar to an IF statement. It is used when the user needs to
execute one code block execution from their own choices out of several code block
execution options. It is based on the outcome of the expression given. Switch
statements hold an expression that is compared to the values of the following cases. If
a match is found, the code associated with that case is executed.
Syntax
switch (expression) {
case first:
//here, we add the code block that is to be executed
Break;
//Break creates a separation between each case
case second:
//here, we add the code block that is to be executed
Break;
case third:
//here, we add the code block that is to be executed
Break;
default:
//here, we add the default code block that is to be executed. It happens if none of the
above cases is executed.
}
Iterative Statement
While Statement
One of the control flow statements is the. When the condition is met, they run a code
block. However, unlike the IF statement, while keeps repeating itself until the
condition is met. The difference between IF and while is that IF executes code when
the condition is met. Whereas while statement keeps repeating itself till the condition
is met.
Syntax
while (the_condition_is_put_here)
{
//the code block is executed when the conditions are met
}
Do-While Statement
We can call the Do-While Statement a sibling of the While Statement. Similar to a
while loop, but with the addition of a condition at the end of the loop. DO-WHILE,
also known as an Exit Control Loop, performs the code and then checks for the
condition.
Syntax:
while
{
//code block gets executed till the condition is satisfied
} (we_add_the_conditon_here)
The loop will get repeated if the condition at the end is met.
For Statement
Now let us take a look at the For Loop. A for loop will run a code block several times.
The FOR statement is shorter and easier to debug than other loops. This is because it
contains initialisation, condition, and increment or decrement on a single line.
Syntax:
for (here_we_put initialize; condition; increment/decrement)
{
//here_we_put_the_code_block_that_we_need_to_execute
}

JAVASCRIPT DOM 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.
 As mentioned earlier, it is the object of window. So

window.document,is same as document

 According to W3C - "The W3C Document Object Model (DOM) is a platform


and language-neutral interface that allows programs and scripts to dynamically
access and update the content, structure, and style of a document."

Properties of document object

The properties of document object that can be accessed and modified by the
document object.
Fig 2.3 Properties of 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 doucment.
writes the given string on the doucment with newline
writeln("string")
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

In this example, we are going to get the value of input text by user. 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.

Simple example of document object that prints name with welcome message.

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

Javascript - document.getElementById() method

The document.getElementById() method returns the element of specified id.

 In the previous topic, 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.

Simple example of document.getElementById() method that prints cube of the


given number.

<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>
Javascript - document.getElementsByName() method
1. getElementsByName() method
2. Example of getElementsByName()

The document.getElementsByName() method returns all the element of specified


name.

The syntax of the getElementsByName() method is given below:

1. document.getElementsByName("name")

Here, name is required.


Example of document.getElementsByName() method

In this example, count total number of genders. Here, we are using


getElementsByName() method to get all the genders.

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

Javascript - document.getElementsByTagName() method

 getElementsByTagName() method

Example of getElementsByTagName()

 The document.getElementsByTagName() method returns all the


element of specified tag name.
 The syntax of the getElementsByTagName() method is given below:

document.getElementsByTagName("name")

Here, name is required.

Example of document.getElementsByTagName() method

 In this example, we going to count total number of paragraphs used in the


document. To do this, we have called the
document.getElementsByTagName("p") method that returns the total
paragraphs.

<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
getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>

 Here, we are going to count total number of paragraphs by


getElementByTagName() method.
 Another example of document.getElementsByTagName() method.In this
example, we going to count total number of h2 and h3 tags used in the
document.

<script type="text/javascript">
function counth2(){
var totalh2=document.getElementsByTagName("h2");
alert("total h2 tags are: "+totalh2.length);
}
function counth3(){
var totalh3=document.getElementsByTagName("h3");
alert("total h3 tags are: "+totalh3.length);
}
</script>
<h2>This is h2 tag</h2>
<h2>This is h2 tag</h2>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<button onclick="counth2()">count h2</button>
<button onclick="counth3()">count h3</button>
Output of the above example
This is h2 tag
This is h2 tag
This is h3 tag
This is h3 tag
This is h3 tag
Note: Output of the given examples may differ on this page because it will count the
total number of para , total number of h2 and total number of h3 tags used in this
document.

Javascript - innerHTML

1. javascript innerHTML
2. Example of innerHTML property
 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.
 In this example, we are dynamically writing the html form inside the div name
having the id mylocation. We are identifing this position by calling the
document.getElementById() method.

<script type="text/javascript" >


function showcommentform() {
var data="Name:<input type='text' name='name'><br>Comment:<br><textare
a rows='5' cols='80'></textarea>
<br><input type='submit' value='Post Comment'>";
document.getElementById('mylocation').innerHTML=data;
}
</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
Show/Hide Comment Form Example using innerHTML
<!DOCTYPE html>
<html>
<head>
<title>First JS</title>
<script>
var flag=true;
function commentform(){
var cform="<form action='Comment'>Enter Name:<br><input type='text' nam
e='name'/><br/>
Enter Email:<br><input type='email' name='email'/><br>Enter Comment:<br/
>
<textarea rows='5' cols='70'></textarea><br><input type='submit' value='Post
Comment'/></form>";
if(flag){
document.getElementById("mylocation").innerHTML=cform;
flag=false;
}else{
document.getElementById("mylocation").innerHTML="";
flag=true;
}
}
</script>
</head>
<body>
<button onclick="commentform()">Comment</button>
<div id="mylocation"></div>
</body>
</html>

Javascript - innerText

1. javascript innerText
2. Example of innerText property

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

Javascript innerText Example

In this example, we are going to display the password strength when releases the
key after press.

<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>
DATE AND OBJECTS
JavaScript Date

 The JavaScript date object can be used to get year, month and day. You can
display a timer on the webpage by the help of JavaScript date object.
 You can use different Date constructors to create date object. It provides
methods to get and set day, month, year, hour, minute and seconds.

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


Methods Description
It returns the integer value between 1 and 31 that represents the day
getDate()
for the specified date on the basis of local time.
It returns the integer value between 0 and 6 that represents the day
getDay()
of the week on the basis of local time.
It returns the integer value that represents the year on the basis of
getFullYears()
local time.
It returns the integer value between 0 and 23 that represents the
getHours()
hours on the basis of local time.
It returns the integer value between 0 and 999 that represents the
getMilliseconds()
milliseconds on the basis of local time.
It returns the integer value between 0 and 59 that represents the
getMinutes()
minutes on the basis of local time.
It returns the integer value between 0 and 11 that represents the
getMonth()
month on the basis of local time.
It returns the integer value between 0 and 60 that represents the
getSeconds()
seconds on the basis of local time.

JavaScript Date Example

Current Date and Time: <span id="txt"></span>


<script>
var today=new Date();
document.getElementById('txt').innerHTML=today;
</script>
JavaScript Current Time Example
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>

JavaScript Digital Clock Example


 The simple example to display digital clock using JavaScript date object.
 There are two ways to set interval in JavaScript: by setTimeout() or
setInterval() method.

Current Time: <span id="txt"></span>


<script>
window.onload=function(){getTime();}
function getTime(){
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
// add a zero in front of numbers<10
m=checkTime(m);
s=checkTime(s);
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
setTimeout(function(){getTime()},1000);
}
//setInterval("getTime()",1000);//another way
function checkTime(i){
if (i<10){
i="0" + i;
}
return i;
}
</script>

JavaScript Object
 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.
 JavaScript is template based not class based. Here, we don't create class to get
the object. But, we direct create objects

Creating Objects in JavaScript


There are 3 ways to create objects.
 By object literal
 By creating instance of Object directly (using new keyword)
 By using an object constructor (using new keyword)

JavaScript Object by object literal

The syntax of creating object using object literal is given below:

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

As you can see, property and value is separated by : (colon).Let’s see the
simple example of creating object in JavaScript.
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

By creating instance of Object

The syntax of creating object directly is given below:

var objectname=new Object();

 Here, new keyword is used to create object.Let’s see the example of


creating object directly.

<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
By using an Object constructor

Here, you 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.The example of creating object by object constructor is given below.
<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>
Defining method in JavaScript Object

We can define method in JavaScript object. But before defining method, we


need to add property in the function with same name as method.The example of
defining method in object is given below.

<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
JavaScript Object Methods
The various methods of Object are as follows:
S.No Methods Description
This method is used to copy enumerable
1 Object.assign() and own properties from a source object to
a target object
This method is used to create a new object
2 Object.create() with the specified prototype object and
properties.
This method is used to describe some
3 Object.defineProperty()
behavioral attributes of the property.
This method is used to create or configure
4 Object.defineProperties()
multiple object properties.
This method returns an array with arrays of
5 Object.entries()
the key, value pairs.
This method prevents existing properties
6 Object.freeze()
from being removed.
This method returns a property descriptor
7 Object.getOwnPropertyDescriptor() for the specified property of the specified
object.
This method returns all own property
8 Object.getOwnPropertyDescriptors()
descriptors of a given object.
This method returns an array of all
9 Object.getOwnPropertyNames()
properties (enumerable or not) found.
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];
values are contained inside [ ] and separated by , (comma). The simple example of
creating and using array in JavaScript.

<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
JavaScript Array directly (new keyword)

The syntax of creating array directly is given below:

var arrayname=new Array();

Here, new keyword is used to create instance of array.The example of creating array
directly.

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

JavaScript array constructor (new keyword)


Here, you need to create instance of array by passing arguments in constructor
so that we don't have to provide value explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>

JavaScript Array Methods

The list of JavaScript array methods with their description.

Methods Description
concat() It returns a new array object that contains two or more merged arrays.
It copies the part of the given array with its own elements and returns the
copywithin()
modified array.
It determines whether all the elements of an array are satisfying the
every()
provided function conditions.
fill() It fills elements into an array with static values.
It returns the new array containing the elements that pass the provided
filter()
function conditions.
It returns the value of the first element in the given array that satisfies the
find()
specified condition.
It returns the index value of the first element in the given array that
findIndex()
satisfies the specified condition.
forEach() It invokes the provided function once for each element of an array.
includes() It checks whether the given array contains the specified element.
It searches the specified element in the given array and returns the index
indexOf()
of the first match.
join() It joins the elements of an array as a string.

JavaScript String
 The JavaScript string is an object that represents a sequence of
characters. There are 2 ways to create string in JavaScript
 By string literal
 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";


Example of creating string literal.

<script>

var str="This is string literal";

document.write(str);

</script>

By string object (using new keyword)

The syntax of creating string object using new keyword is given below:

var stringname=new String("string literal");

Here, new keyword is used to create instance of string.

Example of creating string in JavaScript by new keyword.

<script>

var stringname=new String("hello javascript string");

document.write(stringname);

</script>

JavaScript String Methods

The list of JavaScript string methods with examples.

Methods Description

charAt() It provides the char value present at the specified index.

It provides the Unicode value of a character present at the specified


charCodeAt()
index.

concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given string.

lastIndexOf() It provides the position of a char value present in the given string by
searching a character from the last position.

It searches a specified regular expression in a given string and returns its


search()
position if a match occurs.

It searches a specified regular expression in a given string and returns


match()
that regular expression if a match occurs.

JavaScript String charAt(index) Method

The JavaScript String charAt() method returns the character at the given index.

<script>

var str="javascript";

document.write(str.charAt(2));

</script>

JavaScript String concat(str) Method

The JavaScript String concat(str) method concatenates or joins two strings.

<script>

var s1="javascript ";

var s2="concat example";

var s3=s1.concat(s2);

document.write(s3);

</script>

JavaScript String indexOf(str) Method

The JavaScript String indexOf(str) method returns the index position of the given
string.

<script>

var s1="javascript from javatpoint indexof";

var n=s1.indexOf("from");

document.write(n);

</script>
JavaScript String lastIndexOf(str) Method

The JavaScript String lastIndexOf(str) method returns the last index position
of the given string.

<script>

var s1="javascript from javatpoint indexof";

var n=s1.lastIndexOf("java");

document.write(n);

</script>

JavaScript String toLowerCase() Method

The JavaScript String toLowerCase() method returns the given string in lowercase
letters.

<script>

var s1="JavaScript toLowerCase Example";

var s2=s1.toLowerCase();

document.write(s2);

</script>

JavaScript String toUpperCase() Method

The JavaScript String toUpperCase() method returns the given string in uppercase
letters.

<script>

var s1="JavaScript toUpperCase Example";

var s2=s1.toUpperCase();

document.write(s2);

</script>

JavaScript String slice(beginIndex, endIndex) Method

The JavaScript String slice(beginIndex, endIndex) method returns the parts of


string from given beginIndex to endIndex. In slice() method, beginIndex is inclusive
and endIndex is exclusive.

<script>
var s1="abcdefgh";

var s2=s1.slice(2,5);

document.write(s2);

</script>

JavaScript String trim() Method

The JavaScript String trim() method removes leading and trailing whitespaces
from the string.

<script>

var s1=" javascript trim ";

var s2=s1.trim();

document.write(s2);

</script>

JavaScript Math

The JavaScript math object provides several constants and methods to


perform mathematical operation. Unlike date object, it doesn't have constructors.

JavaScript Math Methods

Let's see the list of JavaScript Math methods with description.

Methods Description

abs() It returns the absolute value of the given number.

acos() It returns the arccosine of the given number in radians.

asin() It returns the arcsine of the given number in radians.

atan() It returns the arc-tangent of the given number in radians.

cbrt() It returns the cube root of the given number.

ceil() It returns a smallest integer value, greater than or equal to the given number.

cos() It returns the cosine of the given number.

cosh() It returns the hyperbolic cosine of the given number.

exp() It returns the exponential form of the given number.


Math.sqrt(n)

The JavaScript math.sqrt(n) method returns the square root of the given number.

Square Root of 17 is: <span id="p1"></span>

<script>

document.getElementById('p1').innerHTML=Math.sqrt(17);

</script>

Math.random()

The JavaScript math.random() method returns the random number between 0


to 1.

Random Number is: <span id="p2"></span>

<script>

document.getElementById('p2').innerHTML=Math.random();

</script>

Math.pow(m,n)

The JavaScript math.pow(m,n) method returns the m to the power of n that is


mn.

3 to the power of 4 is: <span id="p3"></span>

<script>

document.getElementById('p3').innerHTML=Math.pow(3,4);

</script>

JavaScript Number Object

 The JavaScript number object enables you to represent a numeric


value. It may be integer or floating-point.
 JavaScript number object follows IEEE standard to represent the
floating-point numbers.
 By the help of Number() constructor, you can create number object in
JavaScript. For example:

var n=new Number(value);

For example:

var x=102;//integer value


var y=102.7;//floating point value

var z=13e4;//exponent value, output: 130000

var n=new Number(16);//integer value by number object

JavaScript Number Constants

Constant Description

MIN_VALUE returns the largest minimum value.

MAX_VALUE returns the largest maximum value.

POSITIVE_INFINITY returns positive infinity, overflow value.

NEGATIVE_INFINITY returns negative infinity, overflow value.

NaN represents "Not a Number" value.

JavaScript Number Methods

Methods Description

It determines whether the given value is a finite


isFinite()
number.

isInteger() It determines whether the given value is an integer.

It converts the given string into a floating point


parseFloat()
number.

parseInt() It converts the given string into an integer number.

It returns the string that represents exponential notation


toExponential()
of the given number.

It returns the string that represents a number with exact


toFixed()
digits after a decimal point.

It returns the string representing a number of specified


toPrecision()
precision.

toString() It returns the given number in the form of string.

JavaScript Boolean

 JavaScript Boolean is an object that represents value in two states: true or


false. You can create the JavaScript Boolean object by Boolean() constructor
as given below. The default value of JavaScript Boolean object is false.
Boolean b=new Boolean(value);

JavaScript Boolean Example

<script>

document.write(10<20);//true

document.write(10<5);//false

</script>

JavaScript Boolean Properties

Property Description

returns the reference of Boolean function that created


constructor
Boolean object.

enables you to add properties and methods in Boolean


prototype
prototype.

JavaScript Boolean Methods

Method Description

toSource() returns the source of Boolean object as a string.

toString() converts Boolean into String.

valueOf() converts other type into Boolean.

REGULAR EXPRESSIONS

 A regular expression is a sequence of characters that forms a search pattern.


 The search pattern can be used for text search and text replace operations.

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

var patt = /w3schools/i;

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 String
 The search() method searches a string for a specified value and returns
the position of the match:
Example
Use a string to do a search for "W3schools" in a string:
var str = "Visit W3Schools!";
var n = str.search("W3Schools");

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 String
 The search() method searches a string for a specified value and returns the
position of the match:

Example
Use a string to do a search for "W3schools" in a string:

var str = "Visit W3Schools!";

var n = str.search("W3Schools");

Using String replace() With a String

The replace() method replaces a specified value with another value in a string:

var str = "Visit Microsoft!";


var res = str.replace("Microsoft", "W3Schools");

Use String replace() With a Regular Expression

Example

Use a case insensitive regular expression to replace Microsoft with W3Schools


in a string:

var str = "Visit Microsoft!";


var res = str.replace(/microsoft/i, "W3Schools");

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 Matching
m Perform Multiline Matching

Regular Expression Patterns

Brackets are used to find a range of characters:

Expression Description t

[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 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

 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 nnumber xxxx

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

Using exec()

 The exec() method is a RegExp expression method.


 It searches a string for a specified pattern, and returns the found text as an
object.
 If no match is found, it returns an empty (null) object.
 The following example searches a string for the character "e":

EXCEPTION HANDLING

There are three types of errors in programming:

 Syntax Errors
 Runtime Errors, and
 Logical Errors.
Syntax Errors

 Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages and at interpret time in JavaScript.
 For example, the following line causes a syntax error because it is missing a
closing parenthesis.

<script type = "text/javascript">


<!--
window.print(;
//-->
</script>

 When a syntax error occurs in JavaScript, only the code contained within the
same thread as the syntax error is affected and the rest of the code in other
threads gets executed assuming nothing in them depends on the code
containing the error.

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>

 Exceptions also affect the thread in which they occur, allowing other
JavaScript threads to continue normal execution.

Logical Errors

 Logic errors can be the most difficult type of errors to track down. These
errors are not the result of a syntax or runtime error. Instead, they occur when
you make a mistake in the logic that drives your script and you do not get the
result you expected.
 You cannot catch those errors, because it depends on your business
requirement what type of logic you want to put in your program.

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.

Examples

 Here is an example where we are trying to call a non-existing function which


in turn is raising an exception. Let us see how it behaves without try...catch−

<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script>
</head>

<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>

 Now let us try to catch this exception using try...catch and display a user-
friendly message. You can also suppress this message, if you want to hide this
error from a user.

<html>
<head>

<script type = "text/javascript">


<!--
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
}
//-->
</script>

</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>

</body>
</html>
 You can use finally block which will always execute unconditionally after the
try/catch. Here is an example.

<html>
<head>

<script type = "text/javascript">


<!--
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + e.description );
}
finally {
alert("Finally block will always execute!" );
}
}
//-->
</script>

</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>

</body>
</html>

The throw Statement

 You can use throw statement to raise your built-in exceptions or your
customized exceptions. Later these exceptions can be captured and you can
take an appropriate action.

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 = "Click Me" onclick = "myFunc();" />
</form>

</body>
</html>
 You can raise an exception in one function using a string, integer, Boolean, or
an object and then you can capture that exception either in the same function
as we did above, or in another function using a try...catch block.

The onerror() Method


 The onerror event handler was the first feature to facilitate error handling in
JavaScript. The error event is fired on the window object whenever an
exception occurs on the page.

Live Demo

<html>
<head>

<script type = "text/javascript">


<!--
window.onerror = function () {
alert("An error occurred.");
}
//-->
</script>

</head>
<body>
<p>Click the following to see the result:</p>

<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>

</body>
</html>
 The onerror event handler provides three pieces of information to identify the
exact nature of the error –
 Error message − The same message that the browser would display
for the given error
 URL − The file in which the error occurred
 Line number− The line number in the given URL that caused the
error.

VALIDATION
 Form validation normally used to occur at the server, after the client had
entered all the necessary data and then pressed the Submit button.
 If the data entered by a client was incorrect or was simply missing, the server
would have 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 filled in. 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.

Example

<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>

<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit =
"return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">

<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>

<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>

<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>

<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>

<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>

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

Basic Form Validation

 First let us see how to do a basic form validation. In the above form, we are
calling validate() to validate data when onsubmit event is occurring. The
following code shows the implementation of this validate() function.

<script type = "text/javascript">


<!--
// Form validation code will come here.
function validate() {

if( document.myForm.Name.value == "" ) {


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

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


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

Data Format Validation

 Now we will see how we can validate our entered form data before submitting
it to the web server.
 The following example shows how to validate an entered email address. An
email address must contain at least a ‘@’ sign and a dot (.).
 Also, the ‘@’ must not be the first character of the email address, and the last
dot must at least be one character after the ‘@’ sign.

Example

<script type = "text/javascript">


<!--
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");

if (atpos < 1 || ( dotpos - atpos < 2 )) {


alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>
BUILT IN OBJECTS
In JavaScript, almost "everything" is an object.
 Booleans can be objects (if defined with the new keyword)
 Numbers can be objects (if defined with the new keyword)
 Strings can be objects (if defined with the new keyword)
 Dates are always objects
 Maths are always objects
 Regular expressions are always objects
 Arrays are always objects
 Functions are always objects
 Objects are always objects
JavaScript Primitives
 A primitive value is a value that has no properties or methods.
 A primitive data type is data that has a primitive value.
 JavaScript defines 5 types of primitive data types:
 String
 Number
 Boolean
 Null
 undefined
 Primitive values are immutable (they are hardcoded and therefore cannot be
changed).
 if x = 3.14, you can change the value of x. But you cannot change the value of
3.14.

Value Type Comment

"Hello" string "Hello" is always "Hello"

3.14 number 3.14 is always 3.14

true boolean true is always true

false boolean false is always false

null null (object) null is always null

undefined undefined undefined is always undefined

Objects are Variables

JavaScript variables can contain single values:

Example

var person = "John Doe";


 Objects are variables too. But objects can contain many values.
 The values are written as name : value pairs (name and value
separated by a colon).

Example
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};

 A JavaScript object is a collection of named values

Object Properties

 The named values, in JavaScript objects, are called properties.

Property Value

firstName John

lastName Doe

age 50

eyeColor blue


Objects written as name value pairs are similar to:
 Associative arrays in PHP
 Dictionaries in Python
 Hash tables in C
 Hash maps in Java
 Hashes in Ruby and Perl
Object Methods
 Methods are actions that can be performed on objects.
 Object properties can be both primitive values, other objects, and
functions.
 An object method is an object property containing a function
definition.

Property Value

firstName John

lastName Doe

age 50

eyeColor blue

function() {return this.firstName + " " +


fullName
this.lastName;}

 JavaScript objects are containers for named values, called properties


and methods.

Creating a JavaScript Object


 With JavaScript, you can define and create your own objects.
 There are different ways to create new objects:
 Define and create a single object, using an object literal.
 Define and create a single object, with the keyword new.
 Define an object constructor, and then create objects of the constructed
type.
 In ECMAScript 5, an object can also be created with the function
Object.create().

Using an Object Literal

 This is the easiest way to create a JavaScript Object.


 Using an object literal, you both define and create an object in one statement.
 An object literal is a list of name:value pairs (like age:50) inside curly braces
{}.
 The following example creates a new JavaScript object with four properties:

Example

var person = {firstName:"John", lastName:"Doe", age:50,


eyeColor:"blue"};

Using the JavaScript Keyword new

 The following example also creates a new JavaScript object with four
properties:

Example

var person = new Object();


person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

JavaScript Objects are Mutable

 Objects are mutable: They are addressed by reference, not by value.


 If person is an object, the following statement will not create a copy of person:
var x = person; // This will not create a copy of person.
 The object x is not a copy of person. It is person. Both x and person are the
same object.
 Any changes to x will also change person, because x and person are the same
object.

Example
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"}
varx=person;
x.age = 10; // This will change both x.age and person.age

JavaScript Object Properties

 Accessing JavaScript Properties


 The syntax for accessing the property of an object is:

objectName.property // person.age
or
objectName["property"] // person["age"]
or
objectName[expression] // x = "age"; person[x]

JavaScript for...in Loop

 The JavaScript for...in statement loops through the properties of an object.


Syntax
for (variable in object) {
// code to be executed
}
 The block of code inside of the for...in loop will be executed once for each
property.
 Looping through the properties of an object:

Object Methods

Example
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
The this Keyword

 In a function definition, this refers to the "owner" of the function.


 In the example above, this is the person object that "owns" the fullName
function.
 In other words, this.firstName means the firstName property of this object.

JavaScript Methods

 JavaScript methods are actions that can be performed on objects.


 A JavaScript method is a property containing a function definition.
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
fullName function() {return this.firstName + " " + this.lastName;}

Accessing Object Methods

 You access an object method with the following syntax:

objectName.methodName()

 You will typically describe fullName() as a method of the person object, and
fullName as a property.
 The fullName property will execute (as a function) when it is invoked with ().
 This example accesses the fullName() method of a person object:

Example

name = person.fullName();

Using Built-In Methods

 This example uses the toUpperCase() method of the String object, to convert a
text to uppercase:

var message = "Hello world!";


var x = message.toUpperCase();

The value of x, after execution of the code above will be:

HELLO WORLD!

Adding a Method to an Object

Adding a new method to an object is easy:

Example
person.name = function () {
return this.firstName + " " + this.lastName;
};

Object Accessors

JavaScript Accessors (Getters and Setters)

 ECMAScript 5 (2009) introduced Getter and Setters.


 Getters and setters allow you to define Object Accessors (Computed
Properties).

JavaScript Getter (The get Keyword)

This example uses a lang property to get the value of the language property.

Example

// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
language : "en",
get lang() {
return this.language;
}
};

// Display data from the object using a getter:


document.getElementById("demo").innerHTML = person.lang;

JavaScript Setter (The set Keyword)

 This example uses a lang property to set the value of the language property.

Example

var person = {
firstName: "John",
lastName : "Doe",
language : "",
set lang(lang) {
this.language = lang;
}
};
// Set an object property using a setter:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;

Data Quality

 JavaScript can secure better data quality when using getters and setters.
 Using the lang property, in this example, returns the value of the language
property in upper case:

Example

// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
language : "en",
get lang() {
return this.language.toUpperCase();
}
};

// Display data from the object using a getter:


document.getElementById("demo").innerHTML = person.lang;

Object.defineProperty()

 The Object.defineProperty() method can also be used to add Getters and


Setters:

Example

// Define object
var obj = {counter : 0};

// Define setters
Object.defineProperty(obj, "reset", {
get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
set : function (value) {this.counter -= value;}
});

// Play with the counter:


obj.reset;
obj.add = 5;
obj.subtract = 1;
obj.increment;
obj.decrement;

Object Constructors

 Object Types (Blueprints) (Classes)


 The examples from the previous chapters are limited. They only create single
objects.
 Sometimes we need a "blueprint" for creating many objects of the same
"type".
 The way to create an "object type", is to use an object constructor function.
 In the example above, function Person() is an object constructor function.
 Objects of the same type are created by calling the constructor function with
the new keyword:

var myFather = new Person("John", "Doe", 50, "blue");

var myMother = new Person("Sally", "Rally", 48, "green");

The this Keyword

 In JavaScript, the thing called this is the object that "owns" the code.
 The value of this, when used in an object, is the object itself.
 In a constructor function this does not have a value. It is a substitute for the
new object. The value of this will become the new object when a new object is
created.

Adding a Property to an Object

 Adding a new property to an existing object is easy:

Example

myFather.nationality = "English";
Adding a Method to an Object

 Adding a new method to an existing object is easy:

Example

myFather.name = function () {
return this.firstName + " " + this.lastName;
};

Adding a Property to a Constructor

 You cannot add a new property to an object constructor the same way you add
a new property to an existing object:

Example

Person.nationality = "English";

Adding a Method to a Constructor

 Your constructor function can also define methods:

Example

function Person(first, last, age, eyecolor) {

this.firstName = first;

this.lastName = last;

this.age = age;

this.eyeColor = eyecolor;

this.name = function() {return this.firstName + " " + this.lastName;};

Built-in JavaScript Constructors

 JavaScript has built-in constructors for native objects:

Example

var x1 = new Object(); // A new Object object


var x2 = new String(); // A new String object
var x3 = new Number(); // A new Number object
var x4 = new Boolean(); // A new Boolean object
var x5 = new Array(); // A new Array object
var x6 = new RegExp(); // A new RegExp object
var x7 = new Function(); // A new Function object
var x8 = new Date(); // A new Date object

String Objects

 Normally, strings are created as primitives: var firstName = "John"


 But strings can also be created as objects using the new keyword: var
firstName = new String("John")

Number Objects

 Normally, numbers are created as primitives: var x = 123


 But numbers can also be created as objects using the new keyword: var x =
new Number(123)

Boolean Objects

 Normally, booleans are created as primitives: var x = false


 But booleans can also be created as objects using the new keyword: var x =
new Boolean(false)

Object Prototypes

 All JavaScript objects inherit properties and methods from a prototype.

Prototype Inheritance

 All JavaScript objects inherit properties and methods from a prototype:


 Date objects inherit from Date.prototype
 Array objects inherit from Array.prototype
 Person objects inherit from Person.prototype
 The Object.prototype is on the top of the prototype inheritance chain:
 Date objects, Array objects, and Person objects inherit from Object.prototype.

Adding Properties and Methods to Objects

 Sometimes you want to add new properties (or methods) to all existing objects
of a given type.
 Sometimes you want to add new properties (or methods) to an object
constructor.

Using the prototype Property

 The JavaScript prototype property allows you to add new properties to


object constructors:

Example
function Person(first, last, age, eyecolor) {

this.firstName = first;

this.lastName = last;

this.age = age;

this.eyeColor = eyecolor;

Person.prototype.nationality = "English";

 The JavaScript prototype property also allows you to add new methods
to objects constructors:

Example

function Person(first, last, age, eyecolor) {

this.firstName = first;

this.lastName = last;

this.age = age;

this.eyeColor = eyecolor;

Person.prototype.name = function() {

return this.firstName + " " + this.lastName;

};

EVENT HANDLING

 JavaScript's interaction with HTML is handled through events that


occur when the user or the browser manipulates a page.
 When the page loads, it is called an event. When the user clicks a
button, that click too is an event.
 Other examples 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.
 Events are a part of the Document Object Model (DOM) Level 3 and
every HTML element contains a set of events which can trigger
JavaScript Code.

2.8.1 onclick Event Type

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

Example

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

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

onsubmit Event Type

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

Example

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

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

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

onmouseover and onmouseout

 These two event types will help you create nice effects with images or
even with text as well.
 The onmouseover event triggers when you bring your mouse over any
element and the onmouseout triggers when you move your mouse out
from that element.

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

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

2.8.4 HTML 5 Standard Events


The standard HTML 5 events are listed here for your reference. Here script
indicates a Javascript function to be executed against that event.

Attribute Value Description

Offline script Triggers when the document goes offline

Onabort script Triggers on an abort event

onafterprint script Triggers after the document is printed

onbeforeonload script Triggers before the document loads

onbeforeprint script Triggers before the document is printed

onblur script Triggers when the window loses focus

Triggers when media can start play, but might has to stop for
oncanplay script
buffering

Triggers when media can be played to the end, without


oncanplaythrough script
stopping for buffering

onchange script Triggers when an element changes

onclick script Triggers on a mouse click

oncontextmenu script Triggers when a context menu is triggered

ondblclick script Triggers on a mouse double-click

ondrag script Triggers when an element is dragged

DHTML WITH JAVASCRIPT

DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.

Dynamic HTML is not a markup or programming language but it is a term that


combines the features of various web development technologies for creating the web
pages dynamic and interactive.

The DHTML application was introduced by Microsoft with the release of the
4th version of IE (Internet Explorer) in 1997.

Components of Dynamic HTML

DHTML consists of the following four components or languages:

o HTML 4.0
o CSS
o JavaScript
o DOM.

HTML 4.0

HTML is a client-side markup language, which is a core component of the DHTML.


It defines the structure of a web page with various defined basic elements or tags.

CSS

CSS stands for Cascading Style Sheet, which allows the web users or developers for
controlling the style and layout of the HTML elements on the web pages.

JavaScript

JavaScript is a scripting language which is done on a client-side. The various browser


supports JavaScript technology. DHTML uses the JavaScript technology for
accessing, controlling, and manipulating the HTML elements. The statements in
JavaScript are the commands which tell the browser for performing an action.

DOM

DOM is the document object model. It is a w3c standard, which is a standard interface
of programming for HTML. It is mainly used for defining the objects and properties
of all elements in HTML.

Uses of DHTML

Following are the uses of DHTML (Dynamic HTML):

o It is used for designing the animated and interactive web pages that are
developed in real-time.
o DHTML helps users by animating the text and images in their documents.
o It allows the authors for adding the effects on their pages.
o It also allows the page authors for including the drop-down menus or rollover
buttons.
o This term is also used to create various browser-based action games.
o It is also used to add the ticker on various websites, which needs to refresh
their content automatically.

Features of DHTML

Following are the various characteristics or features of DHTML (Dynamic HTML):


o Its simplest and main feature is that we can create the web page dynamically.
o Dynamic Style is a feature, that allows the users to alter the font, size, color,
and content of a web page.
o It provides the facility for using the events, methods, and properties. And, also
provides the feature of code reusability.
o It also provides the feature in browsers for data binding.
o Using DHTML, users can easily create dynamic fonts for their web sites or
web pages.
o The web page functionality is enhanced because the DHTML uses low-
bandwidth effect.

DHTML JavaScript

JavaScript can be included in HTML pages, which creates the content of the page as
dynamic. We can easily type the JavaScript code within the <head> or <body> tag of
a HTML page. If we want to add the external source file of JavaScript, we can easily
add using the <src> attribute.

Following are the various examples, which describes how to use the JavaScript
technology with the DHTML:

Document.write() Method

The document.write() method of JavaScript, writes the output to a web page.

Example 1: The following example simply uses the document.write() method of


JavaScript in the DHTML. In this example, we type the JavaScript code in
the <body> tag.

1. <HTML>
2. <head>
3. <title>
4. Method of a JavaScript
5. </title>
6. </head>
7. <body>
8. <script type="text/javascript">
9. document.write("JavaTpoint");
10. </script>
11. </body>
12. </html>

JavaScript Alone

document.write()

can be used to display dynamic content to a web page.

Example

Using JavaScript to display the current date:

<html>
<body>
<script type="text/javascript">
document.write(Date());
</script>
</body>
</html>

JavaScript and the HTML DOM

 With HTML 4, JavaScript can also be used to change the inner content and
attributes of HTML elements dynamically.
 To change the content of an HTML element use:

document.getElementById(id).innerHTML=new HTML

 To change the attribute of an HTML element use:

document.getElementById(id).attribute=new value

JavaScript and HTML Events

 New to HTML 4 is the ability to let HTML events trigger actions in the
browser, like starting a JavaScript when a user clicks on an HTML element.
 To execute code when a user clicks on an element, use the following event
attribute:

onclick=JavaScript
JavaScript and CSS

 With HTML 4, JavaScript can also be used to change the style of HTML
elements.
 To change the style of an HTML element use:

document.getElementById(id).style.property=new style

Servlet Architecture

Servlets are grouped under the Advanced Java tree that are used to create dynamic
web applications. Servlets are robust in nature, well scalable and are primarily used
in developing server-side applications. If we go a little back in time, we would be
able to witness that before the introduction of servlets, CGI (Common Gateway
Interface) were used. Amid several indigenous tasks that a servlet is capable of
doing, dynamically performing client requests and responses are most common.
Other tasks that a servlet can do effectively are:
 Can easily manage/control the application flow.
 Suitable to implement business logic.
 Can effectively balance the load at the server-side.
 Easily generate dynamic web content.
Talking about the types of servlets, there are primarily two types, namely:
1. Generic Servlets
2. HTTP Servlets
There are three potential ways in which we can employ to create a servlet:
1. Implementing Servlet Interface
2. Extending Generic Servlet
3. Extending HTTP Servlet
Components of Servlet Architecture
Below is the high level architecture diagram of servlet. Let’s see in brief, how does
each component add to the working of a servlet.
Servlet Architecture
1. Client
The client shown in the architecture above is primarily working as a medium who is
sending out HTTP requests over to the web server and again processing the response
it gets back from the server. As we can see in the diagram, our client here is the web
browser.
2. Web Server
Primary job of a web server is to process the requests and responses that a user
sends over time and maintain how a web user would be able to access the files that
has been hosted over the server. The server we are talking about here is a
software which manages access to a centralized resource or service in a network..
There are precisely two types of webservers:
1. Static web server
2. Dynamic web server
3. Web Container
Web container is another typical component in servlet architecture which is
responsible for communicating with the servlets. Two prime tasks of a web
container are:
 Managing the servlet lifecycle
 URL mapping
Web container sits at the server-side managing and handling all the requests that are
coming in either from the servlets or from some JSP pages or potentially any other
file system.
How does a Servlet Request flow?
Every servlet should override the following 3 methods namely:
1. init()
2. service()
3. destroy()
These methods are used to process the request from the user.
Following are the steps in which a request flows through a servlet which can be
observed in the architecture diagram:
 The client sends over a request.
 The request is accepted by the web server and forwarded to the web container.
 In order to obtain the servlet’s address, the web container traces web.xml file
corresponding to the request URL pattern.
 By the time above process takes place, the servlet should have been instantiated
and initialized. If the servlet has not been instantiated and
initialized, init() method is invoked to serve the purpose.
 By passing ServletRequest and Response object, public service() method is
called by the container.
 In the next step, the ServletRequest and ServletResponse objects are type-casted
to HttpServletRequest and HttpServletResponse objects by the public
service() method.
 Now protected service() method is called by the public service() method.
 The protected service() method dispatches the request to the correct handler
method based on the type of request.
 When servlet container shuts down, it unloads all the servlets and
calls destroy() method for each initialized servlets.
Advantages
 Prime functionality of a servlet is that they are independent of server
configuration and they are pretty much compatible with any of the web servers
 Servlets are also protocol-independent supporting FTP, HTTP, SMTP, etc.
protocols to the fullest.
 Until destroyed manually, servlets can be retained in the memory helping
process several requests over time. Also, once a database connection is
established, it can facilitate process several requests for a database in the very
same database session.
 Servlets inherit Java’s property of portability and hence are compatible with
nearly any web server.
 Servlets are first converted into byte codes and then executed, which helps in
increasing the processing time.
Disadvantages
 Designing a servlet can be pretty laborious.
 Exceptions need to be handled while designing a servlet since they are not
thread-safe.
 Developers may need additional skills to program a servlet.
As we already know Servlets are portable (platform/server independent) in nature
and hence are a better option if we talk in terms of other scripting languages. They
process the requests and responses dynamically. Whenever we are developing a web
application where we need to coordinate with different existing protocols, servlets
are preferred over other means because of its capability to support various
protocols. At last we can descend to a conclusion that employing a servlet could
potentially be most suitable while developing a web application.

Life Cycle of a Servlet


The entire life cycle of a Servlet is managed by the Servlet container which uses
the javax.servlet.Servlet interface to understand the Servlet object and manage it.
So, before creating a Servlet object, let’s first understand the life cycle of the Servlet
object which is actually understanding how the Servlet container manages the
Servlet object.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four
stages,
 Loading a Servlet.
 Initializing the Servlet.
 Request handling.
 Destroying the Servlet.
Let’s look at each of these stages in details:
1. Loading a Servlet: The first stage of the Servlet lifecycle involves loading and
initializing the Servlet by the Servlet container. The Web container or Servlet
Container can load the Servlet at either of the following two stages :
 Initializing the context, on configuring the Servlet with a zero or positive integer
value.
 If the Servlet is not preceding stage, it may delay the loading process until the
Web container determines that this Servlet is needed to service a request.
The Servlet container performs two operations in this stage :
 Loading : Loads the Servlet class.
 Instantiation : Creates an instance of the Servlet. To create a new instance of
the Servlet, the container uses the no-argument constructor.
2. Initializing a Servlet: After the Servlet is instantiated successfully, the Servlet
container initializes the instantiated Servlet object. The container initializes the
Servlet object by invoking the Servlet.init(ServletConfig) method which
accepts ServletConfig object reference as parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method only once,
immediately after the Servlet.init(ServletConfig) object is instantiated
successfully. This method is used to initialize the resources, such as JDBC
datasource.
3.
Now, if the Servlet fails to initialize, then it informs the Servlet container by
throwing the ServletException or UnavailableException.
4.
5. 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.
6. 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.
Servlet Life Cycle Methods
There are three life cycle methods of a Servlet :
 init()
 service()
 destroy()
Let’s look at each of these methods in details:
1. init() method: The Servlet.init() method is called by the Servlet container to
indicate that this Servlet instance is instantiated successfully and is about to put
into service.
//init() method

public class MyServlet implements Servlet{


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

public class MyServlet implements Servlet{


public void service(ServletRequest res, ServletResponse res)
throws ServletException, IOException {
// request handling code
}
// rest of code
}
4. destroy() method: The destroy() method runs only once during the lifetime of a
Servlet and signals the end of the Servlet instance.
//destroy() method

public void destroy()


5.
As soon as the destroy() method is activated, the Servlet container releases the
Servlet instance.
6.
Servlet Life Cycle:
Servlet life cycle can be defined as the stages through which the servlet passes from
its creation to its destruction.
The servlet life cycle consists these stages:
 Servlet is borned
 Servlet is initialized
 Servlet is ready to service
 Servlet is servicing
 Servlet is not ready to service
 Servlet is destroyed
Life cycle methods:
Life cycle methods are those methods which are used to control the life cycle of the
servlet. These methods are called in specific order during the servlets’s entire life
cycle.
The class Servlet provides the methods to control and supervise the life cycle of
servlet. There are three life cycle methods in the Servlet interface. There are as
follows:
 init() method :
1. A servlet’s life begins here .
2. This method is called only once to load the servlet.Since it is called only once in
it’s lifetime,therefore “connected architecture” code is written inside it because
we only want once to get connected with the database.
Now Question Arises is that:-
Q.Why can’t we write connected architecture code inside the constructor, since
constructor also run only once in it’s entire life?
Ans. Suppose if the connection doesn’t get established, then we can throw an
exception from init() and the rest of the steps stop executing. But in the
constructor we can’t use, throw in it’s prototype otherwise it is an error.
3. This method receives only one parameter, i.e ServletConfig object.
4. This method has the possibility to throw the ServletException.
5. Once the servlet is initialized, it is ready to handle the client request.
6. The prototype for the init() method:
public void init(ServletConfig con)throws ServletException{ }
7.
where con is ServletConfig object
8.
NOTE:- In programs of servlet,we use non parameterized version of init().
Now,Question Arises is that:-
Q. Why it is recommended to use the non parameterized version of init() instead of
parameterized version as seen above?
Ans. To answer this, we have to go into detail. Think like developers,i.e there must
be some valid reason for this and the answer will blow your mind. Coming to
answer:
APPROACH 1
Whenever the lifecycle method of a servlet starts executing,i.e when public void
init(ServletConfig con) throws ServletException gets call then our class public void
init(ServletConfig con) throws ServletException gets called but we have to run the
code which initializes servlet config object which is written inside “HttpServlet”
method public void init(ServletConfig con) throws ServletException,i.e:
Coding of HttpServlet class be like:
public void init(ServletConfig con) throws ServletException
{
//code to initialise ServletConfig object

init(); //This HttpServlet has 2 init() one which is parameterized and the other one is
non
//parameterized.But this non parameterized version of init() has a blank body.
//So this call is useless.

}
Now see the coding of our class
public void init(ServletConfig con) throws ServletException
{
super.init(con); //Since,our class init() will run first,but to run HttpServlet init() we
// have used super keyword.And Database connectivity code will be their
}
NOTE:- As we can see, total 3 init() calls we have to make.First init() gets called of
our class then of HttpServlet class then non parameterized version of HttpServlet
class.
But now, we will achieve the same thing with less number of calls:
APPROACH 2
Coding of HttpServlet parametrized and non parameterized versions of init() will
remain the same. But in our class instead of overriding parameterized version of
init(), we will override non parameterized version of init().
Let’s see the coding of our class non parameterized version of init():
public void init() throws ServletException
{
//database connectivity code
}
NOTE: Since this method public void init() throws ServletException ,we have
override from HttpServlet class whose coding is like:
public void init() throws ServletException
{
//empty body
}
Since it’s body is blank, therefore it is known as “Helper method” as it is used for
overriding purpose.
Now, as the servlet starts executing its methods, it will call the parameterized
version of init(). Since we have not to override the parameterized version, therefore
it will give a call to the HttpServlet parameterized version of init(). Since coding of
a parameterized version of init() of HttpServlet is as same as above, therefore, from
there on it will call init() (i.e non parameterized version of init). It will give a call to
our class non parameterized version of init() and the code continues.
Now, as you can see, total number of init() calls are 2 which is less than the first
approach. Therefore, execution time is less in 2nd approach and less headache
for CPU for maintaining stack and it’s speed increases as compared to 1st
approach.
Therefore, it is highly recommended to override non parameterized version of
init().Although both will run but due to efficiency first approach is rarely used and
also in first approach we have to use super keyword too.Therefore in below
mentioned program,we have override non parameterized version of init().
 service() method :
1. The service() method is the most important method to perform that provides the
connection between client and server.
2. The web server calls the service() method to handle requests coming from the
client( web browsers) and to send response back to the client.
3. This method determines the type of Http request (GET, POST, PUT, DELETE,
etc.) .
4. This method also calls various other methods such as doGet(), doPost(), doPut(),
doDelete(), etc. as required.
5. This method accepts two parameters.
6. The prototype for this method:
public void service(ServletRequest req, ServletResponse resp)
throws ServletException, IOException { }
7.
where
8.
 req is the ServletRequest object which encapsulates the connection from client
to server
 resp is the ServletResponse object which encapsulates the connection from
server back to the client
 destroy() method :
1. The destroy() method is called only once.
2. It is called at the end of the life cycle of the servlet.
3. This method performs various tasks such as closing connection with the
database, releasing memory allocated to the servlet, releasing resources that are
allocated to the servlet and other cleanup activities.
4. When this method is called, the garbage collector comes into action.
5. The prototype for this method is:
public void destroy() { // Finalization code...}
6.
Below is a sample program to illustrate Servlet in Java:

// Java program to show servlet example


// Importing required Java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class AdvanceJavaConcepts extends HttpServlet
{
private String output;

// Initializing servlet
public void init() throws ServletException
{
output = "Advance Java Concepts";
}

// Requesting and printing the output


public void doGet(HttpServletRequest req,
HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println(output);
}

public void destroy()


{
System.out.println("Over");
}
}

HTML <form> method Attribute

The HTML <form> method Attribute is used to specify the HTTP method used to
send data while submitting the form. There are two kinds of HTTP methods, which
are GET and POST. The method attribute can be used with the <form> element.
Attribute Values:
 GET: In the GET method, after the submission of the form, the form values will
be visible in the address bar of the new browser tab. It has a limited size of about
3000 characters. It is only useful for non-secure data not for sensitive
information.
 POST: In the post method, after the submission of the form, the form values
will not be visible in the address bar of the new browser tab as it was visible in
the GET method. It appends form data inside the body of the HTTP request. It
has no size limitation. This method does not support bookmark the result.

Supported Tags:
 <form>
Syntax:
<form method="get|post">
Example 1: This example illustrates the use of GET method attribute.
 html

<!DOCTYPE html>
<html>

<head>
<title>
HTML form method Attribute
</title>
</head>

<body style="text-align:center;">

<h1 style="color:green;">GeeksforGeeks</h1>

<h3> HTML <form> Method Attribute. </h3>

<form action="/action_page.php" id="users"


action="#" method="GET" target="_blank">

First name: <input type="text" name="fname"


placeholder="Enter first name">

<br><br>
Last name: <input type="text" name="lname"
placeholder="Enter last name">
<br><br>

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

</form>

<p>
By clicking the submit button the Entered<br>
details will be sent to "/action_page.php"
</p>
</body>

</html>

Output:
Example 2: This example illustrates the use of the POST method attribute. This
method sends the form-data as an HTTP post-transaction.

 html

<!DOCTYPE html>
<html>

<head>
<title>
HTML form method Attribute
</title>
</head>

<body style="text-align:center;">

<h1 style="color:green;">GeeksforGeeks</h1>

<h3>HTML <form> Method Attribute.</h3>

<form action="/action_page.php" id="users"


action="#" method="POST" target="_blank">

Email_id: <input type="text" name="Email_id"


placeholder="Enter email_id">

<br><br>

Password: <input type="password"


placeholder="Enter Password">

Confirm Password: <input type="password"


placeholder="Re-enter Password">
<br><br>

<input type="button" value="login">

</form>

<p>
By clicking the login button the Entered<br>
details will be sent to "/action_page.php"
</p>
</body>

</html>

Output:

Servlet – Session Tracking


Servlets are the Java programs that run on the Java-enabled web server or application
server. They are used to handle the request obtained from the webserver, process the
request, produce the response, then send a response back to the webserver
HTTP is a “stateless” protocol, which means that each time a client requests a Web
page, the client establishes a new connection with the Web server, and the server does
not retain track of prior requests.
 The conversion of a user over a period of time is referred to as a session. In
general, it refers to a certain period of time.
 The recording of the object in session is known as tracking.
 Session tracking is the process of remembering and documenting customer
conversions over time. Session management is another name for it.
 The term “stateful web application” refers to a web application that is capable of
remembering and recording client conversions over time.
Why is Session Tracking Required?
 Because the HTTP protocol is stateless, we require Session Tracking to make the
client-server relationship stateful.
 Session tracking is important for tracking conversions in online shopping, mailing
applications, and E-Commerce applications.
 The HTTP protocol is stateless, which implies that each request is treated as a new
one. As you can see in the image below.

Deleting Session Data

We have numerous alternatives once you’ve finished processing a user’s session data.
1. Remove a specific attribute You can delete the value associated with a specific
key by calling the public void removeAttribute(String name) function.
2. Delete your whole session. To delete an entire session, use the public void
invalidate() function.
3. Setting Session Timeout You may set the timeout for a session separately by
calling the public void setMaxInactiveInterval(int interval) function.
4. Log the user out On servers that support servlets 2.4, you may use the logout
method to log the client out of the Web server and invalidate all of the users’
sessions.
5. web.xml Configuration If you’re using Tomcat, you may set the session timeout in
the web.xml file, in addition to the ways listed above.
<session-config> <session-timeout>20</session-timeout></session-config>
The timeout is specified in minutes and overrides Tomcat’s default timeout of 30
minutes.
In a servlet, the getMaxInactiveInterval() function delivers the session’s timeout
period in seconds. GetMaxInactiveInterval() returns 900 if your session is set to 20
minutes in web.xml.

Session Tracking employs Four Different techniques

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
A. Cookies
Cookies are little pieces of data delivered by the web server in the response header
and kept by the browser. Each web client can be assigned a unique session ID by a
web server. Cookies are used to keep the session going. Cookies can be turned off by
the client.
B. Hidden Form Field
The information is inserted into the web pages via the hidden form field, which is then
transferred to the server. These fields are hidden from the user’s view.
Illustration:
<input type = hidden' name = 'session' value = '12345' >
C. URL Rewriting
With each request and return, append some more data via URL as request parameters.
URL rewriting is a better technique to keep session management and browser
operations in sync.
D. HttpSession
A user session is represented by the HttpSession object. A session is established
between an HTTP client and an HTTP server using the HttpSession interface. A user
session is a collection of data about a user that spans many HTTP requests.
Illustration:
HttpSession session = request.getSession( );
Session.setAttribute("username", "password");
The request must be made. Before sending any document content to the client, you
must first call getSession(). The following is a list of the most significant methods
provided by the HttpSession object:

Method Description

This method returns the object in this session


public Object
bound with the supplied name, or null if no
getAttribute(String name)
object is bound with the name.

This function returns an Enumeration of String


public Enumeration
objects with the names of all the items
getAttributeNames()
associated with this session.

This method returns the milliseconds since


public long getCreationTime() midnight January 1, 1970 GMT, when this
session was created.

This function returns a string that contains the


public String getId()
session’s unique identification.

This function returns the session’s most recent


public long
accessible time in milliseconds since midnight
getLastAccessedTime()
on January 1, 1970 GMT.
Method Description

The maximum time interval (seconds) for which


public int the servlet container will keep the session open
getMaxInactiveInterval() between client requests is returned by this
function.

This function unbinds any objects connected to


public void invalidate()
this session and invalidates it.

If the client is unaware of the session or decides


public boolean isNew()
not to join it, this function returns true.

public void The object bound with the supplied name is


removeAttribute(String name) removed from this session using this method.

public void setAttribute(String This function uses the supplied name to tie an
name, Object value) object to this session.

public void This function defines the interval between client


setMaxInactiveInterval(int requests before the servlet container invalidates
interval) this session in seconds.

Implementation: It depicts how to get the creation and last-accessed times for a
session using the HttpSession object. If the request does not already have a session
associated with it, we will create one.

You might also like