0% found this document useful (0 votes)
10 views134 pages

Web Programming: HTML, CSS, JavaScript

The document is a monograph on web programming, covering topics such as HTML, CSS, Bootstrap, advanced JavaScript, servlets, JSP, and ORM with Hibernate. It includes detailed explanations of various web technologies, their structures, and functionalities, as well as practical applications and advantages. The content is organized into chapters, each focusing on specific aspects of web development.

Uploaded by

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

Web Programming: HTML, CSS, JavaScript

The document is a monograph on web programming, covering topics such as HTML, CSS, Bootstrap, advanced JavaScript, servlets, JSP, and ORM with Hibernate. It includes detailed explanations of various web technologies, their structures, and functionalities, as well as practical applications and advantages. The content is organized into chapters, each focusing on specific aspects of web development.

Uploaded by

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

24EIT401-WEB PROGRAMMING

MONOGRAPH
(Internal Circulation Only)

1
TABLE OF CONTENTS

Topic No. Topic Name Page No.


CHAPTER 1
HTML,CSS AND BOOTSTRAP
Introduction 01

1.1.1 Characteristics of HTML 01

1.1.2 Structure of HTML 02


1.1
1.1.3 HTML elements 02

Layout tags 03

1.2.1 Layout structure 04


1.2
1.2.2 Advantages of layout structure 04

1.3 Semantics tags 05

1.4 Application tags 06

1.5 Logical tags 07

1.6 Introduction to HTML5 and its elements 08

1.7 HTML5 Introduced several powerful features and APIs 09

1.8 CSS: Introduction to CSS 11

1.9 Types of CSS styles 13

1.10 Text formatting 17

1.11 Links and Lists 20

1.12 CSS box model 21

1.13 CSS3 23

1.14 CSS Preprocessors 23

1.15 BOOTSTRAP 24

1
CHAPTER 2
ADVANCED JAVASCRIPT
Introduction to java script 37

2.1 2.1.1 Key features of java script 38

2.1.2 Client side and server side nature of java script 38


2

2.1.3 Limitations of java script 39

2.2 Java script functions and objects 40

2.2.1 What are functions? 40

2.2.2 Java script function parameters 40

2.2.3 Java script function expression 41

2.2.4 Java script arrow function 41

2.3 Java script objects 42

2.4 Java script validation of HTML5 forms 45

2.5 Regular expression 47

2.6 ES6 Features: let, const, arrow functions, template literals, destructing, 50
spread/rest operators
2.7 Java scipt ES6 modules 52

2.8 Asynchronous Programming 53

2.8.1 Callbacks 53

2.8.2 Promises 53

2.8.3 Asyn/await 54

2.8.4 Event handling 54

2.8.5 Error handling 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.1.1 Introduction to MVC 58

3.1.2 Features of MVC 58

3.1.3 Components of MVC 58

3.2 Servlet introduction 60

3.3 Servlet lifecycle 61

3.3.1 Loading servlet 61

3.3.2 Initializing a servlet 62

3.3.3 Handling request 62

3.3.4 Destroying a servlet 63

3.4 Types of servlets 63

3.4.1 Generic servlet 63

3.4.2 HTTP servlet 64

3.4.3 Single thread model servlet 64

3.4.4 Synchronous Servlet 64

3.4.5 Asynchronous servlet 64

3.4.6 Load on startup servlet 65

3.5 Servlet configuration with deployment descriptor 65

3.6 Working with servlet context and servlet config object 70

3.7 Attributes in servlets 71

3
3.7.1 Request scope 71

3.7.2 Application scope 71

3.7.3 Session scope 72

3.7.4 Page scope 73

3.8 Response and redirection using request dispatcher 73

3.9 Send redirect method 75

3.10 Session tracking: using cookies, Http session 77

3.11 Performing CRUD (Create, Read, Update, Delete) operation using Servlet 79
with JDBC.
CHAPTER 4
JSP
4.1 Introduction to JSP 88

4.1.1 Features of JSP 88

4.1.2 Basic examples 88

4.2 The difference between servlet and JSP 88

4.3 JSP Architecture 89

4.4 Lifecycle of JSP 92

4.5 Scripting elements 96

4.6 Directives in JSP 98

4.7 Action tags 99

4.8 Implicit objects 101

4.9 Java beans in JSP 102

4
4.10 Expression language in JSP 104

4.11 JSP Standard tag libraries 107

4.12 Session Management 109

4.13 Exception handling 111

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.2 Introduction to hibernate 119

5.3 Hibernate API 120

5.4 Working with objects in hibernates 121

5.5 Hibernate annotation 123

5.6 Querying in Hibernate – Hibernate Query Language (HQL) 123

5.7 Criteria queries – Creating queries with native SQL 127

5.8 Basic O/R mapping 128

5.9 Collections mapping 128

5.10 Association mapping 219

5.11 Inheritance Mapping 219

5.12 Developing web application by integrating Servlet, JSP and Hibernate. 220

5
CHAPTER 1

HTML,CSS AND BOOTSTRAP

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:

 Markup-based, not programming language


 Uses predefined tags
 Case-insensitive
 Platform independent
 Supports multimedia
 Easily integrated with CSS and JavaScript

1
1.1.2 STRUCTURE OF HTML:

<!DOCTYPE html>
<html>
<head>
<title>Title</title>
</head>
<body>
Content
</body>
</html>

 <!DOCTYPE html> → Declares HTML5 document


 <html> → Root element
 <head> → Metadata (title, CSS, scripts)
 <body> → Visible webpage content

1.1.3 HTML ELEMENTS:

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

A typical HTML element has three main parts:


 Start Tag: Marks the beginning of the element (e.g., <h1>, <p>).
 Content: The information displayed to the user or used by the browser (e.g., "My First Heading").
 End Tag: Marks the end of the element (e.g., </h1>, </p>). The end tag has a forward slash before
the tag name.

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.

Common Layout Tags and Their Description

1. <header>

o Represents the top section of a webpage or section

o Contains logo, website title, or introductory content

2. <nav>

o Used to define a navigation section

o Contains links to other pages or sections

3. <section>

o Represents a thematic grouping of related content

o Used to divide content into meaningful sections

4. <article>

o Represents independent, self-contained content

o Examples: blog post, news article

5. <aside>

o Contains side content related to the main content

o Examples: sidebar, advertisements, related links

6. <footer>

o Represents the bottom section of a webpage

o Contains copyright, contact details, or links

3
7. <div>

o Generic container used for grouping elements

o Used when no specific semantic tag is suitable

1.2.1 LAYOUT STRUCTURE:


<header>
<h1>My Website</h1>
</header>

<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>

1.2.2 ADVANTAGES OF LAYOUT STRUCTURE:

Improves page structure and organization


 Makes HTML code more readable and maintainable
 Enhances accessibility for screen readers
 Helps search engines understand content (SEO)
 Supports responsive web design

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.

1.3.1 Common Semantic Tags and Their Uses


1. <header>
o Represents introductory content
o Contains headings, logos, or navigation
2. <main>
o Contains the main content of the webpage
o There should be only one <main> tag
3. <section>
o Groups related content together
o Used to divide the page into sections
4. <article>
o Represents independent content
o Example: blog post, news article
5. <aside>
o Contains side information related to main content
o Example: advertisements, related links
6. <footer>
o Represents footer of a page or section
o Contains copyright or contact info
7. <figure> and <figcaption>
o Used for images and captions

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

1.4 APPLICATION TAGS


Introduction
Application tags in HTML are used to create interactive web applications. These tags allow user interaction,
form submission, multimedia handling, and graphics rendering.

Application tags are HTML elements that support user input, multimedia content, and dynamic web
applications.

1.4.1Types of Application Tags


1. Form-Related Application Tags
1. <form> – Collects user data
2. <input> – Input field
3. <textarea> – Multi-line input
4. <select> – Drop-down list
5. <option> – Options inside dropdown
6. <button> – Submits form or action

2. Multimedia & Graphics Tags


1. <audio> – Plays audio files
2. <video> – Plays video files
3. <canvas> – Draws graphics using JavaScript
4. <svg> – Scalable vector graphics

1.4.3Applications of Application Tags


 Login and registration forms
 Online surveys
 Media players
 Interactive dashboards
 Web-based applications

6
1.4.4Advantages
 Enhances user interaction
 Supports modern web applications
 Plugin-free multimedia support
 Improves user experience

1.5 LOGICAL TAGS

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.

1.5.1Common Logical Tags and Their Uses


1. <strong>
o Indicates important text
2. <em>
o Emphasizes text
3. <code>
o Displays programming code
4. <kbd>
o Represents keyboard input
5. <cite>
o Used for titles or references
6. <abbr>
o Defines abbreviations

1.5.2 Advantages of Logical Tags


 Improves accessibility
 Better SEO
 Meaningful content representation
 Device-independent formatting

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.

 HTML uses tags, and CSS uses rule sets.

 CSS styles are applied to the HTML element using selectors.

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.

 CSS follows a hierarchy-Inline, Internal, External styles.

 Specificity decides which selector has more weight.

 Later rules override earlier ones if they have equal priority.

1.8.1 Working of CSS


CSS works by applying styles to HTML elements, transforming a plain web page into a visually
appealing layout. It works with the browser to match styles to elements, calculate their positions, and
display them on the screen.

The below diagram explains the working of CSS in a mor e simplified manner.

11
1. Load HTML

 Browser requests the HTML file from the server.

 Receives the HTML document as text.

2. Parse HTML

 Browser reads and tokenizes HTML.

 Converts tags into nodes for the DOM tree.

3. Build DOM (Document Object Model)

 The parsed HTML elements form the DOM structure.

 Represents all page elements and hierarchy.

4. Load CSS

 When browser finds a <link> or <style>, it loads CSS files.

 External CSS is render-blocking (page waits until loaded).

5. Parse CSS

 CSS text is parsed into the CSSOM (CSS Object Model).

 Browser understands all CSS rules and selectors.

6. Compute Styles (Match + Cascade)

 Browser matches CSS rules to DOM elements.


12
 Applies cascading rules and calculates final computed styles.

7. Build Render Tree

 Combines DOM + CSSOM to create the Render Tree.

 Includes only visible elements (e.g., skips display: none).

8. Layout (Reflow)

 Calculates exact position and size of each element.

 Determines where elements appear on the page.

9. Paint

 Converts render tree elements into actual pixels.

 Draws colors, borders, text, images, etc.

10. Display (Compositing)

 Browser combines painted layers into the final image.

 Final visual output is displayed on the screen.

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.

1.9 Types of CSS STYLES


CSS can be implemented in three different ways:

 Inline CSS

 Internal or Embedded CSS

 External CSS

1.9.1 Inline CSS


Inline CSS involves applying styles directly to individual HTML elements using the style attribute.
This method allows for specific styling of elements within the HTML document, overriding any
external or internal styles.

<p style="color: #009900;

font-size:50px;

font-style:italic;

text-align:center;">

13
Inline CSS

</p>

OUTPUT:

1.9.2 Internal or Embedded CSS


Internal or Embedded CSS is defined within the HTML document's <style> element. It applies styles
to specified HTML elements. The CSS rule set should be within the HTML file in the head section, i.e.
the CSS is embedded within the <style> tag inside the head section of the HTML file.

<!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="GFG">Internal CSS</div>

<div class="geeks">

Implementation of Internal CSS

</div>

</div>

</body>

</html>

1.9.3 External CSS


External CSS contains separate CSS files that contain only style properties with the help of tag
attributes (For example class, id, heading, ... etc). CSS property is written in a separate file with a .css
extension and should be linked to the HTML document using a link tag. It means that, for each
element, style can be set only once and will be applied across web pages.
15
<!DOCTYPE html>

<html>

<head>

<link rel="stylesheet" href="[Link]">

</head>

<body>

<div class="main">

<div class="GFG">External CSS </div>

<div id="geeks">

This shows implementation of External CSS

</div>

</div>

</body>

</html>

When to Use Inline CSS

 For quick fixes and small changes that don’t require a separate CSS file.

 When you need to override other styles for a particular element.

 If you’re working on emails or HTML-based applications where external CSS is not


supported.
16
When to Use Internal CSS

 When designing a single-page website.

 If you need better control over styling than inline CSS.

 For small to medium-sized projects where external CSS might be unnecessary.

When to Use External CSS

 For large-scale projects where multiple pages share a common design.

 When maintainability and scalability are priorities.

 To improve website performance and load times using CSS caching

1.10 TEXT FORMATTING


CSS text formatting is used to style and control the appearance of text on a webpage. It allows
you to change the font, size, color, spacing, and alignment of text, helping make web content
more readable and visually appealing.

<html>

<head>

<style>

.initials {

font-size: 40px;

font-weight: bold;

color: #4CAF50;

text-transform: uppercase;

font-family: Arial, sans-serif;

</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.

TEXT ALIGN Specifies horizontal alignment of text in a block


or table-cell element.

TEXT ALIGN LAST Sets alignment of last lines occurring in an


element.

TEXT DECORATION Decorates text content.

TEXT DECORATION COLOR Sets color of text decorations like overlines,


underlines, and line-throughs

TEXT DECORATION LINE Sets various text decorations like underline,


overline, line-through

TEXT DECORATION STYLE Combines text-decoration-line and text-


decoration-color properties

TEXT INDENT Indents first line of paragraph.

TEXT JUSTIFY Justifies text by spreading words into complete


lines.

TEXT OVERFLOW Specifies hidden overflow text.

TEXT TRANSFORM Controls capitalization of text.

TEXT SHADOW Adds shadow to text.

LETTER SPACING Specifies space between characters of text.

LINE HEIGHT Sets space between lines.

DIRECTION Sets text direction.

WORD SPACING Specifies space between words of line.

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.

EXAMPLE FOR LINK:

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.

EXAMPLE FOR LIST:

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.

1.12.1 Key components of the box model


Each element in the box model is made up of distinct layers that define its size and spacing on a web page.
7.1.1. Content Area
 The content area is the central part of the CSS box model, containing the main content (e.g., text,
images, videos, or elements like <p> or <span>).
 It can be styled with CSS properties like height and width.
The content edge refers to the four edges of the content area.
 Left content edge
 Right content edge
 Top content edge
 Bottom content edge
1.12..2. Padding Area
 The padding area is the space between the content and the border of an element.

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)

50px (height of content area)


+ 20px (top padding + bottom padding)
+ 10px (top border + bottom border)
= 80px (total height)

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.2 Features of CSS Preprocessors


 Variables – store values like colors, fonts, and sizes for reuse
 Nesting – write CSS rules inside other rules, similar to HTML structure
 Mixins – reuse a set of CSS properties in multiple places
 Inheritance – share styles between selectors
 Functions & Operators – perform calculations and logic

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.

1.15.1 Why Bootstrap?


 Faster and Easier Web Development.
 It creates Platform-independent web pages.
 It creates Responsive Web-pages.
 It is designed to be responsive to mobile devices too.
 It is Free! Available on [Link]

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.

Typography can be used to create:


 Headings
 Subheadings
 Text and Paragraph font color, font type and alignment
 Lists
 Other inline elements
Tags and class to implement typography feature in bootstrap:
 display headings: It is used to create better headings (larger font size and lighter font weight).
 There are four classes exists in display headings which are .display-1, .display-2, .display-3,
and .display-4.
 lead: It is used to make a paragraph stand out i.e. visually better.
 mark: It is used to highlight the text content.
 initialism: It is used to render abbreviation in slightly small text size.
 blockquote: It is used to quote the text content.
 blockquote-footer: It is used to add the footer details for identifying the source of the Quote.
 text-center: It is used to align the text to the center.
 list-inline: It is used to make the element of list inline.
 text-truncate: It is used to shorten the longer text by truncating with an ellipsis.
 text-muted: It is used for text color, text-muted fades the text i.e. text greyed out.
 text-uppercase: It is used to transform text into uppercase.
 text-lowercase: It is used to transform text into lowercase.
 text-capitalize: It is used to transform text to capitalize first letter of each word leaving other
letters in lowercase.
 .font-weight-bold: It sets the font weight to bold. It is used to display the importance of text.
 .font-weight-bolder: It sets the font weight to deep bold. It is used to display the importance of text.
 .font-italic: It sets the font style to italic.
 .font-weight-light: It sets the font weight to light.
 .font-weight-lighter: It sets the lighter font weight.
 .font-weight-normal: It sets the normal font size and weight.
 .lead: It makes the paragraph stand out.
 .small: It is used to create secondary subheadings.
 .text-left: It sets the left alignment of text.
 .text-*-left: It sets the left alignment of text on all screens (small, medium, large or xlarge).
 .text-break: It breaks the long string text into short text substrings.

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:

1.15.3 BOOTSTRAP CRID SYSTEM:


The Bootstrap grid system is a powerful tool for building responsive web layouts. It's based on a 12-column structure,
allowing you to easily arrange and size your content. By using its predefined classes, your website will
effortlessly adapt to various screen sizes, from desktops to mobile phones.

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:

 xs (<576px): For Portrait Mobile Phones.

 sm (>=576px): For Landscapes phones

 md (>=768px): For Tablets/Phablets

 lg (>=992px): For Small-sized Desktops/Laptops

 xl (>=1200px): For Larger-sized Desktops/Laptops

Grid System Rules

Some Bootstrap grid system rules:

 Rows must be placed within a .container (fixed-width) or .container-fluid (full-width) for proper
alignment and padding

 Use rows to create horizontal groups of columns

 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

 The following is a basic structure of a Bootstrap grid:

 <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 rel="stylesheet" href=

"[Link]

<script src=

"[Link]

</script>

<script src=

"[Link]

29
</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>

<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>

1.15.4 Creating Responsive Designs with Bootstrap


 Creating responsive designs with Bootstrap allows websites to automatically adjust to different
screen sizes and devices.
 Bootstrap follows a mobile-first approach, meaning the design is optimized for mobile devices first
and then scaled for larger screens.
 The Bootstrap grid system is the core feature used to build responsive layouts.
 It divides the webpage into 12 flexible columns using rows and containers.
 Bootstrap provides predefined breakpoint classes such as col-sm, col-md, col-lg, and col-xl for
different screen sizes.
 Containers like .container and .container-fluid help control the width of content across devices.
 Bootstrap utility classes allow easy control of spacing, alignment, visibility, and text responsiveness.
 Responsive images are created using the .img-fluid class to scale images properly within containers.
 Navigation bars, cards, and other components automatically adapt to screen size using Bootstrap classes.
 Bootstrap ensures consistent layout and appearance across all browsers and devices.
 Using Bootstrap reduces development time and simplifies responsive web design.

36
CHAPTER 2
ADVANCED JAVASCRIPT

2.1 INTRODUCTION TO 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.

 JavaScript is a single-threaded language that executes one task at a time.


 It is an interpreted language which means it executes the code line by line.
 The data type of the variable is decided at run-time in JavaScript, which is why it is
called dynamically typed.
"Hello, World!" Program in Browser Console
A "Hello, World!" program is the simplest way to get started with any programming language.
Here’s how you can write one using JavaScript.
<html>
<head></head>
<body>
<h1>Check the console for the message!</h1>
<script>
// This is our first JavaScript program
[Link]("Hello, World!");
</script>
</body>
</html>

OUTPUT
37
Hello, World!

2.1.1 Key Features of JavaScript

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.

 Event-Driven: Responds to user actions (clicks, keystrokes) in real-time.

 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.

2.1.2 CLIENT SIDE AND SERVER SIDE NATURE OF


JAVASCRIPT:

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.

2.1.3 Limitations of JavaScript


Despite its power, JavaScript has some limitations to consider:
 Security Risks : Can be used for attacks like Cross-Site Scripting (XSS), where malicious scripts are
injected into a website to steal data by exploiting elements like <img>, <object>, or <script> tags.
 Performance : Slower than traditional languages for complex tasks, but for simple tasks in a browser,
performance is usually not a major issue.
 Complexity : To write advanced JavaScript, programmers need to understand core programming
concepts, objects, and both client- and server-side scripting, which can be challenging.
 Weak Error Handling and Type Checking : Weakly typed, meaning variables don’t require explicit
types. This can lead to issues as type checking is not strictly enforced.

2.2 JavaScript functions and objects


2.2.1What are Functions?
Functions are fundamental building blocks in all programming.
Functions are reusable block of code designed to perform a particular task.
Functions are executed when they are "called" or "invoked".
JavaScript Function Syntax
function name( p1, p2, ... ) {
// code to be executed
}
Functions are defined with the function keyword:
 followed by the function name

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.

2.2.2 JavaScript Function Parameters


function functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are the names listed in the function definition.
Function arguments are the real values passed to (and received by) the function.

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;
}
}

Default Parameter Values


ES6 allows function parameters to have default values.
Example
If y is not passed or undefined, then y = 10.
function myFunction(x, y = 10) {
return x + y;
}
myFunction(5);

Function Rest Parameter


40
The rest parameter (...) allows a function to treat an indefinite number of arguments as an array:
Example
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum;
}

let x = sum(4, 9, 16, 25, 29, 100, 66, 77);

2.2.3 JavaScript Function Expressions


What is a Function Expression?
A function expression is a function assigned to a variable.
A function expression is a way of defining a function within an expression, rather than as a standalone
declaration.
A function expression can be assigned to a variable, passed as an argument to another function, or returned
from a function.
Example
const x = function (a, b) {return a * b};

2.2.4 JavaScript Arrow Functions


Arrow Functions were introduced in ES6.
Arrow Functions allow a shorter syntax for function expressions.
You can skip the function keyword, the return keyword, and the curly brackets:
let myFunction = (a, b) => a * b;
Before Arrow:
Function to compute the product of a and b
let myFunction = function(a, b) {return a * b}

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:

Arrow Functions Return Value by Default:


let hello = () => "Hello World!";

2.3 JavaScript Objects


An Object is a variable that can hold many variables.
Objects are collections of key-value pairs, where each key (known as property names) has a value.
Objects can describe anything like houses, cars, people, animals, or any other subjects.

Car Properties Car Methods

[Link] = Fiat [Link]()

[Link] = 500 [Link]()

[Link] = 850kg [Link]()

[Link] = white [Link]()

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.

2.3.1 JAVASCRIPT OBJECT PROPERTIES


Accessing JavaScript Properties
The syntax for accessing the property of an object is:
// [Link]
let age = [Link];
or
//objectName["property"]
let age = person["age"];
or
//objectName[expression]
let age = person[x];

42
Adding New Properties
You can add new properties to an existing object by simply giving it a value:
Example
[Link] = "English";

Property Default Values


A value given to a property will be a default value for all objects created by the constructor:
Example
function Person(first, last, age, eyecolor) {
[Link] = first;
[Link] = last;
[Link] = age;
[Link] = eyecolor;
[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"];

2.3.1 JavaScript Object Methods


43
Object methods are actions that can be performed on objects.
A method is a function definition stored as a property value.

Property Value

FirstName John

LastName Doe

Age 50

EyeColor Blue

FullName function() {return [Link] + " " + [Link];}

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.

Accessing Object Methods


You access an object method with the following syntax:
[Link]()
If you invoke the fullName property with (), it will execute as a function:
Example
name = [Link]();
If you access the fullName property without (), it will return the function definition:
Example
name = [Link];
Adding a Method to an Object
44
Adding a new method to an object is easy:
Example
[Link] = function () {
return [Link] + " " + [Link];
};

Using JavaScript Methods


This example uses the JavaScript toUpperCase() method to convert a text to uppercase:
Example
[Link] = function () {
return ([Link] + " " + [Link]).toUpperCase();
};

2.3.3How to Display JavaScript Objects?


Displaying a JavaScript object will output [object Object].
Example
// Create an Object
const person = {
name: "John",
age: 30,
city: "New York"
};

let text = person;

2.4 JavaScript validations of HTML form


JavaScript form validation is used to check user input before submitting the form to the server.
It ensures that the data entered by the user is correct, complete, and in the required format. JavaScript
validation is a client-side validation, which improves user experience by giving instant feedback and
reduces unnecessary server requests.
Common form validations include checking whether input fields are empty, validating email format,
verifying password length, confirming numeric values, and ensuring required fields are filled. JavaScript
accesses form elements using the Document Object Model (DOM) and applies conditions using if
statements. If the validation fails, an error message is displayed and the form submission is prevented using
return false.

2.4.1 Common Types of JavaScript Form Validation


 Empty field validation
 Email format validation
 Password length validation
 Numeric value validation
45
 Confirm password validation
2.4.2 EXAMPLE
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<script>
function validateForm() {
var name = [Link]["myForm"]["username"].value;
var email = [Link]["myForm"]["email"].value;

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

2.5 REGULAR EXPRESSION:


let regexp = /pattern/flags;
// or
let regext = new RegExp(pattern, flags)
RexExp Flags / Modifiers
Flags can be added to a regexp pattern to modify its behavior:

Flag Description

/d Performs substring matches (new 2022)

/g Performs a global match (find all)

/i Performs case-insensitive matching

/m Performs multiline matching

/s Allows . (dot) to match line terminators (new 2018)

/u Enables Unicode support (new 2015)

/v An upgrade to the /u flag for better Unicode support (new 2025)

/y Performs a "sticky" search (new 2015)

RexExp Character Classes

47
A character class is one or more characters enclosed in square brackets:

Class Description

[a] Matches the character between the brackets

[^a] Matches all characters NOT between the brackets

[abc] Matches all characters between the brackets

[^abc] Matches all characters NOT between the brackets

[a-z] Matches all characters in the range from a to z

[^a-z] Matches all characters NOT in the range from a to z

[0-9] Matches all characters in the range from 0 to 9

[^0-9] Matches all characters NOT in the range from 0 to 9

RexExp Metacharacters
Metacharacters are characters with a special meaning:

a|b Matches a or b

. Matches any (wildcard) character except line terminators

\w Matches word characters (alphanumeric and _)

\W Matches non-word characters

\d Matches digits (0-9)

\D Matches non-digit characters

\s Matches whitespace characters (space, tab, newline)

\S Matches non-whitespace character

48
[\b] Matches backspace characters

\0 Matches NULL characters

\n Matches new line characters

\f Matches form feed characters

\r Matches carriage returns characters

\t Matches tab characters

\v Matches vertical tab characters

\p{} Matches characters with given Unicode Property (new 2018)

\P{} Matches character NOT with the given Unicode Property (new 2018)

\ddd Matches a character by the octal number ddd

\xhh Matches a character by the hexadecimal number hh

\uhhhh Matches a Unicode character by the hex number hhhh

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

\b Matches from the beginning or end of a word

\B Matches NOT from the beginning or end of a word

(?=...) Matches the subsequent string

49
(?!...) Matches NOT the subsequent string

(?<=...) Matches the previous string (new 2018)

(?<!...) Matches NOT the previous string (new 2018)

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

(x) Matches x and remembers the match

(?<n>x) Matches x and labels it n

(?flag:x) Enables flag(s) for x

(?flag-flag:x) Disables flag(s) for x

RexExp Quantifiers
Quantifiers indicate the numbers of characters or expressions to match:

Code Description

x+ Matches at least one x

x* Matches zero or more occurrences of x

x? Matches zero or one occurrences of x

x{n} Matches n occurences of x

x{n,m} Matches from n to m occurences of x

x{n,} Matches n or more occurences of x

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.3. Arrow Functions


 Arrow functions provide a shorter syntax for writing functions.
 They do not have their own this keyword.
const add = (a, b) => a + b;

2.6.4. Template Literals


 Template literals use backticks ( ) instead of quotes.
 They support string interpolation using ${}.
let name = "MANO";
let msg = `Welcome, ${name}!`;

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;

2.6.6. Spread Operator (...)


 Spread operator expands elements of arrays or objects.
let a = [1, 2, 3];
let b = [...a, 4, 5];

2.6.7. Rest Operator (...)


 Rest operator collects multiple values into an array.
function sum(...nums) {
return [Link]((a, b) => a + b);
}

Advantages of ES6+ Features


 Cleaner and shorter code
 Better readability
 Avoids common JavaScript errors
 Improves performance and maintainability

2.7 JavaScript ES6 Modules


JavaScript modules are a feature introduced in ES6 that allow developers to divide code into separate
files and reuse them when needed. Each module represents an independent unit of code containing variables,
functions, or classes. Modules help in organizing large applications, improving readability, and avoiding
global scope pollution.
In ES6, modules use the export and import keywords. The export keyword is used to make variables,
functions, or classes available outside the module, while the import keyword is used to access them in
another file. ES6 supports named exports and default exports. Modules are executed in strict mode by
default, and each module has its own scope.
Modules improve code maintainability, promote reusability, and make debugging easier. They are widely
used in modern JavaScript frameworks and applications.
52
Types of Exports
Named Export
export const pi = 3.14;
export function area(r) {
return pi * r * r;
}

Default Export
export default function greet() {
[Link]("Hello World");
}

Importing Modules
import { pi, area } from "./[Link]";
import greet from "./[Link]";

2.8 Asynchronous programming:


Asynchronous programming in JavaScript allows tasks such as data fetching, file loading, or timers to
run in the background without blocking the execution of the main program. This helps in building fast,
responsive, and user-friendly applications.

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.8.3. Async / Await


 async and await are built on top of promises and provide a cleaner syntax.
 await pauses execution until the promise is resolved.
async function loadData() {
let result = await promise;
[Link](result);
}
 Makes asynchronous code look like synchronous code.

2.8.4. Event Handling


 Event handling allows JavaScript to respond to user actions like clicks, keypresses, or mouse
movements.
[Link]("btn").addEventListener("click", function() {
alert("Button clicked");
});
 Events are asynchronous and handled when triggered.

2.8.5. Error Handling


 Error handling is used to catch and manage runtime errors.
 In promises, .catch() is used.
54
 In async/await, try...catch is used.
async function fetchData() {
try {
let data = await promise;
[Link](data);
} catch (error) {
[Link]("Error occurred");
}
}

2.8.6 Advantages of Asynchronous Programming


 Non-blocking execution
 Better performance
 Improved user experience
 Efficient handling of multiple tasks

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.

2.9.1 DIFFERENCE BETWEEN AJAX AND FETCH API:

AJAX FETCH API


Uses the older XML Http Request object for Uses the modern fetch() function based on
requests. Promises
Relies on callback functions to handle responses.

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.

2.9.2 What is AJAX?


AJAX (Asynchronous JavaScript and XML) is a technique that allows web pages to communicate with a
server asynchronously without refreshing the whole page. It traditionally uses the XMLHttpRequest (XHR)
object to send and receive data, often in XML or JSON format.
Features of AJAX
 Allows asynchronous communication with the server.
 Supports various data formats including XML, JSON, HTML, and plain text.
 Can track progress events like upload and download progress.
 Works well with older browsers, ensuring broad compatibility.
 Allows partial page updates for a smoother user experience.
Uses of AJAX
 Loading new content without page reload.
 Submitting forms asynchronously.
 Real-time data updates such as live search suggestions or chat messages.
 Fetching data for dynamic user interfaces (dashboards, tables, etc.).

2.9.3 What is Fetch API?


The Fetch API is a modern, promise-based JavaScript interface for making HTTP requests. It simplifies the
process of fetching resources asynchronously and provides a more powerful and flexible feature set
56
compared to AJAX.
Features of Fetch API
 Based on Promises, making code easier to read and maintain.
 Provides built-in methods to parse JSON, text, blobs, and more.
 Supports request and response streaming.
 More concise syntax, especially when used with async/await.
 Easily configurable with options for headers, credentials, cache, and more.
Uses of Fetch API
 Fetching JSON data from APIs.
 Handling RESTful API requests in modern web apps.
 Performing CRUD operations with better readability.
 Ideal for modern JavaScript applications and frameworks

57
CHAPTER 3
SERVLETS

3.1 SERVLETS:

3.1.1 INTRODUCTION TO MVC:


The Model-View-Controller (MVC) framework is an architectural/design pattern that separates an
application into three main logical components Model, View, and Controller. Each architectural
component is built to handle specific development aspects of an application. It isolates the business
logic and presentation layer from each other. It was traditionally used for desktop graphical user
interfaces (GUIs). Nowadays, MVC is one of the most frequently used industry-standard web
development frameworks to create scalable and extensible projects. It is also used for designing
mobile apps.

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.

3.1.2 FEATURES OF MVC:


 It provides a clear separation of business logic, UI logic, and input logic.

 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.

 It supports Test Driven Development (TDD).

3.1.3 COMPONENTS OF MVC:


Components of MVC

The MVC framework includes the following 3 components:

 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:

 Receiving user input and interpreting it.

 Updating the Model based on user actions.

 Selecting and displaying the appropriate View.

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:

 Rendering data to the user in a specific format.

 Displaying the user interface elements.

 Updating the display when the Model changes.

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:

 Managing data: CRUD (Create, Read, Update, Delete) operations.

 Enforcing business rules.

 Notifying the View and Controller of state changes.

Example: In a bookstore application, the Model would handle data related to books, such as the book
title, author, price, and stock level.

3.2 SERVLET INTRODUCTION:


A Servlet is a server-side Java program used to develop dynamic web applications. It runs on a web
server or application server (like Apache Tomcat) and handles requests sent by web clients (such as
browsers), processes them, and generates dynamic responses.

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

 Handling Client Requests

 Destroying a Servlet

3.3.1. Loading a Servlet


The first stage of the Servlet lifecycle involves loading and initializing the Servlet. The Servlet
container performs the following operations:

 Loading: The Servlet container loads the Servlet class into memory.

 Instantiation: The container creates an instance of the Servlet using the no-argument
constructor.

When is a Servlet loaded?

 During application startup (if configured in deployment descriptor).

 On first client request (lazy loading).

61
3.3.2. Initializing a Servlet
After instantiation, the container initializes the Servlet using the init() method.

 init(ServletConfig config) method is called once in the Servlet’s lifetime.

 It prepares the Servlet to handle requests (e.g., database connection setup).

 Called only once, unlike service() which is called per request.

Example:

@Override

public void init() throws ServletException {

// Initialization code (e.g., database connection)

3.3.3. Handling request


Once initialized, the Servlet is ready to handle client requests.

3.1 Request and Response Objects

 ServletRequest and ServletResponse objects are created for each request.

 For HTTP, HttpServletRequest and HttpServletResponse objects are used.

3.2 The service() Method

 The container calls service(ServletRequest req, ServletResponse res) for each request.

 Determines the HTTP request type (GET, POST, PUT, DELETE).

 Delegates the request to appropriate methods: doGet(), doPost(), etc.

Example:

@Override

public void service(ServletRequest req, ServletResponse res)

throws ServletException, IOException {

// Handle request and generate response


62
}

3.3.4. Destroying a Servlet


When the Servlet container decides to remove the Servlet, it follows these steps which are listed
below

 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

3.4 TYPES OF SERVLETS:


Servlets are classified based on the protocol they support and the way they handle client requests.
In Java web development, the most commonly used servlets are HTTP Servlets, but there are
different types available.

3.4.1. Generic Servlet

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:

public class MyServlet extends GenericServlet {

public void service(ServletRequest req, ServletResponse res) {

// 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:

public class LoginServlet extends HttpServlet {

protected void doPost(HttpServletRequest req, HttpServletResponse res) {

// handle login

3.4.3. Single Thread Model Servlet (Deprecated)

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.

3.4.4. Synchronous Servlet

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.

3.4.5. Asynchronous Servlet

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.

3.4.6. Load-on-Startup Servlet

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.

3.5.1 What is a Front Controller?


A Front Controller is a design pattern that provides a single entry point for handling all web requests.
It helps centralize request processing, making tasks like authentication, logging, and routing easier to
manage.

Workflow:

1. A client sends an HTTP request to the server.

2. The DispatcherServlet receives the request.

3. It determines which controller should handle it.

4. The controller processes the request and returns a response.

5. The DispatcherServlet sends the final response back to the client.

Example: If a client sends a request to /student/save, the DispatcherServlet routes it to the controller
responsible for handling /save operations.

3.5.2 How to Create a Front Controller in Spring MVC?


Spring already provides an implementation of the Front Controller pattern through the class
[Link]. We do not need to create one manually. Instead,
we configure this servlet in the [Link] file of the application.

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]

Step 1: Configure DispatcherServlet in [Link]

You need to declare and map the DispatcherServlet inside the [Link] file.

Servlet Configuration

<servlet-mapping>

<!-- Match the servlet name -->

66
<servlet-name>frontcontroller-dispatcher</servlet-name>

<!-- Map all URLs starting with /[Link]/ -->

<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.

Complete [Link] file

Below is the complete [Link] file containing the DispatcherServlet configuration.

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="[Link]

xmlns="[Link]

xsi:schemaLocation="[Link]

[Link]

version="4.0">

<display-name>myfirst-mvc-project</display-name>

<!-- Default welcome files -->

<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>

<!-- DispatcherServlet Configuration -->

<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>

Step 2: Create Spring Configuration File

Each DispatcherServlet requires an associated Spring configuration file. The file name should follow
this convention:

<servlet-name>-[Link]

For this example:

[Link]

Place it under:
68
src/main/webapp/WEB-INF/

Example Configuration:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="[Link]

xmlns:xsi="[Link]

xmlns:context="[Link]

xsi:schemaLocation="

[Link]

[Link]

[Link]

[Link]

<!-- Component scanning or bean definitions can be added here -->

</beans>

Step 3: Testing the Application

1. Deploy the application on a server (like Apache Tomcat).

2. Check the server console logs.

If the DispatcherServlet initializes successfully without exceptions, the setup is correct.

Example Console Output:

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 an object containing some initial parameters or configuration information


created by Servlet Container and passed to the servlet during initialization.

 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.

Servlet Config Servlet Context

ServletConfig is servlet specific ServletContext is for whole application

Parameters of servletConfig are present as Parameters of servletContext are present as


name-value pair in <init-param> inside name-value pair in <context-param> which
<servlet>. is outside of <servlet> and inside <web-
app>

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

3.7 ATTRIBUTES IN SERVLETS:


An attribute in servlet is an object that can be set, get or removed by the following aspects

1. Request Scope

2. Application Scope

3. Session Scope

3.7.1. Request Scope Attributes


Request attributes are available only for a single client request. They are commonly used to pass
data from a servlet to a JSP page using request forwarding.

Methods Used:

 setAttribute(String name, Object value)

 getAttribute(String name)

 removeAttribute(String name)

Example:

[Link]("username", "AYSHA");

Scope:
Valid until the request is completed.

3.7.2. Session Scope Attributes

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:

HttpSession session = [Link]();

[Link]("userId", 101);

Scope:
Valid until the session expires or is invalidated.

3.7.3. Application (Context) Scope Attributes


Application scope attributes are shared across the entire web application and are accessible to all
users and all servlets.

Methods Used:

 getServletContext().setAttribute()

 getServletContext().getAttribute()

Example:

ServletContext context = getServletContext();

[Link]("college", "Karpagam Institute of Technology");

Scope:
Valid until the application is stopped or restarted.

3.7.4. Page Scope Attributes


Page scope attributes are available only within a single JSP page. These are mostly used in JSP, not
72
directly in servlets.

Example (JSP):

<% [Link]("msg", "Welcome"); %>

3.8 Response and Redirection using Request Dispatcher


In Servlets, the RequestDispatcher interface is used to control the flow of a request between
different web resources such as servlets, JSP pages, or HTML files. It enables one servlet to send a
request to another resource for further processing or response generation within the same server.

Request Dispatcher
A Request Dispatcher object is obtained using:

Reques tDispatcher rd = [Link]("[Link]");

It supports two main operations:

1. Forward

2. Include

1. Response using RequestDispatcher – Forward

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

 Same request object is used

 Faster and secure

 Used to send response from another resource

2. Response using RequestDispatcher – Include

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

 Used to reuse components (header, footer)

 Response is combined

 URL remains unchanged

74
Difference Table

Feature RequestDispatcher (Forward) sendRedirect()

Type Server-side Client-side

Request Object Same New request

URL Change No Yes

Speed Faster Slower

Data Sharing Possible Not possible

3.9 send Redirect Method


The sendRedirect() method is used in servlets to redirect the client to a new URL. It is a client-side
redirection technique, where the server instructs the browser to make a new request to a different
resource such as another servlet, JSP page, HTML file, or even an external website.

Definition

sendRedirect() is a method of the HttpServletResponse interface that sends a response to the client
with a redirection instruction.

Syntax

[Link]("url");

How sendRedirect Works

1. Client sends a request to the servlet.

2. Servlet processes the request.

3. Server sends a redirect response (HTTP status code 302).

4. Browser receives the response.

5. Browser makes a new request to the given URL.

75
6. Response is displayed to the client.

Example

public class LoginServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws IOException {

String user = [Link]("username");

String pass = [Link]("password");

if([Link]("admin") && [Link]("1234")) {

[Link]("[Link]");

} else {

[Link]("[Link]");

Key Features of sendRedirect()

 It is a client-side redirection

 Creates a new request and response

 URL in the browser changes

 Can redirect to external websites

 Data sharing using request attributes is not possible

3.10 Session Tracking: using Cookies, HTTP Session


76
Servlets are the Java programs that run on the Java-enabled web server or application server. They are
used to handle the request obtained from the webserver, process the request, produce the response,
then send a response back to the webserver

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.

 The recording of the object in session is known as tracking.

 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.

3.10.2 Why is Session Tracking Required?


 Because the HTTP protocol is stateless, we require Session Tracking to make the client-server
relationship stateful.

 Session tracking is important for tracking conversions in online shopping, mailing


applications, and E-Commerce applications.

 The HTTP protocol is stateless, which implies that each request is treated as a new one. As
you can see in the image below.

Deleting Session Data

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].

Session Tracking employs Four Different techniques

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.

3.11.1 Performing CRUD (Create, Read, Update, Delete) operation


using Servlet with JDBC.

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.

3.11.2 What are CRUD Operations

CRUD stands for:

 C (Create) -> Insert new records into the database.

 R (Read) -> Retrieve records from the database.

 U (Update) -> Modify existing records.

 D (Delete) -> Remove records from the database.

3.11.3 CRUD Operations in JDBC with MySQL

Step 1. Database Setup in MySQL

 In this step, we create a database and a table where student records will be stored.

 Run the following commands in MySQL Workbench / CLI:

CREATE DATABASE studentdb;

USE studentdb;

CREATE TABLE students (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100) NOT NULL,

age INT NOT NULL,

email VARCHAR(150) UNIQUE

);

Step 2. Maven Dependency for MySQL

79
 We add the MySQL connector dependency in [Link] so Java can talk to MySQL.

 This downloads the driver automatically from Maven Central.

[Link]:

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-j</artifactId>

<version>9.0.0</version>

</dependency>

Step 3. Create JDBC connection

 This utility class sets up a connection with MySQL using JDBC.

 Change username and password as per your local MySQL setup.

import [Link];

import [Link];

public class Geeks{

private static final String URL = "jdbc:mysql://localhost:3306/studentdb";

private static final String USER = "root"; // change if different

private static final String PASSWORD = "yourpassword"; // change to your MySQL password

public static Connection getConnection() {

try {

return [Link](URL, USER, PASSWORD);

} catch (Exception e) {

[Link]();

80
return null;

Step 4. Create Operation (Insert Student)

 Use INSERT query to add new student records into the database.

 We use PreparedStatement to prevent SQL Injection.

This will add new student records into the database.

import [Link];

import [Link];

public class CreateStudent {

public static void insertStudent(String name, int age, String email) {

String sql = "INSERT INTO students (name, age, email) VALUES (?, ?, ?)";

try (Connection conn = [Link]();

PreparedStatement stmt = [Link](sql)) {

[Link](1, name);

[Link](2, age);

[Link](3, email);

int rows = [Link]();

81
[Link](rows + " student inserted successfully.");

} catch (Exception e) {

[Link]();

Step 5 Read Operation (Fetch Students)

 Use SELECT query to retrieve student details from the table.

 Results are stored in a ResultSet which we loop through to display records.

import [Link];

import [Link];

import [Link];

public class ReadStudent {

public static void getAllStudents() {

String sql = "SELECT * FROM students";

try (Connection conn = [Link]();

Statement stmt = [Link]();

ResultSet rs = [Link](sql)) {

while ([Link]()) {

82
[Link]([Link]("id") + " | " +

[Link]("name") + " | " +

[Link]("age") + " | " +

[Link]("email"));

} catch (Exception e) {

[Link]();

Step 6. Update Operation (Modify Student Email)

 Use UPDATE query to change existing student details.

 Here we update a student’s email by using their id.

import [Link];

import [Link];

public class UpdateStudent {

public static void updateStudent(int id, String newEmail) {

String sql = "UPDATE students SET email = ? WHERE id = ?";

try (Connection conn = [Link]();

PreparedStatement stmt = [Link](sql)) {

[Link](1, newEmail);

83
[Link](2, id);

int rows = [Link]();

[Link](rows + " student updated successfully.");

} catch (Exception e) {

[Link]();

Step 7. Delete Operation (Remove Student)

 Use DELETE query to remove student records by ID.

 Once deleted, the record will no longer appear in the table.

import [Link];

import [Link];

public class DeleteStudent {

public static void deleteStudent(int id) {

String sql = "DELETE FROM students WHERE id = ?";

try (Connection conn = [Link]();

PreparedStatement stmt = [Link](sql)) {

84
[Link](1, id);

int rows = [Link]();

[Link](rows + " student deleted successfully.");

} catch (Exception e) {

[Link]();

Step 8. Main Class (Testing All CRUD Operations)

 This is the driver class where we test all four operations step by step.

 Insert -> Display -> Update -> Delete -> Display again.

public class MainApp {

public static void main(String[] args) {

// CREATE

[Link]("Alice", 22, "alice@[Link]");

[Link]("Bob", 23, "bob@[Link]");

// READ

[Link]("\nAll Students:");

[Link]();

85
// UPDATE

[Link](1, "alice_new@[Link]");

// DELETE

[Link](2);

// READ again

[Link]("\nAfter Update/Delete:");

[Link]();

Step 9. Run Application

 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

4.1 INTRODUCTION TO JSP


Java Server Pages (JSP) is a server-side technology used to create dynamic web pages
using Java. JSP allows developers to embed Java code directly into HTML using special tags, making
web page development easier and faster compared to servlets.

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.

4.1.1 Features of JSP


 Easy to develop dynamic web pages

 Separation of presentation and logic

 Supports Expression Language (EL)

 Supports JSTL (JSP Standard Tag Library)

 Automatically manages session, request, response objects

 Platform independent

4.1.2 BASIC EXAMPLE

<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

Servlet is a Java code. JSP is an HTML-based compilation code.

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.

In Servlet by default session management is In JSP session management is automatically


not enabled, user have to enable it explicitly. enabled.

In Servlet we have to implement everything In JSP business logic is separated from


like business logic and presentation logic in presentation logic by using JavaBeansclient-
just one servlet file. side.

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.

4.3 JSP ARCHITECTURE:


JSP (Java Server Pages) uses a three-tier architecture with a client, web server, and database. When
the client sends a request, the web server's JSP engine processes the JSP file by converting it into a
servlet, compiling, and executing it. The generated HTML is sent back to the client. The following
diagram shows the architecture of JSP.

JSP (JavaServer Pages): It is a server-side technology used to create dynamic, platform-independent


web applications. It allows embedding Java code directly into HTML or XML using JSP tags. When a
client sends a request, the JSP file is first converted into a servlet by the JSP container, then compiled
and executed.

Below diagram explanation step-by-step working of JSP.


4.3.1 Working of a JSP file

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.

4.4 LIFECYCLE OF JSP:


The life cycle of a JavaServer Page (JSP) consists of various phases that start from its creation,
followed by its translation into a servlet, and finally managed by the servlet lifecycle. The JSP engine
handles this process automatically.
4.4.1 Steps of JSP Life Cycle
1. Translation of JSP page to Servlet

2. Compilation of JSP page(Compilation of JSP into [Link])

3. Classloading ([Link] to [Link])

4. Instantiation(Object of the generated Servlet is created)

5. Initialization(jspInit() method is invoked by the container)

6. Request processing(_jspService()is invoked by the container)

7. JSP Cleanup (jspDestroy() method is invoked by the container)

We can override jspInit(), jspDestroy() but we can't override _jspService() method.

1. Translation of JSP to Servlet

 The JSP file is parsed and converted into a Java servlet source file ([Link]).

 This step checks for syntax correctness.

// The JSP is converted to a servlet class.

public class TestServlet extends HttpServlet {

// The generated servlet code

}
2. Compilation of JSP page

 The generated [Link] file is compiled into a class file ([Link]).

 This step converts the servlet code into bytecode.

// JSP is automatically converted into a servlet, such as

public class TestServlet extends HttpServlet {

// Generated servlet code here

3. Class loading

 The container dynamically loads the compiled class.

4. Instantiation

 The container creates an instance of the generated servlet class.

 This instance handles multiple requests unless explicitly configured otherwise.

// The container creates an instance automatically.

TestServlet servlet = new TestServlet();

5. Initialization (jspInit())

 This method is called only once when the JSP is first loaded.

 It is used for initializing resources like database connections or configurations.

public void jspInit() {

// Initialization code, like setting up resources.

[Link]("JSP Initialized.");

}
6. Request Processing (_jspService())

 This method is called for every request.

 It cannot be overridden because it is auto-generated and declared as final.

 It receives HttpServletRequest and HttpServletResponse objects to handle the request.

public void _jspService(HttpServletRequest request, HttpServletResponse response) {

// Code that handles the request, like generating HTML output.

[Link]().write("<html><body>Hello, World!</body></html>");

7. JSP Cleanup (jspDestroy())

 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.

public void jspDestroy() {

// Clean up resources like closing database connections.

[Link]("JSP Destroyed.");

This Lifecycle ensures that JSP pages are efficiently compiled, managed and cleaned up by the server
container

4.5 Scripting Elements in JSP:


Scripting Elements in JSP (JavaServer Pages) are special tags used to embed Java code directly
into JSP pages. These elements allow dynamic content generation by inserting Java logic inside
HTML.

There are three main types of scripting elements in JSP:

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;

[Link]("Sum = " + (a + b));

%>

Usage

 Writing business logic

 Looping and conditional statements

2. Expression

An Expression is used to output the value of a Java expression directly to the client.

Syntax

<%= expression %>

Example

<p>Current Time: <%= new [Link]() %></p>

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;

%>

<p>Square of 5: <%= square(5) %></p>

Usage

 Declaring global variables

 Defining helper methods

4.6 1. Directives in JSP


Directives provide instructions to the JSP container on how to process the JSP page. They are
processed at translation time.

Types of JSP Directives

(a) Page Directive


Used to define page-level settings.

Syntax:

<%@ page language="java" contentType="text/html" errorPage="[Link]" %>

Attributes:

 language

 contentType

 import

 session

 errorPage

 isErrorPage

(b) Include Directive

Includes the content of another file at translation time.

Syntax:

<%@ include file="[Link]" %>

(c) Taglib Directive

Used to define custom tags or JSTL libraries.

Syntax:

<%@ taglib uri="[Link] prefix="c" %>

4.7 ACTION TAGS:


JSP action tags are special elements that give instructions to the JSP container for handling various
runtime tasks. They execute on the server side and help developers include external resources, forward
requests, and interact with JavaBeans or plugins.

They are always enclosed within <jsp: ... > and can be placed anywhere in the JSP page where
dynamic behavior is required.
Common JSP Action Tags

4.7.1. <jsp:include> Tag

Includes content from another resource (JSP, HTML, or servlet) into the current page at request time.

Syntax:

<jsp:include page="[Link]" />

Usage: Helps in modularizing JSP pages by reusing header, footer, or navigation components.

4.7.2. <jsp:forward> Tag

Forwards the current request to another resource such as a JSP, HTML, or servlet. The client is
unaware of the forwarding.

Syntax:

<jsp:forward page="[Link]" />

Note: Once the forward tag is executed, the rest of the current page is skipped.

4.7.3. <jsp:useBean> Tag

Instantiates or locates an existing JavaBean to use within a JSP page.

Syntax:

<jsp:useBean id="beanId" class="[Link]" />

Example:

<jsp:useBean id="user" class="[Link]" />

Note: If the bean does not exist in the specified scope, a new instance is automatically created.

4.7.4. <jsp:setProperty> Tag

Sets a property value of a JavaBean component.

Syntax:

<jsp:setProperty name="beanName" property="propertyName" value="propertyValue" />

Example:
<jsp:setProperty name="user" property="username" value="John" />

Note: It can also retrieve values directly from request parameters by using property="*".

4.7.5. <jsp:getProperty> Tag

Retrieves and displays the value of a JavaBean property.

Syntax:

<jsp:getProperty name="beanName" property="propertyName" />

Example:

<jsp:getProperty name="user" property="username" />

Usage: Commonly used to display data stored in JavaBeans directly on JSP pages.

4.7.6. <jsp:plugin> Tag

Generates HTML code for browser-specific plugins such as Java applets.

Syntax:

<jsp:plugin type="pluginType" code="pluginCode" />

Example:

<jsp:plugin type="applet" code="[Link]" />

Note: This tag ensures that required browser plugins are loaded properly.

4.7.7. <jsp:attribute> Tag

Defines attribute values for custom JSP tags.

Syntax:

<jsp:attribute name="attributeName" value="attributeValue" />

Example:

<jsp:attribute name="color" value="blue" />

Usage: Used inside custom tag handlers to pass dynamic attributes.

4.7.8. <jsp:body> Tag


Defines the body content of a custom JSP tag.

Syntax:

<jsp:body> Body Content </jsp:body>

Example:

<jsp:body>

<p>This is the body content.</p>

</jsp:body>

4.8 IMPLICIT OBJECTS:

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.

List of JSP Implicit Objects

Implicit Object Type Description

Request HttpServletRequest Holds client request data

Response HttpServletResponse Sends response to client

Out JspWriter Writes output to browser

Session HttpSession Maintains user session

application ServletContext Shares data across application

Config ServletConfig Accesses servlet configuration

pageContext PageContext Provides access to all JSP objects

Page Object Reference to current JSP page

exception Throwable Handles errors (only in error pages)

4.9 JAVABEANS IN JSP


JavaBeans are reusable Java software components used in JSP to encapsulate data and business logic,
promoting a cleaner, more modular separation of concerns (Model-View-Controller architecture).
They are essentially standard Java classes that follow specific naming and design conventions.

JavaBean Conventions

To be considered a JavaBean, a class must adhere to the following rules:

 Public no-argument constructor: This allows the JSP container and development tools to easily
instantiate the bean.

 Private properties: Data fields should be private to enforce encapsulation.

 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.

Using JavaBeans in JSP

JSP provides specific action tags to work with JavaBeans, which abstract away the need for extensive
Java scriptlet code:

 <jsp:useBean>: This action locates or instantiates a bean within a specified scope


(page, request, session, or application). If the bean doesn't exist in the specified scope, it creates
a new instance.

jsp

<jsp:useBean id="userBean" class="[Link]" scope="session" />

 <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:setProperty name="userBean" property="name" value="John Doe" />

<%-- or from a request parameter --%>

<jsp:setProperty name="userBean" property="age" param="userAge" />


<%-- or all matching properties from request parameters --%>

<jsp:setProperty name="userBean" property="*" />

 <jsp:getProperty>: This action retrieves the value of a bean property and inserts it into the
HTML output stream.

jsp

<p>Hello, <jsp:getProperty name="userBean" property="name" />!</p>

4.10 Expression Language (EL) in JSP


Expression Language (EL) is a simplified syntax in JSP used to access data stored in JavaBeans,
implicit objects, collections, and scopes without writing Java code.
It makes JSP pages cleaner, readable, and easier to maintain by reducing the use of scriptlets (<%
%>).

4.10.1 Syntax of EL

${expression}

4.10.2 Features of JSP EL

 No Java code required

 Easy access to data

 Automatic type conversion

 Supports operators

 Works with JavaBeans, Maps, Lists, and Arrays

4.10.3 Accessing Data using EL

1. Accessing Request Parameters

${[Link]}

Equivalent to:

[Link]("username");
2. Accessing Attributes from Scopes

Scope EL Syntax

Page ${[Link]}

Request ${[Link]}

Session ${[Link]}

Application ${[Link]}

Example:

${[Link]}

3. Accessing JavaBeans Properties

If a JavaBean has getName() method:

${[Link]}

4. Accessing Arrays, Lists, and Maps

${colors[0]}

${marks[1]}

${map["key"]}

4.10.4 EL Implicit Objects

EL Object Description

Param Request parameters

paramValues Multiple parameter values

Header Request headers

headerValues Multiple header values

Cookie Cookies

initParam Context init parameters

pageScope Page scope attributes


EL Object Description

requestScope Request scope attributes

sessionScope Session scope attributes

applicationScope Application scope attributes

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

${marks >= 50 ? "Pass" : "Fail"}

EL with JSTL Example

<c:if test="${age >= 18}">

Eligible to Vote

</c:if>

4.10.6 Advantages of EL

 Removes Java code from JSP

 Improves MVC architecture

 Easy to learn and use


 Reduces errors

4.11 JSP Standard Tag Libraries (JSTL) Core Tags:

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.

4.11.1 Why Use JSTL?

 Eliminates the need for scriptlets (<% %>) in JSP pages

 Improves readability and maintainability of JSP files

 Provides built-in tags for iteration, conditional checks, and data formatting

 Supports internationalization (i18n) and localization

 Enables XML data processing and database interactions


JSTL Tag Libraries
Prefi
Library x Description

General-purpose tags for variables, flow


c
Core Tags control, loops, and URL handling

Formatting For number, date, and message formatting


fmt
Tags with localization support

For executing database queries and updates


sql
SQL Tags (for demo/testing only)

XML Tags x For parsing and transforming XML documents

Function Contains utility functions for string and


fn
Tags collection operations

Adding JSTL to a Project

Step 1: Include Dependency


For Maven projects, add the following dependency in [Link]:

<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>

Step 2: Import JSTL in JSP

At the top of your JSP file, include the relevant JSTL tag libraries:

<%@ taglib uri="[Link] prefix="c" %>

<%@ taglib uri="[Link] prefix="fmt" %>

<%@ taglib uri="[Link] prefix="fn" %>

4.12 Session Management


Session Management is the technique used in web applications to maintain user state and data
across multiple HTTP requests.
Since HTTP is stateless, session management helps the server remember who the user is and what
actions they have performed.

4.12.1 Why Session Management is Needed

 To maintain login information

 To store user preferences


 To manage shopping carts

 To track user activities

4.12.2 Common Session Management Techniques

1. Cookies

Cookies are small pieces of data stored on the client’s browser.

Types of Cookies:

 Persistent Cookies – Stored for a specific time

 Non-Persistent Cookies – Deleted when browser closes

Example:

Cookie ck = new Cookie("user", "Akshaya");

[Link](ck);

Advantages:

 Simple to use

 Stores data on client side

Disadvantages:

 Limited size

 Security issues

2. URL Rewriting

Session information is passed through the URL.

Example:

[Link]?user=Akshaya

Advantages:

 Works when cookies are disabled

Disadvantages:

 Data visible in URL


 Not secure

3. Hidden Form Fields

Data is stored inside hidden HTML form fields.

Example:

<input type="hidden" name="user" value="Akshaya">

Advantages:

 Simple implementation

Disadvantages:

 Works only with forms

 Not secure

4. HttpSession (Server-Side Session)

Stores session data on the server using HttpSession.

Example:

HttpSession session = [Link]();

[Link]("user", "Akshaya");

Retrieve Data:

String user = (String) [Link]("user");

4.13 EXCEPTION HANDLING:

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.

4.13.1 Need for Exception Handling

 Prevents application failure

 Improves reliability
 Helps in debugging

 Provides better user experience

4.13.2 Types of Exceptions

1. Checked Exceptions – Occur at compile time (e.g., SQLException, IOException)

2. Unchecked Exceptions – Occur at runtime (e.g., NullPointerException, ArithmeticException)

4.13.3 Exception Handling in Servlets

Using try–catch Block

try {

int a = 10 / 0;

} catch (ArithmeticException e) {

[Link]().println("Error: Division by zero");

Using throws Keyword

public void doGet(HttpServletRequest req, HttpServletResponse res)

throws IOException, ServletException {

// code

4.13.4 Exception Handling in JSP

1. Using try–catch in JSP

<%

try {

int a = 10 / 0;

} catch (Exception e) {

[Link]("Error occurred");

}
%>

2. Using JSP Error Pages (Recommended)

Step 1: Main JSP Page

<%@ page errorPage="[Link]" %>

Step 2: Error JSP Page

<%@ page isErrorPage="true" %>

Error Message: <%= [Link]() %>

🔹 The exception implicit object is available only in error pages.

4.13.5 Exception Handling using [Link]

<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>

4.13.6 Common HTTP Error Codes

Code Meaning

404 Page Not Found

500 Internal Server Error

403 Forbidden

4.13.7 Advantages of Exception Handling

 Application stability
 Clean error management

 Separation of error logic

 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.

This follows the MVC architecture:

 Model → JDBC + Database

 View → JSP

 Controller → Servlet

4.14.1. Required Components

 JSP (for forms and display)

 Servlet (for processing requests)

 JDBC (for database connectivity)

 Database (MySQL / Oracle)

4.14.2. JDBC Connectivity (Common for All CRUD Operations)

[Link]("[Link]");

Connection con = [Link](

"jdbc:mysql://localhost:3306/studentdb", "root", "password");

4.14.3. CREATE Operation (Insert Data)

JSP Page ([Link])

<form action="InsertServlet" method="post">

Name: <input type="text" name="name"><br>


Age: <input type="text" name="age"><br>

<input type="submit" value="Insert">

</form>

Servlet ([Link])

String name = [Link]("name");

int age = [Link]([Link]("age"));

PreparedStatement ps =

[Link]("INSERT INTO student VALUES (?, ?)");

[Link](1, name);

[Link](2, age);

[Link]();

✔ Inserts a new record into the database.

4.14.4. READ Operation (Retrieve Data)

Servlet ([Link])

Statement st = [Link]();

ResultSet rs = [Link]("SELECT * FROM student");

[Link]("result", rs);

RequestDispatcher rd = [Link]("[Link]");

[Link](request, response);

JSP Page ([Link])

<%

ResultSet rs = (ResultSet)[Link]("result");

while([Link]()) {

%>
<%= [Link](1) %> - <%= [Link](2) %><br>

<%

%>

✔ Displays records from the database.

4.14.5. UPDATE Operation (Modify Data)

JSP Page ([Link])

<form action="UpdateServlet" method="post">

Name: <input type="text" name="name"><br>

New Age: <input type="text" name="age"><br>

<input type="submit" value="Update">

</form>

Servlet ([Link])

PreparedStatement ps =

[Link]("UPDATE student SET age=? WHERE name=?");

[Link](1, age);

[Link](2, name);

[Link]();

✔ Updates existing records.

4.14.6. DELETE Operation (Remove Data)

JSP Page ([Link])

<form action="DeleteServlet" method="post">

Name: <input type="text" name="name"><br>

<input type="submit" value="Delete">

</form>
Servlet ([Link])

PreparedStatement ps =

[Link]("DELETE FROM student WHERE name=?");

[Link](1, name);

[Link]();

✔ Deletes records from the database.


CHAPTER 5

OBJECT/RELATIONAL MAPPING

(ORM)WITH HIBERNATE

5.1 Object/Relational Mapping (ORM): Approaches to ORM:

5.1.1 Object / Relational Mapping (ORM)


Object/Relational Mapping (ORM) is a technique that enables developers to map object-oriented
classes to relational database tables. In object-oriented programming, data is handled in the form of
objects, whereas relational databases store data in tables. ORM acts as a bridge between these
two paradigms by automatically converting objects into database records and database records back
into objects. This approach allows developers to interact with the database using object-oriented
concepts instead of writing extensive SQL queries.

5.1.2 Need for ORM

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.

5.1.3 Approaches to ORM

XML-Based Mapping Approach


In the XML-based approach, the mapping information between Java classes and database tables is
defined in external XML configuration files. The Java classes remain independent of database-
specific details, making them clean and reusable. This approach provides high flexibility because
changes in database structure can often be managed by modifying the XML file without changing
the source code. However, XML files can become large and complex in enterprise applications,
which increases maintenance effort.

Annotation-Based Mapping Approach


Annotation-based ORM defines mapping metadata directly within the Java classes using annotations
such as @Entity, @Table, and @Id. This approach tightly integrates the object-relational mapping
with the source code, making it easier to understand and maintain. It significantly reduces
configuration overhead and is widely used in modern ORM frameworks like Hibernate and JPA.
The main limitation is that any change in database structure may require modification of the source
code.

Code-Based (Programmatic) Mapping Approach

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 Design Patterns

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.

Object/Relational Mapping provides an efficient way to integrate object-oriented applications with


relational databases. XML-based, annotation-based, and code-based ORM approaches each have their
own strengths and limitations. The choice of approach depends on application requirements,
complexity, and maintenance needs, with annotation-based ORM being the most widely adopted in
modern enterprise applications.

5.2 – Introduction to Hibernate

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.

5.2.1 Why Use Hibernate?


When working with JDBC, several challenges often arise:
1. Database Portability Issues: Changing the database in the middle of a project is costly because
JDBC code is not portable across different database systems.
2. Mandatory Exception Handling: JDBC requires explicit handling of exceptions for every
database operation, which increases code complexity.
3. Lack of Object-Level Relationships: JDBC works at the table level, so there is no direct support
for managing object relationships.
4. Boilerplate Code: For every project, repetitive code is needed for tasks like establishing
connections, executing queries and handling results. This increases code length and reduces
readability.
To overcome the above problems we use ORM tool i.e. nothing but Hibernate framework. By using
Hibernate we can avoid all the above problems and we can enjoy some additional set of
functionalities

5.3 HIBERNATE API


The Hibernate API provides an Object-Relational Mapping (ORM) framework for Java, allowing
developers to interact with relational databases using Java objects instead of writing raw JDBC code
and SQL queries. It serves as a bridge between the object-oriented Java domain model and the
relational database schema.
Hibernate is also a widely used, feature-rich implementation of the Jakarta Persistence API
(JPA) specification, extending the standard with its own native APIs and functionalities.
Core Components and APIs

The primary interfaces developers use in the Hibernate API are:


 SessionFactory: A thread-safe, immutable object created once per application's database, which
acts as a factory for Session instances.
 Session: A single-threaded, short-lived object representing a conversation between the
application and the database (a "unit of work"). It provides methods for performing CRUD
operations (create, read, update, delete), managing the persistence state of objects, and handling
transactions.
 Transaction: An API to abstract the application from the underlying transaction system (JDBC
or JTA), used to demarcate physical transaction boundaries (commit/rollback).
 Query and Criteria: Interfaces for executing object-oriented queries. Query is used for HQL
(Hibernate Query Language) or native SQL, while the Criteria API (deprecated in recent
versions in favor of JPA Criteria API) provides a programmatic way to build queries.
5.3.1 Key Features
 ORM Support: Automatically maps Java classes (POJOs) to database tables and Java data types
to SQL data types, managing the object-relational impedance mismatch.
 Database Independence: Applications can run on different databases with minimal configuration
changes because Hibernate generates database-specific SQL based on the configured dialect.
 HQL (Hibernate Query Language): An object-oriented query language that references Java
classes and properties rather than table and column names, which is translated into native SQL by
Hibernate.
 Caching: Improves performance by using a first-level cache (associated with the Session) and an
optional second-level cache (associated with the SessionFactory).
 Relationship Mapping: Supports complex object relationships (one-to-one, one-to-many, many-
to-many) using annotations or XML mapping files.
 Hibernate Reactive: A modern, non-blocking API designed for use in reactive programming
environments like Quarkus, offering an alternative to the traditional blocking I/O model of
standard Hibernate/JPA.

5.4 WORKING WITH OBJECTS IN HIBERNETS:


Hibernate is a popular Object/Relational Mapping (ORM) framework that allows Java developers to
work with database data as Java objects instead of writing SQL queries. In Hibernate, database
tables are mapped to Java entity classes, and each row in a table is represented as an object of that
class. This object-centric approach simplifies database operations and improves application
maintainability.

5.4.1 Entity Objects in Hibernate:


In Hibernate, objects are represented by entity classes. An entity class is a normal Java class annotated
with ORM annotations such as @Entity, @Table, and @Id. These classes define the structure of
data that will be stored in the database. Each instance of an entity class corresponds to a single
record in the database table. Hibernate automatically handles the conversion between object fields
and table columns.

5.4.2 Creating and Saving Objects:

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.

5.4.3 Retrieving Objects:

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.

5.4.4 Updating Objects:

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.

5.4.5 Deleting Objects:

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.

5.4.6 Object States in Hibernate:

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.

5.4.7 Transaction Management:

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.

5.4.8 Advantages of Working with Objects in Hibernate:


Hibernate simplifies database interaction by eliminating boilerplate JDBC code and SQL queries. It
improves developer productivity, ensures database independence, and supports advanced features such
as caching and lazy loading. Working with objects also aligns well with object-oriented design
principles, making applications more robust and scalable.

5.5 HIBERNATE ANNOTATIONS:

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.

5.5.1 Introduction to Annotations in Hibernate


Annotations are special metadata tags in Java that provide information to the Hibernate framework
about how a Java class should be mapped to a database table. Hibernate annotations are mainly based
on the Java Persistence API (JPA) standards, which ensures portability across different ORM
frameworks.

5.5.2 Entity Class Declaration


To make a Java class persistent, it must be declared as an entity using the @Entity annotation. The
@Table annotation is used to specify the table name in the database. If @Table is not provided,
Hibernate uses the class name as the table name by default.

5.5.3 Mapping Primary Key


Every entity must have a primary key, which is defined using the @Id annotation. Hibernate supports
automatic key generation using the @GeneratedValue annotation. Different strategies such as AUTO,
IDENTITY, and SEQUENCE can be used depending on the database.

5.5.4 Mapping Columns


The @Column annotation is used to map class fields to database table columns. It allows customization
such as column name, length, and null constraints. If @Column is not specified, Hibernate
automatically maps fields using default naming conventions.

5.5.5 Mapping Relationships


Hibernate annotations support relationships between entities. The @OneToOne, @OneToMany,
@ManyToOne, and @ManyToMany annotations are used to define associations between objects.
These annotations help represent real-world relationships in an object-oriented manner.

5.5.6 Hibernate Configuration using Annotations


When using annotations, Hibernate configuration is done through the [Link] file or a Java-
based configuration class. The entity classes are registered with Hibernate so that it can recognize
and manage them.

5.6 Querying in Hibernate – Hibernate Query Language(HQL)

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.

5.6.3 Aggregate Methods


Similar to SQL, HQL has several aggregation techniques, some of them are mentioned below-
 Average
 Max
 Min
 Count
 Sum
For details and examples regarding each aggregate method is mentioned below.
Average
To find the average of marks
String hib = "SELECT AVG(marks) FROM Student";
Query q=[Link](hib);

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));

5.7 Criteria queries – Creating queries with native SQL


Criteria Queries in Hibernate provide an object-oriented and programmatic way to retrieve data from the
database. Unlike HQL or SQL, criteria queries are written using Java objects and methods, not query
strings. This approach is especially useful when queries need to be dynamic, meaning conditions can
be added or removed at runtime based on application requirements.
Hibernate Criteria queries work on entity objects, not directly on database tables. Developers define
restrictions, projections, ordering, and conditions using predefined methods. Since criteria queries are
type-safe and object-based, they reduce syntax errors and improve readability. They are commonly
used in situations where query conditions depend on user input, such as search filters.
Criteria queries also support features like pagination, sorting, and joining associations between entities.
However, they may become complex and less readable for very large or complicated queries, and in
newer versions of Hibernate, the JPA Criteria API is preferred over the older Hibernate-specific
Criteria API.

5.7.1 Advantages of Criteria Queries


Criteria queries eliminate the need to write SQL or HQL manually, making the application more
database-independent. They are easy to modify dynamically and integrate well with object-oriented
design. This makes them suitable for advanced search and filtering operations in enterprise
applications.

5.7.2 Creating Queries with Native SQL in Hibernate


Native SQL queries allow developers to execute raw SQL statements directly within Hibernate. This
approach is useful when Hibernate features are insufficient, or when working with database-specific
functions, stored procedures, or complex joins that are difficult to express using HQL or Criteria
queries.
In native SQL, developers write queries exactly as they would in JDBC, but Hibernate still manages
session handling, transactions, and result mapping. Native SQL queries can return entity objects, scalar
values, or a combination of both. Hibernate maps the result set either to managed entity classes or to
custom result structures.
Although native SQL provides maximum flexibility and control over database operations, it reduces
portability because the SQL syntax may vary between databases. It also requires careful handling to
avoid errors and security issues such as SQL injection.

5.7.3 Use Cases for Native SQL Queries:


Native SQL queries are commonly used when performance optimization is critical, when working with
legacy databases, or when accessing database-specific features not supported by HQL or Criteria.
They are also helpful when existing SQL queries need to be reused in a Hibernate-based application.

5.7.4 Comparison: Criteria Queries vs Native SQL:


Criteria queries focus on object-oriented querying, offering flexibility and database independence,while
native SQL focuses on direct database interaction, offering power and performance. Criteria queries are
easier to maintain and safer for dynamic queries, whereas native SQL is more suitable for complex or
database-specific operations.

5.8 Basic Object/Relational (O/R) Mapping


Basic O/R mapping is the core concept of Hibernate in which a Java class is mapped to a database table
and the fields of the class are mapped to columns in that table. Each object of the class represents one
row in the table. Hibernate manages this mapping automatically using annotations, allowing developers
to work with objects instead of SQL queries.

Example:
Consider a Student entity mapped to a student table.
@Entity
@Table(name = "student")
public class Student {

@Id
@GeneratedValue(strategy = [Link])
private int id;

private String name;


private int age;

// getters and setters


}

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.

5.9 Collections Mappings


If an entity or class has collection of values for a particular variable, then we can map those values
using any one of the collection interfaces available in java. Hibernate can persist instances
of [Link], [Link], [Link], [Link], [Link], and any array of
persistent entities or values.
[Link]. Collection type & Mapping Description

[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.

5.10 Association Mappings


The mapping of associations between entity classes and the relationships between tables is the soul of
ORM. Following are the four ways in which the cardinality of the relationship between the objects can
be expressed. An association mapping can be unidirectional as well as bidirectional.
[Link]. Mapping type & Description

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

5.11 INHERITANCE MAPPING


Inheritance mapping allows Hibernate to persist class hierarchies into relational tables. This means a
superclass and its subclasses can be stored in the database while preserving inheritance relationships.
Example (Single Table Strategy):

@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.

5.12 Developing a Web Application by Integrating Servlet, JSP,


and Hibernate
Developing a web application by integrating Servlets, JSP, and Hibernate follows the Model–View–
Controller (MVC) architecture and is a standard approach in Java enterprise development. In this
integration, Hibernate handles database persistence, Servlets act as controllers to process client requests
and business logic, and JSP is used for presenting data to the user. This separation of responsibilities
results in a clean, scalable, and maintainable application.

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.

Role of Hibernate (Model Layer)


Hibernate represents the Model in the MVC architecture. It is responsible for mapping Java entity
classes to database tables and performing database operations such as insert, update, delete, and
retrieve. Developers work with Java objects, and Hibernate automatically converts them into SQL
queries. Hibernate also manages sessions and transactions, ensuring data consistency and improving
performance through features like caching and lazy loading.

Role of Servlet (Controller Layer)


Servlets act as the Controller. They receive HTTP requests from the client, read input parameters,
perform validations, and invoke Hibernate operations through service or DAO classes. After processing
the business logic, the Servlet decides which JSP page should be displayed and forwards the request
along with required data. Servlets ensure smooth communication between the view and the model
layers.

Role of JSP (View Layer)


JSP represents the View layer. It is used to design the user interface and display dynamic content. JSP
retrieves data passed by the Servlet, usually through request or session attributes, and presents it using
Expression Language (EL) or JSTL. JSP pages do not contain business logic; instead, they focus only
on presentation, making the application easier to maintain.

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.

Common questions

Powered by AI

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 .

You might also like