Unit 2-1

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 129

UNIT – 2

VI
SEMESTE
R ETCS-
308
Learning Objective
⚫ Introduction to Java Script.
⚫ Basic Syntax of Java Script.

02/23/2024
⚫ Discuss the concept of Variables and Data
Types Used.
⚫ Understand the concept of Literals.
⚫ Discuss the concept of functions of Java Script.
⚫ Objects and Arrays in Java Script
⚫ What are the Built in objects Used.
⚫ Discuss the concept of Java Script Form
Programming.
⚫ Modifying Element Style.
Learning Objective
⚫ Discuss the concept of Document Trees.
⚫ Java Servlets in Server side Programming.

02/23/2024
⚫ Architecture of Servlets.
⚫ Life Cycle of Servlets.
⚫ Understand the concept of Cookies and Sessions.
⚫ Servlets Capabilities.
⚫ Introduction to JSP.
⚫ Discuss the concept of JSP life Cycle and
Custom Tags.
What is JavaScript
JavaScript is a dynamic computer programming language.

02/23/2024
It is lightweight and most commonly used as a part of web pages, whose implementations
allow client-side script to interact with the user and make dynamic pages.
It is an interpreted programming language with object-oriented capabilities.

JavaScript was first known as Live Script, but Netscape changed its name to JavaScript,
possibly because of the excitement being generated by Java.

JavaScript made its first appearance in Netscape 2.0 in 1995 with the name Live Script.
The general-purpose core of the language has been embedded in Netscape, Internet Explorer,
and other web browsers.
Client-Side JavaScript
1. Client-side JavaScript is the most common form of the language.

2.The script should be included in or referenced by an HTML document for the code to be
interpreted by the browser.

02/23/2024
3.It means that a web page need not be a static HTML, but can include programs that
interact with the user, control the browser, and dynamically create HTML content

4.The JavaScript client-side mechanism provides many advantages over traditional CGI
server-side scripts. For example, you might use JavaScript to check if the user has entered a
valid e-mail address in a form field.

5.The JavaScript code is executed when the user submits the form, and only if all the
entries are valid, they would be submitted to the Web Server.

6. JavaScript can be used to trap user-initiated events such as button clicks, link
navigation, and other actions that the user initiates explicitly or implicitly.
Advantages of JavaScript
The merits of using JavaScript are −
•Less server interaction − You can validate user input
before sending the page off

02/23/2024
to the server. This saves server traffic, which means less load
on your server.
•Immediate feedback to the visitors − They don't have to wait for a page reload to see
if they have forgotten to enter something.
•Increased interactivity − You can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
•Richer interfaces − You can use JavaScript to include such items as drag-and-
drop components and sliders to give a Rich Interface to your site visitors.
Limitations of JavaScript
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features −

02/23/2024
•Client-side JavaScript does not allow the reading or writing of files. This has been kept
for security reason.

•JavaScript cannot be used for networking applications because there is no such support
available.

•JavaScript doesn't have any multi-threading or multiprocessor capabilities.

Once again, JavaScript is a lightweight, interpreted programming language that allows


you to build interactivity into otherwise static HTML pages.
BASIC SYNTAX

JavaScript can be implemented using JavaScript statements that are placed within the

02/23/2024
<script>... </script> HTML tags in a web page.

You can place the <script> tags, containing your JavaScript, anywhere within your web page,
but it is normally recommended that you should keep it within the <head> tags.

The <script> tag alerts the browser program to start interpreting all the text between
these tags as a script. A simple syntax of your JavaScript will appear as follows.

<script ...>
JavaScript code
</script>
The script tag takes two important attributes −

•Language − This attribute specifies what scripting language you are using. Typically, its

02/23/2024
value will be javascript. Although recent versions of HTML (and XHTML, its successor)
have phased out the use of this attribute.

•Type − This attribute is what is now recommended to indicate the scripting language in use
and its value should be set to "text/javascript".
So your JavaScript segment will look like −

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


JavaScript code
</script>
Your First JavaScript Code
Let us take a sample example to print out "Hello World".
We added an optional HTML comment that surrounds our JavaScript code.

02/23/2024
This is to save our code from a browser that does not support JavaScript. The comment ends
with a "//-->". Here "//" signifies a comment in JavaScript, so we add that to prevent a
browser from reading the end of the HTML comment as a piece of JavaScript code.

Next, we call a function document.write which writes a string into our


document. HTML
This function can be used to write text, HTML, or both.Take a look at the
following code.
<html>

02/23/2024
<body>
<script language = "javascript" type = "text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

This
code
will
produce
the
followin
g result

Whitespace and Line Breaks
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.You can use spaces,
tabs, and newlines freely in your program and you are free to format and indent your programs
in a neat and consistent way that makes the code easy to read and understand.

02/23/2024
Semicolons are Optional
Simple statements in JavaScript are generally followed by a semicolon character, just as they are
in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if each of your
statements are placed on a separate line. For example, the following code could be written
without semicolons.

<script language = "javascript" type =


"text/javascript">
<!--
var1 = 10
var2 = 20
//-->
</script>
VARIALBLES AND DATATYPES IN JAVA SCRIPT
Datatypes in JavaScript
There are majorly two types of languages. First, one is Statically typed

02/23/2024
language where each variable and expression type is already known at compile time.

Once a variable is declared to be of a certain data type, it cannot hold values of other data
types. Example: C, C++, Java.

// Java(Statically typed)
int x = 5 // variable x is of type int and it will not store any
other type. string y = 'abc' // type string and will only accept
string values

Other, Dynamically typed languages: These languages can


receive different data types over time.
For example- Ruby, Python, JavaScript etc.
// Javascript(Dynamically
typed) var x = 5; // can
store an integer
var name = 'string'; // can
also store a string.

02/23/2024
The latest ECMAScript(ES6) standard defines seven data

types: Out of which six data types are Primitive(predefined).


Numbers: 5, 6.5, 7 etc.
String: “Hello GeeksforGeeks” etc.
Boolean: Represent a logical entity and can have two values: true
or false.
Null:This type has only one value : null.
Undefined: A variable that has not been assigned a value is
undefined.
Object: It is the most important data-type and forms the building blocks for modern
JavaScript.We will learn about these data types in details in further articles.
VARIABLES IN JAVA SCRIPT
Variables in JavaScript are containers which hold reusable data. It is
the basic unit of storage in a program.
•The value stored in a variable can be changed during program

02/23/2024
execution.
•A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
•In JavaScript, all the variables must be declared before they can be used.

•Before ES2015, JavaScript variables were solely declared using the var keyword
followed by the name of the variable and semi-colon. Below is the syntax to create
variables in JavaScript:

var var_name;
var x;
The var_name is the name of the variable which should be defined by the user and should
be unique.

These type of names are also known as identifiers.

02/23/2024
The rules for creating an identifier in JavaScript are, the name of the identifier should not be
any pre-defined word(known as keywords).

Notice in the code sample, we didn’t assign any values to the variables.We are only saying
they exist. If
you were to look at the value of each variable in the code sample, it would be undefined.
We can initialize the variables either at the time of declaration or also later when we want to
use them. Below are some examples of declaring and initializing variables in JavaScript:

// declaring single
variable var name;

02/23/2024
// declaring multiple
variables
var name, title, num;

// initializing
variables
var name =
"Harsh"; name
= "Rakesh";
JAVASCRIPT OBJECT LITERALS
A JavaScript object literal is a comma-separated list of name-value pairs
wrapped in curly braces.

02/23/2024
Object literals encapsulate data, enclosing it in a tidy package. This
minimizes the use of global variables which can cause problems when
combining code.

The following demonstrates an example object literal:

var myObject = {
sProp: 'some string value',
numProp: 2,
bProp: false
};
Object literal property values can be of any data type, including array
literals, functions, and nested object literals.
Here is another object literal example with these property types:

02/23/2024
var Swapper = {
// an array literal
images: ["smile.gif", "grim.gif", "frown.gif",
"bomb.gif"], pos: { // nested object literal
x: 40,
y: 300
},
onSwap: function() { // function
// code here
}
};
Object Literal Syntax
Object literals are defined using the following syntax rules:

1. A colon separates property name[1] from value.


2.A comma separates each name-value pair from the next.

02/23/2024
3.There should be no comma after the last name-value pair.

If any of the syntax rules are broken, such as a missing comma or colon or curly brace, a
JavaScript error will be triggered.

Browser error messages are helpful in pointing out the general location of object literal
syntax errors, but they will not necessarily be completely accurate in pointing out the
nature of the error.
Why and How We Use Object Literals

Several JavaScripts from dyn-web use object literals for setup purposes.

Object literals enable us to write code that supports lots of features yet

02/23/2024
still provide a relatively straightforward process for implementers of our
code.
No need to invoke constructors directly or maintain the correct order of
arguments passed to functions. Object literals are also useful for
unobtrusive event handling; they can hold the data that would otherwise
be passed in function calls from HTML event handler attributes.

There is one drawback: if you are unfamiliar with the syntax, it can be
very easy to introduce errors which cause the code to stop working.
A JavaScript function is a block of code designed to
perform a particular task.

FUNCTIONS IN

02/23/2024
JAVASCRIPT
⚫ A JavaScript function is executed when "something"
invokes it (calls it)

⚫ Example
⚫ function myFunction(p1, p2) {
return p1 * p2; // The function returns the
product of p1 and p2
}
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which


performs a calculation, and returns the
result:</p>

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

<script>
function myFunction(p1,
p2) { return p1 * p2;
}
document.getElementById("demo").innerHTML =
myFunction(4, 3);
</script>

</
body>
</html>
⚫ JavaScript Functions
⚫ This example calls a function which performs a
calculation, and returns the result:

02/23/2024
⚫ 12
JavaScript Function
Syntax

A JavaScript function is defined with the function keyword, followed by a name,

02/23/2024
followed by
parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: { }


⚫ function name(parameter1, parameter2,
parameter3) {
// code to be executed

02/23/2024
}

⚫ Function parameters are listed inside the


parentheses () in the function
definition.
⚫ Function arguments are the values received by the function
when it is invoked.
⚫ Inside the function, the arguments (the parameters) behave as
local variables.
⚫ A Function is much the same as a Procedure or a
Subroutine, in other
programming languages.
Function Invocation

⚫ The code inside the function will execute

02/23/2024
when "something" invokes (calls) the
function:

• When an event occurs (when a user clicks a


button)

• When it is invoked (called) from JavaScript


code
• Automatically (self invoked)
Function Return

⚫ When JavaScript reaches a return statement, the

02/23/2024
function will stop executing.

⚫ If the function was invoked from a statement,


JavaScript will "return" to execute the code after the
invoking statement.

⚫ Functions often compute a return value. The return


value is "returned" back to the "caller":
Why we use
Functions?

02/23/2024
⚫ You can reuse code: Define the code once, and use
it many times.

⚫ You can use the same code many times with


different arguments, to produce different
results
Local
Variables
⚫ Variables declared within a JavaScript function,

02/23/2024
become LOCAL to the function.

⚫ Local variables can only be accessed from within


the function.
⚫ Example
⚫ // code here can NOT use carName

02/23/2024
function myFunction() {
var carName = "Volvo";
// code here CAN use
carName
}

// code here can NOT use


carName
EXAMPLE
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

02/23/2024
<p>Outside myFunction() carName is
undefined.</p>

<p id="demo1"></p>

<p id="demo2"></p>

<script>
myFunction();
function myFunction()
{ var carName =
"Volvo";
document.getElementBy
Id("demo1").innerHTM
L=
typeof carName + "
" + carName;
}

document.getElementBy
Id("demo2").innerHTML
=
typeof carName;
</script>

</body>
JavaScript Functions(OUTPUT)

02/23/2024
⚫ Outside myFunction() carName is undefined.

⚫ string Volvo

⚫ undefined
⚫ Since local variables are only recognized inside
their functions, variables with the same name can

02/23/2024
be used in different functions.

⚫ Local variables are created when a function


starts, and deleted when the function is
completed.
OBJECTS IN JAVASCRIPT

02/23/2024
PRIMITIVES
⚫ A primitive value is a value that has no properties or methods.

⚫ A primitive data type is data that has a primitive value.

02/23/2024
⚫ 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.
02/23/2024
Objects are variables
⚫ JavaScript variables can contain single values:
⚫ Example

02/23/2024
⚫ var person = "John Doe";
OUTPUT
⚫ JavaScript Variables
⚫ John Doe

02/23/2024
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).
ARRAYS IN
JAVASCIPT
⚫ JavaScript arrays are used to store multiple values in

02/23/2024
a single variable.
⚫ Example
⚫ var cars = ["Saab", "Volvo", "BMW"];

⚫ What is an Array?
⚫ An array is a special variable, which can hold more than one value at
a time.
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript

02/23/2024
Arrays</h2>

<p id="demo"></p>
JavaScript Arrays
<script> Saab,Volvo,BMW
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML =
cars;
</script>
</
body>
</html>
If you have a list of items (a list of car names, for example), storing the cars in

:
single variables could look like this

var car1 = "Saab";


var car2 = "Volvo";

02/23/2024
var car3 = "BMW";

However, what if you want to loop through the cars and find a
specific one? And what if you had not 3 cars, but 300?
The solution is an array!
An array can hold many values under a single name, and you
can
access the values by referring to an index number.
⚫ Creating an ⚫ var cars =
Array ["Saab", "Volvo",
⚫ Using an array literal "BMW"]
is the easiest way to ;
create a JavaScript
Array.
⚫ Syntax:
⚫ var array_name
= [item1,
Exampl...];
⚫ item2,
e
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript

02/23/2024
Arrays</h2>

<p id="demo"></p>
JavaScript Arrays
<script> Saab,Volvo,BMW
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML =
cars;
</script>
</
body>
</html>
Using the JavaScript Keyword new

02/23/2024
The following example also creates an Array, and assigns values to it:
Example
var cars = new Array("Saab", "Volvo", "BMW");
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript

02/23/2024
Arrays</h2>

<p id="demo"></p>
JavaScript Arrays
<script> Saab,Volvo,BMW
var cars = new Array("Saab", "Volvo", "BMW");
document.getElementById("demo").innerHTML =
cars;
</script>
</
body>
</html>
The two examples do exactly the same.There is no need to use new Array().

For simplicity, readability and execution speed, use the first one (the array literal method) .

02/23/2024
Access the Elements of an
Array
You access an array element by referring to the index
number. This statement accesses the value of the first
element in cars:
var name =
cars[0];

02/23/2024
Example
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML =cars[0];
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

<p>JavaScript array elements are accessed using


numeric indexes (starting from 0).</p>

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

<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML =
cars[0];
</script>

</body>
</html>
⚫ JavaScript Arrays
⚫ JavaScript array elements are accessed using numeric

02/23/2024
indexes (starting from 0).
⚫ Saab

⚫ Note: Array indexes start with 0.


⚫ [0] is the first element. [1] is the second element.
Arrays are
Objects
Arrays are a special type of objects.The typeof operator in JavaScript returns "object"
for arrays.

02/23/2024
But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its "elements". In this example, person[0] returns John:

Array:
var person = ["John", "Doe", 46];
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Arrays</h2>

02/23/2024
<p>Arrays use numbers to access its
elements.</p>
<p JavaScript Arrays
id="demo"></p> Arrays use numbers to access its elements.
<script> John
var person = ["John", "Doe",
document.getElementById("demo").innerHTML
46]; =
person[0];
</script>

</body>
</html>
Objects use names to access its "members". In this
example,
person.firstName returns John:

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


age:46};
<!DOCTYPE html>
<html> JavaScript Objects
JavaScript uses names to access object properties.
<body> John

<h2>JavaScript Objects</h2>
<p>JavaScript uses names to access object properties.</p>

02/23/2024
<p id="demo"></p>

<script>
var person = { firstName:"John", lastName:"Doe", age:46};
document.getElementById("demo").innerHTML =
person["firstName"];
</script>

</body>
</html>
JAVASCRIPT FORM
VALIDATION
1.It is important to validate the form submitted by the user because it can have

02/23/2024
inappropriate values. So, validation is must to authenticate user.

2.JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation. Most of the web developers prefer JavaScript form validation.

3. Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.
JavaScript Form Validation Example

In this example, we are going to validate the name and password. The
name can’t be empty and password can’t be less than 6 characters long.

Here, we are validating the form on form submit. The user will not be
forwarded to the next page until given values are correct.
function
<script validateform(){
var
>

name=document.myform.name.value ;
var password=document.myform.password.value;

if (name==null | |
name==""){ alert("Name

02/23/2024
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/>
<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

02/23/2024
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="http
://www.javatpoint.com/javascriptpages/valid.jsp"
onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password"
</
name="password">
02/23/2024
Name:

Passwor
d:
register
JAVA SCRIPT EVENTS
1. HTML events are "things" that happen to HTML elements.

02/23/2024
When JavaScript is used in HTML pages, JavaScript can "react" on these events.

HTML Events
An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:

An HTML web page has finished loading


An HTML input field was changed
An HTML button was clicked
Often, when events happen, you may want to do
something. JavaScript lets you execute code when
events are detected.
HTML allows event handler attributes, with JavaScript code, to be

02/23/2024
added to HTML elements.
⚫ With single quotes:
<element event='some JavaScript'>
⚫ With double quotes:
<element event="some JavaScript">
Example
<button onclick="document.getElementById('demo').innerHTML
= Date()">The time is?</button>
<!DOCTYPE html>
<html>
<body>

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

02/23/2024
time is?</button>

<p Sun Feb 09 2020 13:43:57 GMT+0530 (India Standard


id="demo"></p> Time)
</
body> ThTehettiim
</html>
meeis is?
In this example , the JavaScript code changes the content of the element with
id="demo".

In the next example, the code changes the content of its own element (using

02/23/2024
this.innerHTML): Example
<button onclick="this.innerHTML = Date()">The time is?</button>

<!DOCTYPE html>
<html>
<body>

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


</
body> The Ttihmeetiims e
</html> is
JavaScript code is often several lines long. It is more common to see event attributes calling
functions:

Example

02/23/2024
<button onclick="displayDate()">The time is?</button>
<!DOCTYPE html>
<html>
<body>

<p>Click the button to display the date.</p>

<button onclick="displayDate()">The time is?</button> Click the button to display the


date.
<script> The time is?
function displayDate()
{ document.getElementById("demo").innerHTML =
Date();
}
</script>
Common HTML Events
Here is a list of some common
HTML
EVENT events: DESCRIPTION

02/23/2024
onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an


HTML element
onmouseout The user moves the mouse away
from an HTML element
onkeydown The user pushes a keyboard key

onload The browser has finished loading the page


How to change style attribute of an element dynamically
using JavaScript

02/23/2024
Given an HTML document and the task is to change the style properties (CSS
Properties) of an element dynamically with the help of JavaScript.
Approach:
•Select the element whose style properties needs to be change.

•Use element.style property to set the style attribute of an element.

•Set the properties either by using bracket notation or dash notation.


<!DOCTYPE HTML>
<html>

<head>
<title>
How to change style attribute of an
element dynamically using
JavaScript ?
</title>
</head>

02/23/2024
<body style = "text-align:center;" id
= "body">

<h1 id = "h1" style =


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

<p id = "GFG_UP" style =


"font-size: 15px; font-weight:
bold;">
</p>

<button onclick =
"gfg_Run()"> Click here
</button>

<p id = "GFG_DOWN" style


=
"font-size: 23px; font-weight:
bold; color: green; ">
</p>
< button onclick =
Click here
"gfg_Run()">
</button>

<p id = "GFG_DOWN" style =


"font-size: 23px; font-weight: bold; color: green; ">
</p>

<script>

02/23/2024
var el_up =
document.getElementById("GFG_UP"); var
el_down =
document.getElementById("GFG_DOWN");
var heading =
document.getElementById("h1");
el_up.innerHTML = "Click on the button to "
+ "change the style attribute";

function gfg_Run() {
heading.style["background-color"] =
"green"; heading.style["color"] =
"white"; el_down.innerHTML = "Style
Attribute
Changed";
}
</script>
</body>
02/23/2024
Example 2: This example changing the color, background-color and width property

of elements
<!DOCTYPE
<html>
HTML> .
<head>

02/23/2024
<title>
How to change style attribute of an element
dynamically using JavaScript ?
</title>
</head>

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

<p id = "GFG_UP" style =


"font-size: 15px; font-weight:
bold;">
</p>

<button onclick = "gfg_Run()">


Click here
</button>

<p id = "GFG_DOWN" style =


</p>
"font-size: 23px; font-weight:
bold; color: green; ">
< button onclick =
Click here
"gfg_Run()">
</button>

<p id = "GFG_DOWN" style =


"font-size: 23px; font-weight: bold; color: green; ">
</p>

<script>
var el_up = document.getElementById("GFG_UP");
var el_down =

02/23/2024
document.getElementById("GFG_DOWN"); var heading
= document.getElementById("h1"); el_up.innerHTML
= "Click on the button to "
+ "change the style attribute";

function gfg_Run() {
heading.style["color"] = "white";
heading.style["background-color"] =
"green"; heading.style["width"] = "300px";
heading.style["border"] = "1px solid
black";

el_up.style["background-color"] =
"green"; el_up.style["width"] =
"400px"; el_up.style["border"] =
"1px solid black";

el_down.innerHTML = "Style
Attribute Changed";
}
</script>
</center>
</body>

</html>
02/23/2024
DOM
TREE
1.The backbone of an HTML document is tags.
2.According to the Document Object Model (DOM), every HTML tag is an object.

02/23/2024
Nested tags are “children” of the enclosing one.The text inside a tag is an object
as well.
3.All these objects are accessible using JavaScript, and we can use them to modify
the page.

For example, document.body is the object representing the

<body> tag. Running this code will make the <body> red

for 3 seconds:
1.document.body.style.background = 'red'; // make the background red 2.
3.setTimeout(() => document.body.style.background = '', 3000); // return
back

02/23/2024
Here we used style. Background to change the background color of document.body, but there
are many
other properties, such as:

innerHTML – HTML contents of the


node. offsetWidth – the node width
(in pixels)
…and so on.
Soon we’ll learn more ways to
manipulate the DOM, but first we need
to know about its structure.
An example of the DOM

Let’s start with the following simple document:

1.<!DOCTYPE HTML>

02/23/2024
2.<html>
3.<head>
4.<title>About elk</title>
5.</head>
6.<body>
7.The truth about elk.
8.</body>
9.</html>
You can click on element nodes and their children will open/collapse.

Every tree node is an object.

Tags are element nodes (or just elements) and form the tree structure: <html> is at the
root, then
<head> and <body> are its children, etc.

The text inside elements forms text nodes, labelled as #text. A text node contains only
a string. It may not have children and is always a leaf of the tree.

For instance, the <title> tag has the text

"About elk". Please note the special characters

in text nodes:
a newline: ↵ (in JavaScript
known as \n) a space: ␣
spaces and newlines are totally valid characters, like letters and digits.They form text nodes and become a part of the DOM. So, for
instance, in the example above the <head> tag contains some spaces before
<title>, and that text becomes a #text node (it contains a newline and some spaces only).

02/23/2024
There are only two top-level exclusions:

1. Spaces and newlines before <head> are ignored for historical reasons.

2.If we put something after </body>, then that is automatically moved inside the body, at
the end, as the HTML spec requires that all content must be inside <body>. So there can’t
be any spaces after
</body>.
In other cases everything’s straightforward – if there are spaces (just like any character) in the document, then they become text
nodes in the DOM, and if we remove them, then there won’t be any.

Here are no space-only text nodes:

02/23/2024
<!DOCTYPE HTML>
<html><head><title>About elk</title></head><body>The truth about
elk.</body></html>
INTRODUCTION TO JAVA
SERVLETS
1. Today we all are aware of the need of creating dynamic web pages i.e. the ones which
have the capability to change the site contents according to the time or are able to

02/23/2024
generate the contents according to the request received by the client.

2. If you like coding in Java, then you will be happy to know that using Java there also
exists a way to generate dynamic web pages and that way is Java Servlet.

3.Servlets are the Java programs that runs on the Java-enabled web server or application
server. They are used to handle the request obtained from the web server, process the request,
produce the response, then send response back to the web server.
WHAT IS A DYNAMICWEB PAGE?
A dynamic web page is a web page that displays different content each time it's viewed. For example, the page may
change with the time of day, the user that accesses the webpage, or the type of user interaction. There are two

types of dynamic web pages .

02/23/2024
CLIENT-SIDE SCRIPTING
Web pages that change in response to an action within that web page, such as a mouse or a
keyboard
action, use client-side scripting.

Client-side scripts generate client-side content. Client-side content is content that's generated
on the user's computer rather than the server. In these cases, the user's web browser would
download the web page content from the server, process the code that's embedded in the
web page, and then display the updated content to the user

SERVER-SIDE SCRIPTING
Web pages that change when a web page is loaded or visited use server-side scripting. Server-
side content is content that's generatedwhen a web page is loaded. For example, login pages,
forums, submission forms, and shopping carts, all use server-side scripting since those web pages
change according to what is submitted to it.
Properties of Servlets :
•Servlets work on the server-side.
•Servlets are capable of handling complex requests obtained from web server.

02/23/2024
Execution of Servlets :

Execution of Servlets involves six basic steps:


1.The clients send the request to the web server.
2.The web server receives the request.
3. The web server passes the request to the
corresponding servlet.
4.The servlet processes the request and generates the response in the form of output. 5.The
servlet sends the response back to the web server.
6.The web server sends the response back to the client and the client browser
displays it on the screen.
The following diagram shows the servlet architecture:

02/23/2024
The server-side extensions are nothing but the technologies that are used to create
dynamic Web pages.

Actually, to provide the facility of dynamic Web pages, Web pages need a container or Web
server. To meet this requirement, independent Web server providers offer some proprietary

02/23/2024
solutions in the form of APIs(Application Programming Interface).

These APIs allow us to build programs that can run with a Web server. In this
case Java Servlet is also one of the component APIs of Java Platform Enterprise
Edition which sets standards for creating dynamic Web applications in Java.
1. Before learning about something, it’s important to know the need for that
something, it’s not like that this is the only technology available for creating
dynamic Web pages.

02/23/2024
2. The Servlet technology is similar to other Web server extensions such as
Common Gateway Interface(CGI) scripts and Hypertext
Preprocessor (PHP).

However, Java Servlets are more acceptable since they solve the limitations
of CGI such as low performance and low degree scalability.
What is CGI ?
CGI is actually an external application which is written by using any of the
programming languages likeC or C++ and this is responsible for processing client

02/23/2024
requests and generating dynamic content

In CGI application, when a client makes a request to access dynamic Web pages, the Web
server performs the following operations :

•It first locates the requested web page i.e the required CGI application using URL.
•It then creates a new process to service the client’s request.
•Invokes the CGI application within the process and passes the request information to the
server.
•Collects the response from CGI application.
•Destroys the process, prepares the HTTP response and sends it to the client.
02/23/2024
So, in CGI server has to create and destroy the process for every request. It’s
easy to understand that this approach is applicable for handling few clients but as
the number of clients increases, the workload on the server increases and so the
time taken to process requests increases.
SERVLETS ARCHIETURE

This is how a servlet execution


takes place when client (browser)
makes a request to the webserver.

02/23/2024
Servlet architecture includes:
a) Servlet Interface
To write a servlet we need to implement Servlet interface. Servlet interface can be
implemented directly or indirectly by extending Generic Servlet or HttpServlet class.

02/23/2024
b) Request handling methods

There are 3 methods defined in Servlet interface: init(), service() and destroy().

The first time a servlet is invoked, the init method is called. It is called only once
during the lifetime of a servlet. So, we can put all your initialization code here.

The Service method is used for handling the client request. As the client request reaches
to the container it creates a thread of the servlet object, and request and response object
are also created.
These request and response object are then passed as parameter to the service method,
which then process the client request. The service method in turn calls the doGet or doPost
methods (if the user has extended the class from HttpServlet ).
c) Number of instances

Basic structure of servlets


public class firstServlet extends HttpServlet

02/23/2024
{ public void init() {
/* Put your initialization code in this method,
* as this method is called only once */
}
public void service() {
// Service request for Servlet
}
public void destroy() {
// For taking the servlet out of service, this
method is called only once
}
}
LIFE CYCLE OF SERVLETS
A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet.

02/23/2024
•The servlet is initialized by calling the init() method.
•The servlet calls service() method to process a client's request.
•The servlet is terminated by calling the destroy() method.
•Finally, servlet is garbage collected by the garbage collector of the JVM.

The init() Method

The init method is called only once. It is called only when the servlet is created, and not
called for any user requests afterwards. So, it is used for one-time initializations, just as with
the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is first started.
The init method definition looks like this −

public void init() throws ServletException {


// Initialization code...
}

02/23/2024
The service() Method
The service() method is the main method to perform the actual task.The servlet container (i.e. web
server) calls the service() method to handle requests coming from the client( browsers) and to write
the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls
service.The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and
calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method −

public void service(ServletRequest request, ServletResponse


response) throws ServletException, IOException {

}
The service () method is called by the container and service method invokes doGet,
doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with
service() method but you override either doGet() or doPost() depending on what type
of request you receive from the client.
The doGet() Method
•A GET request results from a normal request for a URL or from an HTML form
that has no METHOD specified and it should be handled by doGet() method.

02/23/2024
• public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
• // Servlet code
•}
•The doPost() Method
•A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.

• public void doPost(HttpServletRequest request,


HttpServletResponse response) throws
} ServletException, IOException {
The destroy() Method
The destroy() method is called only once at the end of the life cycle of a servlet.This method gives your
servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk,
and perform other such cleanup activities.

02/23/2024
After the destroy() method is called, the servlet object is marked for garbage collection.The
destroy method definition looks like this −

public void destroy() {


// Finalization code...
}
Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.
•First the HTTP requests coming to the server are delegated to the servlet container.
•The servlet container loads the servlet before invoking the service() method.

02/23/2024
•Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.
JAVASCRIPT FUNCTION
PARAMETER
A JavaScript function does not perform any checking on parameter values
(arguments).

02/23/2024
Function Parameters and Arguments

function functionName(parameter1, parameter2, parameter3) {


// code to be executed
}

Function parameters are the names listed in the function definition.


Function arguments are the real values passed to (and received by) the
function.
Parameter Rules

1. JavaScript function definitions do not specify data types for parameters.


2. JavaScript functions do not perform type checking on the passed
arguments.

02/23/2024
3. JavaScript functions do not check the number of arguments received.

Parameter Defaults
If a function is called with missing arguments (less than declared), the missing values
are set to: undefined
Sometimes this is acceptable, but sometimes it is better to assign a default value to
the parameter:
Example
function myFunction(x,
y) { if (y ===
undefined) {
y = 0;
}
}
<!DOCTYPE html>
<html>
<body>

<p>Setting a default value to a function


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

02/23/2024
<script>
function myFunction(x,
y) { if (y ===
undefined) {
y = 0;
}
return x * y;
}
document.getElementById(
"demo").innerHTML =
myFunction(4);
</script>

</body>
</html>
OUTPUT

Setting a default value to a function parameter.

02/23/2024
0
The Arguments Object
JavaScript functions have a built-in object called the arguments object.

The argument object contains an array of the arguments used when the
function was called (invoked).

02/23/2024
This way you can simply use a function to find (for instance) the highest
value in a list of numbers:
Example
x = findMax(1, 123, 500, 115, 44, 88);

function findMax() {
var i;
var max = -Infinity;
for (i = 0; i <
arguments.length; i++) { if
(arguments[i] > max) {
max = arguments[i];
}
}
return max;
}
<!DOCTYPE html>
<html>
<body>

<p>Finding the largest number.</p>


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

<script>
function

02/23/2024
findMax()
{ var i;
var max = -
Infinity;
for(i = 0; i <
arguments.length;
i++) {
if (arguments[i]
> max) {
max =
arguments[i];
}
}
return max;
}
document.getEleme
Output

02/23/2024
Finding the largest number.
6
02/23/2024
DIFFERENCE BETWEEN SESSIONS
AND COOKIES
Cookie Session

Cookies are stored at client Sessions are stored at


side. server side.
Cookies may or may Session is independent for
not be individual every client i.e. individual
for every client. for every client.

02/23/2024
Size of cookie is limited to There is no limitation on
4KB and number of the size or number of
cookies to be used is also sessions to be used in an
restricted. application.
Cookies can store only Session can store any
“string” type of data because
datatype. the value for data type
is “object”.
Cookie is non-secure since stored Sessions are secured
in text-format at client because it is stored in
side and cookie values are binary format/encrypted
easy to access. form and gets decrypted
COOKIES SESSIONS

02/23/2024
Cookie data is available in our Session data is available for the
browser up to expiration date. browser run. After closing the
browser we lose the session
information.
Cookies saves local user data as website Session is application specific and
specific on local computer on text file. keeps information until the
browser is open.
It contains specific identifier links to server. It contains specific identifier links to user.

Cookie data are easy to modify as they are Session data are not easy to
stored at client side. modify as they are stored at
server side.
Difference between Client side V/S Server side Programming Languages
Client Side Programming Server Side Programming
Languages Languages

Works at the front end and Works in the back end which

02/23/2024
script are could not
visible among the users. be visible at the client end.
Does not need interaction Requires server interaction.
with the server.
Examples are HTML, CSS, Examples are PHP, ASP.net,
JavaScript, VB Script etc. Ruby on Rails, JSP, ColdFusion,
Python, Perl etc.
Response from a client-side Response from a server-
script is faster because the side script is slower
scripts are processed on the because the scripts are
local
Cannotcomputer.
connect to the processed remotely.
It can be connect to the
databases on the web database that is on web
Response from a client-side Response from a server-side
script is faster because the script is slower because the
scripts are processed on the scripts are processed remotely.
local computer.

Cannot connect to the It can be connect to the


databases on the web database that is on web
server. server.

02/23/2024
Relatively Insecure, because Scripts are hidden from
client- view so it is more secure.
side script is visible to the Users only see the HTML
users. output.
Client side programming Server side programming
can’t access the file can access the file system
system that resides at the residing at the web server.
web server.
It is used when the user’s It is used to create dynamic
browser already has all the pages based a number of
code and the page is conditions when the users
altered on the basis of the browser makes a request to
SERVLETS
CONCURRENCY
A Java servlet container / web server is typically multithreaded.That means, that multiple
requests to the same servlet may be executed at the same time.Therefore, you need to take
concurrency into consideration when you implement your servlet.

02/23/2024
To make sure that a servlet is thread safe, there are a few basic rules of thumb you must
follow:
1.Your servlet service() method should not access any member variables, unless these member
variables
are thread safe themselves.
2.our servlet service() should not reassign member variables, as this may affect other threads
executing inside the service() method. If you really, really need to reassign a member variable,
make sure this is done inside a synchronized block.
3. Rule 1 and 2 also counts for static variables.
4.Local variables are always thread safe. Keep in mind though, that the object a local variable
points to, may not be so. If the object was instantiated inside the method, and never escapes,
there will be no problem. On the other hand, a local variable pointing to some shared object,
may still cause problems. Just because you assign a shared object to a local reference, does not
mean that object automatically becomes thread safe.
The request and response objects are of course thread safe to use.
A new instance of these are created for every request into your servlet, and thus for every thread
executing in your servlet.

Here is a diagram which illustrates the servlet concurrency rules / issues mentioned above.The

02/23/2024
red boxes
represent state (variables) that your servlet's service() method should be careful about accessing.
Other Shared Resources
Of course it is not only the member variables and static variables inside the servlet class
itself, that you need to be careful about accessing.

02/23/2024
Static variables in any other class which are accessed by your servlet, must also be thread safe.
The same is true for member variables of any shread objects accessed by your servlet.
Introduction to JSP

It stands for Java Server Pages.


It is a server side technology.

02/23/2024
It is used for creating web application.
It is used to create dynamic web content.
In this JSP tags are used to insert JAVA code into HTML
pages.
It is an advanced version of Servlet Technology.
It is a Web based technology helps us to create dynamic and
platform independent web pages.
In this, Java code can be inserted in HTML/ XML pages or
both.
JSP is first converted into servlet by JSP container before
processing the
client’s request.
JSP pages are more advantageous than Servlet:

They are easy to maintain.


No recompilation or redeployment is
required. JSP has access to entire API

02/23/2024
of JAVA .
JSP are extended version of Servlet
Features of JSP

Coding in JSP is easy :- As it is just


adding JAVA code to HTML/XML.
Reduction in the length of Code :- In
JSP we use action tags, custom tags etc.
Connection to Database is easier :-It is easier to connect website to database and allows to
read or write data easily to the database.
Make Interactive websites :- In this we can create dynamic web pages which helps user to
interact in real time environment.
Portable, Powerful, flexible and easy to maintain :- as these are browser and server
independent. No Redeployment and No Re-Compilation :- It is dynamic, secure and platform
independent so no need to re-compilation.
JSP syntax
Syntax available in JSP are following
1.Declaration Tag :-It is used to declare
variables. Syntax:-
<%! Dec var %>

02/23/2024
Example:-
<%! int var=10; %>

2.Java Scriplets :- It allows us to add any number of JAVA code, variables and
expressions. Syntax:-
<% java code %>
3.JSP Expression :- It evaluates and convert the expression to a
string. Syntax:-
<%= expression
%> Example:-
<% num1 =

02/23/2024
num1+num2 %>
4.JAVA Comments :- It contains the text that is added for information
which has to be ignored.
Syntax:-
<% -- JSP Comments %>
Process of Execution

Steps for Execution of JSP are following:-


Create html page from where request will be sent to server eg
try.html. To handle to request of user next is to create .jsp file
Eg. new.jsp
Create project folder
structure. Create XML
file eg my.xml.
Create WAR
file. Start
02/23/2024
Example of Hello
World

We will make
one .html file
demo.jsp

and .jsp file

02/23/2024
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Hello World - JSP tutorial</title>
</head>
<body>
<%= "Hello World!" %>
</body>
</html>
JSP TAGS
There are four types of JSP tags, which are important and often required.

02/23/2024
1. Directives
These types of tags are used primarily to import packages. Altenatively you can also use these
tags to define error handling pages and for session information of JSP page.
1.Code:
<%@page language="java" %>

2.Code:
<%@page language="java" session="true" %>
3.Code:
<%@page language="java" session="true" errorPage="error.jsp" %>
4.Code:
<%@page language="java" import="java.sql.*, java.util.*" %>
5.Code:
<%@ include file="/title.jsp"%>
2. Declarations
JSP declarations starts with '<%!' and ends with '%>'. In this you can make declarions such as
int i = 1, double pi = 3.1415 etc. If needed, you can also write Java code inside declarations.

02/23/2024
3. Scriptlets
JSP Script lets starts with '<%' and ends with '%>'. This is where the important Java code
for JSP page is written.

02/23/2024
4. Expressions
JSP expressions starts with '<%=' and ends with '%>'. If you want to show some value,
you need to put it in between these tags.

02/23/2024
Advantages of using JSP

It does not require advanced


knowledge of JAVA It is capable of

02/23/2024
handling exceptions
Easy to use and learn
It can tags which are easy to use and
understand
Implicit objects are there which reduces the
length of code It is suitable for both JAVA and
non JAVA programmer

Disadvantages of
using JSP

Difficult to debug for errors.


First time access leads to wastage
of time It’s output is HTML
which lacks features.
JSP LIFE CYCLE
JSP life cycle is defined as the process from its creation till the destruction.
This is similar to a servlet life cycle with an additional step which is required to compile a JSP

02/23/2024
into servlet.

Paths Followed By JSP


The following are the paths followed by a JSP −
Compilati
on
Initializatio
n
Execution
Cleanup

The four major phases of a JSP life cycle are very similar to the Servlet
Life Cycle. The four phases have been described
02/23/2024
JSP Compilation

When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile
the page. If the page has never been compiled, or if the JSP has been modified since it was
last compiled, the JSP engine compiles the page.

02/23/2024
The compilation process involves three steps −
•Parsing the JSP.
•Turning the JSP into a servlet.
•Compiling the servlet.

JSP Initialization

•When a container loads a JSP it invokes the jspInit() method before servicing any
requests. If you need to perform JSP-specific initialization, override the jspInit() method

public void jspInit(){


// Initialization code...
}
Typically, initialization is performed only once and as with the servlet init method, you
generally initialize database connections, open files, and create lookup tables in the
jspInit method.

JSP Execution

02/23/2024
This phase of the JSP life cycle represents all interactions with requests until the JSP is
destroyed.

Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP
engine invokes the _jspService() method in the JSP.

The _jspService() method takes an HttpServletRequest and an HttpServletResponse as


its parameters
as follows −

void _jspService(HttpServletRequest request, HttpServletResponse response) {


// Service handling code...
}
The _jspService() method of a JSP is invoked on request basis.
This is responsible for generating the response for that request and this method is also
responsible for generating responses to all seven of the HTTP methods,
i.e, GET, POST, DELETE, etc.

02/23/2024
JSP Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being removed
from use by a container.

The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
Override jspDestroy
when you need to perform any cleanup, such as releasing database connections or
closing open files.

The jspDestroy() method has the following form −

public void jspDestroy() {


//Your cleanup code goes here.
CUSTOM TAGS
A custom tag is a user-defined JSP language element.
When a JSP page containing a custom tag is translated into a servlet, the tag is converted to

02/23/2024
operations on an object called a tag handler.
The Web container then invokes those operations when the JSP page's servlet is executed.
JSP tag extensions lets you create new tags that you can insert directly into a Java Server Page.
The JSP 2.0 specification introduced the Simple Tag Handlers for writing these custom tags.
To write a custom tag, you can simply extend SimpleTagSupport class and override the
doTag() method, where you can place your code to generate content for the tag.

Create "Hello" Tag


Consider you want to define a custom tag named <ex:Hello> and you want to use it in
the following fashion without a body −
<ex:Hello />
To create a custom JSP tag, you must first create a Java class that acts as a tag handler.
Let us now create the Hello Tag class as follows −
package com.tutorialspoint;

02/23/2024
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*; import
java.io.*;

public class HelloTag extends


SimpleTagSupport {
public void doTag() throws JspException, IOException
{ JspWriter out = getJspContext().getOut();
out.println("Hello Custom Tag!");
}
}
The code has simple coding where the doTag() method takes the current JspContext object
using the getJspContext() method and uses it to send "Hello Custom Tag!" to the
current JspWriter object

02/23/2024
Let us compile the above class and copy it in a directory available in the environment
variable CLASSPATH. Finally, create the following tag library file:
Installation-Directory>webapps\ROOT\WEB-INF\custom.tld. <Tomcat-
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD</short-name>

<tag>
<name>Hello</name>
<tag-class>com.tutorialspoint.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
Let us now use the above defined custom tag Hello in our JSP program as follows −

<%@ taglib prefix = "ex" uri = "WEB-INF/custom.tld"%>

<html>

02/23/2024
<head>
<title>A sample custom tag</title>
</head>

<body>
<ex:Hello/>
</body>
</html>

Call the above JSP and this should produce the following result −

Hello Custom Tag!

You might also like