[go: up one dir, main page]

0% found this document useful (0 votes)
14 views36 pages

WebApp Material 2 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views36 pages

WebApp Material 2 2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

WEB APPLICATION

DEVELOPMENT
Dineshkumar Thangavel

QISCET
Skill Development Course
Web Application Development 1

Table of Content

S.NO TOPIC PAGE REMARKS


JavaScript: Variables, Arrays, String,
1 2
Function

2 JavaScript: DOM, Object, OOPs 11

Maven: Introduction, Build Cycle, Folder


3 18
Structure

4 JDBC: MySQL 21

Servlet: Introduction, Life Cycle,


5 26
Configuration

6 Servlet Context and Configuration 29

7 Servlet Collaboration 30

JSP: Introduction, Elements, Implicit


8 33
Object
Web Application Development 2

JavaScript: Variables, Array, String, Function


1.1 Variables
 In JavaScript, variables are used to store and manage data in a program.
 They are like containers that hold values or references to values.
 You can declare variables using various keywords such as var, let, and const.
 The choice of keyword affects the variables scope and mutability.

Here are the main ways to declare variables in JavaScript:

1. var (function-scoped or globally-scoped):


- Variables declared with var are function-scoped if declared inside a function or globally-scoped if declared
outside any function.
- They can be reassigned and updated.

var x = 10; // globally-scoped variable

function example() {
var y = 5; // function-scoped variable
console.log(x); // accessible inside the function
}

console.log(x); // accessible outside the function


console.log(y); // ReferenceError - y is not defined outside the function

2. let (block-scoped, reassignable):


- Variables declared with let are block-scoped, meaning their scope is limited to the block (enclosed by curly
braces) in which they are defined.
- They can be reassigned but not re-declared within the same block.

if (true) {
let a = 2; // block-scoped variable
console.log(a); // accessible inside the block
}

console.log(a); // ReferenceError - a is not defined outside the block

3. const (block-scoped, immutable):


- Variables declared with const are also block-scoped.
- They cannot be reassigned after their initial assignment.

const PI = 3.14; // block-scoped constant variable

PI = 3.14159; // TypeError - cannot reassign a constant variable


Web Application Development 3

Variables can store different types of values, including numbers, strings, booleans, objects, arrays, and functions.
Here an example with various types of variables:

// Number
let age = 25;

// String
let name = "John";

// Boolean
let isStudent = true;

// Array
let fruits = [apple, banana, orange];

// Object
let person = {
firstName: John,
lastName: Doe
};

// Function
function greet() {
console.log(Hello!);
}

// Using the variables


console.log(age);
console.log(name);
console.log(isStudent);
console.log(fruits[0]);
console.log(person.firstName + + person.lastName);
greet();
Web Application Development 4

1.2 Datatypes
JavaScript is a loosely typed language, which means that variables can hold values of any data type without explicitly
specifying the data type. However, JavaScript has several data types that can be broadly categorized into two
groups: primitive data types and objects.

Primitive Data Types:


1. Number:
- Represents numeric values.
- Example: “let num = 42;”

2. String:
- Represents textual data.
- Example: “let text = "Hello, World!";”

3. Boolean:
- Represents either “true” or “false”.
- Example: “let isTrue = true;”

4. Undefined:
- Represents an uninitialized or undefined value.
- Example: “let variable; // undefined”

5. Null:
- Represents the absence of any object value.
- Example: “let noValue = null;”

6. Symbol:
- Introduced in ECMAScript 6 (ES6).
- Represents a unique identifier.
- Example: “let symbol = Symbol('unique');”

Special Values:
7. NaN (Not a Number):
- Represents a value that is not a legal number.
- Example: “let result = "abc" / 2; // NaN”

8. Infinity and -Infinity:


- Represents positive and negative infinity.
- Example: “let positiveInfinity = Infinity;”

Objects (Reference Types):


9. Object:
- A collection of key-value pairs.
- Example: “let person = { name: "John", age: 30 };”

10. Array:
- An ordered list of values.
- Example: “let numbers = [1, 2, 3, 4, 5];”

Understanding Data Types:


You can use the “typeof” operator to check the data type of a variable:

let example = 42;


console.log(typeof example); // Output: "number"
Web Application Development 5

1.3 Array
In JavaScript, an array is a data structure that allows you to store multiple values in a single variable. Each value in
an array is called an element, and elements can be of any data type, including numbers, strings, objects, or other
arrays. Here's a basic overview of JavaScript arrays and some common operations you can perform:

Creating Arrays:

1. Literal Syntax:

let fruits = ['Apple', 'Banana', 'Orange'];

2. Array Constructor:

let numbers = new Array(1, 2, 3, 4, 5);

Accessing Elements:

let fruits = ['Apple', 'Banana', 'Orange'];

console.log(fruits[0]); // Output: 'Apple'


console.log(fruits[1]); // Output: 'Banana'
console.log(fruits[2]); // Output: 'Orange'
console.log(fruits.length); // Output: 3

Modifying Elements:
let fruits = ['Apple', 'Banana', 'Orange'];

fruits[1] = 'Grapes';
console.log(fruits); // Output: ['Apple', 'Grapes', 'Orange']

Adding and Removing Elements:

let fruits = ['Apple', 'Banana', 'Orange'];

// Add an element to the end


fruits.push('Strawberry');
console.log(fruits); // Output: ['Apple', 'Banana', 'Orange', 'Strawberry']

// Remove the last element


fruits.pop();
console.log(fruits); // Output: ['Apple', 'Banana', 'Orange']

Iterating Over an Array:

let fruits = ['Apple', 'Banana', 'Orange'];

// Using a for loop


for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

// Using forEach method


fruits.forEach(function(fruit) {
Web Application Development 6

console.log(fruit);
});

Array Methods:

1. concat:
- Combines two or more arrays.

let vegetables = ['Carrot', 'Broccoli'];


let combined = fruits.concat(vegetables);
console.log(combined);

2. indexOf and lastIndexOf:


- Returns the index of the first/last occurrence of a specified element.

console.log(fruits.indexOf('Banana')); // Output: 1
console.log(fruits.lastIndexOf('Banana')); // Output: 1

3. slice:
- Extracts a portion of an array.

let slicedFruits = fruits.slice(1, 3);


console.log(slicedFruits); // Output: ['Banana', 'Orange']

4. splice:
- Changes the contents of an array by removing or replacing elements.

fruits.splice(1, 1, 'Grapes', 'Kiwi');


console.log(fruits); // Output: ['Apple', 'Grapes', 'Kiwi', 'Orange']
Web Application Development 7

1.4 String

In JavaScript, a string is a sequence of characters enclosed in single (') or double (‘‘) quotes. Strings are a
fundamental data type and are used to represent textual data. Here are some basic operations and features related
to strings in JavaScript:

1. String Declaration:
let strSingleQuotes = 'Hello, World!';
let strDoubleQuotes = "Hello, World!";

Both single and double quotes can be used to define strings, and they can be used interchangeably.

2. String Concatenation:
You can concatenate strings using the ‘+’ operator.
let firstName = 'John';
let lastName = 'Doe';
let fullName = firstName + ' ' + lastName; // "John Doe"

3. String Length:
The ‘length’ property is used to get the length of a string.
let greeting = 'Hello';
let greetingLength = greeting.length; // 5

4. Accessing Characters:
Individual characters in a string can be accessed using bracket notation and the index.
let message = 'Hello';
let firstChar = message[0]; // 'H'

5. String Methods:
JavaScript provides various methods for manipulating strings. Some common methods include:
- ‘toUpperCase()’ and ‘toLowerCase()’ to change the case.
- ‘charAt(index)’ to get the character at a specific index.
- ‘slice(start, end)’ to extract a portion of a string.
- ‘indexOf(substring)’ to find the index of a substring.
- ‘replace(oldSubstring, newSubstring)’ to replace text.
- ‘split(separator)’ to split a string into an array based on a separator.

let text = 'JavaScript is awesome!';


let upperCaseText = text.toUpperCase();
let lowerCaseText = text.toLowerCase();
let firstCharacter = text.charAt(0);
let slicedText = text.slice(0, 10);
let indexOfIs = text.indexOf('is');
let replacedText = text.replace('awesome', 'amazing');
let splitText = text.split(' ');

6. Template Literals:
Template literals allow you to embed expressions within strings using backticks .

let name = 'John';


let greetingMessage = ‘Hello, ${name}!’;
Web Application Development 8

Template literals support multiline strings and make string interpolation more convenient.

7. Escape Characters:
Special characters in strings are represented using escape characters (e.g., ‘\n’ for a newline, ‘\"‘ for a double
quote).

let multilineString = 'This is a multiline\nstring.';


let escapedQuote = 'He said, "Hello!"';
Web Application Development 9

1.5 Function:

In JavaScript, functions are blocks of reusable code that can be defined and executed when needed. Functions can
take parameters (input), perform a set of actions, and optionally return a value. Here's an overview of how functions
work in JavaScript:

1. Function Declaration:
You can declare a function using the function keyword followed by a name, a list of parameters enclosed in
parentheses, and a block of code enclosed in curly braces.

// Function declaration
function sayHello(name) {
console.log('Hello, ' + name + '!');
}

2. Function Invocation (Calling):’


To execute a function, you use its name followed by parentheses, passing any required arguments.

// Function invocation
sayHello('John'); // Output: Hello, John!

3. Function Parameters:’
Functions can take parameters, which act as variables within the function. You specify parameters when defining
the function and provide arguments when calling it.

function addNumbers(a, b) {
return a + b;
}

let result = addNumbers(5, 3); // Result: 8

4. Return Statement:
Functions can return a value using the return keyword. If no return statement is used, the function returns
undefined by default.

function multiply(a, b) {
return a * b;
}

let product = multiply(4, 6); // Result: 24

5. Anonymous Functions (Function Expressions):


Functions can also be created without a name and assigned to a variable. These are often called anonymous
functions or function expressions.

let divide = function(a, b) {


return a / b;
};
Web Application Development 10

let quotient = divide(8, 2); // Result: 4

6. Arrow Functions (ES6+):’


Arrow functions provide a more concise syntax for defining functions, especially for short, one-line expressions.

let square = (x) => x * x;

let squaredValue = square(5); // Result: 25

7. Default Parameters (ES6+):’


You can specify default values for function parameters, which are used if the corresponding argument is not
provided.

function greet(name = 'Guest') {


console.log('Hello, ' + name + '!');
}

greet(); // Output: Hello, Guest!


greet('John'); // Output: Hello, John!
Web Application Development 11

JavaScript: DOM, Object, OOPs


2.1 Document Object Model (DOM)
The DOM (Document Object Model) in JavaScript represents the structure of an HTML or XML document as a tree-
like structure, where each node corresponds to an element, attribute, or piece of text in the document. JavaScript
can be used to manipulate the DOM, enabling dynamic changes to the content, structure, and style of a web page.

Here are some fundamental concepts and operations related to JavaScript DOM manipulation:

Accessing Elements:

1. getElementById:
- Retrieves an element by its “id” attribute.

let element = document.getElementById('myElementId');

2. getElementsByClassName:
- Retrieves a collection of elements by their class name.

let elements = document.getElementsByClassName('myClassName');

3. getElementsByTagName:
- Retrieves a collection of elements by their tag name.

let elements = document.getElementsByTagName('div');

4. querySelector:
- Retrieves the first element that matches a specified CSS selector.

let element = document.querySelector('#myElementId');

5. querySelectorAll:
- Retrieves a NodeList of elements that match a specified CSS selector.

let elements = document.querySelectorAll('.myClassName');

Manipulating Elements:

6. innerHTML:
- Gets or sets the HTML content of an element.

element.innerHTML = 'New content';

7. textContent:
- Gets or sets the text content of an element.

element.textContent = 'New text content';

8. setAttribute:
- Sets the value of an attribute on an element.

element.setAttribute('class', 'newClass');
Web Application Development 12

9. appendChild:
- Appends a child node to an element.

parentElement.appendChild(newChildElement);

10. removeChild:
- Removes a child node from an element.

parentElement.removeChild(childElement);

Event Handling:

11. addEventListener:
- Attaches an event listener to an element.

element.addEventListener('click', function() {
console.log('Element clicked!');
});

Style Manipulation:

12. style:
- Accessing or modifying the inline style of an element.

element.style.color = 'red';

Document Structure:

13. document.createElement:
- Creates a new element.

let newElement = document.createElement('div');

14. document.createTextNode:
- Creates a new text node.

let newText = document.createTextNode('Hello, World!');

15. document.body:
- Accesses the “<body>“ element of the document.
Web Application Development 13

2.2 Object

In JavaScript, an object is a complex data type that allows you to store and organize data using key-value pairs.
Objects are a fundamental part of the language and are used to represent real-world entities or concepts. Here's
an overview of creating and working with objects in JavaScript:

1. Object Declaration:
You can create an object using curly braces ‘{}’ and defining key-value pairs inside. The keys are strings or identifiers,
and the values can be any valid JavaScript data type, including numbers, strings, booleans, arrays, functions, or even
other objects.

// Object with properties


let person = {
firstName: 'John',
lastName: 'Doe',
age: 30,
isStudent: false,
sayHello: function() {
console.log('Hello!');
}
};

2. Accessing Object Properties:


You can access the values of object properties using dot notation or square bracket notation.

console.log(person.firstName); // Output: John


console.log(person['lastName']); // Output: Doe

3. Adding and Modifying Properties:


You can add new properties or modify existing ones after an object is created.

person.gender = 'Male';
person['isStudent'] = true;

console.log(person.gender); // Output: Male


console.log(person.isStudent); // Output: true

4. Object Methods:
Objects can contain functions as properties, known as methods.

let car = {
make: 'Toyota',
model: 'Camry',
start: function() {
console.log('Engine started!');
}
};

car.start(); // Output: Engine started!


Web Application Development 14

5. Object Destructuring (ES6+):


Object destructuring allows you to extract properties from an object and assign them to variables.

let { firstName, age } = person;

console.log(firstName, age); // Output: John 30

6. Nested Objects:
Objects can contain other objects, creating a nested structure.

let address = {
street: '123 Main St',
city: 'Cityville',
zip: '12345'
};

let user = {
username: 'jsmith',
personalInfo: person,
userAddress: address
};

7. Object Iteration:
You can iterate over the properties of an object using ‘for...in’ loop or ‘Object.keys()’, ‘Object.values()’, or
‘Object.entries()’ methods.

for (let key in person) {


console.log(key + ': ' + person[key]);
}
Web Application Development 15

2.3 OOPs Concepts

JavaScript supports object-oriented programming (OOP) concepts, allowing you to create and work with objects.
Here are some fundamental OOP concepts in JavaScript:

1. Objects:
- In JavaScript, an object is a collection of key-value pairs.
- Objects can contain properties and methods.
- Properties are variables associated with the object, and methods are functions associated with the object.

let person = {
firstName: 'John',
lastName: 'Doe',
sayHello: function() {
console.log('Hello, ' + this.firstName + ' ' + this.lastName);
}
};

person.sayHello(); // Output: Hello, John Doe

2. Constructor Functions:
- Constructor functions are used to create instances (objects) with similar properties and methods.
- They are typically named with an initial uppercase letter.

function Person(firstName, lastName) {


this.firstName = firstName;
this.lastName = lastName;
this.sayHello = function() {
console.log('Hello, ' + this.firstName + ' ' + this.lastName);
};
}

let person1 = new Person('John', 'Doe');


person1.sayHello(); // Output: Hello, John Doe

let person2 = new Person('Jane', 'Smith');


person2.sayHello(); // Output: Hello, Jane Smith

3. Prototypes:
- Prototypes are used to add properties and methods to all instances of a constructor function.
- They allow for the efficient sharing of common functionality among objects.

function Person(firstName, lastName) {


this.firstName = firstName;
this.lastName = lastName;
}

Person.prototype.sayHello = function() {
console.log('Hello, ' + this.firstName + ' ' + this.lastName);
};

let person1 = new Person('John', 'Doe');


person1.sayHello(); // Output: Hello, John Doe
Web Application Development 16

let person2 = new Person('Jane', 'Smith');


person2.sayHello(); // Output: Hello, Jane Smith

4. Inheritance:
- JavaScript uses prototypal inheritance, where objects can inherit properties and methods from other
objects.
- Object instances inherit from their constructor function's prototype.

function Student(firstName, lastName, studentId) {


Person.call(this, firstName, lastName);
this.studentId = studentId;
}

Student.prototype = Object.create(Person.prototype);

Student.prototype.getStudentInfo = function() {
console.log(this.firstName + ' ' + this.lastName + ', Student ID: ' + this.studentId);
};

let student = new Student('Alice', 'Johnson', 'S12345');


student.sayHello(); // Output: Hello, Alice Johnson
student.getStudentInfo(); // Output: Alice Johnson, Student ID: S12345

5. Encapsulation and Abstraction:


- Encapsulation involves bundling data (properties) and methods that operate on that data into a single unit
(object).
- Abstraction involves hiding the complexity of an object and exposing only what is necessary.

function Car(make, model) {


let fuel = 100; // Encapsulated variable

this.getFuel = function() {
return fuel;
};

this.drive = function() {
console.log('Driving ' + make + ' ' + model);
fuel -= 10;
};
}

let myCar = new Car('Toyota', 'Camry');


console.log(myCar.getFuel()); // Output: 100
myCar.drive();
console.log(myCar.getFuel()); // Output: 90

6. Polymorphism:
- Polymorphism allows objects to be treated as instances of their parent type.
- Objects can share a common interface (properties or methods), and different objects can implement that
interface in different ways.

function Animal(name) {
this.name = name;
}
Web Application Development 17

Animal.prototype.speak = function() {
console.log('Animal speaks');
};

function Dog(name) {
Animal.call(this, name);
}

Dog.prototype = Object.create(Animal.prototype);

Dog.prototype.speak = function() {
console.log(this.name + ' barks');
};

function Cat(name) {
Animal.call(this, name);
}

Cat.prototype = Object.create(Animal.prototype);

Cat.prototype.speak = function() {
console.log(this.name + ' meows');
};

let dog = new Dog('Buddy');


let cat = new Cat('Whiskers');

dog.speak(); // Output: Buddy barks


cat.speak(); // Output: Whiskers meows
Web Application Development 18

Maven: Introduction, Build Cycle, Folder


Structure
1.1 Introduction
 Maven is a powerful project management tool that is based on POM (project object model). It is used
for projects build, dependency and documentation.
 It simplifies the build process like ANT. But it is too much advanced than ANT.
 Maven is a popular open-source build tool that the Apache Group developed for building, publishing,
and deploying several projects.
 Maven is based on Project Object Model (POM) and focuses on simplification and standardization of the
building process.
 Current version – Apache Maven 3.9.2

1.2 POM.xml
 POM stands for Project Object Model. It is fundamental unit of work in Maven. It is an XML file that resides
in the base directory of the project as pom.xml.
 The POM contains information about the project and various configuration detail used by Maven to build
the project(s).
 Some of the configuration that can be specified in the POM are following −
o project dependencies
o plugins
o goals
o build profiles

1.3 Architecture
Web Application Development 19

1.4 How it Works?


 The first step refers to configuring Maven, which is stored in a pom.xml.file
 The POM file includes all of the configurations that Maven needs. The second step is to download the
dependencies defined in pom.xml into the local repository from the central repository
 After the user starts working in Maven, the tool provides various default settings, so there is no need to
add every configuration in the pom.xml

2.1 Build Cycle

 Maven follows a build lifecycle consisting of phases. Each phase represents a stage in the lifecycle, and
Maven plugins are executed at these phases.
 The standard Maven build lifecycle includes the following phases:
 validate: Check if the project is correct and all necessary information is available.
 compile: Compile the source code of the project.
 test: Test compiled source code using a suitable testing framework.
 package: Package compiled code into a distributable format, such as a JAR or WAR.
 verify: Run checks on the package to ensure quality.
 install: Install the package into the local repository for use as a dependency in other projects.
 deploy: Copy the final package to the remote repository for sharing with other developers and
projects.
Web Application Development 20

3.1 Folder Structure


Web Application Development 21

JDBC: MySQL
1.1 Introduction
 JDBC is the application programming interface(API) that allows Java program to access database
management systems.
 The enterprise data stored in a relational database(RDB) can be accessed with the help of JDBC APIs.
 DBC is an API(Application programming interface) used in java programming to interact with
databases. The classes and interfaces of JDBC allow the application to send requests made by users to the
specified database.
 JDBC API consists of a set of interfaces and classes written in the Java Programming language.

1.2 Uses
 Connects database to Java application
 Works on queries like create and update to the database
 Retrieves the results received from the database in respond to the query
 JDBC is platform and database independent

2.1 Architecture
Web Application Development 22

2.2 Components
 JDBC API
 JDBC Driver Manager
 JDBC Test suite
 JDBC Drivers

2.3 Drivers

JDBC - ODBC
• The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver
converts JDBC method calls into the ODBC function calls.

• It is not written entirely in java.

• This driver software is built-in with JDK so no need to install separately.

• It is a database independent driver.

Native API
• The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls
into native calls of the database API. It is not written entirely in java.

• Driver needs to be installed separately in individual client machines

• The Vendor client library needs to be installed on client machine.

Network Protocol
• The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. It is fully written in java.

• Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to
be done in the middle tier.

Thin Driver
• Type-4 driver is also called native protocol driver. This driver interact directly with database. It does not
require any native database library, that is why it is also known as Thin Driver.

• It is fully written in Java language, hence they are portable drivers.


Web Application Development 23

3.1 JDBC Interfaces and Classes

Interface:
 Driver interface
o The JDBC Driver interface provided implementations of the abstract classes such
as java.sql.Connection, Statement, PreparedStatement, Driver, etc. provided by the JDBC API.
 Connection interface
o The connection interface is used to create a connection with the
database. getConnection() method of DriverManager class of the Connection interface is used to
get a Connection object.
 Statement interface
o The Statement interface provides methods to execute SQL queries on the
database. executeQuery(), executeUpdate() methods of the Statement interface are used to run
SQL queries on the database.
 ResultSet interface
o ResultSet interface is used to store and display the result obtained by executing a SQL query on
the database. executeQuery() method of statement interface returns a resultset object.
Web Application Development 24

Classes
 DriverManager class
o DriverManager class is a member of the java.sql package. It is used to establish a connection
between the database and its driver.
 Blob class
o A java.sql.Blob is a binary large object that can store large amounts of binary data, such as
images or other types of files. Fields defined as TEXT also hold large amounts of data.
 Clob class
o The java.sql.Clob interface of the JDBC API represents the CLOB datatype. Since the Clob object in
JDBC is implemented using an SQL locator, it holds a logical pointer to the SQL CLOB (not the
data).
 Types class
o Type class defined and store constants that are used to identify generic SQL types also known as
JDBC types.

4.1 Working with JDBC

Step 1: Import Package


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.Statement;

import java.sql.ResultSet;

import java.sql.SQLException;

Step 2: Load the drive


Class.forName("com.mysql.cj.jdbc.Driver");

Step 3: Create the connection


String jdbcURL = "jdbc:mysql://localhost:3306/your_database";

String username = "your_username";

String password = "your_password";

try (Connection connection = DriverManager.getConnection(jdbcURL, username, password)) {

// Database connection established

} catch (SQLException e) {

e.printStackTrace();

}
Web Application Development 25

Step 4: Create Query


String selectQuery = "SELECT * FROM your_table";

Step 5: Create Statement


Statement statement = connection.createStatement()) {

Step 6: Execute the Statement


statement.executeQuery(selectQuery)

Step 7: Close the Connection


Web Application Development 26

Servlet: Introduction, Life Cycle, Configuration


1.1 Introduction

 We define a Java Servlet or Jakarta Servlet as the technology to design and deploy dynamic web pages
using the Java Programming Language. It implements a typical servlet in the client-server architecture,
and the Servlet lives on the server-side.
 There are several varieties of interfaces and classes available in the Servlet API. Some of them are as
follows:
o HTTP Servlet
o Generic Servlet
o Servlet Request
o Servlet Response

1.2 Architecture

1.2 Web Container

 A web container is built on top of the Java EE platform, and it implements the Servlet API and the services
required to process HTTP (and other Transmission Control/Internet Protocol [TCP/IP]) requests.
 Java Servlets are components that must exist in a web container. Web container activates the Servlet that
matches the requested URL by calling the service method on an instance of Servlet class.
 Activation of the service method for a given HTTP request is handled in a separate thread within the web
container protocol.
Web Application Development 27

2.1 Servlet: Life Cycle

The Servlet life cycle involves several stages, including loading, instantiation, initialization, servicing, and destroying.
Here's an overview of each stage:

1. Loading:
- The servlet container loads the servlet class into memory during its startup or when the first request is
made to the servlet.
- This involves loading the servlet class bytecode using a ClassLoader.

2. Instantiation:
- After loading the servlet class, the servlet container creates an instance of the servlet using its no-argument
constructor.
- The public no-argument constructor is required in the servlet class for this purpose.

3. Initialization:
- Once the servlet instance is created, the container initializes the servlet by calling its init method.
- The init method is passed a ServletConfig object, which contains configuration information for the servlet.
- The init method is typically used for one-time initialization tasks.

public void init(ServletConfig config) throws ServletException {


// Initialization code
}

4. Servicing:
- After initialization, the servlet is ready to handle client requests.
- The servlet container calls the service method for each incoming request.
- The service method, in turn, dispatches the request to the appropriate HTTP method-specific method (e.g.,
doGet, doPost) for processing.
public void service(ServletRequest request, ServletResponse response) throws ServletException,
IOException {
// Request handling code
}

5. Destroying:
- When the servlet is being taken out of service, the container may call the destroy method to allow the
servlet to release any resources it holds.
- The destroy method is the place to perform cleanup tasks before the servlet is unloaded.
public void destroy() {
// Cleanup code
}
Web Application Development 28

3.1 Servlet Configuration and Deploy


Web Application Development 29

Servlet Context and Configuration


1.1 Servlet Config
- The config object is created by the web container based on the initialization parameters specified in the
deployment descriptor
- One ServletConfig per Servlet
- This parameters available only to that particular servlet

Example:

<servlet>

<servlet-name>login</servlet-name>

<servlet-class>com.Authentication.LoginServlet</servlet-class>

<init-param>

<param-name>a</param-name>

<param-value>10</param-value>

</init-param>

</servlet>

1.3 Servlet Context


- To share application-specific data across independent web components
- One ServletContext per application
- The context object is accessible to all Servlets in web application
- ServletContext object is the runtime representation of the web application
Example:

<context-param>

<param-name>url</param-name>

<param-value>jdbc:mysql://localhost:3306/</param-value>

</context-param>
Web Application Development 30

Servlet Collaboration:
- The Servlet collaboration involves sharing of information among the Servlets.
- Collaborating Servlets is passing the common information that is to be shared directly by one Servlet to
another Servlet of HTML or JSP through various invocations of methods.
- The servlet api provides two interfaces namely:
o javax.servlet.RequestDispatcher
o javax.servlet.http.HttpServletResponse
- These two interfaces include the methods responsible for achieving the objective of sharing information
between servlets.

1.1 Request Dispatcher

In Java servlets, the RequestDispatcher interface is used for forward and include operations. It allows a servlet to
dispatch a request to another resource (servlet, JSP, or HTML file) on the server.

Here's an example of using RequestDispatcher for forwarding a request from one servlet to another:

Assume you have two servlets, Servlet1 and Servlet2, and you want to forward a request from Servlet1 to
Servlet2.

Servlet1:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class Servlet1 extends HttpServlet {


Web Application Development 31

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Some processing logic in Servlet1

// Get the RequestDispatcher for Servlet2


RequestDispatcher dispatcher = request.getRequestDispatcher("/servlet2");

// Forward the request to Servlet2


dispatcher.forward(request, response);
}
}

Servlet2:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class Servlet2 extends HttpServlet {


protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Some processing logic in Servlet2

// Response to the client


response.getWriter().println("Response from Servlet2");
}
}

Deployment Descriptor (web.xml):


Make sure to map both servlets in your web.xml file:

<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>com.example.Servlet1</servlet-class>
</servlet>

<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>com.example.Servlet2</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
Web Application Development 32

1.2 Session Management

 Session Management is a mechanism used by the web container to store session information for a
particular user.
 Session is a conversional state between client and server, and it can consist of multiple requests and
responses between client and server.
 Sessions are used for maintaining user specific state, including persistent objects.
 User Session: It refers to a series of user application interactions that are tracked by the server.
 Types
o Hidden Form Field
o URL Writing
o Cookies
o HttpSession
Web Application Development 33

JSP: Introduction, Elements, Implicit Object


1.1 Introduction

JSP (Java Server Pages) is a text document consisting of Hyper Text Markup Language(HTML), ExtensibleMarkup
language(XML), and JSP elements which can be expressed in standard and XML syntax.

1.2 Architecture

1.3 Difference

JSP SERVLETS
JSP is a web page scripting language that can Servlets are Java programs that are Compiled. They
generate dynamic content. create dynamic pages.

It is easier to code in JSP than in Java Servlet. Involves writing a lot of code

In MVC model, JSP acts as a view. In MVC model, Servlets act as controllers.

Custom tag can directly call Java beans. There is no such custom tag.

JSP is generally preferred when there is not Servlets are best for use when there is more processing
much processing of data required. It runs and manipulation involved. Servlet runs faster than JSP.
slower compared to Servlet as it takes
compilation time to convert into Java Servlet.
Web Application Development 34

1.4 Life Cycle

2.1 JSP Elements

JSP elements in a JSP page can be expressed in two types of syntax:

1. Standard

2. XML

Syntax Elements Standard Syntax XML Syntax

Comments <%-- --%> <-- -->

<jsp: declaration>
Declaration <%! %>
</jsp: declaration>

<% @include %> <jsp: directive include…/>

Directives <% @page %> <jsp: directive page…/>

<% @taglib %> <xmlns: prefix = “tag library url”>

<jsp: expression>
Expression <% = %>
</jsp: expression>

<jsp: scriptlet>
Scriptlets <% %>
</jsp: scriptlet>
Web Application Development 35

2.2 JSP Comment Tag


 JSP comment is used when you are creating a JSP page and want to put in comments about what you are
doing.

 JSP comments are only seen in the JSP page.

 These comments are not included in servlet source code during translation phase; they do not appear in
the HTTP response.

2.3 JSP Declaration Tag


 We can declare a variable or method in JSP inside declaration tag.

 Declaration is made inside the Servlet class but outside the service (or any other method).

 We can declare static member, instance variable, and method inside declaration tag.

2.4 JSP Directive Tag


 This tag is used for special instruction to web container.

 It includes three tags:

• <% @ page %> defines page dependent properties such as language session error page.

• <% @ page %> defines page-dependent properties such as language session error page.

• It defines a number of page-dependent properties that communicate with the web


container.

• Attributes: import, language, extends, session, isThreadSafe, isErrorPage, errorPage,


contentType, autoFlush, buffer

• <%@ taglib %> declares tag library used in the page.

• <%@ taglib %> declares the tag library used in the page.

• JSP allows you to define custom JSP tags that look like HTML or XML tags:

• A tag library is a set of user-defined tags that implements custom behavior.

• A taglib directive is used to define the tag library that the current JSP page uses.

• A JSP page might include several tag libraries.

• <%@ include %> defines file to be included.

• <%@ include %> defines the file to be included and the source code.

• It has an attribute for file.

2.5 JSP Scriptlet Tag


 Scriptlet tag allows you to write java code inside JSP page.

 Scriptlet tag implements the _jspService method functionality by writing script/Java code.

 Everything written inside the scriptlet tag is compiled as Java code.

You might also like