WebApp Material 2 2
WebApp Material 2 2
DEVELOPMENT
Dineshkumar Thangavel
QISCET
Skill Development Course
Web Application Development 1
Table of Content
4 JDBC: MySQL 21
7 Servlet Collaboration 30
function example() {
var y = 5; // function-scoped variable
console.log(x); // accessible inside the function
}
if (true) {
let a = 2; // block-scoped variable
console.log(a); // accessible inside the block
}
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!);
}
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.
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”
10. Array:
- An ordered list of values.
- Example: “let numbers = [1, 2, 3, 4, 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:
2. Array Constructor:
Accessing Elements:
Modifying Elements:
let fruits = ['Apple', 'Banana', 'Orange'];
fruits[1] = 'Grapes';
console.log(fruits); // Output: ['Apple', 'Grapes', 'Orange']
console.log(fruit);
});
Array Methods:
1. concat:
- Combines two or more arrays.
console.log(fruits.indexOf('Banana')); // Output: 1
console.log(fruits.lastIndexOf('Banana')); // Output: 1
3. slice:
- Extracts a portion of an array.
4. splice:
- Changes the contents of an array by removing or replacing elements.
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.
6. Template Literals:
Template literals allow you to embed expressions within strings using backticks .
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).
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 + '!');
}
// 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;
}
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;
}
Here are some fundamental concepts and operations related to JavaScript DOM manipulation:
Accessing Elements:
1. getElementById:
- Retrieves an element by its “id” attribute.
2. getElementsByClassName:
- Retrieves a collection of elements by their class name.
3. getElementsByTagName:
- Retrieves a collection of elements by their tag name.
4. querySelector:
- Retrieves the first element that matches a specified CSS selector.
5. querySelectorAll:
- Retrieves a NodeList of elements that match a specified CSS selector.
Manipulating Elements:
6. innerHTML:
- Gets or sets the HTML content of an element.
7. textContent:
- Gets or sets the text content of an element.
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.
14. document.createTextNode:
- Creates a new text node.
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.
person.gender = 'Male';
person['isStudent'] = 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!');
}
};
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.
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);
}
};
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.
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.
Person.prototype.sayHello = function() {
console.log('Hello, ' + this.firstName + ' ' + this.lastName);
};
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.
Student.prototype = Object.create(Person.prototype);
Student.prototype.getStudentInfo = function() {
console.log(this.firstName + ' ' + this.lastName + ', Student ID: ' + this.studentId);
};
this.getFuel = function() {
return fuel;
};
this.drive = function() {
console.log('Driving ' + make + ' ' + model);
fuel -= 10;
};
}
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');
};
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
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
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.
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.
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.
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.
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
} catch (SQLException e) {
e.printStackTrace();
}
Web Application Development 25
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
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
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.
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
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>
<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.
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;
Servlet2:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
<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
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 (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. Standard
2. XML
<jsp: declaration>
Declaration <%! %>
</jsp: declaration>
<jsp: expression>
Expression <% = %>
</jsp: expression>
<jsp: scriptlet>
Scriptlets <% %>
</jsp: scriptlet>
Web Application Development 35
These comments are not included in servlet source code during translation phase; they do not appear in
the HTTP response.
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.
• <% @ page %> defines page dependent properties such as language session error page.
• <% @ page %> defines page-dependent properties such as language session error 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 taglib directive is used to define the tag library that the current JSP page uses.
• <%@ include %> defines the file to be included and the source code.
Scriptlet tag implements the _jspService method functionality by writing script/Java code.