You are on page 1of 147

IT8501 - Web Technology - Java Script

Scripting Basics

Web Page
• web page is a document available on world wide web. Web Pages are
stored on web server and can be viewed using a web browser.
• A web page can cotain huge information including text, graphics,
audio, video and hyper links. These hyper links are the link to other
web pages.

03/21/22 satheesh.research18@gmail.com 1
IT8501 - Web Technology - Java Script

Static Web page


• Static web pages are also known as flat or stationary web page. They
are loaded on the client’s browser as exactly they are stored on the
web server. Such web pages contain only static information. User can
only read the information but can’t do any modification or interact
with the information.
• Static web pages are created using only HTML. Static web pages are
only used when the information is no more required to be modified.

03/21/22 satheesh.research18@gmail.com 2
IT8501 - Web Technology - Java Script

Dynamic Web page


• Dynamic web page shows different information at different point of time. It
is possible to change a portaion of a web page without loading the entire
web page. It has been made possible using Ajax technology.
SERVER-SIDE DYNAMIC WEB PAGE:
• It is created by using server-side scripting. There are server-side scripting
parameters that determine how to assemble a new web page which also
include setting up of more client-side processing.
CLIENT-SIDE DYNAMIC WEB PAGE
• It is processed using client side scripting such as JavaScript. And then
passed in to Document Object Model (DOM).

03/21/22 satheesh.research18@gmail.com 3
IT8501 - Web Technology - Java Script

03/21/22 satheesh.research18@gmail.com 4
IT8501 - Web Technology - Java Script
Scripting Basics

Scripting basics- Client side and server side scripting.


What is a script?
• Script is a small, embedded program.
• The most popular scripting languages on the web are, JavaScript or
VBScript.
• HTML does not have scripting capability, you need to use <script>
tag.
• The <script> tag is used to generate a script.
• The </script> tag indicates the end of the script or program.

03/21/22 satheesh.research18@gmail.com 5
IT8501 - Web Technology - Java Script
Scripting Basics

Scripting basics- Client side and server side scripting.


Example : Type attribute
<script type = “text/javascript”>
     document.write(“TutorialRide”);
</script>
Example : Language attribute
<script language= “javascript”>
     document.write(“TutorialRide”);
</script>

03/21/22 satheesh.research18@gmail.com 6
IT8501 - Web Technology - Java Script
Scripting Basics

Scripting basics- Client side and server side scripting.


1. Client-Side Scripting
– Client-Side Scripting is an important part of the Dynamic HTML
(DHTML).
– JavaScript is the main client-side scripting language for the web.
– The scripts are interpreted by the browser.
– Client-Side scripting is used to make changes in the web page after they
arrive at the browser.
– It is useful for making the pages a bit more interesting and user-friendly.
– It provides useful gadgets such as calculators, clocks etc.
– It enables interaction within a web page.
– It is affected by the processing speed of the user's computer.

03/21/22 satheesh.research18@gmail.com 7
IT8501 - Web Technology - Java Script
Scripting Basics

Client side side scripting.

03/21/22 satheesh.research18@gmail.com 8
IT8501 - Web Technology - Java Script
Scripting Basics

Client side Diagram Explanation.


– The user requests a web page from the server.
– The server finds the page and sends it to the user.
– The page is displayed on the browser with any scripts running during or after the
display.
– Client-Side scripting is used to make web page changes after they arrive at the
browser.
– These scripts rely on the user's computer. If the computer is slow, then they may
run slow.
– These scripts may not run at all if the browser does not understand the scripting
language.

03/21/22 satheesh.research18@gmail.com 9
IT8501 - Web Technology - Java Script
Scripting Basics

Server side scripting:


• Server-Side Scripting is used in web development.
• The server-side environment runs a scripting language which is called a web server.
• Server-Side Scripting is used to provide interactive web sites.
• It is different from Client-Side Scripting where the scripts are run by viewing the
web browser, usually in JavaScript.
• It is used for allowing the users to have individual accounts and providing data from
databases.
• It allows a level of privacy, personalization and provision of information that is very
useful.
• It includes ASP.NET and PHP.
• It does not rely on the user having specific browser or plug-in.
• It is affected by the processing speed of the host server.

03/21/22 satheesh.research18@gmail.com 10
IT8501 - Web Technology - Java Script
Scripting Basics

server side scripting.

03/21/22 satheesh.research18@gmail.com 11
IT8501 - Web Technology - Java Script
Scripting Basics

server side scripting Diagram Explanation


• The client requests a web page from the server.
• The script in the page is interpreted by the server, creating or changing the
page content to suit the user (client) and the passing data around.
• The page in its final form is sent to the user(client) and then cannot be
changed using Server-Side Scripting.
• Server-Side Scripting tends to be used for allowing the users to have
individual accounts and provides data from the databases.
• These scripts are never seen by the user.
• Server-Side script runs on the server and generate results which are sent to the
user.
• Running all the scripts puts a lot of load onto a server but not on the user's
system.

03/21/22 satheesh.research18@gmail.com 12
IT8501 - Web Technology - Java Script
Scripting Basics

Scripting basics- Client side and server side scripting.

03/21/22 satheesh.research18@gmail.com 13
IT8501 - Web Technology - Java Script

Scripting basics- Client side and server side scripting.

03/21/22 satheesh.research18@gmail.com 14
IT8501 - Web Technology - Java Script

Client-Side scripting languages:


JavaScript
• It is a prototype based scripting language. It inherits its naming conventions
from java. All java script files are stored in file having .js extension.
ActionScript
• It is an object oriented programming language used for the development of
websites and software targeting Adobe flash player.
Dart
• It is an open source web programming language developed by Google. It
relies on source-to-source compiler to JavaScript.
VBScript
• It is an open source web programming language developed by Microsoft. It
is superset of JavaScript and adds optional static typing class-based object
oriented programming.

03/21/22 satheesh.research18@gmail.com 15
IT8501 - Web Technology - Java Script
Server-Side scripting languages
ASP
• Active Server Pages (ASP)is server-side script engine to create dynamic web pages. It
supports Component Object Model (COM) which enables ASP web sites to access
functionality of libraries such as DLL.
ActiveVFP
• It is similar to PHP and also used for creating dynamic web pages. It uses native Visual
Foxpro language and database.
ASP.net
• It is used to develop dynamic websites, web applications, and web services.
Java
• Java Server Pages(JSP) are used for creating dynamic web applications. The Java code is
compiled into byte code and run by Java Virtual Machine (JVM).
Python
• It supports multiple programming paradigms such as object-oriented, and functional
programming. It can also be used as non-scripting language using third party tools such
as Py2exe or Pyinstaller.
WebDNA
• It is also a server-side scripting language with an embedded database system.

03/21/22 satheesh.research18@gmail.com 16
IT8501 - Web Technology - Java Script
Java Script

Java Script:
• Object, names, literals,
• Operators and expressions
• Statements and features
• Events – windows
• Documents
• Frames
• Data types
• Built-in functions
• Browser object model
• Verifying forms.

03/21/22 satheesh.research18@gmail.com 17
IT8501 - Web Technology - Java Script
Java Script

Introduction :
• JavaScript is an Object-oriented Computer Programming
Language.
• It is an Interpreted programming or script language from
Netscape.
• The scripting languages are easier and faster to code.
• Its first appearance was in Netscape 2.0 in 1995 with the
name 'LiveScript'.

03/21/22 satheesh.research18@gmail.com 18
IT8501 - Web Technology - Java Script
Java Script

Features of JavaScript
– JavaScript is an open source scripting language.
– It is lightweight.
– It creates network-centric applications.
– It is platform independent.
– It validates form data.
– It reduces server load.

03/21/22 satheesh.research18@gmail.com 19
IT8501 - Web Technology - Java Script
Java Script

Advantages of JavaScript
– JavaScript saves server traffic.
– It performs the operations very fast.
– It is simple to learn and implement.
– It is versatile.
– JavaScript pages are executed on the client side.
– JavaScript extends its functionality to the web pages.

03/21/22 satheesh.research18@gmail.com 20
IT8501 - Web Technology - Java Script
Java Script

Disadvantages of JavaScript
– JavaScript cannot be used for networking applications.
– It doesn't have any multithreading or multiprocessor
capabilities.
– It has security issues being a client-side scripting language.

03/21/22 satheesh.research18@gmail.com 21
IT8501 - Web Technology - Java Script
Java Script - Variables
JavaScript Variables
• JavaScript uses variables which can be thought of as Named
Containers.
• Variables are declared with the 'var' keyword.
Example:
var a;
var b;
• Variable names are case sensitive.
• You can declare multiple variables with the
same 'var' keyword.
03/21/22 satheesh.research18@gmail.com 22
IT8501 - Web Technology - Java Script
Java Script - Variables
JavaScript Variables Scope:
1. Global Variable
• Declaring a variable outside the function makes it a Global Variable.
• Variable is accessed everywhere in the document.
2. Local Variable
• A variable declared within a function is called as Local Variable.
• It can be accessed only within the function.

03/21/22 satheesh.research18@gmail.com 23
IT8501 - Web Technology - Java Script
Java Script – Variables
Example : Simple Program on Global Variable
<html> 
     <head> 
     <script type = "text/javascript"> 
     count = 5;     //Global variable 
     var a = 4;     //Global variable 
     function funccount()     // Function Declaration  Output:
     {  
          count+=5;     // Local variable 
          a+=4; 
Outside function Global Count: 5
          document.write("<b>Inside function Global Count: </b>"+count+"<br>");  Outside function Global A: 4
          document.write("<b>Inside function Global A: </b>"+a+"<br>");  Inside function Global Count: 10
     } 
     </script> 
Inside function Global a: 8
     </head> 
<body> 
     <script type="text/javascript"> 
          document.write("<b>Outside function Global Count: </b>"+count+"<br>"); 
          document.write("<b>Outside function Global a: </b>"+a+"<br>"); 
          funccount(); 
     </script> 
</body> 
</html>

03/21/22 satheesh.research18@gmail.com
IT8501 - Web Technology - Java Script
Java Script - Variables
Example : Simple Program on Local Variable
<html> 
     <head> 
     <script type="text/javascript"> 
     function funccount(a)     // Function with Argument 
Output:
     { 
          var count=5;     // Local variable 
          count+=2;  Inside Count: 7
          document.write("<b>Inside Count: </b>"+count+"<br>");  Inside A: 6
          a+=3; 
          document.write("<b>Inside A: </b>"+a+"<br>");  Outside Count: 0
     }  Outside A: 3
     </script> 
     </head> 
<body> 
     <script type="text/javascript"> 
          var a=3, count = 0; 
          funccount(a);  
          document.write("<b>Outside Count: </b>"+count+"<br>"); 
          document.write("<b>Outside A: </b>    "+a+"<br>"); 
     </script> 
</body> 
</html>

03/21/22 satheesh.research18@gmail.com 25
IT8501 - Web Technology - Java Script
Java Script
There are three ways of executing JavaScript on a web browser.
1.Inside <HEAD> tag
2.Within <BODY> tag
3.In an External File

03/21/22 satheesh.research18@gmail.com 26
IT8501 - Web Technology - Java Script
Java Script
Simple JavaScript Program using <HEAD> tag
<html>
     <head>
     <script type = "text/javascript">
     function abc()
     {
          document.write("CareerRide Info");
     }
     </script>
     </head> CareerRide Info
<body>
     Click the button 
     <input type=button onclick="abc()" value="Click">
</body>
</html>

03/21/22 satheesh.research18@gmail.com 27
IT8501 - Web Technology - Java Script
Java Script
Simple JavaScript Program using <BODY> tag

<html> 
     <body> 
     <script type="text/javascript"> 
          document.write("CareerRide Info"); 
     </script> 
     </body>  Output:
</html> CareerRide Info

03/21/22 satheesh.research18@gmail.com 28
IT8501 - Web Technology - Java Script
Java Script

Simple JavaScript Program using External File


<html> 
     <body> 
          <script type="text/javascript" src="abc.js"> 
          </script> 
     </body> 
</html Output:
CareerRide Info
------------------------------------------------
abc.js          //External File Name
document.write("CareerRide Info");
03/21/22 satheesh.research18@gmail.com 29
IT8501 - Web Technology - Java Script
Java Script

Rules for writing the JavaScript code


• Script should be placed inside the <script> tag.
• A semicolon at the end of each statement is optional.
• The single line comment is just two slashes (//) and multiple
line comment starts with /* and ends with */.
• Use 'document.write' for writing a string into HTML
document.
• JavaScript is case sensitive.
• You can insert special characters with backslash (\& or \$).

03/21/22 satheesh.research18@gmail.com 30
IT8501 - Web Technology - Java Script
JavaScript Objects
• JavaScript is an Object Oriented Programming (OOP) language. A
programming language can be called object-oriented if it provides four basic
capabilities to developers −
• Encapsulation − the capability to store related information, whether data or
methods, together in an object.
• Aggregation − the capability to store one object inside another object.
• Inheritance − the capability of a class to rely upon another class (or number
of classes) for some of its properties and methods.
• Polymorphism − the capability to write one function or method that works in
a variety of different ways.
• Objects are composed of attributes. If an attribute contains a function, it is
considered to be a method of the object, otherwise the attribute is considered a
property.

03/21/22 satheesh.research18@gmail.com 31
IT8501 - Web Technology - Java Script
Java Script - Object

Object Properties
• Object properties can be any of the three primitive data types,
or any of the abstract data types, such as another object.
• Object properties are usually variables that are used internally
in the object's methods, but can also be globally visible
variables that are used throughout the page.
syntax for adding a property to an object is:

objectName.objectProperty = propertyValue;
03/21/22 satheesh.research18@gmail.com 32
IT8501 - Web Technology - Java Script
Java Script - Object

Object Methods
• Methods are the functions that let the object do something or let something
be done to it. There is a small difference between a function and a method –
at a function is a standalone unit of statements and a method is attached to
an object and can be referenced by the thiskeyword.
• Methods are useful for everything from displaying the contents of the object
to the screen to performing complex mathematical operations on a group of
local properties and parameters.
• For example − Following is a simple example to show how to use
the write() method of document object to write any content on the
document.
document.write("This is test");

03/21/22 satheesh.research18@gmail.com 33
IT8501 - Web Technology - Java Script
Java Script - Object
User-Defined Objects:
• All user-defined objects and built-in objects are descendants of an object
called Object.
The new Operator:
• The new operator is used to create an instance of an object. To create an object,
the newoperator is followed by the constructor method.
• In the following example, the constructor methods are Object(), Array(), and Date().
These constructors are built-in JavaScript functions.

var employee = new Object();


var books = new Array("C++", "Perl", "Java");
var day = new Date("August 15, 1947");

03/21/22 satheesh.research18@gmail.com 34
IT8501 - Web Technology - Java Script
Java Script - Object
The Object() Constructor:
• A constructor is a function that creates and initializes an object.
JavaScript provides a special constructor function
called Object() to build the object. The return value of
the Object() constructor is assigned to a variable.
• The variable contains a reference to the new object. The
properties assigned to the object are not variables and are not
defined with the var keyword.

03/21/22 satheesh.research18@gmail.com 35
IT8501 - Web Technology - Java Script
Java Script - Object
Example : how to create an Object –Java Script:
<html>
<head>
<title>User-defined objects</title>

<script type="text/javascript"> Output:


var book = new Object(); // Create the object
book.subject = "Perl"; // Assign properties to the object Book name is : Perl
book.author = "Mohtashim"; Book author is : Mohtashim
</script>

</head>

<body>

<script type="text/javascript">
document.write("Book name is : " + book.subject + "<br>");
document.write("Book author is : " + book.author + "<br>");
</script>

</body>
</html>

03/21/22 satheesh.research18@gmail.com 36
IT8501 - Web Technology - Java Script
Java Script - Object
create an object with a User-Defined Function. Here thiskeyword is used to refer
to the object that has been passed to a function.
<html>
<head>

<title>User-defined objects</title>
Output:
<script type="text/javascript"> Book name is : Perl
function book(title, author){
this.title = title; Book author is : Mohtashim
this.author = author;
}
</script>

</head>
<body>

<script type="text/javascript">
var myBook = new book("Perl", "Mohtashim");
document.write("Book title is : " + myBook.title + "<br>");
document.write("Book author is : " + myBook.author + "<br>");
</script>

</body>
</html>

03/21/22 satheesh.research18@gmail.com 37
IT8501 - Web Technology - Java Script
Java Script - Object
Defining Methods for an Object
• The previous examples demonstrate how the constructor creates the object and assigns
properties. But we need to complete the definition of an object by assigning methods to it.
• Example - Try the following example; it shows how to add a function along with an
object.
<html>
<head>
<title>User-defined objects</title>

<script type="text/javascript"> </head>


// Define a function which will work as a method <body>
function addPrice(amount){
this.price = amount; <script type="text/javascript">
} var myBook = new book("Perl", "Mohtashim");
myBook.addPrice(100);
function book(title, author){
this.title = title; document.write("Book title is : " + myBook.title + "<br>");
this.author = author; document.write("Book author is : " + myBook.author + "<br>");
this.addPrice = addPrice; document.write("Book price is : " + myBook.price + "<br>");
// Assign that method as property.
</script>
}
</script> Output:
</body> Book name is : Perl
</html>
Book author is : Mohtashim
03/21/22 satheesh.research18@gmail.com
Book price is : 100 38
IT8501 - Web Technology - Java Script
Java Script - Object
JavaScript Native Objects
• JavaScript has several built-in or native objects. These objects are accessible
anywhere in your program and will work the same way in any browser running in
any operating system.
• Here is the list of all important JavaScript Native Objects −
– JavaScript Number Object
– JavaScript Boolean Object
– JavaScript String Object
– JavaScript Array Object
– JavaScript Date Object
– JavaScript Math Object
– JavaScript RegExp Object

03/21/22 satheesh.research18@gmail.com 39
IT8501 - Web Technology - Java Script
Java Script – Number Object
• The Number object represents numerical date, either integers
or floating-point numbers. In general, you do not need to worry
about Number objects because the browser automatically
converts number literals to instances of the number class.
var val = new Number(number);
• In the place of number, if you provide any non-number
argument, then the argument cannot be converted into a
number, it returns NaN (Not-a-Number).

03/21/22 satheesh.research18@gmail.com 40
IT8501 - Web Technology - Java Script
Java Script – Number Object
Number Properties
• MAX_VALUE : The largest possible value a number in JavaScript can have
1.7976931348623157E+308
• MIN_VALUE : The smallest possible value a number in JavaScript can have 5E-324
• NaN : Equal to a value that is not a number.
• NEGATIVE_INFINITYA : value that is less than MIN_VALUE.
• POSITIVE_INFINITYA : value that is greater than MAX_VALUE
• prototypeA : static property of the Number object. Use the prototype property to
assign new properties and methods to the Number object in the current document
• Constructor : Returns the function that created this object's instance. By default this is
the Number object.

03/21/22 satheesh.research18@gmail.com 41
IT8501 - Web Technology - Java Script
Java Script – Number Object
Number Methods
• toExponential() : Forces a number to display in exponential notation, even if the
number is in the range in which JavaScript normally uses standard notation.
• toFixed() : Formats a number with a specific number of digits to the right of the
decimal.
• toLocaleString() : Returns a string value version of the current number in a format that
may vary according to a browser's local settings.
• toPrecision() : Defines how many total digits (including digits to the left and right of
the decimal) to display of a number.
• toString() : Returns the string representation of the number's value.
• valueOf() : Returns the number's value.

03/21/22 satheesh.research18@gmail.com 42
IT8501 - Web Technology - Java Script
Java Script – Boolean Object
• The Boolean object represents two values, either "true" or "false". If value parameter is
omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an
initial value of false.
Syntax ; var val = new Boolean(value);
Boolean Properties
• Constructor : Returns a reference to the Boolean function that created the object.
• prototype : The prototype property allows you to add properties and methods to an object.
Boolean Methods
• toSource() : Returns a string containing the source of the Boolean object; you can use this
string to create an equivalent object.
• toString() : Returns a string of either "true" or "false" depending upon the value of the
object.
• valueOf() : Returns the primitive value of the Boolean object.

03/21/22 satheesh.research18@gmail.com 43
IT8501 - Web Technology - Java Script
Java Script - String Object

• The String object lets you work with a series of characters; it


wraps Javascript's string primitive data type with a number of
helper methods.
• As JavaScript automatically converts between string primitives
and String objects, you can call any of the helper methods of
the String object on a string primitive.
Syntax: var val = new String(string);

03/21/22 satheesh.research18@gmail.com 44
IT8501 - Web Technology - Java Script
Java Script – String Object
String Properties
• Constructor : Returns a reference to the String function that created the object.
• Length : Returns the length of the string.
• Prototype : The prototype property allows you to add properties and methods
to an object.
String Methods
• charAt() : Returns the character at the specified index.
• charCodeAt() : Returns a number indicating the Unicode value of the character at the
given index.
• concat() : Combines the text of two strings and returns a new string.
• indexOf() : Returns the index within the calling String object of the first occurrence of
the specified value, or -1 if not found.
• lastIndexOf() : Returns the index within the calling String object of the last occurrence
of the specified value, or -1 if not found.

03/21/22 satheesh.research18@gmail.com 45
IT8501 - Web Technology - Java Script
Java Script – String Object

String Methods
• localeCompare() : Returns a number indicating whether a reference string comes before or after or is the same
as the given string in sort order.
• match() : Used to match a regular expression against a string.
• replace() : Used to find a match between a regular expression and a string, and to replace the matched
substring with a new substring.
• search() : Executes the search for a match between a regular expression and a specified string.
• slice() : Extracts a section of a string and returns a new string.
• split() : Splits a String object into an array of strings by separating the string into substrings.
• substr() : Returns the characters in a string beginning at the specified location through the specified number of
characters.
• substring() : Returns the characters in a string between two indexes into the string.
• toLocaleLowerCase() : The characters within a string are converted to lower case while respecting the current
locale.
• toLocaleUpperCase() : The characters within a string are converted to upper case while respecting the current
locale.
• toLowerCase() : Returns the calling string value converted to lower case.
• toString() : Returns a string representing the specified object.
• toUpperCase() : Returns the calling string value converted to uppercase.
• valueOf() : Returns the primitive value of the specified object.

03/21/22 satheesh.research18@gmail.com 46
IT8501 - Web Technology - Java Script
Java Script – Array Object
• The Array object lets you store multiple values in a single variable. It stores
a fixed-size sequential collection of elements of the same type. An array is
used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.
Syntax :
var fruits = new Array( "apple", "orange", "mango" );
OR
var fruits = [ "apple", "orange", "mango" ];
OR
fruits[0] is the first element
fruits[1] is the second element
fruits[2] is the third element

03/21/22 satheesh.research18@gmail.com 47
IT8501 - Web Technology - Java Script
Java Script – Array Object
Array Properties
• Constructor : Returns a reference to the array function that created the object.
• index : The property represents the zero-based index of the match in the string
• Input : This property is only present in arrays created by regular expression matches.
• length : Reflects the number of elements in an array.
• Prototype : The prototype property allows you to add properties and methods to an object.

Array Methods
• concat() : Returns a new array comprised of this array joined with other array(s) and/or value(s).
• every() : Returns true if every element in this array satisfies the provided testing function.
• filter() : Creates a new array with all of the elements of this array for which the provided
filtering function returns true.
• forEach() : Calls a function for each element in the array.
• indexOf() : Returns the first (least) index of an element within the array equal to the specified
value, or -1 if none is found.
• join() : Joins all elements of an array into a string.

03/21/22 satheesh.research18@gmail.com 48
IT8501 - Web Technology - Java Script
Java Script – Array Object
Array Methods
• lastIndexOf() : Returns the last (greatest) index of an element within the array equal to the specified value, or
-1 if none is found.
• map() : Creates a new array with the results of calling a provided function on every element in this array.
• pop() : Removes the last element from an array and returns that element.
• push() : Adds one or more elements to the end of an array and returns the new length of the array.
• reduce() : Apply a function simultaneously against two values of the array (from left-to-right) as to reduce it
to a single value.
• reduceRight() : Apply a function simultaneously against two values of the array (from right-to-left) as to
reduce it to a single value.
• reverse() : Reverses the order of the elements of an array -- the first becomes the last, and the last becomes
the first.
• shift() : Removes the first element from an array and returns that element.
• slice() : Extracts a section of an array and returns a new array.
• some() : Returns true if at least one element in this array satisfies the provided testing function.
• toSource() : Represents the source code of an object
• sort() : Sorts the elements of an array
• splice() : Adds and/or removes elements from an array.
• toString() : Returns a string representing the array and its elements.
• unshift() : Adds one or more elements to the front of an array and returns the new length of the array.

03/21/22 satheesh.research18@gmail.com 49
IT8501 - Web Technology - Java Script
Java Script – Date Object
• The Date object is a datatype built into the JavaScript language. Date objects are created with the new
Date( ) as shown below.
• Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow
you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using
either local time or UTC (universal, or GMT) time.
• The ECMAScript standard requires the Date object to be able to represent any date and time, to millisecond
precision, within 100 million days before or after 1/1/1970. This is a range of plus or minus 273,785 years, so
JavaScript can represent date and time till the year 275755.

Syntax
new Date( )
Note − Parameters in the brackets are always optional.
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])

03/21/22 satheesh.research18@gmail.com 50
IT8501 - Web Technology - Java Script
Java Script – Date Object
Description of the parameters 
• No Argument − With no arguments, the Date() constructor creates a Date object set to the current date and
time.
• milliseconds − When one numeric argument is passed, it is taken as the internal numeric representation of
the date in milliseconds, as returned by the getTime() method. For example, passing the argument 5000
creates a date that represents five seconds past midnight on 1/1/70.
• datestring − When one string argument is passed, it is a string representation of a date, in the format
accepted by the Date.parse() method.
• 7 agruments − To use the last form of the constructor shown above. Here is a description of each argument −
– year − Integer value representing the year. For compatibility (in order to avoid the Y2K problem), you
should always specify the year in full; use 1998, rather than 98.
– month − Integer value representing the month, beginning with 0 for January to 11 for December.
– date − Integer value representing the day of the month.
– hour − Integer value representing the hour of the day (24-hour scale).
– minute − Integer value representing the minute segment of a time reading.
– second − Integer value representing the second segment of a time reading.
– millisecond − Integer value representing the millisecond segment of a time reading.

03/21/22 satheesh.research18@gmail.com 51
IT8501 - Web Technology - Java Script
Java Script – Date Object
Date Properties
• Constructor : Specifies the function that creates an object's prototype.
• prototype : The prototype property allows you to add properties and methods to an object
Date Methods
• Date() : Returns today's date and time
• getDate() : Returns the day of the month for the specified date according to local time.
• getDay() : Returns the day of the week for the specified date according to local time.
• getFullYear() : Returns the year of the specified date according to local time.
• getHours() : Returns the hour in the specified date according to local time.
• getMilliseconds() : Returns the milliseconds in the specified date according to local time.
• getMinutes() : Returns the minutes in the specified date according to local time.
• getMonth() : Returns the month in the specified date according to local time.
• getSeconds() : Returns the seconds in the specified date according to local time.
• getTime() : Returns the numeric value of the specified date as the number of milliseconds
since January 1, 1970, 00:00:00 UTC.
• getTimezoneOffset() : Returns the time-zone offset in minutes for the current locale.
• getUTCDate() : Returns the day (date) of the month in the specified date according to universal time

03/21/22 satheesh.research18@gmail.com 52
IT8501 - Web Technology - Java Script
Java Script – Math Object

• The math object provides you properties and methods for mathematical


constants and functions. Unlike other global objects, Math is not a
constructor. All the properties and methods of Math are static and can be
called by using Math as an object without creating it.
• Thus, you refer to the constant pi as Math.PI and you call the sine function
as Math.sin(x), where x is the method's argument.
Syntax
var pi_val = Math.PI;
var sine_val = Math.sin(30);

03/21/22 satheesh.research18@gmail.com 53
IT8501 - Web Technology - Java Script
Java Script – Math Object
Math Properties
• E \ : Euler's constant and the base of natural logarithms,
approximately 2.718.
• LN2 : Natural logarithm of 2, approximately 0.693.
• LN10 : Natural logarithm of 10, approximately 2.302.
• LOG2E : Base 2 logarithm of E, approximately 1.442.
• LOG10E : Base 10 logarithm of E, approximately 0.434.
• PI : Ratio of the circumference of a circle to its diameter,
approximately 3.14159.
• SQRT1_2 : Square root of 1/2; equivalently, 1 over the square
root of 2, approximately 0.707.
• SQRT2 : Square root of 2, approximately 1.414.

03/21/22 satheesh.research18@gmail.com 54
IT8501 - Web Technology - Java Script
Java Script – Math Object
Math Methods
• abs() : Returns the absolute value of a number.
• acos() : Returns the arccosine (in radians) of a number.
• asin() : Returns the arcsine (in radians) of a number.
• atan() : Returns the arctangent (in radians) of a number.
• atan2() : Returns the arctangent of the quotient of its arguments.
• ceil() : Returns the smallest integer greater than or equal to a number.
• cos() : Returns the cosine of a number.
• exp() : Returns EN, where N is the argument, and E is Euler's constant, the base of the natural logarithm.
• floor() : Returns the largest integer less than or equal to a number.
• log() : Returns the natural logarithm (base E) of a number.
• max() : Returns the largest of zero or more numbers.
• min() : Returns the smallest of zero or more numbers.
• pow() : Returns base to the exponent power, that is, base exponent.
• random() : Returns a pseudo-random number between 0 and 1.
• round() : Returns the value of a number rounded to the nearest integer.
• sin() : Returns the sine of a number.
• sqrt() : Returns the square root of a number.
• tan() : Returns the tangent of a number.
• toSource() : Returns the string "Math".

03/21/22 satheesh.research18@gmail.com 55
IT8501 - Web Technology - Java Script
Java Script – Regular Expressions and RegExp Object

• A regular expression is an object that describes a pattern of characters.

• The JavaScript RegExp class represents regular expressions, and both String


and RegExpdefine methods that use regular expressions to perform
powerful pattern-matching and search-and-replace functions on text.
Syntax
var pattern = new RegExp(pattern, attributes);
or simply
var pattern = /pattern/attributes;

03/21/22 satheesh.research18@gmail.com 56
IT8501 - Web Technology - Java Script
Java Script – Statement

03/21/22 satheesh.research18@gmail.com 57
IT8501 - Web Technology - Java Script
Java Script – Statement

03/21/22 satheesh.research18@gmail.com 58
IT8501 - Web Technology - Java Script
Java Script – Statement

03/21/22 satheesh.research18@gmail.com 59
IT8501 - Web Technology - Java Script
Java Script – Statement

03/21/22 satheesh.research18@gmail.com 60
IT8501 - Web Technology - Java Script
Java Script – Statement

03/21/22 satheesh.research18@gmail.com 61
IT8501 - Web Technology - Java Script
Java Script – EVENTS
What is an Event ?
• 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.

03/21/22 satheesh.research18@gmail.com 62
IT8501 - Web Technology - Java Script

03/21/22 satheesh.research18@gmail.com 63
IT8501 - Web Technology - Java Script
Java Script – EVENTS
onclick Event Type
<html>
<head>
<script type="text/javascript"> This is the most frequently used event type
<!--
function sayHello() { which occurs when a user clicks the left
alert("Hello World") button of his mouse. You can put your
}
//-->
validation, warning etc., against this event
</script> type.
</head>

<body>
<p>Click the following button and see result</p>

<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>

</body>
</html>

03/21/22 satheesh.research18@gmail.com 64
IT8501 - Web Technology - Java Script
Java Script – EVENTS
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.
<html>
<head>

<script type="text/javascript">
<!-- Here we are calling a validate()function
function validation() {
all validation goes here before submitting a form data to the
.........
return either true or false webserver. If validate() function returns
}
//-->
true, the form will be submitted,
</script> otherwise it will not submit the data.
</head>
<body>

<form method="POST" action="t.cgi" onsubmit="return validate()">


.......
<input type="submit" value="Submit" />
</form>

</body>
</html>

03/21/22 satheesh.research18@gmail.com 65
IT8501 - Web Technology - Java Script
Java Script – EVENTS
onmouseover and onmouseout
<html>
<head>

<script type="text/javascript">
<!--
function over() { • These two event types will help you create nice
document.write ("Mouse Over");
} effects with images or even with text as well.
function out() { • The onmouseover event triggers when you bring
}
document.write ("Mouse Out");
your mouse over any element and
the onmouseout triggers when you move your
//-->
</script> mouse out from that element.
</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>

03/21/22 satheesh.research18@gmail.com 66
IT8501 - Web Technology - Java Script
Java Script – Windows
• The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.
The Browser Object Model (BOM)
• There are no official standards for the Browser Object Model (BOM).
• Since modern browsers have implemented (almost) the same methods and
properties for JavaScript interactivity, it is often referred to, as methods and
properties of the BOM.
The Window Object
• The window object is supported by all browsers. It represents the browser's window.
• All global JavaScript objects, functions, and variables automatically become members of the window object.
• Global variables are properties of the window object.
• Global functions are methods of the window object.
• Even the document object (of the HTML DOM) is a property of the window object:
window.document.getElementById("header");
is the same as:
document.getElementById("header");

03/21/22 satheesh.research18@gmail.com 67
IT8501 - Web Technology - Java Script
Java Script – Windows
Window Size
• Two properties can be used to determine the size of the browser window.
• Both properties return the sizes in pixels:
• window.innerHeight - the inner height of the browser window (in pixels)
• window.innerWidth - the inner width of the browser window (in pixels)
Example
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

03/21/22 satheesh.research18@gmail.com 68
IT8501 - Web Technology - Java Script
Java Script – Windows
Other Window Methods
• window.open() - open a new window
• window.close() - close the current window
• window.moveTo() -move the current window
• window.resizeTo() -resize the current window

03/21/22 satheesh.research18@gmail.com 69
IT8501 - Web Technology - Java Script
Java Script – Data Type

• JavaScript includes data types similar to other programming languages like


Java or C#. Data type indicates characteristics of data. It tells the compiler
whether the data value is numeric, alphabetic, date etc., so that it can
perform the appropriate operation.
• JavaScript includes primitive and non-primitive data types 

Primitive Data Types


• String Non-primitive Data Type
• Number • Object
• Boolean • Date
• Null • Array
• Undefined

03/21/22 satheesh.research18@gmail.com 70
IT8501 - Web Technology - Java Script
Java Script – Data Type
• JavaScript is a dynamic or loosely-typed language because a
variable can hold value of any data type at any point of time.
• Example: Loosely-typed JavaScript
var myVar = 100;
myVar = true;
myVar will hold last assigned
myVar = null; value to it that is string "Steve".
myVar = undefined;
JavaScript is a dynamic type language, means
myVar = "Steve";
you don't need to specify type of the variable
because it is dynamically used by JavaScript
alert(myVar); // Steve engine. You need to use var here to specify the
data type. It can hold any type of values such as
numbers, strings etc

03/21/22 satheesh.research18@gmail.com 71
IT8501 - Web Technology - Java Script
Java Script – built-in functions

• JavaScript provides functions similar to most of the scripting and


programming languages.
• In JavaScript, a function allows you to define a block of code, give it a name
and then execute it as many times as you want.
Example: Define and Call a Function
function ShowMessage()
{
alert("Hello World!");
}
ShowMessage();

03/21/22 satheesh.research18@gmail.com 72
IT8501 - Web Technology - Java Script
Java Script – Function

Function Parameters
• A function can have one or more parameters, which will be supplied by the calling
code and can be used inside a function. JavaScript is a dynamic type scripting
language, so a function parameter can have value of any data type.
Example:
function ShowMessage(firstName, lastName) {
alert("Hello " + firstName + " " + lastName);
}

ShowMessage("Steve", "Jobs");
ShowMessage("Bill", "Gates");
ShowMessage(100, 200);

03/21/22 satheesh.research18@gmail.com 73
IT8501 - Web Technology - Java Script
Java Script – Function
The Arguments Object
• All the functions in JavaScript can use arguments object by default. An arguments
object includes value of each parameter.
• The arguments object is an array like object. You can access its values using index
similar to array. However, it does not support array methods.
Example: 
function ShowMessage(firstName, lastName) {
alert("Hello " + arguments[0] + " " + arguments[1]);
}
ShowMessage("Steve", "Jobs");
ShowMessage("Bill", "Gates");
ShowMessage(100, 200);

03/21/22 satheesh.research18@gmail.com 74
IT8501 - Web Technology - Java Script
Java Script – Function
Function Expression
• JavaScript allows us to assign a function to a variable and then
use that variable as a function. It is called function expression.
Example
var add = function sum(val1, val2) {
return val1 + val2;
};

var result1 = add(10,20);


var result2 = sum(10,20); // not valid

03/21/22 satheesh.research18@gmail.com 75
IT8501 - Web Technology - Java Script
Java Script – Function
Anonymous Function
• JavaScript allows us to define a function without any name. This unnamed function
is called anonymous function. Anonymous function must be assigned to a variable.
• Anonymous function is useful in passing callback function, creating closure or
Immediately invoked function expression.
Example:
var showMessage = function (){
alert("Hello World!");
};
showMessage();
var sayHello = function (firstName) {
alert("Hello " + firstName);
};
showMessage();
sayHello("Bill");

03/21/22 satheesh.research18@gmail.com 76
IT8501 - Web Technology - Java Script
Java Script – Function
Nested Functions
• In JavaScript, a function can have one or more inner functions. These nested
functions are in the scope of outer function. Inner function can access
variables and parameters of outer function. However, outer function cannot
access variables defined inside inner functions.
Example:
function ShowMessage(firstName)
{
function SayHello() {
alert("Hello " + firstName);
}
return SayHello();
}
ShowMessage("Steve");

03/21/22 satheesh.research18@gmail.com 77
IT8501 - Web Technology - Java Script
Java Script – Function
Points to Remember
• JavaScript a function allows you to define a block of code, give it a name and then
execute it as many times as you want.
• A function can be defined using function keyword and can be executed using ()
operator.
• A function can include one or more parameters. It is optional to specify function
parameter values while executing it.
• JavaScript is a loosely-typed language. A function parameter can hold value of any
data type.
• You can specify less or more arguments while calling function.
• All the functions can access arguments object by default instead of parameter names.
• A function can return a literal value or another function.
• A function can be assigned to a variable with different name.
• JavaScript allows you to create anonymous functions that must be assigned to a
variable.

03/21/22 satheesh.research18@gmail.com 78
IT8501 - Web Technology - Java Script
JavaScript Operators
• Arithmetic Operators
• Relational Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Special Operators

03/21/22 satheesh.research18@gmail.com 79
IT8501 - Web Technology - Java Script
Java Script
.

03/21/22 satheesh.research18@gmail.com 80
IT8501 - Web Technology - Java Script
Java Script

03/21/22 satheesh.research18@gmail.com 81
IT8501 - Web Technology - Java Script
Java Script

03/21/22 satheesh.research18@gmail.com 82
IT8501 - Web Technology - Java Script
Java Script

03/21/22 satheesh.research18@gmail.com 83
IT8501 - Web Technology - Java Script
Java Script

03/21/22 satheesh.research18@gmail.com 84
IT8501 - Web Technology - Java Script
Java Script

03/21/22 satheesh.research18@gmail.com 85
IT8501 - Web Technology - Java Script
Arithmetic operators in JavaScript.

<html> document.write("a + b + c = ");


<body> result = a + b + c;
document.write(result);
<script type="text/javascript"> document.write(linebreak);
<!--
var a = 33; a = ++a;
var b = 10; document.write("++a = ");
var c = "Test"; result = ++a;
var linebreak = "<br />"; document.write(result);
document.write(linebreak);
document.write("a + b = ");
result = a + b; b = --b;
document.write(result); document.write("--b = ");
document.write(linebreak); result = --b;
document.write(result);
document.write("a - b = "); document.write(linebreak);
result = a - b; //-->
document.write(result); </script>
document.write(linebreak);
Set the variables to different values and then try...
document.write("a / b = "); </body>
result = a / b; </html> Output
document.write(result); a + b = 43
document.write(linebreak); a - b = 23
a / b = 3.3
document.write("a % b = "); a%b=3
result = a % b; a + b + c = 43Test
document.write(result); ++a = 35
document.write(linebreak); --b = 8
Set the variables to different values and then try…

03/21/22 satheesh.research18@gmail.com 86
IT8501 - Web Technology - Java Script
Comparison operators in JavaScript.

<html>
<body> document.write("(a != b) => ");
result = (a != b);
document.write(result);
<script type="text/javascript"> document.write(linebreak);
<!--
var a = 10; document.write("(a >= b) => ");
var b = 20; result = (a >= b);
document.write(result);
var linebreak = "<br />"; document.write(linebreak);

document.write("(a == b) => "); document.write("(a <= b) => ");


result = (a == b); result = (a <= b);
document.write(result); document.write(result);
document.write(linebreak);
document.write(linebreak); //-->
</script>
document.write("(a < b) => ");
result = (a < b); Set the variables to different values and different operators and
document.write(result); then try...
</body> Output:
document.write(linebreak); </html> (a == b) => false
document.write("(a > b) => "); (a < b) => true
result = (a > b); (a > b) => false
document.write(result); (a != b) => true
document.write(linebreak); (a >= b) => false
a <= b) => true
Set the variables to different values and
03/21/22 satheesh.research18@gmail.com different operators and then try… 87
IT8501 - Web Technology - Java Script
Bitwise operator in JavaScript.
<html> document.write("(~b) => ");
<body> result = (~b);
document.write(result);
<script type="text/javascript">
<!--
document.write(linebreak);
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11 document.write("(a << b) => ");
var linebreak = "<br />"; result = (a << b);
document.write(result);
document.write("(a & b) => "); document.write(linebreak);
result = (a & b);
document.write(result);
document.write(linebreak); document.write("(a >> b) => ");
result = (a >> b);
document.write("(a | b) => "); document.write(result);
result = (a | b); document.write(linebreak);
document.write(result); //-->
document.write(linebreak); </script>
document.write("(a ^ b) => ");
result = (a ^ b); <p>Set the variables to different values and different
document.write(result); operators and then try...</p>
document.write(linebreak); </body> Output
</html> (a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 16
(a >> b) => 0
Set the variables to different values and different
operators and then try...
03/21/22 satheesh.research18@gmail.com 88
IT8501 - Web Technology - Java Script
Java Script-Verifying Forms
JavaScript Form Validation:
• It is important to validate the form submitted by the user because it can have
inappropriate values. So validation is must.
• The JavaScript provides you the facility the validate the form on the client
side so processing will be fast than server-side validation. So, most of the
web developers prefer JavaScript form validation.
• Through JavaScript, we can validate name, password, email, date, mobile
number etc fields.
JavaScript form validation example
• Next example, we are going to validate the name and password. The name
can’t be empty and password can’t be less than 6 characters long.
• Here, we are validating the form on form submit. The user will not be
forwarded to the next page until given values are correct.

03/21/22 satheesh.research18@gmail.com 89
IT8501 - Web Technology - Java Script
Java Script-Verifying Forms
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
} }
</script>
<body>
<form name="myform" method="post" action="abc.jsp" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>

03/21/22 satheesh.research18@gmail.com 90
IT8501 - Web Technology - Java Script
Java Script – Validation Forms
JavaScript Retype Password Validation
<script type="text/javascript">  
function matchpass(){  
var firstpassword=document.f1.password.value;  
var secondpassword=document.f1.password2.value;  
  
if(firstpassword==secondpassword){  
return true;  
}  
else{  
alert("password must be same!");  
return false;  
}  
}  
</script>  
  
<form name="f1" action="register.jsp" onsubmit="return matchpass()">  
Password:<input type="password" name="password" /><br/>  
Re-enter Password:<input type="password" name="password2"/><br/>  
<input type="submit">  
</form>

03/21/22 satheesh.research18@gmail.com 91
IT8501 - Web Technology - Java Script
Java Script – Form Validation
JavaScript Number Validation
<script>  
function validate(){  
var num=document.myform.num.value;  
if (isNaN(num)){  
  document.getElementById("numloc").innerHTML="Enter Numeric value only";  
  return false;  
}else{  
  return true;  
  }  
}  
</script>  
<form name="myform" onsubmit="return validate()" >  
Number: <input type="text" name="num"><span id="numloc"></span><br/>  
<input type="submit" value="submit">  
</form>  

03/21/22 satheesh.research18@gmail.com 92
IT8501 - Web Technology - Java Script
Java Script - Validation
JavaScript validation with image
<script>  
function validate(){   <form name="f1" action="#" onsubmit="return vali
var name=document.f1.name.value;  
var password=document.f1.password.value;  
date()">  
var status=false;   <table>  
   <tr><td>Enter Name:</
if(name.length<1){  
document.getElementById("nameloc").innerHTML=   td><td><input type="text" name="name"/>  
" <img src='unchecked.gif'/> Please enter your name";   <span id="nameloc"></span></td></tr>  
status=false;  
}else{  
<tr><td>Enter Password:</
document.getElementById("nameloc").innerHTML=" <img src='checked.gif'/>";   td><td><input type="password" name="password"
status=true;   />  
}  
if(password.length<6){   <span id="passwordloc"></span></td></tr>  
document.getElementById("passwordloc").innerHTML=   <tr><td colspan="2"><input type="submit" value=
" <img src='unchecked.gif'/> Password must be at least 6 char long";  
status=false;  
"register"/></td></tr>  
}else{   </table>  
document.getElementById("passwordloc").innerHTML=" <img src='checked.gif'/>";   </form>  
}  
return status;  
}  
</script>  

03/21/22 satheesh.research18@gmail.com 93
IT8501 - Web Technology - Java Script
Java Script:Form
Validation
JavaScript email validation
• There are many criteria that need to be follow to validate the
email id such as:
• email id must contain the @ and . character
• There must be at least one character before and after the @.
• There must be at least two characters after . (dot).
• Let's see the simple example to validate the email field.

03/21/22 satheesh.research18@gmail.com 94
IT8501 - Web Technology - Java Script
Java Script – Form Validation
<script>  
function validateemail()  
{  
var x=document.myform.email.value;  
var atposition=x.indexOf("@");  
var dotposition=x.lastIndexOf(".");  
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){  
  alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);  
  return false;  
  }  
}  
</script>  
<body>  
<form name="myform"  method="post" action="#" onsubmit="return validateemail();">  
Email: <input type="text" name="email"><br/>  
  
<input type="submit" value="register">  
</form>

03/21/22 satheesh.research18@gmail.com 95
Java Servlet

Servlet technology is used to create a web application (resides at


server side and generates a dynamic web page).
Why?
Servlet technology is robust and scalable because of java
language. Before Servlet, CGI (Common Gateway Interface)
scripting language was common as a server-side programming
language. However, there were many disadvantages to this
technology.
What is a Servlet?

Servlet can be described in many ways, depending on the context.


– Servlet is a technology which is used to create a web
application.
– Servlet is an API that provides many interfaces and classes
including documentation.
– Servlet is an interface that must be implemented for
creating any Servlet.
– Servlet is a class that extends the capabilities of the servers
and responds to the incoming requests. It can respond to
any requests.
– Servlet is a web component that is deployed on the server
to create a dynamic web page.
What is a web application?

• A web application is an application accessible from the web. A


web application is composed of web components like Servlet,
JSP, Filter, etc. and other elements such as HTML, CSS, and
JavaScript. The web components typically execute in Web
Server and respond to the HTTP request.
CGI (Common Gateway Interface)

• CGI technology enables the web server to call an external program and pass
HTTP request information to the external program to process the request.
For each request, it starts a new process.
CGI Vs Servlet
Advantages of Servlet
There are many advantages of Servlet over CGI.
Disadvantages of CGI
The web container creates threads for handling the
• If the number of clients multiple requests to the Servlet. Threads have
increases, it takes more time for many benefits over the Processes such as they
sending the response. share a common memory area, lightweight,
• For each request, it starts a cost of communication between the threads are
low. 
process, and the web server is
• Better performance: because it
limited to start processes. creates a thread for each request, not
• It uses platform dependent process.
language e.g. C, C++, perl. • Portability: because it uses Java
language.
• Robust: JVM manages Servlets, so we
don't need to worry about the memory
leak, garbage collection, etc.
• Secure: because it uses java language.
CGI Vs Servlet

CGI

Servlet
Servlet Terminology

Website: static vs dynamic:


It is a collection of related web pages that may contain text, images, audio and
video.
HTTP : It is the data communication protocol used to establish communication
between client and server.
HTTP Requests:
It is the request send by the computer to a web server that contains all sorts
of potentially interesting information.
Get vs Post:
It gives the difference between GET and POST request.
Container : It is used in java for dynamically generating the web pages on the
server side.
Server: Web vs Application : It is used to manage the network resources and
for running the program or software that provides services.
Content Type: It is HTTP header that provides the description about what are
you sending to the browser.
Static vs Dynamic website
HTTP (Hyper Text Transfer Protocol)

HTTP (Hyper Text Transfer Protocol)


• The Hypertext Transfer Protocol (HTTP) is application-level
protocol for collaborative, distributed, hypermedia information
systems. It is the data communication protocol used to establish
communication between client and server.

• HTTP is TCP/IP based communication protocol, which is used


to deliver the data like image files, query results, HTML files
etc on the World Wide Web (WWW) with the default port is
TCP 80. It provides the standardized way for computers to
communicate with each other.
The Basic Characteristics of HTTP (Hyper Text Transfer Protocol):
• It is the protocol that allows web servers and browsers to exchange data over the
web.
• It is a request response protocol.
• It uses the reliable TCP connections by default on TCP port 80.
• It is stateless means each request is considered as the new request. In other words,
server doesn't recognize the user by default.
The Basic Features of HTTP 

There are three fundamental features that make the HTTP a simple and
powerful protocol used for communication:
• HTTP is media independent: It specifies that any type of media
content can be sent by HTTP as long as both the server and the client
can handle the data content.
• HTTP is connectionless: It is a connectionless approach in which
HTTP client i.e., a browser initiates the HTTP request and after the
request is sent the client disconnects from server and waits for the
response.
• HTTP is stateless: The client and server are aware of each other
during a current request only. Afterwards, both of them forget each
other. Due to the stateless nature of protocol, neither the client nor
the server can retain the information about different request across
the web pages.
The Basic Architecture of HTTP

HTTP is request/response protocol


which is based on client/server based
architecture. In this protocol, web
browser, search engines, etc. behave
as HTTP clients and the Web server
like Servlet behaves as a server
HTTP Requests

The request sent by the computer to a web server, contains all sorts of potentially
interesting information; it is known as HTTP requests.
The HTTP client sends the request to the server in the form of request message which
includes following information:

• The Request-line
• The analysis of source IP address, proxy and port
• The analysis of destination IP address, protocol, port and host
• The Requested URI (Uniform Resource Identifier)
• The Request method and Content
• The User-Agent header
• The Connection control header
• The Cache control header

The HTTP request method indicates the method to be performed on the resource identified
by theRequested URI (Uniform Resource Identifier). This method is case-sensitive and
should be used in uppercase.
 HTTP request methods are
Get vs. Post
Servlet Container

• It provides the runtime environment for JavaEE (j2ee)


applications. The client/user can request only a static
WebPages from the server. If the user wants to read the web
pages as per input then the servlet container is used in java.
Servlet Container

The servlet container is the part of web server which can be run in a separate process. We
can classify the servlet container states in three types:

Servlet Container States


The servlet container is the part of web server which can be run in a separate process. We can
classify the servlet container states in three types:
Standalone: It is typical Java-based servers in which the servlet container and the web servers
are the integral part of a single program. For example:- Tomcat running by itself
In-process: It is separated from the web server, because a different program runs within the
address space of the main server as a plug-in. For example:- Tomcat running inside the JBoss.
Out-of-process: The web server and servlet container are different programs which are run in a
different process. For performing the communications between them, web server uses the plug-
in provided by the servlet container.
The Servlet Container performs many
operations that are given below:
• Life Cycle Management
• Multithreaded support
• Object Pooling
• Security etc.
Life Cycle of a Servlet
1) Servlet class is loaded

The classloader is responsible to load the servlet class. The


servlet class is loaded when the first request for the servlet is
received by the web container.
2) Servlet instance is created

The web container creates the instance of a servlet after loading


the servlet class. The servlet instance is created only once in
the servlet life cycle.
3) init method is invoked

The web container calls the init method only once after
creating the servlet instance. The init method is used to
initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init
method is given below:
public void init(ServletConfig config) throws ServletExc
eption  
4) service method is invoked

The web container calls the service method each time when
request for the servlet is received. If servlet is not initialized, it
follows the first three steps as described above then calls the
service method. If servlet is initialized, it calls the service
method. Notice that servlet is initialized only once. The syntax
of the service method of the Servlet interface is given below:

public void service(ServletRequest request, ServletResponse res
ponse)     throws ServletException, IOException  
5) destroy method is invoked

The web container calls the destroy method before removing the
servlet instance from the service. It gives the servlet an
opportunity to clean up any resource for example memory,
thread etc. The syntax of the destroy method of the Servlet
interface is given below:
public void destroy()  
Steps to create a servlet example

The servlet example can be created by three ways:


1.By implementing Servlet interface,
2.By inheriting GenericServlet class, (or)
3.By inheriting HttpServlet class
Steps to create the servlet using Tomcat server

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet
1)Create a directory structures

The directory structure defines that where to put the different types of files


so that web container may get the Information and respond to the client.
2)Create a Servlet – Repeat

There are three ways to create the servlet.


1.By implementing the Servlet interface
2.By inheriting the GenericServlet class
3.By inheriting the HttpServlet class
 HttpServlet class
• The HttpServlet class is widely used to create the servlet because it provides
methods to handle http requests such as doGet(), doPost, doHead() etc.
import javax.servlet.http.*;  
import javax.servlet.*;  
import java.io.*;  
public class DemoServlet extends HttpServlet
{  
public void doGet(HttpServletRequest req,HttpServletResponse res)  
throws ServletException,IOException  
{  
res.setContentType("text/html");//setting the content type  
PrintWriter pw=res.getWriter();//get the stream to write the data  
  
//writing html in the stream  
pw.println("<html><body>");  
pw.println("Welcome to servlet");  
pw.println("</body></html>");  
  
pw.close();//closing the stream  
}} 
3)Compile the servlet

For compiling the Servlet, jar file is required to be loaded.


Different Servers provide different jar files:
4)Create the deployment descriptor (web.xml
file)
• The deployment descriptor is an xml file, from which Web
Container gets the information about the servet to be invoked.
• The web container uses the Parser to get the information from
the web.xml file. There are many xml parsers such as SAX,
DOM and Pull.
• There are many elements in the web.xml file. Here is given
some necessary elements to run the simple servlet program.
web.xml file
<web-app>   //  represents the whole application
  
<servlet>  // is sub element of <web-app> and represents the servlet.
<servlet-name>sonoojaiswal</servlet-name>  //is sub element of <servlet>
represents the name of the servlet.
<servlet-class>DemoServlet</servlet-class>  //  is sub element of <servlet>
represents the class of the servlet.
</servlet>  
  
<servlet-mapping>   // is sub element of <web-app>. It is used to map the servlet.
<servlet-name>sonoojaiswal</servlet-name>  
<url-pattern>/welcome</url-pattern>   // is sub element of <servlet-mapping>.
This pattern is used at client side to invoke the servlet
</servlet-mapping>  
  
</web-app> 
5)Start the Server and deploy the project

To start Apache Tomcat server, double click on the startup.bat


file under apache-tomcat/bin directory.
War File

A war (web archive) File contains files of a web project. It may


have servlet, xml, jsp, image, html, css, js etc. files.
What is war file?
web archive (war) file contains all the contents of a web
application. It reduces the time duration for transferring file.
Advantage of war file
saves time: The war file combines all the files into a single unit.
So it takes less time while transferring file from client to server.
Unit 5

• XML
– XSL
– XSLT
• Web Services
– WSDL
– UDDI
– Java Web Services

Note : Refer Book & Study Materials


• CSS
• JDBC Driver Types
• RMI
• JSP – Sessions & Cookies

03/21/22 satheesh.research18@gmail.com 132


Repeated University Questions

Unit 1 Unit 3
1. JS Objects with example 1.JDBC with example program
2.RMI Architecture with example program
2. JS form Validation with example
3.Implement Java Beans with example program
3. CSS & its Types with example 4.TCP vs UDP with example program
4. Client & Server Side Scripting with example
5. JS Program – Ref : Lab Record
6. Web Page Creation – online Library, Online Purchase / supermarket

Unit 2 Unit 4
1. Inheritance Types with example program 1.Applet Life cycle and Applet programs Ref : Lab Record
(Calculator, Images, sound, parameter passing, JDBC)
2. Exception Handling with example program
2.Servlet Life cycle, & Http Request, Http Response
3. Package with example program 3.Servlet Session Tracking and Cookies example program
4. Array with example program 4.Java Layouts and its types with suitable program
5. Mutithread with example program 5.JSP Vs Servlet

Unit 5
1.XML Document Development – Ex Cricket Player details, CD catalog
2.Explain UDDI, WSDL & SOAP (Case study – Railway Reservation, Calculator, discovery
and analysis webservices current trents
3.XSL, XSLT and XML Name Space with example
4.Creation Java Webservices

03/21/22 satheesh.research18@gmail.com 133


University Question

1. April / May 2018


2. NOV / DEC 2017
3. NOV / DEC 2016
4. April/May 2017
5. NOV / DEC 2015
6. May / June 2016

03/21/22 satheesh.research18@gmail.com 134


03/21/22 satheesh.research18@gmail.com 135
03/21/22 satheesh.research18@gmail.com 136
03/21/22 satheesh.research18@gmail.com 137
03/21/22 satheesh.research18@gmail.com 138
03/21/22 satheesh.research18@gmail.com 139
03/21/22 satheesh.research18@gmail.com 140
03/21/22 satheesh.research18@gmail.com 141
03/21/22 satheesh.research18@gmail.com 142
03/21/22 satheesh.research18@gmail.com 143
03/21/22 satheesh.research18@gmail.com 144
03/21/22 satheesh.research18@gmail.com 145
03/21/22 satheesh.research18@gmail.com 146
03/21/22 satheesh.research18@gmail.com 147

You might also like