Full Unit 2 Notes
Full Unit 2 Notes
Here to begin with a “Hello World!” JavaScript program. There’s just one
problem:JavaScript itself has no statement for performing output. Instead, the
JavaScript language specification leaves it up to browsers to supply output (and input)
methods.
alert(), to write a JavaScript “Hello World!” program
window.alert("Hello World!");
Definition of Web-application
Let's understand how the flow of the typical web application looks like.
1. In general, a user sends a request to the web-server using web browsers such
as Google Chrome, Microsoft Edge, Firefox, etc over the internet.
2. Then, the request is forwarded to the appropriate web application server by
the web-server.
3. Web application server performs the requested operations/ tasks
like processing the database, querying the databases; produces the result
of the requested data.
4. The obtained result is sent to the web-server by the web application server
along with the requested data/information or processed data.
5. The web server responds to the user with the requested or processed
data/information and provides the result to the user's screen .
o Any typical web application can run or accessible on any operating system
such as the Windows, Mac, Linux as long as the browser is compatible.
o A web application is usually not required to install in the hard drive of the
computer system, thus it eliminates all the issues related to the space
limitation.
o All the users are able to access the same version of the web application, which
eliminates all compatibility issues.
o It also reduces software piracy in subscription-based web applications, for
example, SAAS (or Software as a service).
As we all know, there are two sides of anything; if something has some advantages, it
may also have limitations/ disadvantages. Consider the following disadvantages of the
web applications.
o As we all know that many users like to use different web browsers according
to their needs and choices. So while creating a web application, you must
remember that your application must support several web browsers, including
new and old versions of browsers.
.
In Javascript, popup boxes are used to display the message or notification to the
user. There are three types of pop-up boxes in JavaScript namely Alert
Box, Confirm Box and Prompt Box.
Alert Box: It is used when a warning message is needed to be produced. When the
alert box is displayed to the user, the user needs to press ok and proceed.
Syntax:
alert("your Alert here")
Prompt Box: It is a type of pop up box which is used to get the user input for
further use. After entering the required details user have to click ok to proceed next
stage else by pressing the cancel button user returns the null value.
Syntax:
prompt("your Prompt here")
Confirm Box: It is a type of pop-up box that is used to get authorization or
permission from the user. The user has to press the ok or cancel button to proceed.
Syntax:
confirm("your query here")
Control Statements in JS
Control statements are intended to allow users to write scripts which determine which
lines of code get evaluated and how many times they get evaluated. Control
statements are classified into two types: conditional statements and loop statements.
The properties of document object that can be accessed and modified by the
document object.
Fig 2.3 Properties of Document Object
Method Description
write("string") writes the given string on the doucment.
writes the given string on the doucment with newline
writeln("string")
character at the end.
getElementById() returns the element having the given id value.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name
In this example, we are going to get the value of input text by user. Here, we
are using document.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.
form1 is the name of the form.
name is the attribute name of the input text.
value is the property, that returns the value of the input text.
Simple example of document object that prints name with welcome message.
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form>
Javascript - document.getElementsByName() method
1. getElementsByName() method
2. Example of getElementsByName()
1. document.getElementsByName("name")
<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">
<input type="button" onclick="totalelements()" value="Total Genders">
</form>
getElementsByTagName() method
Example of getElementsByTagName()
document.getElementsByTagName("name")
<script type="text/javascript">
function countpara(){
var totalpara=document.getElementsByTagName("p");
alert("total p tags are: "+totalpara.length);
}
</script>
<p>This is a pragraph</p>
<p>Here we are going to count total number of paragraphs by
getElementByTagName() method.</p>
<p>Let's see the simple example</p>
<button onclick="countpara()">count paragraph</button>
<script type="text/javascript">
function counth2(){
var totalh2=document.getElementsByTagName("h2");
alert("total h2 tags are: "+totalh2.length);
}
function counth3(){
var totalh3=document.getElementsByTagName("h3");
alert("total h3 tags are: "+totalh3.length);
}
</script>
<h2>This is h2 tag</h2>
<h2>This is h2 tag</h2>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<h3>This is h3 tag</h3>
<button onclick="counth2()">count h2</button>
<button onclick="counth3()">count h3</button>
Output of the above example
This is h2 tag
This is h2 tag
This is h3 tag
This is h3 tag
This is h3 tag
Note: Output of the given examples may differ on this page because it will count the
total number of para , total number of h2 and total number of h3 tags used in this
document.
Javascript - innerHTML
1. javascript innerHTML
2. Example of innerHTML property
The innerHTML property can be used to write the dynamic html on the html
document.
It is used mostly in the web pages to generate the dynamic html such as
registration form, comment form, links etc.
In this example, we are going to create the html form when user clicks on the
button.
In this example, we are dynamically writing the html form inside the div name
having the id mylocation. We are identifing this position by calling the
document.getElementById() method.
Javascript - innerText
1. javascript innerText
2. Example of innerText property
The innerText property can be used to write the dynamic text on the html
document. Here, text will not be interpreted as html text but a normal text.
It is used mostly in the web pages to generate the dynamic content such as
writing the validation message, password strength etc.
In this example, we are going to display the password strength when releases the
key after press.
</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>
DATE AND OBJECTS
JavaScript Date
The JavaScript date object can be used to get year, month and day. You can
display a timer on the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides
methods to get and set day, month, year, hour, minute and seconds.
Constructor
Date()
Date(milliseconds)
Date(dateString)
Date(year, month, day, hours, minutes, seconds, milliseconds)
JavaScript Object
A javaScript object is an entity having state and behavior (properties and
method).For example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don't create class to get
the object. But, we direct create objects
object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon).Let’s see the
simple example of creating object in JavaScript.
<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
By using an Object constructor
Here, you need to create function with arguments. Each argument value can be
assigned in the current object by using this keyword.The this keyword refers to the
current object.The example of creating object by object constructor is given below.
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
Defining method in JavaScript Object
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary){
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>
JavaScript Object Methods
The various methods of Object are as follows:
S.No Methods Description
This method is used to copy enumerable
1 Object.assign() and own properties from a source object to
a target object
This method is used to create a new object
2 Object.create() with the specified prototype object and
properties.
This method is used to describe some
3 Object.defineProperty()
behavioral attributes of the property.
This method is used to create or configure
4 Object.defineProperties()
multiple object properties.
This method returns an array with arrays of
5 Object.entries()
the key, value pairs.
This method prevents existing properties
6 Object.freeze()
from being removed.
This method returns a property descriptor
7 Object.getOwnPropertyDescriptor() for the specified property of the specified
object.
This method returns all own property
8 Object.getOwnPropertyDescriptors()
descriptors of a given object.
This method returns an array of all
9 Object.getOwnPropertyNames()
properties (enumerable or not) found.
JavaScript Array
JavaScript array is an object that represents a collection of similar type of
elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
JavaScript array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
values are contained inside [ ] and separated by , (comma). The simple example of
creating and using array in JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
JavaScript Array directly (new keyword)
Here, new keyword is used to create instance of array.The example of creating array
directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
Methods Description
concat() It returns a new array object that contains two or more merged arrays.
It copies the part of the given array with its own elements and returns the
copywithin()
modified array.
It determines whether all the elements of an array are satisfying the
every()
provided function conditions.
fill() It fills elements into an array with static values.
It returns the new array containing the elements that pass the provided
filter()
function conditions.
It returns the value of the first element in the given array that satisfies the
find()
specified condition.
It returns the index value of the first element in the given array that
findIndex()
satisfies the specified condition.
forEach() It invokes the provided function once for each element of an array.
includes() It checks whether the given array contains the specified element.
It searches the specified element in the given array and returns the index
indexOf()
of the first match.
join() It joins the elements of an array as a string.
JavaScript String
The JavaScript string is an object that represents a sequence of
characters. There are 2 ways to create string in JavaScript
By string literal
By string object (using new keyword)
By string literal
The string literal is created using double quotes. The syntax of creating
string using string literal is given below:
<script>
document.write(str);
</script>
The syntax of creating string object using new keyword is given below:
<script>
document.write(stringname);
</script>
Methods Description
indexOf() It provides the position of a char value present in the given string.
lastIndexOf() It provides the position of a char value present in the given string by
searching a character from the last position.
The JavaScript String charAt() method returns the character at the given index.
<script>
var str="javascript";
document.write(str.charAt(2));
</script>
<script>
var s3=s1.concat(s2);
document.write(s3);
</script>
The JavaScript String indexOf(str) method returns the index position of the given
string.
<script>
var n=s1.indexOf("from");
document.write(n);
</script>
JavaScript String lastIndexOf(str) Method
The JavaScript String lastIndexOf(str) method returns the last index position
of the given string.
<script>
var n=s1.lastIndexOf("java");
document.write(n);
</script>
The JavaScript String toLowerCase() method returns the given string in lowercase
letters.
<script>
var s2=s1.toLowerCase();
document.write(s2);
</script>
The JavaScript String toUpperCase() method returns the given string in uppercase
letters.
<script>
var s2=s1.toUpperCase();
document.write(s2);
</script>
<script>
var s1="abcdefgh";
var s2=s1.slice(2,5);
document.write(s2);
</script>
The JavaScript String trim() method removes leading and trailing whitespaces
from the string.
<script>
var s2=s1.trim();
document.write(s2);
</script>
JavaScript Math
Methods Description
ceil() It returns a smallest integer value, greater than or equal to the given number.
The JavaScript math.sqrt(n) method returns the square root of the given number.
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>
Math.random()
<script>
document.getElementById('p2').innerHTML=Math.random();
</script>
Math.pow(m,n)
<script>
document.getElementById('p3').innerHTML=Math.pow(3,4);
</script>
For example:
Constant Description
Methods Description
JavaScript Boolean
<script>
document.write(10<20);//true
document.write(10<5);//false
</script>
Property Description
Method Description
REGULAR EXPRESSIONS
/pattern/modifiers;
Example
Example explained:
In JavaScript, regular expressions are often used with the two string
methods: search() and replace().
The search() method uses an expression to search for a match, and
returns the position of the match.
The replace() method returns a modified string where the pattern is
replaced.
Using String search() With a String
The search() method searches a string for a specified value and returns
the position of the match:
Example
Use a string to do a search for "W3schools" in a string:
var str = "Visit W3Schools!";
var n = str.search("W3Schools");
In JavaScript, regular expressions are often used with the two string methods:
search() and replace().
The search() method uses an expression to search for a match, and returns the
position of the match.
The replace() method returns a modified string where the pattern is replaced.
Using String search() With a String
The search() method searches a string for a specified value and returns the
position of the match:
Example
Use a string to do a search for "W3schools" in a string:
var n = str.search("W3Schools");
The replace() method replaces a specified value with another value in a string:
Example
Modifier Description
i Perform Case-insensitive Matching
g Perform a Global Matching
m Perform Multiline Matching
Expression Description t
Metacharacter Description
\d Find a digit
\s Find a whitespace character
Quantifier Description
Using test()
Using exec()
EXCEPTION HANDLING
Syntax Errors
Runtime Errors, and
Logical Errors.
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional
programming languages and at interpret time in JavaScript.
For example, the following line causes a syntax error because it is missing a
closing parenthesis.
When a syntax error occurs in JavaScript, only the code contained within the
same thread as the syntax error is affected and the rest of the code in other
threads gets executed assuming nothing in them depends on the code
containing the error.
Runtime Errors
Exceptions also affect the thread in which they occur, allowing other
JavaScript threads to continue normal execution.
Logical Errors
Logic errors can be the most difficult type of errors to track down. These
errors are not the result of a syntax or runtime error. Instead, they occur when
you make a mistake in the logic that drives your script and you do not get the
result you expected.
You cannot catch those errors, because it depends on your business
requirement what type of logic you want to put in your program.
catch ( e ) {
// Code to run if an exception occurs
[break;]
}
[ finally {
// Code that is always executed regardless of
// an exception occurring
}]
//-->
</script>
The try block must be followed by either exactly one catch block or one
finally block (or one of both). When an exception occurs in the try block, the
exception is placed in e and the catch block is executed.
The optional finally block executes unconditionally after try/catch.
Examples
<html>
<head>
<script type = "text/javascript">
<!--
function myFunc() {
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
Now let us try to catch this exception using try...catch and display a user-
friendly message. You can also suppress this message, if you want to hide this
error from a user.
<html>
<head>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
You can use finally block which will always execute unconditionally after the
try/catch. Here is an example.
<html>
<head>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
You can use throw statement to raise your built-in exceptions or your
customized exceptions. Later these exceptions can be captured and you can
take an appropriate action.
Example:
<html>
<head>
try {
if ( b == 0 ) {
throw( "Divide by zero error." );
} else {
var c = a / b;
}
}
catch ( e ) {
alert("Error: " + e );
}
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
You can raise an exception in one function using a string, integer, Boolean, or
an object and then you can capture that exception either in the same function
as we did above, or in another function using a try...catch block.
Live Demo
<html>
<head>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type = "button" value = "Click Me" onclick = "myFunc();" />
</form>
</body>
</html>
The onerror event handler provides three pieces of information to identify the
exact nature of the error –
Error message − The same message that the browser would display
for the given error
URL − The file in which the error occurred
Line number− The line number in the given URL that caused the
error.
VALIDATION
Form validation normally used to occur at the server, after the client had
entered all the necessary data and then pressed the Submit button.
If the data entered by a client was incorrect or was simply missing, the server
would have to send all the data back to the client and request that the form be
resubmitted with correct information.
This was really a lengthy process which used to put a lot of burden on the
server.
JavaScript provides a way to validate form's data on the client's computer
before sending it to the web server. Form validation generally performs two
functions.
Basic Validation − First of all, the form must be checked to make sure all the
mandatory fields are filled in. It would require just a loop through each field in
the form and check for data.
Data Format Validation − Secondly, the data that is entered must be checked
for correct form and value. Your code must include appropriate logic to test
correctness of data.
Example
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit =
"return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
First let us see how to do a basic form validation. In the above form, we are
calling validate() to validate data when onsubmit event is occurring. The
following code shows the implementation of this validate() function.
Now we will see how we can validate our entered form data before submitting
it to the web server.
The following example shows how to validate an entered email address. An
email address must contain at least a ‘@’ sign and a dot (.).
Also, the ‘@’ must not be the first character of the email address, and the last
dot must at least be one character after the ‘@’ sign.
Example
Example
Example
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
Object Properties
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
Objects written as name value pairs are similar to:
Associative arrays in PHP
Dictionaries in Python
Hash tables in C
Hash maps in Java
Hashes in Ruby and Perl
Object Methods
Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and
functions.
An object method is an object property containing a function
definition.
Property Value
firstName John
lastName Doe
age 50
eyeColor blue
Example
The following example also creates a new JavaScript object with four
properties:
Example
Example
var person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"}
varx=person;
x.age = 10; // This will change both x.age and person.age
objectName.property // person.age
or
objectName["property"] // person["age"]
or
objectName[expression] // x = "age"; person[x]
Object Methods
Example
var person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
The this Keyword
JavaScript Methods
objectName.methodName()
You will typically describe fullName() as a method of the person object, and
fullName as a property.
The fullName property will execute (as a function) when it is invoked with ().
This example accesses the fullName() method of a person object:
Example
name = person.fullName();
This example uses the toUpperCase() method of the String object, to convert a
text to uppercase:
HELLO WORLD!
Example
person.name = function () {
return this.firstName + " " + this.lastName;
};
Object Accessors
This example uses a lang property to get the value of the language property.
Example
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
language : "en",
get lang() {
return this.language;
}
};
This example uses a lang property to set the value of the language property.
Example
var person = {
firstName: "John",
lastName : "Doe",
language : "",
set lang(lang) {
this.language = lang;
}
};
// Set an object property using a setter:
person.lang = "en";
// Display data from the object:
document.getElementById("demo").innerHTML = person.language;
Data Quality
JavaScript can secure better data quality when using getters and setters.
Using the lang property, in this example, returns the value of the language
property in upper case:
Example
// Create an object:
var person = {
firstName: "John",
lastName : "Doe",
language : "en",
get lang() {
return this.language.toUpperCase();
}
};
Object.defineProperty()
Example
// Define object
var obj = {counter : 0};
// Define setters
Object.defineProperty(obj, "reset", {
get : function () {this.counter = 0;}
});
Object.defineProperty(obj, "increment", {
get : function () {this.counter++;}
});
Object.defineProperty(obj, "decrement", {
get : function () {this.counter--;}
});
Object.defineProperty(obj, "add", {
set : function (value) {this.counter += value;}
});
Object.defineProperty(obj, "subtract", {
set : function (value) {this.counter -= value;}
});
Object Constructors
In JavaScript, the thing called this is the object that "owns" the code.
The value of this, when used in an object, is the object itself.
In a constructor function this does not have a value. It is a substitute for the
new object. The value of this will become the new object when a new object is
created.
Example
myFather.nationality = "English";
Adding a Method to an Object
Example
myFather.name = function () {
return this.firstName + " " + this.lastName;
};
You cannot add a new property to an object constructor the same way you add
a new property to an existing object:
Example
Person.nationality = "English";
Example
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
Example
String Objects
Number Objects
Boolean Objects
Object Prototypes
Prototype Inheritance
Sometimes you want to add new properties (or methods) to all existing objects
of a given type.
Sometimes you want to add new properties (or methods) to an object
constructor.
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
Person.prototype.nationality = "English";
The JavaScript prototype property also allows you to add new methods
to objects constructors:
Example
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
Person.prototype.name = function() {
};
EVENT HANDLING
This is the most frequently used event type which occurs when a user clicks
the left button of his mouse. You can put your validation, warning etc., against this
event type
Example
<html>
<head>
<script type = "text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</form>
</body>
</html>
onsubmit is an event that occurs when you try to submit a form. You
can put your form validation against this event type.
Example
The following example shows how to use onsubmit. Here we are calling a
validate() function before submitting a form data to the webserver. If validate()
function returns true, the form will be submitted, otherwise it will not submit the data.
<html>
<head>
<script type = "text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
<form method = "POST" action = "t.cgi" onsubmit = "return validate()">
.......
<input type = "submit" value = "Submit" />
</form>
</body>
</html>
These two event types will help you create nice effects with images or
even with text as well.
The onmouseover event triggers when you bring your mouse over any
element and the onmouseout triggers when you move your mouse out
from that element.
<head>
<script type = "text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
<div onmouseover = "over()" onmouseout = "out()">
<h2> This is inside the division </h2>
</div>
</body>
</html>
Triggers when media can start play, but might has to stop for
oncanplay script
buffering
DHTML stands for Dynamic Hypertext Markup language i.e., Dynamic HTML.
The DHTML application was introduced by Microsoft with the release of the
4th version of IE (Internet Explorer) in 1997.
o HTML 4.0
o CSS
o JavaScript
o DOM.
HTML 4.0
CSS
CSS stands for Cascading Style Sheet, which allows the web users or developers for
controlling the style and layout of the HTML elements on the web pages.
JavaScript
DOM
DOM is the document object model. It is a w3c standard, which is a standard interface
of programming for HTML. It is mainly used for defining the objects and properties
of all elements in HTML.
Uses of DHTML
o It is used for designing the animated and interactive web pages that are
developed in real-time.
o DHTML helps users by animating the text and images in their documents.
o It allows the authors for adding the effects on their pages.
o It also allows the page authors for including the drop-down menus or rollover
buttons.
o This term is also used to create various browser-based action games.
o It is also used to add the ticker on various websites, which needs to refresh
their content automatically.
Features of DHTML
DHTML JavaScript
JavaScript can be included in HTML pages, which creates the content of the page as
dynamic. We can easily type the JavaScript code within the <head> or <body> tag of
a HTML page. If we want to add the external source file of JavaScript, we can easily
add using the <src> attribute.
Following are the various examples, which describes how to use the JavaScript
technology with the DHTML:
Document.write() Method
1. <HTML>
2. <head>
3. <title>
4. Method of a JavaScript
5. </title>
6. </head>
7. <body>
8. <script type="text/javascript">
9. document.write("JavaTpoint");
10. </script>
11. </body>
12. </html>
JavaScript Alone
document.write()
Example
<html>
<body>
<script type="text/javascript">
document.write(Date());
</script>
</body>
</html>
With HTML 4, JavaScript can also be used to change the inner content and
attributes of HTML elements dynamically.
To change the content of an HTML element use:
document.getElementById(id).innerHTML=new HTML
document.getElementById(id).attribute=new value
New to HTML 4 is the ability to let HTML events trigger actions in the
browser, like starting a JavaScript when a user clicks on an HTML element.
To execute code when a user clicks on an element, use the following event
attribute:
onclick=JavaScript
JavaScript and CSS
With HTML 4, JavaScript can also be used to change the style of HTML
elements.
To change the style of an HTML element use:
document.getElementById(id).style.property=new style
Servlet Architecture
Servlets are grouped under the Advanced Java tree that are used to create dynamic
web applications. Servlets are robust in nature, well scalable and are primarily used
in developing server-side applications. If we go a little back in time, we would be
able to witness that before the introduction of servlets, CGI (Common Gateway
Interface) were used. Amid several indigenous tasks that a servlet is capable of
doing, dynamically performing client requests and responses are most common.
Other tasks that a servlet can do effectively are:
Can easily manage/control the application flow.
Suitable to implement business logic.
Can effectively balance the load at the server-side.
Easily generate dynamic web content.
Talking about the types of servlets, there are primarily two types, namely:
1. Generic Servlets
2. HTTP Servlets
There are three potential ways in which we can employ to create a servlet:
1. Implementing Servlet Interface
2. Extending Generic Servlet
3. Extending HTTP Servlet
Components of Servlet Architecture
Below is the high level architecture diagram of servlet. Let’s see in brief, how does
each component add to the working of a servlet.
Servlet Architecture
1. Client
The client shown in the architecture above is primarily working as a medium who is
sending out HTTP requests over to the web server and again processing the response
it gets back from the server. As we can see in the diagram, our client here is the web
browser.
2. Web Server
Primary job of a web server is to process the requests and responses that a user
sends over time and maintain how a web user would be able to access the files that
has been hosted over the server. The server we are talking about here is a
software which manages access to a centralized resource or service in a network..
There are precisely two types of webservers:
1. Static web server
2. Dynamic web server
3. Web Container
Web container is another typical component in servlet architecture which is
responsible for communicating with the servlets. Two prime tasks of a web
container are:
Managing the servlet lifecycle
URL mapping
Web container sits at the server-side managing and handling all the requests that are
coming in either from the servlets or from some JSP pages or potentially any other
file system.
How does a Servlet Request flow?
Every servlet should override the following 3 methods namely:
1. init()
2. service()
3. destroy()
These methods are used to process the request from the user.
Following are the steps in which a request flows through a servlet which can be
observed in the architecture diagram:
The client sends over a request.
The request is accepted by the web server and forwarded to the web container.
In order to obtain the servlet’s address, the web container traces web.xml file
corresponding to the request URL pattern.
By the time above process takes place, the servlet should have been instantiated
and initialized. If the servlet has not been instantiated and
initialized, init() method is invoked to serve the purpose.
By passing ServletRequest and Response object, public service() method is
called by the container.
In the next step, the ServletRequest and ServletResponse objects are type-casted
to HttpServletRequest and HttpServletResponse objects by the public
service() method.
Now protected service() method is called by the public service() method.
The protected service() method dispatches the request to the correct handler
method based on the type of request.
When servlet container shuts down, it unloads all the servlets and
calls destroy() method for each initialized servlets.
Advantages
Prime functionality of a servlet is that they are independent of server
configuration and they are pretty much compatible with any of the web servers
Servlets are also protocol-independent supporting FTP, HTTP, SMTP, etc.
protocols to the fullest.
Until destroyed manually, servlets can be retained in the memory helping
process several requests over time. Also, once a database connection is
established, it can facilitate process several requests for a database in the very
same database session.
Servlets inherit Java’s property of portability and hence are compatible with
nearly any web server.
Servlets are first converted into byte codes and then executed, which helps in
increasing the processing time.
Disadvantages
Designing a servlet can be pretty laborious.
Exceptions need to be handled while designing a servlet since they are not
thread-safe.
Developers may need additional skills to program a servlet.
As we already know Servlets are portable (platform/server independent) in nature
and hence are a better option if we talk in terms of other scripting languages. They
process the requests and responses dynamically. Whenever we are developing a web
application where we need to coordinate with different existing protocols, servlets
are preferred over other means because of its capability to support various
protocols. At last we can descend to a conclusion that employing a servlet could
potentially be most suitable while developing a web application.
init(); //This HttpServlet has 2 init() one which is parameterized and the other one is
non
//parameterized.But this non parameterized version of init() has a blank body.
//So this call is useless.
}
Now see the coding of our class
public void init(ServletConfig con) throws ServletException
{
super.init(con); //Since,our class init() will run first,but to run HttpServlet init() we
// have used super keyword.And Database connectivity code will be their
}
NOTE:- As we can see, total 3 init() calls we have to make.First init() gets called of
our class then of HttpServlet class then non parameterized version of HttpServlet
class.
But now, we will achieve the same thing with less number of calls:
APPROACH 2
Coding of HttpServlet parametrized and non parameterized versions of init() will
remain the same. But in our class instead of overriding parameterized version of
init(), we will override non parameterized version of init().
Let’s see the coding of our class non parameterized version of init():
public void init() throws ServletException
{
//database connectivity code
}
NOTE: Since this method public void init() throws ServletException ,we have
override from HttpServlet class whose coding is like:
public void init() throws ServletException
{
//empty body
}
Since it’s body is blank, therefore it is known as “Helper method” as it is used for
overriding purpose.
Now, as the servlet starts executing its methods, it will call the parameterized
version of init(). Since we have not to override the parameterized version, therefore
it will give a call to the HttpServlet parameterized version of init(). Since coding of
a parameterized version of init() of HttpServlet is as same as above, therefore, from
there on it will call init() (i.e non parameterized version of init). It will give a call to
our class non parameterized version of init() and the code continues.
Now, as you can see, total number of init() calls are 2 which is less than the first
approach. Therefore, execution time is less in 2nd approach and less headache
for CPU for maintaining stack and it’s speed increases as compared to 1st
approach.
Therefore, it is highly recommended to override non parameterized version of
init().Although both will run but due to efficiency first approach is rarely used and
also in first approach we have to use super keyword too.Therefore in below
mentioned program,we have override non parameterized version of init().
service() method :
1. The service() method is the most important method to perform that provides the
connection between client and server.
2. The web server calls the service() method to handle requests coming from the
client( web browsers) and to send response back to the client.
3. This method determines the type of Http request (GET, POST, PUT, DELETE,
etc.) .
4. This method also calls various other methods such as doGet(), doPost(), doPut(),
doDelete(), etc. as required.
5. This method accepts two parameters.
6. The prototype for this method:
public void service(ServletRequest req, ServletResponse resp)
throws ServletException, IOException { }
7.
where
8.
req is the ServletRequest object which encapsulates the connection from client
to server
resp is the ServletResponse object which encapsulates the connection from
server back to the client
destroy() method :
1. The destroy() method is called only once.
2. It is called at the end of the life cycle of the servlet.
3. This method performs various tasks such as closing connection with the
database, releasing memory allocated to the servlet, releasing resources that are
allocated to the servlet and other cleanup activities.
4. When this method is called, the garbage collector comes into action.
5. The prototype for this method is:
public void destroy() { // Finalization code...}
6.
Below is a sample program to illustrate Servlet in Java:
// Initializing servlet
public void init() throws ServletException
{
output = "Advance Java Concepts";
}
The HTML <form> method Attribute is used to specify the HTTP method used to
send data while submitting the form. There are two kinds of HTTP methods, which
are GET and POST. The method attribute can be used with the <form> element.
Attribute Values:
GET: In the GET method, after the submission of the form, the form values will
be visible in the address bar of the new browser tab. It has a limited size of about
3000 characters. It is only useful for non-secure data not for sensitive
information.
POST: In the post method, after the submission of the form, the form values
will not be visible in the address bar of the new browser tab as it was visible in
the GET method. It appends form data inside the body of the HTTP request. It
has no size limitation. This method does not support bookmark the result.
Supported Tags:
<form>
Syntax:
<form method="get|post">
Example 1: This example illustrates the use of GET method attribute.
html
<!DOCTYPE html>
<html>
<head>
<title>
HTML form method Attribute
</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">GeeksforGeeks</h1>
<br><br>
Last name: <input type="text" name="lname"
placeholder="Enter last name">
<br><br>
</form>
<p>
By clicking the submit button the Entered<br>
details will be sent to "/action_page.php"
</p>
</body>
</html>
Output:
Example 2: This example illustrates the use of the POST method attribute. This
method sends the form-data as an HTTP post-transaction.
html
<!DOCTYPE html>
<html>
<head>
<title>
HTML form method Attribute
</title>
</head>
<body style="text-align:center;">
<h1 style="color:green;">GeeksforGeeks</h1>
<br><br>
</form>
<p>
By clicking the login button the Entered<br>
details will be sent to "/action_page.php"
</p>
</body>
</html>
Output:
We have numerous alternatives once you’ve finished processing a user’s session data.
1. Remove a specific attribute You can delete the value associated with a specific
key by calling the public void removeAttribute(String name) function.
2. Delete your whole session. To delete an entire session, use the public void
invalidate() function.
3. Setting Session Timeout You may set the timeout for a session separately by
calling the public void setMaxInactiveInterval(int interval) function.
4. Log the user out On servers that support servlets 2.4, you may use the logout
method to log the client out of the Web server and invalidate all of the users’
sessions.
5. web.xml Configuration If you’re using Tomcat, you may set the session timeout in
the web.xml file, in addition to the ways listed above.
<session-config> <session-timeout>20</session-timeout></session-config>
The timeout is specified in minutes and overrides Tomcat’s default timeout of 30
minutes.
In a servlet, the getMaxInactiveInterval() function delivers the session’s timeout
period in seconds. GetMaxInactiveInterval() returns 900 if your session is set to 20
minutes in web.xml.
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
A. Cookies
Cookies are little pieces of data delivered by the web server in the response header
and kept by the browser. Each web client can be assigned a unique session ID by a
web server. Cookies are used to keep the session going. Cookies can be turned off by
the client.
B. Hidden Form Field
The information is inserted into the web pages via the hidden form field, which is then
transferred to the server. These fields are hidden from the user’s view.
Illustration:
<input type = hidden' name = 'session' value = '12345' >
C. URL Rewriting
With each request and return, append some more data via URL as request parameters.
URL rewriting is a better technique to keep session management and browser
operations in sync.
D. HttpSession
A user session is represented by the HttpSession object. A session is established
between an HTTP client and an HTTP server using the HttpSession interface. A user
session is a collection of data about a user that spans many HTTP requests.
Illustration:
HttpSession session = request.getSession( );
Session.setAttribute("username", "password");
The request must be made. Before sending any document content to the client, you
must first call getSession(). The following is a list of the most significant methods
provided by the HttpSession object:
Method Description
public void setAttribute(String This function uses the supplied name to tie an
name, Object value) object to this session.
Implementation: It depicts how to get the creation and last-accessed times for a
session using the HttpSession object. If the request does not already have a session
associated with it, we will create one.