Web Programming: HTML, CSS, JavaScript
Web Programming: HTML, CSS, JavaScript
MONOGRAPH
(Internal Circulation Only)
1
TABLE OF CONTENTS
Layout tags 03
1.13 CSS3 23
1.15 BOOTSTRAP 24
1
CHAPTER 2
ADVANCED JAVASCRIPT
Introduction to java script 37
2.6 ES6 Features: let, const, arrow functions, template literals, destructing, 50
spread/rest operators
2.7 Java scipt ES6 modules 52
2.8.1 Callbacks 53
2.8.2 Promises 53
2.8.3 Asyn/await 54
2.9 Ajax and fetch API: Working with AJAX and API for asynchronous 55
data fetching
CHAPTER 3
SERVLETS
2
3.1 SEVLETS 58
3
3.7.1 Request scope 71
3.11 Performing CRUD (Create, Read, Update, Delete) operation using Servlet 79
with JDBC.
CHAPTER 4
JSP
4.1 Introduction to JSP 88
4
4.10 Expression language in JSP 104
4.14 Performing CRUD (Create, Read, Update, Delete) operation using JSP and 114
Servlet with JDBC.
CHAPTER 5
OBJECT RELATIONAL MAPPING(ORM) WITH HIBERNATE
5.1 OBJECT RELATIONAL MAPPING(ORM): Approaches to ORM 118
5.12 Developing web application by integrating Servlet, JSP and Hibernate. 220
5
CHAPTER 1
1.1 Introd
uction
HTML stands for Hyper Text Markup Language and is the standard markup language used to
create and structure content on the World Wide Web. It is the foundation of every webpage and tells a
web browser how to display text, images, and other multimedia.
Key Concepts
HyperText: Refers to the links (hyperlinks) that connect web pages to one another, allowing
users to navigate between different websites and pages non-linearly.
Markup: Involves using a series of short, simple codes called tags to annotate text and define the
structure of a document. These tags instruct the browser on how to present the content.
Language: A computer system understands and interprets this language to render the specified
content.
1.1.1Characteristics of HTML:
1
1.1.2 STRUCTURE OF HTML:
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
Content
</body>
</html>
An HTML element is a fundamental building block of a web page that defines its structure and content.
It consists of a start tag, content, and an end tag, which together tell a web browser how to display
content.
Anatomy of an HTML Element
2
1.2 LAYOUT TAGS
Layout tags in HTML are used to structure and organize the
content of a web page into different sections. They help developers
design clear, meaningful, and well-structured web pages. Layout tags
improve readability, accessibility, maintainability, and responsive
design of websites. Most layout tags were introduced in HTML5.
1. <header>
2. <nav>
3. <section>
4. <article>
5. <aside>
6. <footer>
3
7. <div>
<nav>
<a href="#">Home</a>
<a href="#">About</a>
</nav>
<section>
<article>
<h2>Article Title</h2>
<p>Article content</p>
</article>
</section>
<aside>
<p>Related information</p>
</aside>
<footer>
<p>© 2025 My Website</p>
</footer>
4
1.3 SEMANTIC TAG
might include tangible items such as business cards, print ads in newspapers or magazines. It can
also include posters, commer
Introduction
Semantic tags in HTML are elements that clearly describe the meaning of the content they contain. These tags
help browsers, developers, and search engines understand the structure and purpose of a webpage. Semantic
tags were introduced mainly in HTML5 to replace excessive use of non-meaningful <div> tags.
Semantic tags are HTML tags that provide logical meaning to the content rather than just defining its
appearance.
5
1.3.2Advantages of Semantic Tags
Improves SEO (Search Engine Optimization)
Better accessibility for screen readers
Clean and meaningful code structure
Easier maintenance and readability
Application tags are HTML elements that support user input, multimedia content, and dynamic web
applications.
6
1.4.4Advantages
Enhances user interaction
Supports modern web applications
Plugin-free multimedia support
Improves user experience
Logical tags in HTML are used to define the meaning and importance of text rather than its appearance. These
tags help browsers and search engines understand the purpose of the content.
Logical tags describe the logical structure and emphasis of text content.
7
1.6 INTRODUCTION TO HTML5 AND ITS ELEMENTS:
HTML5 is the fifth version of Hypertext Markup Language (HTML), a standard language used to structure
webpages.
It defines how content on a webpage should be structured and displayed. Here are some key points of HTML5.
Provides multimedia support by embedding audio and video without plugins.
Adds new form controls like date and email input types.
Enables web storage to store data offline for better performance.
Uses semantic elements such as <header> and <footer> for clearer structure.
Delivers improved performance, especially on mobile devices.
1.6..1 STRUCTURE:
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple HTML Page</title>
</head>
<body>
<header>
<h1>Hello, World!</h1>
</header>
<main>
<p>This is a simple HTML5 page.</p>
</main>
<footer>
<p>@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved</p>
</footer>
</body>
</html>
8
1.7 HTML5 introduced several powerful features and APIs:
New Semantic Elements: These tags improve the structure and meaning of content, making it clearer
for both developers and assistive technologies like screen readers.
o <header>: Defines a header for a document or section.
o <footer>: Defines a footer for a document or section, often containing copyright or contact
information.
o <nav>: Defines a section of navigation links.
o <article>: Defines self-contained content, such as a blog post or news story.
o <section>: Defines a section of a document.
o <aside>: Defines content aside from the main content (e.g., a sidebar).
o <figure> and <figcaption>: Used to group media content (like images or diagrams) with a
caption.
Multimedia Support: Native support for audio and video elements eliminated the need for external
plugins.
o <audio>: Embeds sound content.
o <video>: Embeds video content.
o <source> and <track>: Define multiple media sources and text tracks (subtitles/captions) for
media elements.
Graphics:
o <canvas>: Provides a rectangular area on the webpage for drawing graphics, animations, and
games dynamically using JavaScript.
o SVG (Scalable Vector Graphics): Allows developers to embed vector graphics directly into
HTML, which scales without losing quality.
Form Enhancements: New input types and attributes streamline user input and validation.
o New input types: email, url, date, time, number, range, color, search, and tel.
o Attributes: placeholder (provides a hint in the input field), required (specifies mandatory
fields), and autofocus.
New APIs (Application Programming Interfaces):
o Geolocation: Enables web applications to access a user's physical location with their permission.
o Web Storage: Provides localStorage and sessionStorage for storing large amounts of data
locally within the user's browser, persisting across sessions much better than cookies.
o Drag and Drop: Native support for drag-and-drop functionality, making it easier to build
intuitive user interfaces.
o Web Workers: Allows JavaScript to run in the background thread, preventing web pages from
becoming slow or unresponsive during intensive tasks.
o WebSockets: Enables a full-duplex (two-way) communication channel between the client and
the server for real-time applications.
o
HTML5 Advantages:
HTML5 offers several benefits that enhance modern web development like:
Works on all major browsers and devices (cross-platform).
Lets websites access user location (geolocation).
Supports offline use through Web Storage or AppCache.
Uses semantic tags for cleaner, simpler code.
Optimized for smooth performance on mobile devices.
9
HTML5 Disadvantages:
Despite its strengths, HTML5 comes with some drawbacks:
Older browsers may not support all HTML5 features (browser inconsistencies).
Some older mobile devices struggle with HTML5 (mobile compatibility issues).
Web Storage and similar features can pose security risks if misused.
Advanced APIs introduce complexity for beginners.
IE 8 and below show poor support for HTML5.
10
1.8 CSS: INTODUCTION TO CSS
CSS (Cascading Style Sheets) is a language designed to simplify the process of making web pages
presentable.
It allows you to apply styles to HTML documents by prescribing colors, fonts, spacing, and
positioning.
The main advantages are the separation of content (in HTML) and styling (in CSS) and the
same CSS rules can be used across all pages and not have to be rewritten.
Cascading in CSS refers to the way styles are applied to elements when there are multiple rules
targeting the same element.
It determines which CSS rule takes priority based on a set of principles like importance, specificity,
and source order.
The below diagram explains the working of CSS in a mor e simplified manner.
11
1. Load HTML
2. Parse HTML
4. Load CSS
5. Parse CSS
8. Layout (Reflow)
9. Paint
CSS is used to style and layout web pages, controlling the appearance of HTML elements. It allows
developers to create visually appealing designs and ensure a consistent look across a website.
Inline CSS
External CSS
font-size:50px;
font-style:italic;
text-align:center;">
13
Inline CSS
</p>
OUTPUT:
<!DOCTYPE html>
<html>
<head>
<style>
.main {
text-align: center;
.GFG {
color: #009900;
font-size: 50px;
font-weight: bold;
14
.geeks {
font-style: bold;
font-size: 20px;
</style>
</head>
<body>
<div class="main">
<div class="geeks">
</div>
</div>
</body>
</html>
<html>
<head>
</head>
<body>
<div class="main">
<div id="geeks">
</div>
</div>
</body>
</html>
For quick fixes and small changes that don’t require a separate CSS file.
<html>
<head>
<style>
.initials {
font-size: 40px;
font-weight: bold;
color: #4CAF50;
text-transform: uppercase;
</style>
</head>
<body>
<p class="initials">M.B.</p>
</body>
</html>
17
18
PROPERTY DESCRIPTION
TEXT COLOR Sets the color of the text using color name, hex
value, or RGB value.
19
1.11 LINKS AND LISTS
Links and Lists in CSS are used to enhance the visual appearance and usability of web pages by allowing
designers to control how hyperlinks and lists are displayed. Links are created using the HTML anchor (<a>)
tag, and CSS is applied to style them according to user interaction. CSS supports different link states such
asunvisited (a:link), visited (a:visited), hover (a:hover), and active (a:active).
For example, a link can be styled to appear in blue without an underline, change to red when the mouse
hovers over it, and turn green when clicked. This improves user interaction and clearly indicates clickable
elements. CSS can also be used to convert links into button-like components by adding background color,
padding, and borders, which are commonly used in navigation menus and call-to-action buttons.
a{
color: blue;
text-decoration: none;
a:hover {
color: red;
text-decoration: underline;
Lists in CSS help in organizing content in a structured and readable manner. HTML provides ordered lists
(<ol>), unordered lists (<ul>), and list items (<li>), while CSS controls their appearance. The list-style-type
property is used to define bullet styles or numbering formats such as circles, squares, decimals, or Roman
numerals. The list-style-position property controls the placement of bullets, and list-style-image allows
custom images as bullets. In modern web design, list bullets are often removed to create clean navigation
menus. Lists can also be styled by adjusting spacing, font size, color, and display properties to improve
layout and readability.
ul {
list-style-type: square;
li {
padding: 5px;
color: darkblue;
20
1.12 CSS BOX MODEL
The CSS Box Model defines how elements are sized, positioned, and rendered on a webpage. When a
browser loads an HTML document, it creates a DOMTREE and assigns a box to each element. This box
calculates the element's dimensions and position relative to its parent or the root <html> element, ensuring
accurate layout and spacing.
Content: The area where text or other content is displayed.
Padding: Space between the content and the element's border.
Border: A frame that wraps around the padding and content.
Margin: Space between the element's border and neighbouring elements.
21
It includes the areas highlighted in light green and skin color in the example.
The distance between the content edge and the border is the padding.
The border marks the end of the padding area.
The padding area contributes to the element's total dimensions.
Padding can be adjusted using CSS properties.
It works similarly with box-sizing: content-box and box-sizing: border-box, but with slight
calculation differences.
1.12.3. Border Area
The area that marks the end of an element is called as the border it is the outer fencing for the
element.
The default border properties are provided in CSS to control the thickness of this outer fencing.
The border area also add 's up to the complete height and width of the element.
The more the border width the more will be the height or width of the element.
In the above image the area marked with skin color is called the border area.
1.12..4. Margin Area
The area outside the border of an element is called the margin area.
Basically this area depends on the parent of the element.
The distance between the border of the parent element and the border of the child element is called as
the margin.
CSS has provides certain margin properties to get control over this scenario
Example
This <div> element will have a total width of 350px and a total height of 80px:
div {
width: 320px;
height: 50px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}
320px (width of content area)
+ 20px (left padding + right padding)
+ 10px (left border + right border)
= 350px (total width)
22
The total width of an element should be calculated like this:
Total element width = width + left padding + right padding + left border + right border
The total height of an element should be calculated like this:
Total element height = height + top padding + bottom padding + top border + bottom border
1.13.css3
CSS3 (Cascading Style Sheets Level 3) is the latest advanced version of CSS used to design and style
modern web pages. It is used to control the layout, colors, fonts, spacing, animations, and overall visual
presentation of websites. CSS3 was introduced to overcome the limitations of earlier CSS versions by
providing more powerful, flexible, and efficient styling features. Unlike previous versions, CSS3 is
modular in nature, meaning it is divided into separate modules such as Selectors, Box Model,
Backgrounds and Borders, Text Effects, Transitions, Animations, and Media Queries. This modular
approach allows browsers to support new features independently and improves performance.
One of the major advantages of CSS3 is its ability to create visually rich designs without relying heavily on
images or JavaScript. Features such as rounded corners (border-radius), shadows (box-shadow and text-
shadow), gradients, and multiple background images help in creating attractive user interfaces. CSS3
also introduces advanced layout techniques like Flexbox and Grid, which make it easier to design
responsive and flexible web page layouts. Additionally, CSS3 supports media queries that enable
responsive web design, allowing web pages to adapt automatically to different screen sizes such as
mobiles, tablets, and desktops.
CSS3 also enhances user interaction through transitions, transforms, and animations. Transitions allow
smooth changes between styles, transforms enable elements to be rotated, scaled, or moved, and
animations make web pages more dynamic and engaging. Overall, CSS3 simplifies web development,
improves user experience, reduces page loading time, and ensures consistency across devices and
browsers, making it an essential technology for modern web design.
[Link] preprocessors
CSS preprocessors are scripting languages that extend the capabilities of standard CSS and make stylesheet
writing more efficient, organized, and reusable. They allow developers to write CSS using additional
features such as variables, nesting, mixins, functions, and inheritance, which are not available in plain
CSS. The preprocessor code is then compiled into regular CSS, which can be understood by all web
browsers. CSS preprocessors are widely used in large and complex web projects to improve
maintainability and reduce repetition.
23
1.14.1 Popular CSS Preprocessors
Sass (SCSS) – most widely used
LESS
Stylus
1.14.3 Advantages
Reduces code repetition
Improves readability and maintainability
Saves development time
Easy to manage large and complex stylesheets.
[Link]
Bootstrap is a free and open-source tool collection for creating responsive websites and web applications.
It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites.
It solves many problems which we had once, one of which is the cross-browser compatibility issue. Nowadays,
the websites are perfect for all the browsers (IE, Firefox, and Chrome) and for all sizes of screens (Desktop,
Tablets, Phablets, and Phones). All thanks to Bootstrap developers -Mark Otto and Jacob Thornton of Twitter,
though it was later declared to be an open-source project. Bootstrap has evolved many versions and every time
when we want to use this framework we can select the version which we want to use.
24
25
1.15.2 FORMATTING AND STYLING IN BOOTSTRAP
Typography is a feature of Bootstrap for styling and formatting the text content. It is used to
create customized headings, inline subheadings, lists, paragraphs, aligning, adding more design-
oriented font styles, and much more. Bootstrap support global settings for the font stack,
Headings and Link styles to be used in the web app for every type of OS and Device to deliver the
best user interface.
EXAMPLE :
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Bootstrap Typography example
</title>
26
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<link rel="stylesheet" href=
"[Link]
<script src=
"[Link]
</script>
<script src=
"[Link]
</script>
<script src=
"[Link]
</script>
</head>
<body>
<div class="container">
<h1>Heading Lists</h1>
<h1 class="display-1">GeeksforGeeks</h1>
<h1 class="display-2">GeeksforGeeks</h1>
<h1 class="display-3">GeeksforGeeks</h1>
<h1 class="display-4">GeeksforGeeks</h1>
</div>
</body>
</html>
OUTPUT:
27
Advantages and disadvantages of traditional marketing
Benefits of Traditional Marketing (Advantages) We can easily reach your target local
audience.
Grid Classes: The Bootstrap grid system has four classes that can be combined to make more flexible
layouts:
Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper
alignment and padding
Content should be placed within columns, and only columns may be immediate children of rows
Predefined classes like .row and .col-sm-4 are available for quickly making grid layouts
Columns create gutters (gaps between column content) via padding. That padding is offset in rows for
the first and last column via negative margin on .rows
Grid columns are created by specifying the number of 12 available columns you wish to span. For
example, three equal columns would use three .col-sm-4
28
Column widths are in percentage, so they are always fluid and sized relative to their parent element
<div class="container">
<div class="row">
<div class="col-*-*"></div>
<div class="col-*-*"></div>
</div>
<div class="row">
<div class="col-*-*"></div>
<div class="col-*-*"></div>
<div class="col-*-*"></div>
</div>
<div class="row">
...
</div>
</div>
Containers: Bootstrap requires a containing element to wrap site contents and house our grid system.
The word 'container' is a container of row elements and row elements are 'containers' of the column
elements. You will understand it more in the latter part of the article where we have dealt with
columns. Use 'container' for a responsive fixed width container and use 'container-fluid' for a full
width container, spanning the entire width of your viewport
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
"[Link]
<script src=
"[Link]
</script>
<script src=
"[Link]
29
</script>
<script src=
"[Link]
</script>
</head>
<body>
<header>
<div class="container">
</div>
</header>
<footer>
<hr/>
<div class="container">
<p>
<a href="[Link]
Visit
</a>
our website
</p>
<p>
<a href="[Link]
Like
</a>
us on facebook
</p>
30
</div>
</footer>
</body>
</html>
Rows: Rows must be placed within a 'container' or 'container-fluid' for proper alignment and padding. We use
rows to create horizontal groups of columns. Example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<link rel="stylesheet" href=
"[Link]
<script src=
"[Link]
</script>
<script src=
"[Link]
</script>
<script src=
"[Link]
</script>
</head>
<body>
<header>
31
<div class="container">
<h1 style="color: green">GeeksforGeeks</h1>
<strong>
A computer Science portal for Geeks
</strong>
</div>
</header>
<div class="container">
<div class="row">
<div class="bg bg-primary w-100">
First row
</div>
</div>
<div class="row">
<div class="bg bg-success w-100">
Second row
</div>
</div>
<div class="row">
<div class="bg bg-primary w-100">
Third row
</div>
</div>
<div class="row">
<div class="bg bg-success w-100">
Fourth row
</div>
</div>
<div class="row">
<div class="bg bg-primary w-100">
Fifth row
</div>
</div>
</div>
<footer>
<hr />
<div class="container">
32
<p>
<a href="[Link]
Visit
</a>
our website
</p>
<p>
<a href="[Link]
Like
</a>
us on facebook
</p>
</div>
</footer>
</body>
</html>
Columns: Grid columns are created by specifying the number of twelve available columns you wish
to span. For example, three equal columns would use three "col-sm-4". Example:
<!DOCTYPE html>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
33
<meta charset="utf-8">
<meta name="viewport"
content="width=device-width, initial-scale=1">
<link rel="stylesheet" href=
"[Link]
<script src=
"[Link]
</script>
<script src=
"[Link]
</script>
<script src=
"[Link]
</script>
</head>
<body>
<header>
<div class="container">
<h1 style="color: green">GeeksforGeeks</h1>
<strong>
A computer Science portal for Geeks
</strong>
</div>
</header>
<div class="container">
<div class="row">
<div class="bg bg-primary w-100">
First row
</div>
</div>
<div class="row">
<div class="bg bg-success w-100">
Second row
</div>
</div>
34
</div>
<br/>
<div class="container">
<div class="row">
<div class="col-sm-4">
<div class="well bg bg-danger">
1st Column
</div>
</div>
<div class="col-sm-4">
<div class="well bg bg-warning">
2nd Column
</div>
</div>
<div class="col-sm-4">
<div class="well bg bg-secondary">
3rd Column
</div>
</div>
</div>
</div>
<footer>
<hr />
<div class="container">
<p>
<a href="[Link]
Visit
</a>
our website
</p>
<p>
<a href="[Link]
Like
</a>
us on facebook
35
</p>
</div>
</footer>
</body>
</html>
36
CHAPTER 2
ADVANCED JAVASCRIPT
JavaScript is a versatile, dynamically typed programming language that brings life to web pages by making
them interactive. It is used for building interactive web applications, supports both client-side and server-side
development, and integrates seamlessly with HTML, CSS, and a rich standard library.
OUTPUT
37
Hello, World!
Here are some key features of JavaScript that make it a powerful language for web
development:
Client-Side Scripting: JavaScript runs on the user's browser, so has a faster response time
without needing to communicate with the server.
Versatile: Can be used for a wide range of tasks, from simple calculations to complex
server-side applications.
Asynchronous: It can handle tasks like fetching data from servers without freezing the user
interface.
Rich Ecosystem: There are numerous libraries and frameworks built on JavaScript, such
as React, Angular, and [Link], which make development faster and more efficient.
38
JavaScript's flexibility extends to both the client-side and server-side, allowing developers to create complete
web applications. Here’s how it functions in each environment:
Client-Side:
Involves controlling the browser and its DOM (Document Object Model).
Handles user events like clicks and form inputs.
Common libraries include AngularJS, ReactJS, and VueJS
.
Server-Side:
Involves interacting with databases, manipulating files, and generating responses.
[Link] and frameworks like [Link] are widely used for server-side JavaScript, enabling full-stack
development.
39
followed by parentheses ( )
followed by brackets { }
The function name follows the naming rules for variables.
Optional parameters are listed inside parentheses: ( p1, p2, ... )
Code to be executed is listed inside curly brackets: { }
Functions can return an optional value back to the caller.
Parameter Rules
JavaScript function definitions do not specify data types for parameters.
JavaScript functions do not perform type checking on the passed arguments.
JavaScript functions do not check the number of arguments received.
Default Parameters
If a function is called with missing arguments (less than declared), the missing values are set to undefined.
Sometimes this is acceptable, but sometimes it is better to assign a default value to the parameter:
Example
function myFunction(x, y) {
if (y === undefined) {
y = 2;
}
}
With Arrow
let myFunction = (a, b) => a * b;
Before Arrow:
let hello = function() {
return "Hello World!";
}
With Arrow Function:
41
let hello = () => {
return "Hello World!";
}
If the function has only one statement that returns a value, you can remove the
brackets and the return keyword:
Different cars have the same properties, but the property values can differ from car to car.
Different cars have the same methods, but the methods can be performed at different times.
42
Adding New Properties
You can add new properties to an existing object by simply giving it a value:
Example
[Link] = "English";
Deleting Properties
The delete keyword deletes a property from an object:
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
delete [Link];
or delete person["age"];
Example
const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
delete person["age"];
Property Value
FirstName John
LastName Doe
Age 50
EyeColor Blue
Example
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName: function() {
return [Link] + " " + [Link];
}
};
In the example above, this refers to the person object:
[Link] means the firstName property of person.
[Link] means the lastName property of person.
if (name == "") {
alert("Name must be filled out");
return false;
}
if (email == "") {
alert("Email must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()">
Name: <input type="text" name="username"><br><br>
Email: <input type="text" name="email"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
46
2.4.3 Advantages of JavaScript Form Validation
Saves time by detecting errors instantly
Reduces server load
Improves user experience
Ensures accurate and complete data
Flag Description
47
A character class is one or more characters enclosed in square brackets:
Class Description
RexExp Metacharacters
Metacharacters are characters with a special meaning:
a|b Matches a or b
48
[\b] Matches backspace characters
\P{} Matches character NOT with the given Unicode Property (new 2018)
RexExp Assertions
Assertions include boundaries, which indicate the beginnings and endings of lines and words:
Char Description
^ Matches from beginning of a string, or the beginning of a line if the m (multiline) flag is
$ Matches from the end of a string, or the end of a line if the m (multiline) flag is set
49
(?!...) Matches NOT the subsequent string
RexExp Groups
Regular Expression Groups (aka capturing groups) allows parts of a matched string to be extracted and
reused. They are created by enclosing a pattern within parentheses ():
Char Description
RexExp Quantifiers
Quantifiers indicate the numbers of characters or expressions to match:
Code Description
50
2.6 ES6+ features: let, const, arrow functions, template
literals, destructuring, spread/rest operators
2.6.1. let
let is used to declare block-scoped variables.
It avoids problems of variable redeclaration seen with var.
let x = 10;
if (x > 5) {
let y = 20;
}
2.6.2 const
const is used to declare constants whose values cannot be reassigned.
It is also block-scoped.
const PI = 3.14;
// PI = 3.15; ❌ Error
2.6.5. Destructuring
Destructuring allows extracting values from arrays or objects easily.
Array Destructuring
51
let colors = ["red", "blue"];
let [c1, c2] = colors;
Object Destructuring
let user = { name: "Ravi", age: 22 };
let { name, age } = user;
Default Export
export default function greet() {
[Link]("Hello World");
}
Importing Modules
import { pi, area } from "./[Link]";
import greet from "./[Link]";
2.8.1. Callbacks
A callback is a function passed as an argument to another function and executed after a task is
completed.
Callbacks are commonly used in timers, events, and asynchronous operations.
function greet(name, callback) {
callback(name);
}
greet("MANO", function(msg) {
[Link]("Hello " + msg);
});
53
Disadvantage: Multiple nested callbacks can lead to callback hell, making code hard to read.
2.8.2. Promises
A Promise represents a value that may be available now, later, or never.
It has three states: pending, fulfilled, and rejected.
let promise = new Promise((resolve, reject) => {
resolve("Data loaded");
});
[Link](result => [Link](result))
.catch(error => [Link](error));
Promises improve readability compared to callbacks.
2.9 AJAX and Fetch API: Working with AJAX and the Fetch API for
asynchronous data fetching.
Both AJAX and the Fetch API are techniques used in web development to make
asynchronous HTTP requests to servers without reloading the entire webpage. This allows web applications
to update content dynamically, improving user experience by making web pages faster and more responsive.
AJAX uses the older XMLHttpRequest object
Fetch API is a modern, promise-based method for making HTTP requests.
55
Often requires more boilerplate code for simple Allows shorter, more concise code for common
requests. request patterns.
Requires manual parsing of response data (e.g., Provides convenient methods
responseText, responseXML). like .json(), .text(), .blob() to parse responses
automatically.
Supports progress events for monitoring Does not natively support progress events
upload/download. (requires additional APIs).
More verbose and can lead to "callback hell" in Cleaner and more readable syntax, especially
complex scenarios. with async/await.
Fully supported in all browsers, including very Supported in modern browsers; not supported in
old versions. Internet Explorer without polyfills.
Provides detailed control over request headers Supports flexible configuration through the
and states via XHR events. Request object and options parameter
Error handling relies on checking HTTP status Uses Promise rejection for network errors
codes and onerror events. and .catch() for error handling.
Traditionally used with XML, but commonly Primarily used with JSON and other modern web
with JSON now. formats.
57
CHAPTER 3
SERVLETS
3.1 SERVLETS:
MVC was created by Trygve Reenskaug. The main goal of this design pattern was to solve the
problem of users controlling a large and complex data set by splitting a large application into specific
sections that all have their own purpose.
It offers full control over your HTML and URLs which makes it easy to design web
application architecture.
It is a powerful URL-mapping component using which we can build applications that have
comprehensible and searchable URLs.
Controller
58
Model
View
Controller:
The controller is the component that enables the interconnection between the views and the model so
it acts as an intermediary. The controller doesn’t have to worry about handling data logic, it just tells
the model what to do. It processes all the business logic and incoming requests, manipulates data
using the Model component, and interact with the View to render the final output.
Responsibilities:
Example: In a bookstore application, the Controller would handle actions such as searching for a
book, adding a book to the cart, or checking out.
View:
The View component is used for all the UI logic of the application. It generates a user interface for the
user. Views are created by the data which is collected by the model component but these data aren’t
59
taken directly but through the controller. It only interacts with the controller.
Responsibilities:
Example: In a bookstore application, the View would display the list of books, book details, and
provide input fields for searching or filtering books.
Model:
The Model component corresponds to all the data-related logic that the user works with. This can
represent either the data that is being transferred between the View and Controller components or any
other business logic-related data. It can add or retrieve data from the database. It responds to the
controller's request because the controller can't interact with the database by itself. The model
interacts with the database and gives the required data back to the controller.
Responsibilities:
Example: In a bookstore application, the Model would handle data related to books, such as the book
title, author, price, and stock level.
Servlets are part of the Java EE (Jakarta EE) platform and are mainly used to build web-based
applications by extending the capabilities of a server. They act as a controller between the client
request and server response.
60
3.3 SERVLET LIFECYCLE:
The Servlet life cycle consists of four main stages:
Loading a Servlet
Initializing a Servlet
Destroying a Servlet
Loading: The Servlet container loads the Servlet class into memory.
Instantiation: The container creates an instance of the Servlet using the no-argument
constructor.
61
3.3.2. Initializing a Servlet
After instantiation, the container initializes the Servlet using the init() method.
Example:
@Override
The container calls service(ServletRequest req, ServletResponse res) for each request.
Example:
@Override
Allow Active Threads to Complete: The container ensures that all threads executing the
service() method complete their tasks.
Invoke the destroy() Method: The container calls the destroy() method to allow the Servlet
to release resources (e.g., closing database connections, freeing memory).
Release Servlet Instance: After the destroy() method is executed, the Servlet container
releases all references to the Servlet instance, making it eligible for garbage collection
A Generic Servlet is a protocol-independent servlet. It is an abstract class that implements the Servlet
and ServletConfig interfaces. It can handle requests from any protocol, such as HTTP, FTP, or SMTP.
Developers must override the service() method to process requests. Generic Servlets are rarely used in
real-time web applications because most applications use the HTTP protocol.
Example:
// processing logic
}
63
3.4.2. HTTP Servlet
An HTTP Servlet is a servlet designed specifically for handling HTTP requests. It extends the
HttpServlet class and provides methods like doGet(), doPost(), doPut(), and doDelete() to handle
different HTTP request types. HTTP Servlets are widely used for developing web applications.
Example:
// handle login
This type of servlet implements the SingleThreadModel interface to ensure that only one thread
executes the servlet at a time. It was used to handle thread safety issues but caused performance
problems. Hence, it is deprecated and no longer recommended.
A Synchronous Servlet processes client requests one at a time in a blocking manner. The client must
wait until the server finishes processing before receiving a response. This is the traditional and default
way servlets handle requests.
An Asynchronous Servlet allows the server to process requests in the background without blocking
the client. This improves performance for long-running tasks like database access or web services. It
was introduced in Servlet 3.0.
This servlet is loaded when the server starts rather than waiting for the first request. It is configured in
the [Link] file and is useful for initializing resources such as database connections.
64
3.5 Servlet Configuration with Deployment Descriptor
In a Spring MVC web application, the DispatcherServlet acts as the Front Controller. It is responsible
for handling all incoming client requests and delegating them to the appropriate controllers within the
application.
Workflow:
Example: If a client sends a request to /student/save, the DispatcherServlet routes it to the controller
responsible for handling /save operations.
65
3.5.3 What is [Link]?
The [Link] file, also known as the Web Application Deployment Descriptor, defines the
configuration details of a web application such as servlets, filters, listeners, and mappings.
It resides inside:
src/main/webapp/WEB-INF/[Link]
You need to declare and map the DispatcherServlet inside the [Link] file.
Servlet Configuration
<servlet-mapping>
66
<servlet-name>frontcontroller-dispatcher</servlet-name>
<url-pattern>/[Link]/*</url-pattern>
</servlet-mapping>
This configuration ensures that all requests starting with /[Link]/ (like /[Link]/save or
/[Link]/get) are handled by the DispatcherServlet.
Note: <load-on-startup>1</load-on-startup> ensures that the servlet initializes when the server
starts, not on the first request.
<web-app xmlns:xsi="[Link]
xmlns="[Link]
xsi:schemaLocation="[Link]
[Link]
version="4.0">
<display-name>myfirst-mvc-project</display-name>
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
<welcome-file>[Link]</welcome-file>
<welcome-file>[Link]</welcome-file>
67
<welcome-file>[Link]</welcome-file>
<welcome-file>[Link]</welcome-file>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>frontcontroller-dispatcher</servlet-name>
<servlet-class>[Link]</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>frontcontroller-dispatcher</servlet-name>
<url-pattern>/[Link]/*</url-pattern>
</servlet-mapping>
</web-app>
Each DispatcherServlet requires an associated Spring configuration file. The file name should follow
this convention:
<servlet-name>-[Link]
[Link]
Place it under:
68
src/main/webapp/WEB-INF/
Example Configuration:
<beans xmlns="[Link]
xmlns:xsi="[Link]
xmlns:context="[Link]
xsi:schemaLocation="
[Link]
[Link]
[Link]
[Link]
</beans>
69
3.6.1 Working with Servlet Context and Servlet Config Object
ServletConfig and ServletContext, both are objects created at the time of servlet initialization and
used to provide some initial parameters or configuration information to the servlet. But, the difference
lies in the fact that information shared by ServletConfig is for a specific servlet, while information
shared by ServletContext is available for all servlets in the web application. ServletConfig:
ServletConfig is for a particular servlet, that means one should store servlet specific
information in [Link] and retrieve them using this object.
Example: Suppose, one is building a job portal and desires to share different email ids (which
may get change over time) to recruiter and job applicant. So, he decides to write two servlets
one for handling recruiter's request and another one for the job applicant. Where to store
email-ids? Put email-id as a name-value pair for different servlet inside [Link] which can
further be retrieved using getServletConfig().getInitParameter("name") in the servlet.
3.6.2 ServletContext:
ServletContext is the object created by Servlet Container to share initial parameters or
configuration information to the whole application.
Example: Suppose, the name of one's job portal is "[Link]". Showing the website
name at the top of webpages delivered by different servlets, one needs to store the website
name in every servlet inviting redundancy. Since the information shared by ServletContext can
be accessed by every Servlet, it is better to go with ServletContext and retrieve the website
name using [Link]("Name") whenever required.
70
ServletConfig object is obtained by ServletContext object is obtained by
getServletConfig() method. getServletContext() method.
Each servlet has got its own ServletConfig ServletContext object is only one and used
object. by different servlets of the application.
Use ServletConfig when only one servlet Use ServletContext when whole application
needs information shared by it. needs information shared by it
1. Request Scope
2. Application Scope
3. Session Scope
Methods Used:
getAttribute(String name)
removeAttribute(String name)
Example:
[Link]("username", "AYSHA");
Scope:
Valid until the request is completed.
71
Session attributes are used to store data for a specific user session. They are maintained across
multiple requests from the same user.
Methods Used:
[Link]()
[Link]()
Example:
[Link]("userId", 101);
Scope:
Valid until the session expires or is invalidated.
Methods Used:
getServletContext().setAttribute()
getServletContext().getAttribute()
Example:
Scope:
Valid until the application is stopped or restarted.
Example (JSP):
Request Dispatcher
A Request Dispatcher object is obtained using:
1. Forward
2. Include
Forwarding
The forward() method transfers the same request and response objects to another resource. The
client is not aware of this transfer, and the URL in the browser does not change.
Syntax
[Link](request, response);
Example
if([Link]("admin")) {
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
73
} else {
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
Key Points
Server-side operation
Including
The include() method includes the output of another resource in the current response. Control
returns to the original servlet after execution.
Syntax
[Link](request, response);
Example
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
Key Points
Response is combined
74
Difference Table
Definition
sendRedirect() is a method of the HttpServletResponse interface that sends a response to the client
with a redirection instruction.
Syntax
[Link]("url");
75
6. Response is displayed to the client.
Example
throws IOException {
[Link]("[Link]");
} else {
[Link]("[Link]");
It is a client-side redirection
HTTP is a "stateless" protocol, which means that each time a client requests a Web page, the client
establishes a new connection with the Web server, and the server does not retain track of prior
requests.
The conversation of a user over a period of time is referred to as a session. In general, it refers
to a certain period of time.
Session tracking is the process of remembering and documenting customer conversations over
time. Session management is another name for it.
The term "stateful web application" refers to a web application that is capable of remembering
and recording client conversations over time.
The HTTP protocol is stateless, which implies that each request is treated as a new one. As
you can see in the image below.
We have numerous alternatives once you've finished processing a user's session data.
1. Remove a specific attribute You can delete the value associated with a specific key by calling
the public void removeAttribute(String name) function.
2. Delete your whole session. To delete an entire session, use the public void invalidate()
function.
77
3. Setting Session Timeout You may set the timeout for a session separately by calling the public
void setMaxInactiveInterval(int interval) function.
4. Log the user out On servers that support servlets 2.4, you may use the logout method to log the
client out of the Web server and invalidate all of the users' sessions.
5. [Link] Configuration If you're using Tomcat, you may set the session timeout in the
[Link] file, in addition to the ways listed above.
<session-config>
<session-timeout>20</session-timeout>
</session-config>
The timeout is specified in minutes and overrides Tomcat's default timeout of 30 minutes.
In a servlet, the getMaxInactiveInterval() function delivers the session's timeout period in seconds.
GetMaxInactiveInterval() returns 900 if your session is set to 20 minutes in [Link].
1. Cookies
2. HttpSession
3.10.3 COOKIES:
Cookies are little pieces of data delivered by the web server in the response header and kept by
the browser. Each web client can be assigned a unique session ID by a web server. Cookies are
used to keep the session going. Cookies can be turned off by the client.
3.10.4 HTTPSESSION:
A user session is represented by the HttpSession object. A session is established between an
HTTP client and an HTTP server using the HttpSession interface. A user session is a
collection of data about a user that spans many HTTP requests.
78
CRUD operations are a common task in many applications and JDBC (Java Database Connectivity) is
a Java API that allows you to connect to a database and perform these operations. We will guide you
through the steps of setting up a simple CRUD (Create, Read, Update, Delete) operation using JDBC.
In this step, we create a database and a table where student records will be stored.
USE studentdb;
);
79
We add the MySQL connector dependency in [Link] so Java can talk to MySQL.
[Link]:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>9.0.0</version>
</dependency>
import [Link];
import [Link];
private static final String PASSWORD = "yourpassword"; // change to your MySQL password
try {
} catch (Exception e) {
[Link]();
80
return null;
Use INSERT query to add new student records into the database.
import [Link];
import [Link];
String sql = "INSERT INTO students (name, age, email) VALUES (?, ?, ?)";
[Link](1, name);
[Link](2, age);
[Link](3, email);
81
[Link](rows + " student inserted successfully.");
} catch (Exception e) {
[Link]();
import [Link];
import [Link];
import [Link];
ResultSet rs = [Link](sql)) {
while ([Link]()) {
82
[Link]([Link]("id") + " | " +
[Link]("email"));
} catch (Exception e) {
[Link]();
import [Link];
import [Link];
[Link](1, newEmail);
83
[Link](2, id);
} catch (Exception e) {
[Link]();
import [Link];
import [Link];
84
[Link](1, id);
} catch (Exception e) {
[Link]();
This is the driver class where we test all four operations step by step.
Insert -> Display -> Update -> Delete -> Display again.
// CREATE
// READ
[Link]("\nAll Students:");
[Link]();
85
// UPDATE
[Link](1, "alice_new@[Link]");
// DELETE
[Link](2);
// READ again
[Link]("\nAfter Update/Delete:");
[Link]();
Run the MainApp class and check the output in IntelliJ console.
You should see the effect of each operation one after the other.
Output:
86
87
CHAPTER 4
JSP
JSP is mainly used for the presentation layer (View) in web applications, while servlets are
used for business logic and request handling (Controller). Internally, a JSP page is converted into
a servlet by the JSP container and then executed.
Platform independent
<html>
<body>
<h2>Welcome to JSP</h2>
<p>Current Date: <%= new [Link]() %></p>
</body>
</html>
4.2 The difference between Servlet and JSP is as follows:
SERVLET JSP
Writing code for servlet is harder than JSP as JSP is easy to code as it is java in HTML.
it is HTML in java.
Servlet plays a controller role in the ,MVC JSP is the view in the MVC approach for
approach. showing output.
Servlet is faster than JSP. JSP is slower than Servlet because the first
step in the JSP lifecycle is the translation of
JSP to java code and then compile.
Servlet can accept all protocol requests. JSP only accepts HTTP requests.
In Servlet, we can override the service() In JSP, we cannot override its service()
method. method.
Modification in Servlet is a time-consuming JSP modification is fast, just need to click the
compiling task because it includes reloading, refresh button.
recompiling, JavaBeans and restarting the
server.
It does not have inbuilt implicit objects. In JSP there are inbuilt implicit objects.
There is no method for running JavaScript on While running the JavaScript at the client side
the client side in Servlet. in JSP, client-side validation is used.
Packages are to be imported on the top of the Packages can be imported into the JSP
program. program (i.e, bottom , middleclient-side, or
top )
It can handle extensive data processing. It cannot handle extensive data processing
very efficiently.
The facility of writing custom tags is not The facility of writing custom tags is present.
present.
Servlets are hosted and executed on Web Before the execution, JSP is compiled in Java
Servers. Servlets and then it has a similar lifecycle as
Servlets.
1. When a user accesses a webpage with a .jsp extension, the browser sends an HTTP request to
the web server for that JSP file.
2. The web server checks if a compiled version of the JSP already exists. If it does, it uses that. If
not, the request is passed to the JSP engine for processing.
3. The JSP engine reads the JSP file and translates it into a Java Servlet by converting the HTML
and JSP code into equivalent Java code.
4. This Java Servlet is then compiled into a .class file (bytecode) that the server can execute.
5. The servlet runs on the server, generates dynamic content (usually HTML), and prepares it as a
response.
6. Finally, the web server sends this generated HTML back to the user’s browser, which displays
the resulting webpage.
The JSP file is parsed and converted into a Java servlet source file ([Link]).
}
2. Compilation of JSP page
3. Class loading
4. Instantiation
5. Initialization (jspInit())
This method is called only once when the JSP is first loaded.
[Link]("JSP Initialized.");
}
6. Request Processing (_jspService())
[Link]().write("<html><body>Hello, World!</body></html>");
This method is called once before removing the JSP from service.
It is used for releasing resources, such as closing database connections or cleaning up open
files.
[Link]("JSP Destroyed.");
This Lifecycle ensures that JSP pages are efficiently compiled, managed and cleaned up by the server
container
1. Scriptlet
A Scriptlet is used to write Java statements that are executed when the JSP page is requested.
Syntax
<%
Java code
%>
Example
<%
int a = 10;
int b = 20;
%>
Usage
2. Expression
An Expression is used to output the value of a Java expression directly to the client.
Syntax
Example
Usage
Displaying values
Printing variables
3. Declaration
A Declaration is used to declare variables and methods that become part of the generated servlet
class.
Syntax
<%!
declaration
%>
Example
<%!
int count = 0;
int square(int n) {
return n * n;
%>
Usage
Syntax:
Attributes:
language
contentType
import
session
errorPage
isErrorPage
Syntax:
Syntax:
They are always enclosed within <jsp: ... > and can be placed anywhere in the JSP page where
dynamic behavior is required.
Common JSP Action Tags
Includes content from another resource (JSP, HTML, or servlet) into the current page at request time.
Syntax:
Usage: Helps in modularizing JSP pages by reusing header, footer, or navigation components.
Forwards the current request to another resource such as a JSP, HTML, or servlet. The client is
unaware of the forwarding.
Syntax:
Note: Once the forward tag is executed, the rest of the current page is skipped.
Syntax:
Example:
Note: If the bean does not exist in the specified scope, a new instance is automatically created.
Syntax:
Example:
<jsp:setProperty name="user" property="username" value="John" />
Note: It can also retrieve values directly from request parameters by using property="*".
Syntax:
Example:
Usage: Commonly used to display data stored in JavaBeans directly on JSP pages.
Syntax:
Example:
Note: This tag ensures that required browser plugins are loaded properly.
Syntax:
Example:
Syntax:
Example:
<jsp:body>
</jsp:body>
Implicit objects in JSP are predefined objects created by the JSP container and made available
automatically to the JSP page.
The programmer does not need to declare or instantiate them. These objects help in handling
requests, responses, session tracking, application data, and output generation.
JavaBean Conventions
Public no-argument constructor: This allows the JSP container and development tools to easily
instantiate the bean.
Public getter and setter methods: Properties are accessed and modified using
public getPropertyName() and setPropertyName() methods. For boolean
properties, isPropertyName() can be used as the getter.
Serialization: The class should implement the [Link] interface to allow its state to
be saved (persisted) and restored across sessions or systems.
JSP provides specific action tags to work with JavaBeans, which abstract away the need for extensive
Java scriptlet code:
jsp
<jsp:setProperty>: This action sets the value of a property in a declared bean. It can take a
static value, a param from the HTTP request, or use the wildcard * to automatically set all
matching properties from request parameters.
jsp
<jsp:getProperty>: This action retrieves the value of a bean property and inserts it into the
HTML output stream.
jsp
4.10.1 Syntax of EL
${expression}
Supports operators
${[Link]}
Equivalent to:
[Link]("username");
2. Accessing Attributes from Scopes
Scope EL Syntax
Page ${[Link]}
Request ${[Link]}
Session ${[Link]}
Application ${[Link]}
Example:
${[Link]}
${[Link]}
${colors[0]}
${marks[1]}
${map["key"]}
EL Object Description
Cookie Cookies
4.10.5 Operators in EL
Arithmetic Operators
${a + b}
${a * b}
Relational Operators
${a > b}
${a == b}
Logical Operators
${a && b}
${a || b}
Conditional Operator
Eligible to Vote
</c:if>
4.10.6 Advantages of EL
JSTL (JavaServer Pages Standard Tag Library) is a collection of custom tags that encapsulate core
functionalities commonly used in JSP pages. It helps reduce Java code embedded in JSPs (known as
scriptlets) and promotes a cleaner MVC-based web application design.
JSTL is part of the Jakarta EE (formerly Java EE) specification and is supported in all modern servlet
containers.
Provides built-in tags for iteration, conditional checks, and data formatting
<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>[Link]</groupId>
<artifactId>[Link]</artifactId>
<version>3.0.1</version>
</dependency>
At the top of your JSP file, include the relevant JSTL tag libraries:
1. Cookies
Types of Cookies:
Example:
[Link](ck);
Advantages:
Simple to use
Disadvantages:
Limited size
Security issues
2. URL Rewriting
Example:
[Link]?user=Akshaya
Advantages:
Disadvantages:
Example:
Advantages:
Simple implementation
Disadvantages:
Not secure
Example:
[Link]("user", "Akshaya");
Retrieve Data:
Exception handling is the mechanism used to handle runtime errors that occur during program
execution.
In Servlets and JSP, exception handling ensures that errors are managed gracefully without crashing
the application and provides user-friendly error messages.
Improves reliability
Helps in debugging
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
// code
<%
try {
int a = 10 / 0;
} catch (Exception e) {
[Link]("Error occurred");
}
%>
<error-page>
<exception-type>[Link]</exception-type>
<location>/[Link]</location>
</error-page>
OR
<error-page>
<error-code>404</error-code>
<location>/[Link]</location>
</error-page>
Code Meaning
403 Forbidden
Application stability
Clean error management
Easy maintenance
4.14 Performing CRUD (Create, Read, Update, Delete) operation using JSP and
Servlet with JDBC.
CRUD operations refer to the four basic database operations: Create, Read, Update, and Delete.
In a Java Web Application, JSP is used for presentation (UI), Servlets handle business logic, and JDBC
is used to interact with the database.
View → JSP
Controller → Servlet
[Link]("[Link]");
</form>
Servlet ([Link])
PreparedStatement ps =
[Link](1, name);
[Link](2, age);
[Link]();
Servlet ([Link])
Statement st = [Link]();
[Link]("result", rs);
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
<%
ResultSet rs = (ResultSet)[Link]("result");
while([Link]()) {
%>
<%= [Link](1) %> - <%= [Link](2) %><br>
<%
%>
</form>
Servlet ([Link])
PreparedStatement ps =
[Link](1, age);
[Link](2, name);
[Link]();
</form>
Servlet ([Link])
PreparedStatement ps =
[Link](1, name);
[Link]();
OBJECT/RELATIONAL MAPPING
(ORM)WITH HIBERNATE
ORM is required to overcome the mismatch between object-oriented programming and relational
databases. Writing database code using JDBC involves repetitive tasks such as connection
handling, query execution, and result processing. ORM reduces this boilerplate code, improves
developer productivity, enhances code readability, and makes applications easier to maintain. It
also promotes database independence, allowing applications to work with different databases with
minimal changes.
In the code-based approach, object-relational mapping is defined using Java code instead of XML or
annotations. Mapping configurations are created dynamically using ORM framework APIs. This
approach offers high flexibility and is useful for complex or dynamic applications. However, it
requires more coding effort and can reduce code readability, making it less popular for simple
applications.
ORM frameworks generally follow certain design patterns. The Active Record pattern combines both
data and database access logic within the same class, making it simple but less suitable for large
applications. The Data Mapper pattern, used by frameworks like Hibernate, separates business
logic from database access logic, resulting in better scalability and maintainability.
Advantages of ORM
ORM simplifies database interaction, reduces SQL dependency, improves application portability, and
enhances maintainability. By allowing developers to work with objects rather than database tables,
ORM leads to cleaner code and faster application development.
Hibernate is an open-source Object Relational Mapping (ORM) framework for Java. It simplifies
database connection by mapping Java classes (objects) to database tables and Java data types to SQL
data types. Instead of writing long SQL queries, developers can use Hibernate APIs or HQL
(HibernateQuery Language) to perform CRUD operations.
Hibernate acts as a bridge between Java objects and relational databases, thereby reducing the need for
boilerplate JDBC code.
Working with objects in Hibernate begins by creating an object of an entity class and setting its values.
Once the object is created, it is persisted in the database using a Hibernate Session. The save() or
persist() method is used to store the object in the database. Hibernate generates the required SQL
internally and executes it, freeing the developer from writing SQL manually.
Hibernate allows retrieval of objects using several approaches. Objects can be fetched using the primary
key with methods like get() or find(). Hibernate also supports object retrieval using HQL (Hibernate
Query Language) and Criteria API, which operate on objects rather than database tables. Retrieved
data is returned as fully initialized Java objects, making it easy to work with them in the application.
To update data, Hibernate requires changes to be made directly to the object. Once an object is
retrieved and modified, Hibernate automatically detects the changes and synchronizes them with the
database when the transaction is committed. This process is known as automatic dirty checking, and it
eliminates the need for explicit update queries in many cases.
Deleting an object in Hibernate is straightforward. The object to be deleted is first retrieved from the
database and then removed using the delete() or remove() method of the session. Hibernate handles the
generation of the appropriate SQL delete statement and ensures data consistency.
Hibernate objects exist in different states during their lifecycle. A transient object is created using the
new keyword and is not associated with any Hibernate session. A persistent object is associated with a
session and corresponds to a database record. A detached object was once persistent but is no longer
associated with a session. Understanding these states is crucial for effectively working with Hibernate
objects.
Hibernate manages database operations within transactions to ensure data consistency. When working
with objects, developers typically begin a transaction, perform create, read, update, or delete
on objects, and then commit the transaction. If an error occurs, the transaction can be rolled back,
maintaining database integrity.
Hibernate with annotations is a modern and widely used approach for implementing Object/Relational
Mapping (ORM) in Java applications. Instead of defining mappings in external XML files, annotations
allow developers to specify mapping information directly inside Java classes. This makes the code more
readable, concise, and easier to maintain.
Hibernate Query Language (HQL) is an object-oriented query language used in Hibernate to interact
with the database. Unlike SQL, which works directly with tables and columns, HQL works with
persistent objects (entities) and their properties. HQL is database-independent, meaning queries are
written in terms of entity classes and attributes and Hibernate automatically translates them into the
appropriate SQL for the underlying database.
5.6.1 Key Features of HQL:
Object-Oriented: Operates on entity objects instead of database tables.
Portable: Database-independent same HQL query works on different databases.
Powerful Queries: Supports joins, aggregations, grouping, ordering, subqueries, etc.
Polymorphic Queries: Supports inheritance queries can work on parent classes and include child
class entities.
Automatic Mapping: Properties in HQL map directly to Java class fields, not column names.
The Query interface provides object-oriented methods and capabilities for representing and
manipulating HQL queries.
Note:
Keywords like FROM, SELECT and WHERE are not case-sensitive in HQL.
Table and Column names are case-sensitive in HQL.
5.6.2 Hibernate Query Language (HQL) Clauses
There are many HQL clauses available to interact with relational databases and several of them are
listed below:
1. FROM Clause
2. SELECT Clause
3. WHERE Clause
4. ORDER BY Clause
5. UPDATE Clause
6. DELETE Clause
7. INSERT Clause
For details and examples regarding each clause is mentioned below.
1. FROM Clause
To load a whole persistent object into memory, the FROM clause is used.
String hib = "FROM Student";
Query query = [Link](hib);
List results = [Link]();
2. SELECT Clause
The SELECT clause is used when only a few attributes of an object are required rather than the entire
object.
String hib = "SELECT [Link] FROM Student S";
Query query = [Link](hib);
List results = [Link]();
3. WHERE Clause
Filtering records is done with the WHERE clause. It's used to retrieve only the records that meet a set of
criteria.
String hib = "FROM Student S WHERE [Link] = 5";
Query query = [Link](hib);
List results = [Link]();
4. ORDER BY Clause
The ORDER BY clause is used to sort the results of an HQL query.
String hib = "FROM Student S WHERE [Link] > 5 ORDER BY [Link] DESC";
Query query = [Link](hib);
List results = [Link]();
NOTE:
1. Order By - DESC will sort in descending order
2. Order By - ASC will sort in ascending order
5. UPDATE Clause
The UPDATE clause is required to update the value of an attribute.
String hib = "UPDATE Student set name=:n WHERE roll=:i";
Query q=[Link](hib);
[Link]("n","John");
[Link]("i",23);
int status=[Link]();
[Link](status);
6. DELETE Clause
It is required to delete a value of an attribute.
String hib = "DELETE FROM Student WHERE id=10";
Query query=[Link](hib);
[Link]();
7. INSERT Clause
It is required to Insert values into the relation.
String hib = "INSERT INTO Student(first_name, last_name)" +
"SELECT first_name, last_name FROM backup_student";
Query query = [Link](hib);
int result = [Link]();
Pagination using Query
For pagination using query we have two methods available for it, below table contains the methods and
its description.
1. Query setMaxResults(int max): Instructs Hibernate to get a specific number of items.
2. Query setFirstResult(int starting_no): Takes an integer as an argument that represents the first row
in your result set, beginning with row 0.
Example for pagination using HQL
To fetch the few row data at a time we can use pagination using HQL. For this example we are fetching
the rows 5 to 10.
String hib = "FROM Student"
Query query=[Link](hib);
[Link](5);
[Link](10);
List list=[Link]();
The above example returns the list of records from 5 to 10.
Max
To find the maximum mark among all the available marks.
String hib = "SELECT MAX(marks) FROM Student";
Query q=[Link](hib);
Min
To find the minimum mark among all the available marks.
String hib = "SELECT MIN(marks) FROM Student";
Query q=[Link](hib);
Count
To find the count of id present.
String hib = "SELECT COUNT(id) FROM Student";
Query q=[Link](hib);
Sum
To find the sum of all the marks of Student.
String hib = "SELECT SUM(marks) FROM Student";
Query q=[Link](hib);
List<Integer> list=[Link]();
[Link]([Link](0));
Example:
Consider a Student entity mapped to a student table.
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = [Link])
private int id;
In this example, the Student class is mapped to the student table, id is the primary key, and name and
age are mapped to columns. This is a simple or basic O/R mapping.
[Link]
1
This is mapped with a <set> element and initialized with [Link]
[Link]
2 This is mapped with a <set> element and initialized with [Link]. The sort
attribute can be set to either a comparator or natural ordering.
[Link]
3
This is mapped with a <list> element and initialized with [Link]
[Link]
4
This is mapped with a <bag> or <ibag> element and initialized with [Link]
[Link]
5
This is mapped with a <map> element and initialized with [Link]
[Link]
6 This is mapped with a <map> element and initialized with [Link]. The sort
attribute can be set to either a comparator or natural ordering.
Arrays are supported by Hibernate with <primitive-array> for Java primitive value types and <array>
for everything else. However, they are rarely used, so I am not going to discuss them in this tutorial.
If you want to map a user defined collection interfaces, which is not directly supported by Hibernate,
you need to tell Hibernate about the semantics of your custom collections, which is not very easy and
not recommend to be used.
Many-to-One
1
Mapping many-to-one relationship using Hibernate
One-to-One
2
Mapping one-to-one relationship using Hibernate
One-to-Many
3
Mapping one-to-many relationship using Hibernate
Many-to-Many
4
Mapping many-to-many relationship using Hibernate
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Vehicle {
@Id
private int id;
private String brand;
}
@Entity
public class Car extends Vehicle {
private int seatingCapacity;
}
In this strategy, both Vehicle and Car data are stored in a single table, with Hibernate managing a
discriminator column internally.
Example (Joined Strategy):
@Entity
@Inheritance(strategy = [Link])
public class Employee {
@Id
private int id;
private String name;
}
@Entity
public class Manager extends Employee {
private String department;
}
Here, data is stored across multiple tables linked by primary keys, providing better normalization.
Overall Architecture
In this integrated approach, the client (browser) sends a request to the Servlet. The Servlet processes
the request, interacts with the database using Hibernate, and then forwards the processed data to a JSP
page. The JSP page displays the data in a user-friendly format. Hibernate manages object-relational
mapping and database communication internally, eliminating the need for direct JDBC code.
Development Steps
Step 1: Create the Database
Design and create the required tables in the database, such as user or student tables.
Step 2: Create Hibernate Entity Classes
Define Java classes and annotate them with Hibernate/JPA annotations to map them to database
tables.
Step 3: Configure Hibernate
Create the Hibernate configuration file ([Link]) to specify database connection details
and entity classes.
Step 4: Create DAO or Service Layer
Implement Data Access Object (DAO) classes that use Hibernate sessions to perform CRUD
operations.
Step 5: Develop Servlets
Create Servlets to handle client requests, call DAO methods, and control application flow.
Step 6: Design JSP Pages
Develop JSP pages for input forms and output display using EL and JSTL.
Step 7: Configure Deployment Descriptor
Map Servlets in [Link] or using annotations.
The CSS cascading mechanism determines which styles are applied to HTML elements by prioritizing styles based on importance, specificity, and source order. The hierarchy is as follows: inline styles have the highest priority, followed by internal styles, and external styles . Specificity is determined by counting the number of type selectors, class selectors, and ID selectors . Cascade rules further dictate that later rules in the stylesheet override earlier rules if they have equal specificity and importance .
HTML5 offers advantages such as cross-platform compatibility, access to user location via geolocation, support for offline use through Web Storage or AppCache, and the use of semantic tags for cleaner, simpler code. It is also optimized for smooth performance on mobile devices . However, it also has disadvantages including lack of full feature support in older browsers, compatibility issues with older mobile devices, potential security risks from Web Storage misuse, added complexity with advanced APIs for beginners, and poor support in Internet Explorer 8 and below .
Session management is crucial in maintaining state across different requests from the same user. JSP automatically manages sessions, enabling seamless state management without additional coding from the developer . In contrast, session management in Servlets requires explicit handling by the developer, necessitating code to create and manage HttpSession objects . This difference simplifies JSP-based application development, particularly for dynamic content that requires user-specific data storage, while offering more fine-grained control in Servlets at the expense of greater complexity .
Web Storage provides a mechanism for storing key/value pairs in a web browser and persists data beyond a session, making it an appealing option for client-side data storage . However, it poses security risks if not implemented with caution. It can potentially store sensitive information that may be accessed or modified by unauthorized scripts or extensions running in the browser . Furthermore, because data is stored in plain text, it is susceptible to XSS attacks if input is not sanitized effectively . Appropriate security measures, like encryption and strict input validation, are necessary to mitigate these risks .
Web Workers enhance JavaScript applications by running scripts in background threads, preventing the main thread from slowing or becoming unresponsive during intensive tasks . This leads to a smoother user interface and the ability to perform complex operations like data processing or real-time updates efficiently . However, potential drawbacks include increased complexity in managing asynchronous tasks and communication between the main thread and workers, as data needs to be serialized and passed using message events, which might complicate the app's architecture .
The Render Tree plays a critical role in displaying a webpage by combining the DOM (Document Object Model) and CSSOM (CSS Object Model). It only includes visible elements, omitting those with 'display: none' . The Render Tree is crucial in the layout (reflow) step, where it helps the browser calculate the exact position and size for each element on the page, and in the paint step, where it determines the colors, borders, and text to draw on the screen . Finally, the Render Tree is involved in the compositing process, during which the browser combines layers into a final visual output .
Inline CSS is used for quick fixes and specific element styling when external or internal styles aren't needed; it's often seen in applications like emails where external CSS isn't supported . Internal CSS fits single-page design scenarios where greater styling control is essential without the need for separate files . External CSS is best for large-scale projects due to the convenience of applying styles across multiple pages and enhancing performance via caching . Each CSS type serves unique purposes, balancing complexity, speed of application, and maintainability .
WebSockets provide a full-duplex communication channel that enables real-time data exchange between clients and servers . Unlike traditional HTTP, which is unidirectional where the client must initiate requests for information, WebSockets allow for both the client and server to send and receive messages independently of each other. This reduces latency and can significantly improve the performance of applications that require constant and immediate data updates, such as online gaming, live sports score updates, or chat applications .
Hibernate, Servlets, and JSPs collaborate under the MVC architecture by distributing responsibilities across three layers: model, view, and controller . Hibernate acts as the model layer, handling database interactions and managing data persistence through Object-Relational Mapping (ORM). Servlets perform the controller's role, receiving client requests, invoking Hibernate operations, processing business logic, and deciding which JSP to render . JSPs function as the view layer, presenting data using Expression Language (EL) and JSTL without embedding business logic, ensuring a clean separation between application logic and presentation . This approach enhances maintainability, scalability, and clarity across complex applications .
The JSP lifecycle begins with the translation of the JSP file into a servlet. This involves checking the JSP for syntax correctness and converting it into a Java source file . Next, the JSP source file is compiled into a Java class file. The class file then goes through class loading, instantiation, and initialization, where the jspInit() method is invoked by the container . During request processing, the _jspService() method is executed. Finally, during cleanup, the jspDestroy() method is called by the container . These steps collectively handle the translation, compilation, execution, and cleanup of JSPs .