Unit 2-1
Unit 2-1
Unit 2-1
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 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 −
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.
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.
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
02/23/2024
The latest ECMAScript(ES6) standard defines seven data
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.
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.
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:
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 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
02/23/2024
followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).
02/23/2024
}
02/23/2024
when "something" invokes (calls) the
function:
02/23/2024
function will stop executing.
02/23/2024
⚫ You can reuse code: Define the code once, and use
it many times.
02/23/2024
become LOCAL to the function.
02/23/2024
function myFunction() {
var carName = "Volvo";
// code here CAN use
carName
}
<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.
02/23/2024
PRIMITIVES
⚫ A primitive value is a value that has no properties or methods.
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.
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
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 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
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:
<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:
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>
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>
Example
02/23/2024
<button onclick="displayDate()">The time is?</button>
<!DOCTYPE html>
<html>
<body>
02/23/2024
onchange An HTML element has been changed
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.
<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">
<button onclick =
"gfg_Run()"> Click here
</button>
<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>
<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.
<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:
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.
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.
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.
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
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 :
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
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
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 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 −
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.
}
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.
02/23/2024
After the destroy() method is called, the servlet object is marked for garbage collection.The
destroy method definition looks like this −
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
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>
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
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>
<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
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.
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
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:
02/23/2024
of JAVA .
JSP are extended version of Servlet
Features of JSP
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
We will make
one .html file
demo.jsp
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
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
02/23/2024
into servlet.
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
−
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.
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.
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.
02/23/2024
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*; import
java.io.*;
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 −
<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 −