WT unit2
WT unit2
The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":
Example
document.getElementById("demo").innerHTML = "Hello JavaScript";
Try it Yourself »
Example
document.getElementById('demo').innerHTML = 'Hello JavaScript';
Try it Yourself »
JavaScript Can Change HTML Attribute Values
In this example JavaScript changes the value of the src (source) attribute of
an <img> tag:
Example
document.getElementById("demo").style.fontSize = "35px";
JavaScript Can Hide HTML Elements.
Example
document.getElementById("demo").style.display = "none";
JavaScript Can Show HTML Elements.
Showing hidden HTML elements can also be done by changing the display style:
Example
document.getElementById("demo").style.display = "block";
1. Client-side scripting :
Web browsers execute client-side scripting. It is used when browsers have all code.
Source code is used to transfer from webserver to user’s computer over
the internet and run directly on browsers. It is also used for validations and
functionality for user events.
It allows for more interactivity. It usually performs several actions without going to
the user. It cannot be basically used to connect to databases on a web server. These
scripts cannot access the file system that resides in the web browser. Pages are
altered on basis of the user’s choice. It can also be used to create “cookies” that
store data on the user’s computer.
2. Server-side scripting :
Web servers are used to execute server-side scripting. They are basically used to
create dynamic pages. It can also access the file system residing at the webserver.
A server-side environment that runs on a scripting language is a web server.
Scripts can be written in any of a number of server-side scripting languages
available. It is used to retrieve and generate content for dynamic pages. It is used to
require to download plugins. In this load times are generally faster than client-side
scripting. When you need to store and retrieve information a database will be used
to contain data. It can use huge resources of the server. It reduces client-side
computation overhead. The server sends pages to the request of the user/client.
Difference between client-side scripting and server-side scripting :
Client-side scripting Server-side scripting
JavaScript Objects
Real Life Objects
In real life, objects are things like: houses, cars, people, animals, or any other
subjects.
car.name = Fiat
car.model = 500
car.weight = 850kg
car.color = white
Object Properties
Car objects have the same properties, but the values differ from car to car.
Object Methods
Car objects have the same methods, but the methods are performed at different
times.
JavaScript Variables
Example
let car = "Fiat";
Objects are variables too. But objects can contain many values.
This code assigns many values (Fiat, 500, white) to an object named car:
Example
const car = {type:"Fiat", model:"500", color:"white"};
Examples
// Create an Object
const person = {firstName:"harjas", lastName:"singh", age:50, eyeColor:"blue"};
Spaces and line breaks are not important. An object initializer can span multiple
lines:
// Create an Object
const person = {
firstName: "harjas",
lastName: "singh",
age: 50,
eyeColor: "blue"
};
This example creates an empty JavaScript object, and then adds 4 properties:
// Create an Object
const person = {};
// Add Properties
person.firstName = "harjas";
person.lastName = "singh";
person.age = 50;
person.eyeColor = "blue";
Using the new Keyword
This example create a new JavaScript object using new Object(), and then adds 4
properties:
Example
// Create an Object
const person = new Object();
// Add Properties
person.firstName = "harjas";
person.lastName = "singh";
person.age = 50;
person.eyeColor = "blue";
Object Properties
Property Value
firstName harjas
lastName singh
age 50
eyeColor blue
objectName.propertyName
objectName["propertyName"]
Examples
person.lastName;
person["lastName"];
firstName harjas
lastName singh
age 50
eyeColor blue
JavaScript Primitives
string
number
boolean
null
undefined
symbol
bigint
Immutable
Primitive values are immutable (they are hardcoded and cannot be changed).
if x = 3.14, you can change the value of x, but you cannot change the value of 3.14.
If person is an object, the following statement will not create a copy of person:
const x = person;
The object x and the object person share the same memory address.
Example
//Create an Object
const person = {
firstName:"harjas",
lastName:"singh",
age:50, eyeColor:"blue"
}
// Create a copy
const x = person;
// Change Age in both
x.age = 10;
At a high level, an expression is a valid unit of code that resolves to a value. There
are two types of expressions: those that have side effects (such as assigning values)
and those that purely evaluate.
As the examples above also illustrate, all complex expressions are joined
by operators, such as = and +. In this section, we will introduce the following
operators:
Assignment operators
Comparison operators
Arithmetic operators
Bitwise operators
Logical operators
BigInt operators
String operators
Conditional (ternary) operator
Comma operator
Unary operators
Relational operators
JSCopy to Clipboard
const x = 1 + 2 * 3;
const y = 2 * 3 + 1;
JavaScript has both binary and unary operators, and one special ternary operator,
the conditional operator. A binary operator requires two operands, one before the
operator and one after the operator:
A unary operator requires a single operand, either before or after the operator:
operator operand
operand operator
For example, x++ or ++x. The operator operand form is called a prefix unary
operator, and the operand operator form is called a postfix unary operator. ++ and -
- are the only postfix operators in JavaScript — all other operators, like !, typeof,
etc. are prefix.
Assignment operators
An assignment operator assigns a value to its left operand based on the value of its
right operand. The simple assignment operator is equal (=), which assigns the
value of its right operand to its left operand. That is, x = f() is an assignment
expression that assigns the value of f() to x.
There are also compound assignment operators that are shorthand for the
operations listed in the following table:
Assigning to properties
obj.x = 3;
console.log(obj.x); // Prints 3.
console.log(obj); // Prints { x: 3 }.
JSCopy to Clipboard
const val = 0;
val.x = 3;
In strict mode, the code above throws, because one cannot assign properties to
primitives.
Destructuring
JSCopy to Clipboard
const foo = ["one", "two", "three"];
With destructuring, you can extract multiple values into distinct variables using a
single statement:
JSCopy to Clipboard
In general, assignments are used within a variable declaration (i.e., with const, let,
or var) or as standalone statements.
JSCopy to Clipboard
However, like other expressions, assignment expressions like x = f() evaluate into
a result value. Although this result value is usually not used, it can then be used by
another expression.
JSCopy to Clipboard
let x;
const y = (x = f()); // Or equivalently: const y = x = f();
console.log(y); // Logs the return value of the assignment x = f().
The evaluation result matches the expression to the right of the = sign in the
"Meaning" column of the table above. That means that x = f() evaluates into
whatever f()'s result is, x += f() evaluates into the resulting sum x + f(), x **=
f() evaluates into the resulting power x ** f(), and so on.
In the case of logical assignments, x &&= f(), x ||= f(), and x ??= f(), the return
value is that of the logical operation without the assignment, so x && f(), x || f(),
and x ?? f(), respectively.
Note that, for all assignment operators other than = itself, the resulting values are
always based on the operands' values before the operation.
For example, assume that the following functions f and g and the
variables x and y have been declared:
JSCopy to Clipboard
function f() {
console.log("F!");
return 2;
}
function g() {
console.log("G!");
return 3;
}
let x, y;
Consider these three examples:
JSCopy to Clipboard
y = x = f();
y = [f(), x = g()];
x[f()] = g();
Evaluation example 1
Evaluation example 2
Evaluation example 3
x[f()] = g() also evaluates from left to right. (This example assumes that x is
already assigned to some object. For more information about objects,
read Working with Objects.)
JSCopy to Clipboard
const z = y = x = f();
Comparison operators
A comparison operator compares its operands and returns a logical value based on
whether the comparison is true. The operands can be numerical, string, logical,
or object values. Strings are compared based on standard lexicographical ordering,
using Unicode values. In most cases, if the two operands are not of the same type,
JavaScript attempts to convert them to an appropriate type for the comparison. This
behavior generally results in comparing the operands numerically. The sole
exceptions to type conversion within comparisons involve
the === and !== operators, which perform strict equality and inequality
comparisons. These operators do not attempt to convert the operands to compatible
types before checking equality. The following table describes the comparison
operators in terms of this sample code:
JSCopy to Clipboard
const var1 = 3;
const var2 = 4;
Comparison operators
Examples
Operator Description
returning tr
Comparison operators
Examples
Operator Description
returning tr
3 == var1
Equal (==) Returns true if the operands are equal. "3" == var1
3 == '3'
var1 != 4
Not equal (!=) Returns true if the operands are not equal.
var2 != "3"
Returns true if the operands are equal and of the same type. See
Strict equal (===) 3 === var1
also Object.is and sameness in JS.
Strict not Returns true if the operands are of the same type but not equal, var1 !== "3"
equal (!==) or are of different type. 3 !== '3'
Greater than or Returns true if the left operand is greater than or equal to the var2 >= var1
equal (>=) right operand. var1 >= 3
Less than or Returns true if the left operand is less than or equal to the right var1 <= var2
equal (<=) operand. var2 <= 5
Arithmetic operators
JSCopy to Clipboard
1 / 2; // 0.5
1 / 2 === 1.0 / 2.0; // this is true
In addition to the standard arithmetic operations (+, -, *, /), JavaScript provides the
arithmetic operators listed in the following table:
Arithmetic operators
Unary operator. Subtracts one from its operand. If x is 3, then --x sets x to 2
Decrement (--) The return value is analogous to that for the returns 2, whereas x-- retur
increment operator. and, only then, sets x to 2.
Bitwise operators
A bitwise operator treats their operands as a set of 32 bits (zeros and ones), rather
than as decimal, hexadecimal, or octal numbers. For example, the decimal number
nine has a binary representation of 1001. Bitwise operators perform their
operations on such binary representations, but they return standard JavaScript
numerical values.
Returns a one in each bit position for which the corresponding bits of b
Bitwise AND a&b
operands are ones.
Returns a zero in each bit position for which the corresponding bits of b
Bitwise OR a|b
operands are zeros.
Returns a zero in each bit position for which the corresponding bits are
Bitwise XOR a ^ b same. [Returns a one in each bit position for which the corresponding b
are different.]
Sign-propagating Shifts a in binary representation b bits to the right, discarding bits shifte
a >> b
right shift off.
Zero-fill right a >>> Shifts a in binary representation b bits to the right, discarding bits shifte
shift b off, and shifting in zeros from the left.
For example, the binary representation of nine is 1001, and the binary
representation of fifteen is 1111. So, when the bitwise operators are applied to
these values, the results are as follows:
~15 -16 ~ 0000 0000 … 0000 1111 = 1111 1111 … 1111 0000
Note that all 32 bits are inverted using the Bitwise NOT operator, and that values
with the most significant (left-most) bit set to 1 represent negative numbers (two's-
complement representation). ~x evaluates to the same value that -x - 1 evaluates to.
The bitwise shift operators take two operands: the first is a quantity to be shifted,
and the second specifies the number of bit positions by which the first operand is to
be shifted. The direction of the shift operation is controlled by the operator used.
Shift operators convert their operands to thirty-two-bit integers and return a result
of either type Number or BigInt: specifically, if the type of the left operand
is BigInt, they return BigInt; otherwise, they return Number.
This operator shifts the first operand the 19>>>2 yields 4, because 10011 shifte
specified number of bits to the right. bits to the right becomes 100, which is
Zero-fill right
Excess bits shifted off to the right are For non-negative numbers, zero-fill rig
shift (>>>)
discarded. Zero bits are shifted in from shift and sign-propagating right shift y
the left. the same result.
Logical operators
Logical operators are typically used with Boolean (logical) values; when they are,
they return a Boolean value. However, the &&, ||, and ?? operators actually return
the value of one of the specified operands, so if these operators are used with non-
Boolean values, they may return a non-Boolean value. As such, they are more
adequately called "value selection operators". The logical operators are described
in the following table.
Logical operators
Examples of expressions that can be converted to false are those that evaluate
to null, 0, 0n, NaN, the empty string (""), or undefined.
The following code shows examples of the && (logical AND) operator.
JSCopy to Clipboard
JSCopy to Clipboard
JSCopy to Clipboard
const n1 = null ?? 1; // 1
const n2 = undefined ?? 2; // 2
const n3 = false ?? 3; // false
const n4 = 0 ?? 4; // 0
Note how ?? works like ||, but it only returns the second expression when the first
one is "nullish", i.e. null or undefined. ?? is a better alternative than || for setting
defaults for values that might be null or undefined, in particular when values
like '' or 0 are valid values and the default should not apply.
JSCopy to Clipboard
Short-circuit evaluation
As logical expressions are evaluated left to right, they are tested for possible
"short-circuit" evaluation using the following rules:
The rules of logic guarantee that these evaluations are always correct. Note that
the anything part of the above expressions is not evaluated, so any side effects of
doing so do not take effect.
BigInt operators
JSCopy to Clipboard
// BigInt addition
const a = 1n + 2n; // 3n
// Division with BigInts round towards zero
const b = 1n / 2n; // 0n
// Bitwise operations with BigInts do not truncate either side
const c = 40000000000000000n >> 2n; // 10000000000000000n
One exception is unsigned right shift (>>>), which is not defined for BigInt values.
This is because a BigInt does not have a fixed width, so technically it does not
have a "highest bit".
JSCopy to Clipboard
const d = 8n >>> 2n; // TypeError: BigInts have no unsigned right shift, use >>
instead
BigInts and numbers are not mutually replaceable — you cannot mix them in
calculations.
JSCopy to Clipboard
This is because BigInt is neither a subset nor a superset of numbers. BigInts have
higher precision than numbers when representing large integers, but cannot
represent decimals, so implicit conversion on either side might lose precision. Use
explicit conversion to signal whether you wish the operation to be a number
operation or a BigInt one.
JSCopy to Clipboard
const a = Number(1n) + 2; // 3
const b = 1n + BigInt(2); // 3n
JSCopy to Clipboard
String operators
In addition to the comparison operators, which can be used on string values, the
concatenation operator (+) concatenates two string values together, returning
another string that is the union of the two operand strings.
For example,
JSCopy to Clipboard
For example,
JSCopy to Clipboard
The conditional operator is the only JavaScript operator that takes three operands.
The operator can have one of two values based on a condition. The syntax is:
JSCopy to Clipboard
If condition is true, the operator has the value of val1. Otherwise it has the value
of val2. You can use the conditional operator anywhere you would use a standard
operator.
For example,
JSCopy to Clipboard
This statement assigns the value "adult" to the variable status if age is eighteen or
more. Otherwise, it assigns the value "minor" to status.
Comma operator
The comma operator (,) evaluates both of its operands and returns the value of the
last operand. This operator is primarily used inside a for loop, to allow multiple
variables to be updated each time through the loop. It is regarded bad style to use it
elsewhere, when it is not necessary. Often two separate statements can and should
be used instead.
JSCopy to Clipboard
Unary operators
delete
JSCopy to Clipboard
delete object.property;
delete object[propertyKey];
delete objectName[index];
If the delete operator succeeds, it removes the property from the object. Trying to
access it afterwards will yield undefined. The delete operator returns true if the
operation is possible; it returns false if the operation is not possible.
JSCopy to Clipboard
delete Math.PI; // returns false (cannot delete non-configurable properties)
const myObj = { h: 4 };
delete myObj.h; // returns true (can delete user-defined properties)
Deleting array elements
Since arrays are just objects, it's technically possible to delete elements from them.
This is, however, regarded as a bad practice — try to avoid it. When you delete an
array property, the array length is not affected and other elements are not re-
indexed. To achieve that behavior, it is much better to just overwrite the element
with the value undefined. To actually manipulate the array, use the various array
methods such as splice.
typeof
The typeof operator returns a string indicating the type of the unevaluated
operand. operand is the string, variable, keyword, or object for which the type is to
be returned. The parentheses are optional.
JSCopy to Clipboard
The typeof operator returns the following results for these variables:
JSCopy to Clipboard
JSCopy to Clipboard
For a number or string, the typeof operator returns the following results:
JSCopy to Clipboard
For property values, the typeof operator returns the type of value the property
contains:
JSCopy to Clipboard
For methods and functions, the typeof operator returns results as follows:
JSCopy to Clipboard
JSCopy to Clipboard
Relational operators
A relational operator compares its operands and returns a Boolean value based on
whether the comparison is true.
in
The in operator returns true if the specified property is in the specified object. The
syntax is:
JSCopy to Clipboard
propNameOrNumber in objectName
JSCopy to Clipboard
// Arrays
const trees = ["redwood", "bay", "cedar", "oak", "maple"];
0 in trees; // returns true
3 in trees; // returns true
6 in trees; // returns false
"bay" in trees; // returns false
// (you must specify the index number, not the value at that index)
"length" in trees; // returns true (length is an Array property)
// built-in objects
"PI" in Math; // returns true
const myString = new String("coral");
"length" in myString; // returns true
// Custom objects
const myCar = { make: "Honda", model: "Accord", year: 1998 };
"make" in myCar; // returns true
"model" in myCar; // returns true
instanceof
The instanceof operator returns true if the specified object is of the specified object
type. The syntax is:
JSCopy to Clipboard
Use instanceof when you need to confirm the type of an object at runtime. For
example, when catching exceptions, you can branch to different exception-
handling code depending on the type of exception thrown.
For example, the following code uses instanceof to determine whether obj is
a Map object. Because obj is a Map object, the statements inside the if block
execute.
JSCopy to Clipboard
Basic expressions
All operators eventually operate on one or more basic expressions. These basic
expressions include identifiers and literals, but there are a few other kinds as well.
They are briefly introduced below, and their semantics are described in detail in
their respective reference sections.
this
Use the this keyword to refer to the current object. In general, this refers to the
calling object in a method. Use this either with the dot or the bracket notation:
JSCopy to Clipboard
this["propertyName"];
this.propertyName;
Suppose a function called validate validates an object's value property, given the
object and the high and low values:
JSCopy to Clipboard
You could call validate in each form element's onChange event handler,
using this to pass it to the form element, as in the following example:
HTMLCopy to Clipboard
Grouping operator
JSCopy to Clipboard
const a = 1;
const b = 2;
const c = 3;
// default precedence
a + b * c // 7
// evaluated by default like this
a + (b * c) // 7
// which is equivalent to
a * c + b * c // 9
Property accessor
The property accessor syntax gets property values on objects, using either dot
notation or bracket notation.
JSCopy to Clipboard
object.property;
object["property"];
The working with objects guide goes into more details about object properties.
Optional chaining
The optional chaining syntax (?.) performs the chained operation on an object if it
is defined and non-null, and otherwise short-circuits the operation and
returns undefined. This allows you to operate on a value that may
be null or undefined without causing a TypeError.
JSCopy to Clipboard
maybeObject?.property;
maybeObject?.[property];
maybeFunction?.();
new
You can use the new operator to create an instance of a user-defined object type or
of one of the built-in object types. Use new as follows:
JSCopy to Clipboard
JSCopy to Clipboard
JavaScript control statement is used to control the execution of a program based
on a specific condition. If the condition meets then a particular block of action
will be executed otherwise it will execute another block of action that satisfies
that particular condition.
Types of Control Statements in JavaScript
Conditional Statement: These statements are used for decision-making, a
decision
n is made by the conditional statement based on an expression that is passed.
Either YES or NO.
Iterative Statement: This is a statement that iterates repeatedly until a
condition is met. Simply said, if we have an expression, the statement will
keep repeating itself until and unless it is satisfied.
There are several methods that can be used to perform control statements in
JavaScript:
Table of Content
If Statement
Using If-Else Statement
Using Switch Statement
Using the Ternary Operator (Conditional Operator)
Using For loop
If Statement
In this approach, we are using an if statement to check a specific condition, the
code block gets executed when the given condition is satisfied.
Syntax:
if ( condition_is_given_here ) {
// If the condition is met,
//the code will get executed.
}
Example: In this example, we are using an if statement to check our given
condition.
Javascript
const num = 5;
if (num > 0) {
};
Output
else
Output
switch (num) {
case 0:
console.log("Number is zero.");
break;
case 1:
console.log("Nuber is one.");
break;
case 2:
console.log("Number is two.");
break;
default:
};
Output
Output
if (i % 2 === 0) {
console.log(i);
};
Output
0
2
4
6
8
10
JavaScript Arrays
An array is a special variable, which can hold more than one value:
Use of Arrays
If you have a list of items (a list of car names, for example), storing the cars in
single variables could look like this:
An array can hold many values under a single name, and you can access the values
by referring to an index number.
Creating an Array
Syntax:
Learn more about const with arrays in the chapter: JS Array Const.
Example
const cars = ["Saab", "Volvo", "BMW"];
Spaces and line breaks are not important. A declaration can span multiple lines:
Example
const cars = [
"Saab",
"Volvo",
"BMW"
];
You can also create an array, and then provide the elements:
Example
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
The following example also creates an Array, and assigns values to it:
Example
const cars = new Array("Saab", "Volvo", "BMW");
For simplicity, readability and execution speed, use the array literal method.
cars[0] = "Opel";
Example
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
Converting an Array to a String
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
Result:
Banana,Orange,Apple,Mango
With JavaScript, the full array can be accessed by referring to the array name:
Example
const cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
Arrays are a special type of objects. The typeof operator in JavaScript returns
"object" for arrays.
Arrays use numbers to access its "elements". In this example, person[0] returns
John:
Array:
const person = ["ab", "", 20];
Because of this, you can have variables of different types in the same Array.
You can have objects in an Array. You can have functions in an Array. You can
have arrays in an Array:
myArray[0] = Date.now;
myArray[1] = myFunction;
myArray[2] = myCars;
The real strength of JavaScript arrays are the built-in array properties and methods:
The length property of an array returns the length of an array (the number of array
elements).
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;
The length property is always one more than the highest array index.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction(value) {
text += "<li>" + value + "</li>";
}
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits.push("Lemon"); // Adds a new element (Lemon) to fruits
New element can also be added to an array using the length property:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[fruits.length] = "Lemon"; // Adds "Lemon" to fruits
Adding elements with high indexes can create undefined "holes" in an array:
Example
const fruits = ["Banana", "Orange", "Apple"];
fruits[6] = "Lemon"; // Creates undefined "holes" in fruits
Associative Arrays
Arrays with named indexes are called associative arrays (or hashes).
Example
const person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;
person.length; // Will return 3
person[0]; // Will return "John"
If you use named indexes, JavaScript will redefine the array to an object.
After that, some array methods and properties will produce incorrect results.
Example:
const person = [];
person["firstName"] = "John";
person["lastName"] = "Doe";
person["age"] = 46;
person.length; // Will return 0
person[0]; // Will return undefined
These two different statements both create a new empty array named points:
These two different statements both create a new array containing 6 numbers:
A Common Error
const points = [40];
Solution 1:
Array.isArray(fruits);
Solution 2:
Example
const myObj = {
name: "ab",
age: 30,
cars: [
{name:"Ford", models:["Fiesta", "Focus", "Mustang"]},
{name:"BMW", models:["320", "X3", "X5"]},
{name:"Fiat", models:["500", "Panda"]}
]
}
To access arrays inside arrays, use a for-in loop for each array:
Example
for (let i in myObj.cars) {
x += "<h1>" + myObj.cars[i].name + "</h1>";
for (let j in myObj.cars[i].models) {
x += myObj.cars[i].models[j];
}
}
JavaScript Functions
Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).
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.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the
function:
Function Return
When JavaScript reaches a return statement, the 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":
Example
function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}
You can use the same code with different arguments, to produce different results.
The () Operator
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
Accessing a function without () returns the function and not the function result:
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
Functions can be used the same way as you use variables, in all types of formulas,
assignments, and calculations.
Example
let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";
Local Variables
function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}
Example
const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");
const mySister = new Person("Anna", "Rally", 18, "green");
A value given to a property will be a default value for all objects created by the
constructor:
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.nationality = "English";
}
Example
myFather.nationality = "English";
Example
Person.nationality = "English";
To add a new property, you must add it to the constructor function prototype:
Example
Person.prototype.nationality = "English";
Example
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
this.fullName = function() {
return this.firstName + " " + this.lastName;
};
}
Example
myMother.changeName = function (name) {
this.lastName = name;
}
Example
Person.changeName = function (name) {
this.lastName = name;
}
myMother.changeName("Doe");
Example
Person.prototype.changeName = function (name) {
this.lastName = name;
}
myMother.changeName("Doe");
Example
""; // primitive string
0; // primitive number
false; // primitive boolean
With the HTML DOM, JavaScript can access and change all the elements of an
HTML document.
When a web page is loaded, the browser creates a Document Object Model of the
page.
With the object model, JavaScript gets all the power it needs to create dynamic
HTML:
HTML DOM
The HTML DOM is a standard object model and programming interface for
HTML. It defines:
Web Browser JS
The web browser environment in JavaScript is the environment in which
JavaScript code runs in a web browser. It's also known as the host environment.
Provides objects and functions that are specific to the platform
Allows developers to manipulate the Document Object Model (DOM)
Allows developers to handle events
Allows developers to interact with the user
Components
Window: A global object that represents the browser window and JavaScript code
Document Object Model (DOM): Represents all page content as objects that can
be modified
How it works
Browsers like Chrome, Firefox, and Edge have built-in JavaScript engines
These engines use a public API to create host objects that reflect the DOM into
JavaScript
Examples
V8: The JavaScript engine used in Chrome
SpiderMonkey: The JavaScript engine used in Firefox
Chakra: The JavaScript engine used in Edge
JavaScript Form Validation
If a form field (fname) is empty, this function alerts a message, and returns false, to
prevent the form from being submitted:
JavaScript Example
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
Submit
If a form field (fname) is empty, the required attribute prevents this form from
being submitted:
Data Validation
Data validation is the process of ensuring that user input is clean, correct, and
useful.
Server side validation is performed by a web server, after input has been sent to
the server.
Attribute Description
Introduction to JSP
In Java, JSP stands for Jakarta Server Pages( (JSP; formerly JavaServer
Pages)). It is a server-side technology that is used for creating web applications. It
is used to create dynamic web content. JSP consists of both HTML tags and JSP
tags. In this, JSP tags are used to insert JAVA code into HTML pages. It is an
advanced version of Servlet Technology i.e. a web-based technology that 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 a servlet by the
JSP container before processing the client’s request. JSP has various features like
JSP Expressions, JSP tags, JSP Expression Language, etc.
JSP more Advantageous than Servlet
They are easy to maintain.
No recompilation or redeployment is required.
Less coding is required in JSP.
JSP has access to the entire API of JAVA.
JSP are extended version of Servlet.
Features of JSP
Coding in JSP is Easy: As it involves adding Java code to HTML/XML.
Easy to Use and Learn: It is straightforward and accessible for both Java and
non-Java programmers.
It Does Not Require Advanced Knowledge of Java: Suitable for users with
basic Java skills.
Reduction in the Length of Code: JSP uses action tags, custom tags, etc., to
minimize code length.
Java Scriplets: Allows embedding Java code, variables, and expressions within
JSP pages.
JSP Expression: Evaluates expressions and converts them to strings.
Declaration Tag: Used to declare variables and methods within JSP pages.
Implicit Objects: Provides built-in objects that reduce the length of code.
Make Interactive Websites: Facilitates the creation of dynamic web pages that
interact with users in real-time.
Connection to Database is Easier: Simplifies connecting to databases and
allows for easy data reading and writing.
Extension to Servlet: Inherits all features of servlets and includes implicit
objects and custom tags.
Portable, Powerful, Flexible, and Easy to Maintain: Browser and server
independent, making it versatile and easy to manage.
No Redeployment and No Re-Compilation: JSP is dynamic, secure, and
platform-independent, so no need for redeployment or recompilation.
Create HTML Page from Where Request Will Be Sent: For
example, try.html for sending requests to the server.
To Handle User Requests, Create .jsp File: For instance, new.jsp for handling
requests.
Create Project Folder Structure: Organize files and resources into a project
structure.
Create XML File: For configuration or data, e.g., my.xml.
Create WAR File: Package the application into a WAR (Web Application
Archive) file for deployment.
Start Tomcat: Ensure the servlet container (Tomcat) is running.
Run Application: Deploy and test the JSP application.
It is Capable of Handling Exceptions: JSP can manage errors and exceptions
effectively.
Difficult to Debug for Errors: Debugging JSP pages can be challenging due to
their mixed nature of HTML and Java code.
First-Time Access Leads to Wastage of Time: Initial access can be slower as
JSP pages need to be compiled.
Output is HTML Which Lacks Features: JSP generates HTML, which may
not support advanced features.
Creating a simple JSP Page
hello.JSP :
JSP simply puts Java inside HTML pages. You can take any existing HTML page
and change its extension to “.jsp” instead of “.html”. In fact, this is the perfect
exercise for your first JSP.
Take the HTML file you used in the previous exercise. change its extension from
“.html” to “jsp”. Now load the new file, with the “.jsp” extension, in your browser.
You will see the same output, but it will take longer! But only the first time. If you
reload it again, it will load normally.
What is happening behind the scenes is that your JSP is being turned into a Java
file, compiled, and loaded. This compilation only happens once, so after the first
load, the file doesn’t take long to load anymore. (But every time you change the
JSP file, it will be re-compiled again.)
Of course, it is not very useful to just write HTML pages with a .jsp extension! We
now proceed to see what makes JSP so useful.
Adding dynamic content via expressions:
As we saw in the previous section, any HTML file can be turned into a JSP file by
changing its extension to .jsp . Of course , what makes JSP useful is the ability to
embed Java. Put the following text in a file. jsp extension (let us call it hello.jsp) ,
place it in your JSP directory, and view it in a browser.
<HTML>
<BODY>
Hello! The time is now <%= new java.util.Date() %>
</BODY>
</HTML>
Notice that each time you reload the page in the browser, it comes up with the
current time. The character sequence.
<%= and %> enclose Java expressions, which are evaluated at run time.
This is what makes it possible to use JSP to generate dynamic HTML pages that
change in response to user actions or vary from user to user.
Explain JSP Elements:
We will learn about the various elements available in JSP with suitable examples.
In JSP elements can be divided into 4 different types.
These are:
Expression
Scriplets
Directives
Declarations
Expression:
We can use this tag to output any data on the generated page. These data are
automatically converted to string and printed on the output stream.
Syntax:
JSP Expressions are : <%="Anything" %>
NOTE : JSP Expressions start with Syntax of JSP Scriptles are with <%=and ends
with %>. Between these, you can put anything that will convert to the String and
that will be displayed.
Example:
<%="HelloWorld!" %>
Scriplets:
In this tag we can insert any amount of valid java code and these codes are placed
in the _jsp Service method by the JSP engine.
Syntax:
<%//java codes%>
NOTE : JSP Scriptlets begins with <% and ends %> . We can embed any amount
of Java code in the JSP Scriptlets. JSP Engine places these codes in the
_jspService() method.
Variables available to the JSP Scriptlets are:
Request
Response
Session
Out
Directives:
A JSP “directive” starts with <%@ characters. In the directives, we can import
packages , and define error-handling pages or the session information of the JSP
page.
Syntax:
<%@directive attribute="value"% >
page
include
taglib
Declarations :
This tag is used for defining the functions and variables to be used in the JSP.
Syntax:
<%!
//java codes
%>
NOTE : JSP Declaratives begins with <%! and ends %> with We can embed any
amount of java code in the JSP Declaratives. Variables and functions defined in
the declaratives are class-level and can be used anywhere on the JSP page.
Example :
<%@page import="java.util.*"%>
<HTML>
<BODY>
<%!
Date theDate = new Date(); // Corrected the unwanted space in the declaration
Date getDate() {
System.out.println("In getDate() method");
return theDate;
}
%>
Hello! The time is now <%=getDate()%>
</BODY>
</HTML>
Example of a JSP Web Page:
<HTML>
<HEAD>
<TITLE>A Web Page</TITLE>
</HEAD>
<BODY>
<%out.println("Hello there!");%>
</BODY>
</HTML>
Run a Simple JSP Page:
Step 1: Save the JSP file using “.jsp” extension (ex- “hello.jsp”)
Step 2: Start the server
Step 3: Place your application inside a folder
Step 4: To execute the JSP script, simply start tomcat server and use a browser
to browse an URL of the JSP page i.e.
http://localhost:portnumber/YourApplicationContextRoot/jspfile then you will
see the jsp file is being compiled.
JSP Declaration
Declaration tag is one of the scripting elements in JSP.
This Tag is used for declare the variables. Along with this, Declaration Tag can
also declare method and classes. Jsp initializer scans the code and find the
declaration tag and initializes all the variables, methods, and classes. JSP container
keeps this code outside of the service method (_JSPService()) to make them class
level variables and methods.
Syntax of JSP-Declaration Tag
HTML
pageEncoding="ISO-8859-1"%>
"http:www.gtbit.org">
<html>
<head>
<title>WT</title>
</head>
<body>
<html>
<body>
<%!
int factorial(int n)
{
if (n == 0)
return 1;
return n*factorial(n-1);
%>
</body>
</html>
</body>
</html>
JSP Page
A JSP page is a normal web page with JSP elements for generating the parts of the
web page that differ for each request. A simple JSP web page that contains the JSP
elements and template text. Everything on the page that is not a JSP element is
called Template text. Template text can be any text, i.e., HTML, XML, WML or
even plain text.JSP has no dependency on HTML, it can be used with any markup
language. Template text is always passed straight to the browser.
JSP Elements
There are three types of JSP elements present:
1. Directive
2. Action
3. Scripting
New Components were added in JSP 2.0 as an Expression Language(EL) and let’s
call this a fourth element type, even though it’s a bit different than the other three.
1. Directive Elements
page: <%@ page … %>
Defines page-dependent attributes, such as session tracking, error page, and
buffering requirements.
is used for importing a package.
is used for Handling an Exception.
Attributes that we can use are:
language=”Scripting language” : is used to set which type of language it is.
import=”import List” : is used to import the packages,and so on…
session=”true/false”
contentType=”ctinfo”
errorPage=”error-url”
isErrorPage=”true/false”
info=”information”
isELIgnored=”true/false”
isThreadSafe=”true/false”
In all the above “import” attribute can be used many times.
Example:
<%@ page language="java" import="java.util.*,java.sql.*" info="Contact page"
extends="com.rajkumar.User" contextType="text/html"
isELIgnored="false"
isThreadSafe="false" session="false" %>
include: <%@ include … %>
Includes a file during the translation phase
for using other JSP pages in the current JSP page
Example:
<%@ include file="filename" %>
<%@ include file="header.jsp" %>
taglib: <%@ taglib … %>
Declares a tag library, containing custom actions, that is used on the page for using
Spring Frameworks
Template Text
Template data refers to the static HTML or XML content of the JSP. Aside from
the usual substitutions, such as those based on quoting and escape sequences, the
template data is written verbatim as part of the JSP response.
2. Action Tag/Element
JSP Action tags or Elements are used to perform some specific tasks. The action
tags are used to control the flow between pages and to use Java Beans. There are
many JSP action tags.
jsp:forward: forwards the request and response to another resource.
jsp:include: includes another resource.
jsp:useBean: creates or locates bean object.
jsp:setProperty: sets the value of property in bean object.
jsp:getProperty: prints the value of the property of the bean.
jsp:plugin: embeds another component such as applet.
jsp:param: sets the parameter value. It is used in forward and includes mostly.
jsp:fallback: can be used to print the message if the plugin is working. It is
used in jsp:plugin.
3. Scripting Element
Scriptlet elements must be written within the <% … %> tags.The Scriptlet tag
allows writing Java code statements within the JSP page.The tag is responsible for
implementing the functionality of “_jspService()” by scripting the java code.The
JSP engine will process any code written within the pair of <% and %> tags and
any other code is treated as plain text while translating the JSP page. There are
three main subdivisions of Scripting Elements in Java Server Pages.
Expression Tag
Scriptlet Tag
Declaration Tag
JSP - Architecture
The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP
container is responsible for intercepting requests for JSP pages. This tutorial makes
use of Apache which has built-in JSP container to support JSP pages development.
A JSP container works with the Web server to provide the runtime environment
and other services a JSP needs. It knows how to understand the special elements
that are part of JSPs.
Following diagram shows the position of JSP container and JSP files in a Web
application.
JSP Processing
The following steps explain how the web server creates the Webpage using JSP −
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it
to a JSP engine. This is done by using the URL or JSP page which ends
with .jsp instead of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content.
This conversion is very simple in which all template text is converted to println( )
statements and all JSP elements are converted to Java code. This code implements
the corresponding dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the
original request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML format. The
output is furthur passed on to the web server by the servlet engine inside an HTTP
response.
The web server forwards the HTTP response to your browser in terms of static
HTML content.
Finally, the web browser handles the dynamically-generated HTML page inside
the HTTP response exactly as if it were a static page.
All the above mentioned steps can be seen in the following diagram −
Typically, the JSP engine checks to see whether a servlet for a JSP file already
exists and whether the modification date on the JSP is older than the servlet. If the
JSP is older than its generated servlet, the JSP container assumes that the JSP
hasn't changed and that the generated servlet still matches the JSP's contents. This
makes the process more efficient than with the other scripting languages (such as
PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without having
to be a Java programming wiz. Except for the translation phase, a JSP page is
handled exactly like a regular servlet.
JSP - Directives
A JSP directive affects the overall structure of the servlet class. It usually has the
following form −
Directives can have a number of attributes which you can list down as key-value
pairs and separated by commas.
The blanks between the @ symbol and the directive name, and between the last
attribute and the closing %>, are optional.
You can write the XML equivalent of the above syntax as follows −
Attributes
Following table lists out the attributes associated with the page directive −
1 buffer
Specifies a buffering model for the output stream.
2 autoFlush
Controls the behavior of the servlet output buffer.
3 contentType
Defines the character encoding scheme.
errorPage
4 Defines the URL of another JSP that reports on Java unchecked runtime
exceptions.
isErrorPage
5 Indicates if this JSP page is a URL specified by another JSP page's errorPage
attribute.
6 extends
Specifies a superclass that the generated servlet must extend.
import
7 Specifies a list of packages or classes for use in the JSP as the Java import
statement does for Java classes.
8 info
Defines a string that can be accessed with the servlet's getServletInfo() method.
9 isThreadSafe
Defines the threading model for the generated servlet.
10 language
Defines the programming language used in the JSP page.
11 session
Specifies whether or not the JSP page participates in HTTP sessions
12 isELIgnored
Specifies whether or not the EL expression within the JSP page will be ignored.
13 isScriptingEnabled
Determines if the scripting elements are allowed for use.
The include directive is used to include a file during the translation phase. This
directive tells the container to merge the content of other external files with the
current JSP during the translation phase. You may code the include directives
anywhere in your JSP page.
The filename in the include directive is actually a relative URL. If you just specify
a filename with no associated path, the JSP compiler assumes that the file is in the
same directory as your JSP.
The JavaServer Pages API allow you to define custom JSP tags that look like
HTML or XML tags and a tag library is a set of user-defined tags that implement
custom behavior.
The taglib directive declares that your JSP page uses a set of custom tags,
identifies the location of the library, and provides means for identifying the custom
tags in your JSP page.
The taglib directive follows the syntax given below −
Here, the uri attribute value resolves to a location the container understands and
the prefix attribute informs a container what bits of markup are custom actions.
A JSP code snippet is a code sample that shows you how to add Commerce
functionality to your store. JSP code snippets may be added to a starter store, or to
a store previously published and migrated. JSP code snippets are intended to help
you:
JSP code snippets use the JSP Standard Tag Library (JSTL). Each JSP code
snippet is well commented, easy to read, easy to understand, and easy to
customize.
"Name_of_the_snippet ":
{
"prefix": "prefix_of_the_snippet",
"body": [
],
"description": "description_about_the_snippet"
import java.util.*;
import java.util.Map.Entry;
import java.io.*;
import java.util.regex.Pattern;
BufferedReader br;
StringTokenizer st;
public FastReader()
br = new BufferedReader(
new InputStreamReader(System.in));
String next()
try {
st = new StringTokenizer(br.readLine());
catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
double nextDouble()
return Double.parseDouble(next());
String nextLine()
try {
str = br.readLine();
catch (IOException e) {
e.printStackTrace();
return str;
Output:
JSP stands for Java Server Pages, and it’s a server side technology. It’s used for
creating web applications and dynamic web content. The main property of JSP is
that we can insert our java code inside our HTML page using JSP tag. JSP
provides you platform-independent pages.
html
<%@ page language = "java" contentType = "text/html; charset = UTF-8"
pageEncoding = "UTF-8"%>
Transitional//EN" "http://www.gtbit.org">
<html>
<head>
</head>
<body>
</body>
</html>
Implicit objects are a set of Java objects that the JSP Container makes available to
developers on each page. These objects may be accessed as built-in variables via
scripting elements and can also be accessed programmatically by JavaBeans and
Servlets.JSP provide you Total 9 implicit objects which are as follows
1. request: This is the object of HttpServletRequest class associated with the
request.
2. response: This is the object of HttpServletResponse class associated with the
response to the client.
3. config: This is the object of ServletConfig class associated with the page.
4. application: This is the object of ServletContext class associated with the
application context.
5. session: This is the object of HttpSession class associated with the request.
6. page context: This is the object of PageContext class that encapsulates the use
of server-specific features. This object can be used to find, get or remove an
attribute.
7. page object: The manner we use the keyword this for current object, page
object is used to refer to the current translated servlet class.
8. exception: The exception object represents all errors and exceptions which is
accessed by the respective jsp. The exception implicit object is of
type java.lang.Throwable.
9. out: This is the PrintWriter object where methods like print and println help
for displaying the content to the client.
In this article, two of the main objects which are request and response are
discussed
request Object
The JSP request is an implicit object which is provided by HttpServletRequest. In
the servlet, we have to first import javax.servlet.http.HttpServletRequest then we
have to create its object for taking input from any HTML form as.
Syntax :
import javax.servlet.http.HttpServletRequest;
html
<html>
<head>
</head>
<body>
</form>
</body>
</html>
response object
This is the HttpServletResponse object associated with the response to the client.
The response object also defines the interfaces that deal with creating new HTTP
headers. Through this object the JSP programmer can add new cookies or date
stamps, HTTP status codes, etc.
html
pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
<%
String name=request.getParameter("username");
out.print("Welcome "+ name);
%>
</body>
</html>
In JSP the response object is implicitly defined, so you don’t have to create an
object. JSP response object is created by the web container for each request of the
client. It basically is used for redirecting to any other resource.
In the below example we use the response object to send the user on
Geeksforgeeks homepage.
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>GeeksforGeeks</title>
</head>
<body>
<%
//below line in JSP redirect you to geeksforgeeks page
response.sendRedirect("geeksforgeeks.org");
%>
</body>
</html>
Servlets are difficult to code than JSP. In another way, we can say, JSP is the
replacement for Servlets.
In Servlets, both static code and dynamic code are put together. In JSP, they are
separated.
The objects of PrintWriter, ServletConfig, ServletContext, HttpSession and
RequestDispatcher etc. are created by the Programmer in Servlets. But in JSP,
they are built-in and are known as implicit objects.
Disadvantage :
JavaBeans
A JavaBean is a specially constructed Java class written in the Java and coded
according to the JavaBeans API specifications.
Following are the unique characteristics that distinguish a JavaBean from other
Java classes −
A JavaBean property is a named attribute that can be accessed by the user of the
object. The attribute can be of any Java data type, including the classes that you
define.
A JavaBean property may be read, write, read only, or write only. JavaBean
properties are accessed through two methods in the JavaBean's implementation
class −
setPropertyName()
2 For example, if property name is firstName, your method name would
be setFirstName() to write that property. This method is called mutator.
JavaBeans Example
package com.tutorialspoint;
public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}
Accessing JavaBeans
The useBean action declares a JavaBean for use in a JSP. Once declared, the
bean becomes a scripting variable that can be accessed by both scripting elements
and other custom tags used in the JSP. The full syntax for the useBean tag is as
follows −
Here values for the scope attribute can be a page, request, session or application
based on your requirement. The value of the id attribute may be any value as a
long as it is a unique name among other useBean declarations in the same JSP.
<html>
<head>
<title>useBean Example</title>
</head>
<body>
<jsp:useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>
Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to
access the get methods and the <jsp:setProperty/> action to access the set
methods. Here is the full syntax −
Following example shows how to access the data using the above syntax −
<html>
<head>
<title>get and set properties Example</title>
</head>
<body>
<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">
<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>
<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>
<jsp:setProperty name = "students" property = "age" value = "10"/>
</jsp:useBean>
<p>Student First Name:
<jsp:getProperty name = "students" property = "firstName"/>
</p>
<p>Student Age:
<jsp:getProperty name = "students" property = "age"/>
</p>
</body>
</html>
Student Age: 20
Connection to Database in JSP
A JSP database connection is interfacing Java Server Pages with a database using
JDBC (Java Database Connectivity). JDBC serves as a crucial bridge, enabling
your JSP pages to interact with a database. It uses a Java API that manages
database interactions via Java methods and SQL queries. This functionality is
critical to creating dynamic web applications that require data storage, retrieval,
and manipulation.
Begin by importing the necessary Java SQL packages in your JSP file. These
packages contain the classes and interfaces required for database operations.
JDBC drivers are specific to your database, such as MySQL or Oracle. Loading the
driver is your first step in establishing a connection.
Copy Code<%
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
%>
Establishing Connection
Copy Code<%
Connection con = null;
try {
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/DatabaseName",
"username", "password");
// Add your database operations here
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
%>
Creating Statements
With the connection established, create SQL statements to interact with your
database. This step involves preparing your SQL commands for execution.
Utilize the created statements for data retrieval, updates, or other SQL operations.
Closing your database connection, statement, and result set after use is vital. This
practice prevents memory leaks and other issues, ensuring resource efficiency.
Copy Coders.close();
stmt.close();
con.close();
Code Example
Here's a straightforward example demonstrating how to retrieve and display data
from a 'users' database table:
try {
// Load JDBC Driver
Class.forName("com.mysql.jdbc.Driver");
// Establish Connection
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/DatabaseName", "username", "password");
// Create Statement
stmt = con.createStatement();
// Execute Query
rs = stmt.executeQuery("SELECT * FROM users");
across
as
Pages)
webthey
applications
Session multiple
provides
navigateHTTP
trackingvarious
across
to
is associate
essential
requests,
different
mechanisms
in
requests
web
which
pages
development
towith
are
ofimplement
astateless
web application.
specifictosession
by
users
maintain
nature.
and
tracking,
JSP
retain
user
(JavaServer
state
user
allowing
and
datadata
JSP supports multiple methods for session tracking, including:
Cookies: A small piece of data stored on the client side by the browser. The
server sends a cookie to the client, which is included in future requests from the
client. Cookies are commonly used for session tracking as they can persist
information even after the user closes the browser.
URL Rewriting: Involves appending session information directly to the URL.
This method is useful when the client has disabled cookies. The JSP session ID
can be added to the URL using the response.encodeURL() method.
Hidden Form Fields: Form elements that are not visible to the user but carry
session data from one request to another. These fields can be included in HTML
forms and are used to pass session information when submitting forms.
Implementation of Session Tracking in JSP
We will create a JSP project for session tracking. This example will demonstrate a
simple login system where the user's session is tracked across multiple pages.
Step 1: Create the Dynamic Web Project
Create a new Dynamic Web Project using Eclipse. After creating the project, the
file structure should look like the following:
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
/**
* Handles POST requests for user login.
*
* @param request HttpServletRequest object containing request details
* @param response HttpServletResponse object to send response
* @throws ServletException If an error occurs during request processing
* @throws IOException If an I/O error occurs
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
/**
* Handles GET requests to the dashboard page.
*
* @param request HttpServletRequest object containing request details
* @param response HttpServletResponse object to send response
* @throws ServletException If an error occurs during request processing
* @throws IOException If an I/O error occurs
*/
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session == null || session.getAttribute("username") == null) {
response.sendRedirect("login.jsp");
} else {
request.getRequestDispatcher("dashboard.jsp").forward(request, response);
}
}
}
This servlet handles requests to the dashboard page. It checks if a session exists
and if the username is set. If not, it redirects to the login page; otherwise, it
forwards the request to the dashboard page.
Step 4: Create the LogoutServlet Class
File: LogoutServlet.java:
package com.example;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
/**
* Handles POST requests to log out the user.
*
* @param request HttpServletRequest object containing request details
* @param response HttpServletResponse object to send response
* @throws ServletException If an error occurs during request processing
* @throws IOException If an I/O error occurs
*/
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
HttpSession session = request.getSession(false);
if (session != null) {
session.invalidate();
}
response.sendRedirect("logout.jsp");
}
}
This servlet handles logout requests. It invalidates the session and redirects to the
logout page.
Step 5: Create the Login Page
File: login.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h2>Login</h2>
<form action="login" method="post">
<input type="text" name="username" placeholder="Enter Username"
required>
<input type="password" name="password" placeholder="Enter Password"
required>
<input type="submit" value="Login"> <!-- Button text is "Login" -->
</form>
</div>
</body>
</html>
This JSP page provides a form for users to enter their username and password. The
form submits a POST request to the LoginServlet.
Step 6: Create the Dashboard Page
File: dashboard.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page session="true" %>
<%
String username = (String) session.getAttribute("username");
if (username == null) {
response.sendRedirect("login.jsp");
return;
}
%>
<html>
<head>
<title>Dashboard</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h2>Welcome, <%= username %>!</h2>
<p>This is your dashboard.</p>
<form action="logout" method="post">
<input type="submit" value="Logout">
</form>
</div>
</body>
</html>
This JSP page displays a welcome message to the logged-in user. If the session is
invalid or the username is not set, it redirects to the login page. Otherwise, it shows
the dashboard and provides a logout button.
Step 7: Create the Logout Page
File: logout.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Logout</title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="container">
<h2>You have successfully logged out.</h2>
<a href="login.jsp">Login again</a>
</div>
</body>
</html>
This JSP page informs the user that they have successfully logged out and provides
a link to log in again.
Step 8: Create the StyleSheet
File: style.css:
body {
background-color: #f0f8f7;
font-family: Arial, sans-serif;
}
.container {
width: 30%;
margin: 100px auto;
background-color: #d8f3dc;
border-radius: 10px;
padding: 20px;
box-shadow: 0px 0px 10px #333;
}
h2 {
color: #40916c;
text-align: center;
}
input[type="submit"] {
background-color: #40916c;
color: #fff;
border: none;
}
This CSS file styles the JSP pages. It includes styling for the background,
container, headers, and form elements.
Step 9: Configure the web.xml
File: web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="https://jakarta.ee/xml/ns/jakartaee"
xsi:schemaLocation="https://jakarta.ee/xml/ns/jakartaee
https://jakarta.ee/xml/ns/jakartaee/web-app_6_0.xsd" id="WebApp_ID"
version="6.0">
<display-name>SessionTrackingExample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.jsp</welcome-file>
<welcome-file>default.htm</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.example.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>DashboardServlet</servlet-name>
<servlet-class>com.example.DashboardServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DashboardServlet</servlet-name>
<url-pattern>/dashboard</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.example.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout> <!-- Timeout in minutes -->
</session-config>
</web-app>
This configuration file maps the servlets to their respective URL patterns. It tells
the server which servlet to use for each URL pattern.
Step 10: Run the Project
Output:
1. Login Page:
2. Dashboard:
3. Logout page: