KEMBAR78
Full Stack Web Development - Handbook | PDF | World Wide Web | Internet & Web
100% found this document useful (1 vote)
204 views483 pages

Full Stack Web Development - Handbook

The document is a comprehensive guide on Full Stack Web Development, detailing essential topics such as front-end design with HTML, CSS, and JavaScript, back-end data handling with Java Servlets and JSP, and modern frameworks like ReactJS and Spring. It outlines learning outcomes, including knowledge of internet architecture, web technologies, and database management. The content is structured into chapters that cover both theoretical and practical aspects of web development.

Uploaded by

madhan444
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
204 views483 pages

Full Stack Web Development - Handbook

The document is a comprehensive guide on Full Stack Web Development, detailing essential topics such as front-end design with HTML, CSS, and JavaScript, back-end data handling with Java Servlets and JSP, and modern frameworks like ReactJS and Spring. It outlines learning outcomes, including knowledge of internet architecture, web technologies, and database management. The content is structured into chapters that cover both theoretical and practical aspects of web development.

Uploaded by

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

2022

Full Stack
Web Development

© Edunet Foundation. All rights reserved .1


Table of Content
Description Page No

Table of Content

Learning Outcomes

Chapter 1 – Building Front Face for Web

• Understanding the Web

• HTML for web Layout

• CSS for Page Design

• JS for Client-side scripting

• Building Dynamic web pages using HTML 5, CSS3 and JS

Chapter 2 – Handling the web data at backend

• Revisiting Java Object Oriented Paradigms

• Understanding Server-Side Scripting

• Introduction to Servlets and JSP

• Handling Client-side data

• Managing Sessions at Server and Cookies at Client

Chapter 3 – Connecting End-to-End

• Introduction to relational databases- MySQL

• Managing data in databases using JSP & Servlet

Chapter 4 – Modern web development using ReactJS

• Introduction to ReactJS

• Building React Native Application from Scratch

Chapter 5 – Web Development using Spring Framework

• Understanding MVC

• Integrating web template UI with Spring

© Edunet Foundation. All rights reserved .2


© Edunet Foundation. All rights reserved .3
Learning Outcomes

After going through this handbook, the reader will be able to:

• Knowledge of Internet, Domains, Networking

• Understanding architecture of a website

• Core JAVA (J2SE) Programming and Coding Skills

• Work with most popular web development technologies

• Create and host websites and web apps for commercial usage

• Create responsive and interactive UI

• Work with React JS framework to create responsive web applications

• Work with JAVA Spring framework for end-to-end web solutions

• Fundamentals of Databases

• Work with databases in web apps

• Basics of working with Windows and Linux OS

© Edunet Foundation. All rights reserved .4


Chapter 1 – Building Front Face for
the Web
Learning Outcomes:
• Understand and use basic internet functionalities
• Understand architecture of a website
• Design front-end of a web page and modify its content through HTML
and CSS
• Demonstrate understanding of client-side scripting

1.1 - Understanding the Web

Internet
What is Internet?
The Internet is essentially a global network of computing resources. You can think of
the Internet as a physical collection of routers and circuits as a set of shared
resources.
Some common definitions given in the past include −

• A network of networks based on the TCP/IP communications protocol.


• A community of people who use and develop those networks.

The Internet is the biggest world-wide communication network of computers. The


short form of internet is the 'net'. ... It is used by billions of people all over the world.

It enables the users to send, receive, collect, store, update, delete, and many other
operations of the data across the world.You can do all of this by connecting a computer
to the Internet, which is also called going online. When someone says a computer
is online, it's just another way of saying it's connected to the Internet.

How does the Internet work?

It's important to realize that the Internet is a global network of physical cables, which
can include copper telephone wires, TV cables, and fibre optic cables. Even wireless
connections like Wi-Fi and 3G/4G rely on these physical cables to access the Internet.

When you visit a website, your computer sends a request over these wires to a server.
A server is where websites are stored, and it works a lot like your computer's hard

© Edunet Foundation. All rights reserved .5


drive. Once the request arrives, the server retrieves the website and sends the correct
data back to your computer.

Internet-Based Services

Some of the basic services available to Internet users are −


• Email − A fast, easy, and inexpensive way to communicate with other Internet
users around the world.
• Telnet − Allows a user to log into a remote computer as though it were a local
system.
• FTP − Allows a user to transfer virtually every kind of file that can be stored on
a computer from one Internet-connected computer to another.
• UseNet news − A distributed bulletin board that offers a combination news and
discussion service on thousands of topics.
• World Wide Web (WWW) − A hypertext interface to Internet information
resources.

History and Evolution of the Internet


The Internet completely revolutionised communication and technology across the
Globe. Initially, computerised devices were only used for large industries but later its
usage increased massively.

It is also mandatory for people to know that it is not possible for a single person to
develop something as broad and wide as the Internet all by himself/herself. It was a
combined effort of multiple researchers and programmers that the Internet was
discovered.
Given below are a few important points which played an extremely important role in
the development of the Internet and making it one of the most widely used resources
across the world.

• The first development was the introduction of host-to-host network interactions.


This was first observed in ARPANET in 1969. It was developed by Advanced
Research Projects Agency (APRA) of the Department of Defence, U.S. It was
one of the first general usage of compu ter networks.
• Next step was commercialising the usage and making the transistors and
transmitters fit in smaller devices for convenient Internet usage for the general
public. This was introduced in the 1970s
• Moving forward, satellites and wireless communication was the main target.
Defence Advanced Research Projects Agency (formerly ARPA), supported
satellite-based radio packets for mobile usage of networks

© Edunet Foundation. All rights reserved .6


• The next was the development of Transmission Control Protocol (TCP). This
enabled different machines and networks across the world to assemble data
packets. It was in the 1980s that the TCP/IP approach was adapted by
researchers and technologists, following the footsteps of the U.S. Department
of Defence
• With the introduction of personal computers, the demand for commercial
Internet usage increased. This was the time when Ethernet and other Local
Area Networks cam in the foreground
• In 1993, the web browser was introduced, which followed the point-and-click
approach and is now a widely used operation for In ternet users
• The late 1990s was the time when thousands of Internet Service Providers has
taken up the market and most of them were from the U.S.
• And then the 21st century brought in an amalgamation of technology and
wireless Internet accessibility for its users. Wherein, wireless broadband
services came in as a boon for Internet users

Understanding HTTP Basics


HTTP stands for hypertext transfer protocol and is used to transfer data across the
Web.

It is a critical protocol for web developers to understand and because of it widespread


use it is also used in transferring data and commands in IOT applications.

How It Works

Like most of the Internet protocols http it is a command and response text
based protocol using a client server communications model.

Image: HTTP protocol


Reference: http://www.steves-internet-guide.com/http-basics/

The client makes a request and the server responds.

The HTTP protocol is also a stateless protocol meaning that the server isn’t
required to store session information, and each request is independent of the other.
© Edunet Foundation. All rights reserved .7
This means:

• All requests originate at the client ( your browser)


• The server responds to a request.
• The requests(commands) and responses are in readable text.
• The requests are independent of each other and the server doesn’t need to
track the requests.

Pros and Cons of Using the Internet


Intentionally or unintentionally, Internet usage is a part in the day to day lives of every
individual. The Internet has made lives easy and comfortable, but at the same time
made human being dependable for the smallest or biggest of information. Discussed
below are the uses of the internet, along with a few cons that it brings along.
Pros of Internet

• Easy Access to Information – Information on anything and everything are


available online. The Internet makes it convenient to learn about new things at
any point in time and get details on various subjects, irrespective of time and
place
• Platform for Online Education – With the advanced technology, even
students and adults wish to learn new things and gaining knowledge at various
online portals has become more accessible
• Job Hunting – Employers can look for employees on the internet and the job
seekers can apply online for jobs using the Internet
• Platform to become an Entrepreneur – Today, thousands of people have
started their own websites and getting good business and users/customers by
making their own websites and selling products or services. This has become
accessible due to Internet connectivity
• Visual and Graphical Representation of Things – Various researches have
shown that a person tends to get more engaged with a graphical representation
of things. Internet has made this facility also convenient for both user and
creator
• Reduced the parameter of Distance – Social media has reduced the distance
between people as communication has become much easier because of
Internet connection
With the Internet being an extremely essential part of daily life, it is important that a
person is well aware of the disadvantages of the Internet and its excess usage.

Cons of Internet

© Edunet Foundation. All rights reserved .8


• Dependency – The dependency of people for looking things and information
online has increased massively since the introduction of Internet and its easy
access
• Cyber Crime – People do not just use internet for learning purposes,
cybercrime has also been at a distinctive high because of effortless availability
of resources
• Distraction – People can easily find online games, interesting information, etc.
online which may be a cause of distraction for may
• Bullying and Trolls – Online platforms are being used for unethical practises
like bullying people and trolling them.

Web Page
Web page is a document available on world wide web. Web Pages are stored on web
server and can be viewed using a web browser.

A web page can contain huge information inclu ding text, graphics, audio, video and
hyperlinks. These hyperlinks are the link to other web pages.

Collection of linked web pages on a web server is known as website. There is


unique Uniform Resource Locator (URL) is associated with each web page.

A web page is a simple document displayable by a browser. Such documents are


written in the HTML language. A web page can embed a variety of different types of
resources such as:

• style information — controlling a page's look-and-feel


• scripts — which add interactivity to the page
• media — images, sounds, and videos.

Note: Browsers can also display other documents such as PDF files or images, but the
term web page specifically refers to HTML documents. Otherwise, we only use the
term document.

All web pages available on the web are reachable through a unique address. To access
a page, just type its address in your browser address bar:

© Edunet Foundation. All rights reserved .9


Image: Web Page
Reference:https://developer.mozilla.org/enUS/docs/Learn/Commonquestion/Pagessitesserversandsearchengines

What is Hyperlink?

A hyperlink or simply a link is a selectable element in an electronic document that


serves as an access point to other electronic resources. Typically, you click the
hyperlink to access the linked resource. Familiar hyperlinks include buttons, icons,
image maps, and clickable text links.

Type of Web Pages


Static Web page
Static web pages are also known as flat or stationary web page. They are loaded on
the client’s browser as exactly they are stored on the web server. Such web pages
contain only static information. User can only read the information but can’t do any
modification or interact with the information.
Static web pages are created using only HTML. Static web pages are only used when
the information is no more required to be modified.

Image: Static Web Page


Reference: https://www.tutorialspoint.com/internet_technologies/web_pages.htm

Dynamic Web page

© Edunet Foundation. All rights reserved .10


Dynamic web page shows different information at different point of time. It is possible
to change a portion of a web page without loading the entire web page. It has been
made possible using Ajax technology.

Server-side dynamic web page


It is created by using server-side scripting. There are server-side scripting parameters
that determine how to assemble a new web page which also includes setting up of
more client-side processing.

Client-side dynamic web page


It is processed using client side scripting such as JavaScript. And then passed in
to Document Object Model (DOM).

Image: Dynamic Web Page


Reference: https://www.tutorialspoint.com/internet_technologies/web_pages.htm

Website
A collection of web pages which are grouped together and usually connected
together in various ways. Often called a "web site" or a "site.

A website is a collection of linked web pages (plus their associated resources) that
shares a unique domain name. Each web page of a given website provides explicit
links—most of the time in the form of clickable portion of text—that allow the user to
move from one page of the website to another.

To access a website, type its domain name in your browser address bar, and the
browser will display the website's main web page, or homepage (casually referred as
"the home"):

What is ISP?
© Edunet Foundation. All rights reserved .11
ISP stands for Internet Service Provider. They are the companies who provide you
service in terms of internet connection to connect to the internet.
You will buy space on a Web Server from any Internet Service Provider. This space
will be used to host your Website.

Image: Internet Service Provider


Reference:https://developer.mozilla.org/enUS/docs/Learn/Common_questions/Pages_sites_servers_and_search_engines

The ideas of a web page and a website are especially easy to confuse for
a website that contains only one web page. Such a website is sometimes called
a single-page website.

A website is a collection of publicly accessible, interlinked Web pages that share a


single domain name. Websites can be created and maintained by an individual, group,
business or organization to serve a variety of purposes.

Together, all publicly accessible websites constitute the World Wide Web.

Although it is sometimes called “web page,” this definition is wrong, since a website
consists of several webpages. A website is also known as a “web presence” or simply
“site”.

Why you need a Website?

Here, are prime reasons why you need a website:

• An effective method to showcase your products and services


• Developing a site helps you to create your social proof
• Helps you in branding your business

© Edunet Foundation. All rights reserved .12


• Helps you to achieve your business goals
• Allows you to increase your customer support.

Web Application
A web application is a software or program which is accessible using any web browser.
Its frontend is usually created using languages like HTML, CSS, Javascript, which are
supported by major browsers. While the backend could use any programming stack
like LAMP, MEAN, etc. Unlike mobile apps, there is no specific SDK for developing
web applications.

Why you need a Web Application?

Web applications are more popular because of the following reasons:

• Compared to desktop applications, web applications are easier to maintain by


as they use the same code in the entire application. There are no compatibility
issues.
• Web applications can be used on any platform: Windows, Linux, Mac… as
they all support modern browsers.
• Mobile App store approval not required in web applications.
• Released any time and in any form. No need to remind users to update their
applications.
• You can access these web applications 24 hours of the day and 365 days a
year from any PC.
• You can either make use of the computer or your mobile device to access the
required data.
• Web applications are a cost-effective option for any organization. Seat
Licenses for Desktop software are expensive where SasS, are generally, pay
as you go.
• Web-Based Apps are Internet-enabled apps that are accessed through the
mobile's web browser. Therefore, you don't require downloading or installing
them.

Here is how a web application works:

1. The user creates a request to the web server over the Internet through the
application's user interface.
2. The web server sends this request to the web application server.
3. The web application server executes the requested task, then generates the
results of the required data.
4. The web application server sends those results back to the web server
(requested information or processed data).
5. The web server carries the requested information to the client (tablet, mobile
device or desktop).
6. The requested information appears on the user's display.
© Edunet Foundation. All rights reserved .13
Difference Between Web application and Website

Web Application: Web application is a piece of software that can be accessed by the
browser. A Browser is an application that is used to browse the internet.

Web application needs authentication. The web application uses a combination of


server-side scripts and client-side scripts to present information. It requires a server to
manage requests from the users.

Example: Google Apps

Website: Website is a collection of related web pages that contains images, text, audio,
video, etc. It can be consist of one page, two pages, and n number of pages.

A website provides visual and text content that users can view and read.

To view a website requires a browser(chrome, firefox). There are many types of


websites like Archive website, Blog, Community website, Dating website, etc.

Example: Amazon, youtube, etc.

Image: Web Site vs Web Application


Reference: https://www.guru99.com/difference-web-application-website.html

© Edunet Foundation. All rights reserved .14


Image: Web Site vs Web Application
Reference: https://www.guru99.com/difference-web-application-website.html

Image: Web Site vs Web Application


Reference: https://www.guru99.com/difference-web-application-website.html

Practical Activities
© Edunet Foundation. All rights reserved .15
Open/run the HTML file in a web browser to check the output.(40min)

Steps to run the HTML file in a web browser:

1. Press "Windows-E" to launch Windows Explorer.

2. Navigate to the folder that contains your HTML file.

3. Double-click the file. Your default browser displays the HTML document. If the
browser is not open, Windows launches it.

Program:

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>Black Goose Bistro</title>

</head>

<body text="blue">

<h1>Black Goose Bistro</h1>

<hr color="green">

<h2 text="blue">The Restaurant</h2>

<p>The Black Goose Bistro offers casual lunch and dinner fare in a hip atmosphere.
The menu changes regularly to highlight the freshest ingredients.</p>

<h2>Catering</h2>

You have fun... we'll do the cooking. Black Goose catering can handle events from
snacks for bridge club to elegant corporate fundraisers.

<h2>Location and Hours</h2>

Seekonk, Massachusetts; Monday through Thursday 11am to 9pm, Friday and


Saturday, 11am to midnight

</body>

© Edunet Foundation. All rights reserved .16


</html>

Output/Results snippet:

1.2 - HTML for web Layout

HTML Basic Components

HTML stands for Hyper Text Markup Language, is the standard markup language
used to create web pages. Along with CSS, and JavaScript, HTML is a cornerstone
technology used to create web pages, as well as to create user interfaces for mobile
and web applications.
✓ HTML stands for Hyper Text Markup Language
✓ HTML elements are the building blocks of HTML pages
✓ HTML describes the structure of Web pages using HyperText markup
language
✓ HTML elements are represented by tags
✓ When you test your page on browsers. Browsers do not display the HTML
tags, but use them to render the content of the page.
✓ HTML page extension always will be .html (example.html)

HTML Files

Every web page is actually a HTML file. Each HTML file is just a plain -text file, but with
a (.html) file extension instead of (.txt,) and is made up of many HTML tags as well as
the content for a web page.
A web site will often contain many html files that link to each other. You can edit HTML
files with your favourite editor. Like Dreamweaver, Notepad etc.

Creating HTML Document:


Creating an HTML document is easy. To begin coding HTML you need only two
things: a simple-text editor and a web browser. Notepad is the most basic of simple-
text editors and you will probably code a fair amount of HTML with it.

• Open Notepad or another text editor.


© Edunet Foundation. All rights reserved .17
• At the top of the page type <html>.
• On the next line, indent spaces and now add the opening header tag: <head>.
• On the next line, indent ten spaces and type <title> </title>.
• Go to the next line, indent five spaces from the margin and insert the closing
header tag: </head>.
• Five spaces in from the margin on the next line, type <body>.
• Now drop down another line and type the closing tag right below its
mate: </body>.
• Finally, go to the next line and type </html>.
• In the File menu, choose Save As.
• In the Save as Type option box, choose All Files.
• Name the file template.htm.
• Click Save.

HMTL Example

<!DOCTYPE html>
<html>
<body>
<h1>HTML Tutorial</h1>
<p>HTML Introduction</p>
</body>
</html>

HTML Page Structure


<html>
<head>
<title>Page title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>

<DOCTYPE! html>:
This tag is used to tells the HTML version. This currently tells that the version is
HTML 5.
<html>:
This is called HTML root element and used to wrap all the code.
© Edunet Foundation. All rights reserved .18
<head>:
Head tag contains metadata, title, page CSS etc. All the HTML elements that can be
used inside the <head> element are:
• <style>
• <title>
• <base>
• <noscript>
• <script>
• <meta>
• <title>
<body>:
Body tag is used to enclosed all the data which a web page has from texts to links.
All of the content that you see rendered in the browser is contained within this
element.

Example: HTML page can be created using any text editor (notepad). Then save that
file using .htm or .html extension and open that file in browser. It will get the HTML
page response.

Why learn HTML?


• It is a simple mark up language. Its implemen tation is easy.
• It is used to create a website.
• Helps in developing fundamentals about web programming.
• Boost professional career.

Features of HTML:
• It is easy to learn and easy to use.
• It is platform independent.
• Images, video and audio can be added to a web page.
• Hypertext can be added to text.
• It is a markup language.
Advantages:
• HTML is used to build a websites.
• It is supported by all browsers.
• It can be integrated with other languages like CSS, JavaScript etc.
Disadvantages:
• HTML can create only static webpages so for dynamic web page other
languages
have to be used.
• Large amount of code has to be written to create a simple web page.
• Security feature is not good.

List

© Edunet Foundation. All rights reserved .19


HTML List Tags are used to specify information in the form of list.
HTML Lists are very useful to group related information together. Often List items
look well-structured and they are easy to read for users. A list can contain one or
more list elements.

HTML List Types

List Type Description Tags used

Unordered
used to group a set of items without any order. <ul>,<li>
List

Ordered List used to group a set of items, in a specific order. <ol>,<li>

used to display some definition term (dt) & definition’s


Definition List <dl>,<dt>,<dd>
description (dd)

Unordered lists

Unordered lists are used to list set of items when they have no special order or
sequence. It is also called as bulleted list. Undordered list is created using
HTML <ul> tag. Each item in the list start with the <li> tag

Example of Unordered List

<ul>
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ul>

List Tags
<li> tag is used to display list elements and it is used in ordered and unordered list.
Above example will list items with bullets (small black circles) by default. There are
different list style available such as bullet, circle etc.
Unordered List Style Type Attribute
Like ordered list, type attribute is used to customize bullet style for the list of elements.
By default, a solid circle is used as bullets.
Type value : Numbering style
Disc : A solid circle
Square : A solid square
© Edunet Foundation. All rights reserved .20
Circle : An unfilled circle

HTML List Types

List Style Type Description Example & Syntax

disc Starts a list using discs type bullets (default) <ul type="disc">

circle Starts a list using circle type bullets <ul type="circle">

square Starts a list using square type bullets <ul type="square">

none Starts a list without bullets <ul type="type:none">

Example of Unordered List with Different List Styles


<html>
<title> Unordered List Example Test - Tutorials Class </title>
<body>

<h2>Unordered List of Fruits with Disc Bullets</h2>


<ul type="disc">
<li>Apple</li>
<li>Banana</li>
<li>Mango</li>
</ul>

<h2>Unordered List of Colors with Circle Bullets</h2>


<ul type="circle">
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ul>

<h2>Unordered List of Fruits with Square Bullets</h2>


<ul type="square">
<li>Apple</li>
<li>Banana</li>
<li>Mango</li>
</ul>

<h2>Unordered List of Colors without bullets</h2>


<ul type="none">
<li>Black</li>
<li>Green</li>
© Edunet Foundation. All rights reserved .21
<li>Blue</li>
</ul>

</body>
</html>

Ordered lists

Ordered list is used to list related items in a numbered or other specific order. This is
useful when you want to show counts of items in some way. Ordered list is created
using HTML <ol> tag. Each item in the list start with the <li> tag

Example of Ordered List

<ul>
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ul>

Above example will list colors items with numbers by default. There are different list
style available for ordered list such as numbers, letters etc.

Ordered List Style Type Attribute

There are two attributes can be used to customize ordered list, they are

(1) Type - changing numbering style

(2) Start - changing numbering order.

Type – is used to change the number style. The default number style is standard
Arabic numerals (1,2,3,…………).

Start – is used to specify the number of letter with which start the list. The default
starting point is 1. The value of the start attribute should be a decimal number,
regardless of the numbering style being used

HTML Ordered List Style Type Attribute

Example and
List Style Type Description
Syntax

© Edunet Foundation. All rights reserved .22


Numbers Starts a list using numbers (default) <ol type="1">

Uppercase letters Starts a list using uppercase letters <ol type="A">

Lowercase letters Starts a list using lowercase letters <ol type="a">

Uppercase roman Starts a list using uppercase roman


<ol type="I">
numbers numbers

Lowercase roman Starts a list using lowercase roman


<ol type="i">
numbers numbers

<html>
<title> Ordered List Example - Tutorials Class </title>
<body>

<h2>Ordered List of Fruits with Numbers </h2>


<ol type="1">
<li>Banana</li>
<li>Apple</li>
<li>Grapes</li>
</ol>

<h2>Ordered List of Fruits with Uppercase letters</h2>


<ol type="A">
<li>Apple</li>
<li>Banana</li>
<li>Mango</li>
</ol>

<h2>Ordered List of Colors with Lowercase letters</h2>


<ol type="a">
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ol>

<h2>Ordered List of Colors with Uppercase roman numbers</h2>


<ol type="I">
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ol>

© Edunet Foundation. All rights reserved .23


<h2>Ordered List of Colors with Lowercase roman numbers</h2>
<ol type="i">
<li>Red</li>
<li>Green</li>
<li>Blue</li>
</ol>

</body>
</html>

Definition Lists

Definition list is different from other two types of list. No bullet or number is provided
for the list items. In this list type, the list element has two parts.

(1) A definition term

(2) The definition description

Definition list is surrounded within <DL> ……. </DL> tags.

Definition term is presented in between <DT> ….. </DT> tag and

Definition description should be surrounded within <DD> ………… </DD> tag.

<dl>
<dt>Computer</dt>
<dd>Computer is an electronic device that is design ed to work with
Information.</dd>
<dt>HTML</dt>
<dd>HyperText Markup Language (HTML) is the standard markup language for
creating web pages and web applications.</dd>
</dl>

Tables
you can create tables for your website using the <table> tag in conjunction with
the <tr>, <td> and <th> tags.
The HTML tables allow displaying the data (e.g. image, text, link) in columns and
rows of cells. Table rows may be grouped into a head, foot, and body sections (via
the <thead>, <tfoot> and <tbody> elements, respectively).

The <caption> tag defines a table caption.The <caption> tag must be inserted
immediately after the <table> tag.

Note: You can specify only one caption per table.


© Edunet Foundation. All rights reserved .24
Cellpaddding - The cell padding attribute places spacing around data within
each cell.
Cellspacing - The cell spacing attribute places space around each cell in the table
Th - Table Head
Tr - Table Row
Td - Table Data

thead, tbody, and tfoot elements

<!DOCTYPE html>
<html>
<head>
<style>
thead {color:green;}
tbody {color:blue;}
tfoot {color:red;}

table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>

<h1>The thead, tbody, and tfoot elements</h1>

<table>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
© Edunet Foundation. All rights reserved .25
</tbody>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
</table>

<p><b>Tip:</b> The thead, tbody, and tfoot elements will not affect the layout of the
table by default. However, you can use CSS to style these elements.</p>

</body>
</html>

Month Savings
January $100
February $80
Sum $180

The <td> elements are the data containers of the table.


They can contain all sorts of HTML elements; text, images, lists, other tables, etc.

Simple Table

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
table, th, td {
border: 1px solid #666;
}
</style>
</head>
<body>
<table style="width:80%;">
<tr>
<th>Month</th>

© Edunet Foundation. All rights reserved .26


<th>Date</th>
</tr>
<tr>
<td>January</td>
<td>10.01.2014</td>
</tr>
<tr>
<td>February</td>
<td>10.01.2014</td>
</tr>
</table>
</body>
</html>

Month Date
January 10.01.2014
February 10.01.2014

ISBN Title Price


3476896 My first HTML $53
5869207 My first CSS $49

Graphics
What are Graphics?

Web graphics are visual representations used on a Web site to enhance or enable the
representation of an idea or feeling, in order to reach the Web site user. Graphics may
entertain, educate, or emotionally impact the user, and are crucial to strength of
branding, clarity of illustration, and ease of use for interfaces.
Examples of graphics include maps, photographs, designs and patterns, family trees,
diagrams, architectural or engineering blueprints, bar charts and pie charts,
typography, schematics, line art, flowcharts, and many other image forms.
Graphic designers have many tools and technologies at their disposal for everything
from print to Web development, and W3C provides many of the underlying formats
that can be used for the creation of content on the open Web platform.

© Edunet Foundation. All rights reserved .27


What are Graphics Used For?

Graphics are used for everything from enhancing the appearance of Web pages to
serving as the presentation and user interaction layer for full-fledged Web
Applications.
Different use cases for graphics demand different solutions, thus there are several
different technologies available. Photographs are best represented with PNG, while
interactive line art, data visualization, and even user interfaces need the power of SVG
and the Canvas API. CSS exists to enhance other formats like HTML or SVG.
WebCGM meets the needs for technical illustration and documentation in many
industries.

Graphic Elements in HTML5

• Canvas
• Scalable Vector Graphics (SVG)

Canvas Element

The <canvas> element:

• helps the browser to draw shapes and images without any plugin.
• is used to draw graphics, on the fly, via scripting.
• has several methods for drawing paths, boxes, circles, characters and adding
images.

The following is a sample of drawing a rectangle using a Canvas Element:

© Edunet Foundation. All rights reserved .28


The following is a sample of drawing a circle using a Canvas Element:

© Edunet Foundation. All rights reserved .29


Scalable Vector Graphics (SVG)

A <SVG> element:

• is based on vector-based family of graphics.


• defines graphics in XML Format.
• creates graphics that does not lose any quality when zoomed or resized

The following is a sample of drawing a rectangle using an <SVG> Element:

© Edunet Foundation. All rights reserved .30


The following is a sample of drawing a circle using an SVG Element:

© Edunet Foundation. All rights reserved .31


Differences between Canvas and SVG elements

Canvas svg
Canvas draws 2D graphics, on the fly
SVG defines the graphics in XML format.
(with a JavaScript).
Resolution dependent. Resolution independent.
In SVG, each drawn shape is
Canvas is rendered pixel by pixel.
remembered as an object.

Multimedia
What is Multimedia?

Multimedia comes in many different formats. It can be almost anything you can hear
or see, like images, music, sound, videos, records, films, animations, and more.Web
pages often contain multimedia elements of different types and formats.

Browser Support

The first web browsers had support for text only, limited to a single font in a single
color.Later came browsers with support for colors, fonts, images, and multimedia!

Multimedia Formats

Multimedia elements (like audio or video) are stored in media files.The most
common way to discover the type of a file, is to look at the file extension.Multimedia
files have formats and different extensions like: .wav, .mp3, .mp4, .mpg, .wmv, and
.avi.

Audio format

© Edunet Foundation. All rights reserved .32


Image: HTML Audio Format
Reference: https://www.sitesbay.com/html5/html5-audio-tag

Video format

Image: HTML Video Format


Reference: https://www.sitesbay.com/html5/html5-video-tag

The HTML5 <audio> element has specified a standard method to embed audio in a
web page.

<audio controls>
<source src="horse.ogg" type="audio/ogg">
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

The controls attribute is used to add audio controls, like play, pause, and volume.

© Edunet Foundation. All rights reserved .33


Text between the <audio> and </audio> tags will be displayed in browsers which
does not support the <audio> element.

Multiple <source> elements can be linked to different audio files. The browser will
be using the first recognized format.

The HTML5 <video> element is used to specify a standard way of embeding a video
in a web page.

<video width="320" height="240" controls>


<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>

The controls attribute is used to add video controls, like play, pause, and volume.
It is a good method to always use width and height attributes.
If height and width are not mentioned, the browser will not know the size of the video.
The effect of this is that page will be changing (or flicker) while the video gets loaded.
Text between the <video> and </video> tags will only get displayed in browsers which
do not support the <video> element.
Multiple <source> elements can be used to link different video files. The browser will
be using the first recognized format.

Forms

© Edunet Foundation. All rights reserved .34


HTML Forms are required to collect different kinds of user inputs, such as contact
details like name, email address, phone numbers, or details like credit card
information, etc.

Forms contain special elements called controls like inpu tbox, checkboxes, radio-
buttons, submit buttons, etc. Users generally complete a form by modifying its controls
e.g. entering text, selecting items, etc. and submitting this form to a web server for
further processing.

FORM ATTRIBUTES

Action Attribute

The action attribute defines the action to be performed when the form is submitted.

Usually, the form data is sent to a page on the server when the user clicks on the
submit button.

In the example above, the form data is sent to a page on the server called
"/action_page.php". This page contains a server-side script that handles the form
data:

<form action="/action_page.php">

If the action attribute is omitted, the action is set to the current page.

Target Attribute

The target attribute specifies if the submitted result will open in a new browser tab, a
frame, or in the current window.

The default value is "_self" which means the form will be submitted in the current
window.

To make the form result open in a new browser tab, use the value "_blank".

Here, the submitted result will open in a new browser tab:

<form action="/action_page.php" target="_blank">

Method Attribute

The method attribute specifies the HTTP method (GET or POST) to be used when
submitting the form data.

© Edunet Foundation. All rights reserved .35


<form action="/action_page.php" method="get">

<form action="/action_page.php" method="post">

EXAMPLE:

<form action="/action_page.php" target="_blank" method="post">

<label for="fname">First name:</label><br>

<input type="text" id="fname" name="fname" value="John"><br>

<label for="lname">Last name:</label><br>

<input type="text" id="lname" name="lname" value="Doe"><br><br>

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

</form>

Name Attribute

Each input field must have a name attribute to be submitted.

If the name attribute is omitted, the data of that input field will not be sent at all.

<form> <label>Username: <input type="text"></label>

<label>Password: <input type="password"></label>

<input type="submit" value="Submit"> </form>

Input Element

This is the most commonly used element within HTML forms. It allows you to specify
various types of user input fields, depending on the type attribute. An input element
can be of type text field, password field, checkbox, radio button, submit button, reset
button, file select box, as well as several new input types introduced in HTML5.

<input> element can be displayed in several ways, depending on the type attribute. If
the type attribute is omitted, the input field gets the default type: "text".

<form>
<label for="fname">Firstname:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Lastname:</label><br>
<input type="text" id="lname" name="lname">
</form>

© Edunet Foundation. All rights reserved .36


The for attribute of the <label> tag should be equal to the id attribute of the <input>
element to bind them together.

<label> Element

The <label> tag defines a label for many form elements.

The <label> element is useful for screen-reader users, because the screen-reader
will read out load the label when the user is focused on the input element.

Text Fields

Text fields are one line areas that allow the user to input text.

<form> <label for="username">Username:</label>

<input type="text" name="username" id="username"> </form>

Password Field

Password fields are similar to text fields. The only difference is; characters in a
password field are masked, i.e. they are shown as asterisks or dots. This is to prevent
someone else from reading the password on the screen .

<form> <label for="user-pwd">Password:</label>

<input type="password" name="user-password" id="user-pwd"> </form>

<button> Element

The <button> element defines a clickable button:

<button type="button" onclick="alert('Hello World!')">Click Me!</button>

Radio Buttons

Radio buttons are used to let the user select exactly one option from a pre-defined set
of options.

<form> <input type="radio" name="gender" id="male">

<label for="male">Male</label>

© Edunet Foundation. All rights reserved .37


<input type="radio" name="gender" id="female"> <label for="female">Female</label>
</form>

<form>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label><br>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label><br>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
</form>

Checkboxes

Checkboxes allows the user to select one or more option from a pre-defined set of
options. It is created using an <input> element whose type attribute has a value
of checkbox.

<form> <input type="checkbox" name="sports" id="soccer"> <label


for="soccer">Soccer</label> <input type="checkbox" name="sports" id="cricket">
<label for="cricket">Cricket</label> <input type="checkbox" name="sports"
id="baseball"> <label for="baseball">Baseball</label> </form>

<form> <input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">


<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a
car</label><br><input type="checkbox" id="vehicle3" name="vehicle3" value="Bot">
<label for="vehicle3"> I have a boat</label>
</form>

File Select box

The file fields allow a user to browse for a local file and send it as an attachment with
the form data.

<form> <label for="file-select">Upload:</label>

<input type="file" name="upload" id="file-select"> </form>

© Edunet Foundation. All rights reserved .38


Textarea

Textarea is a multiple-line text input control that allows a user to enter more than one
line of text. Multi-line text input controls are created using an <textarea> element.

<form> <label for="address">Address:</label>

<textarea rows="3" cols="30" name="address" id="address"></textarea> </form>

The rows attribute specifies the visible number of lines in a text area.

The cols attribute specifies the visible width of a text area.

Select Boxes

A select box is a dropdown list of options that allows user to select one or more option
from a pull-down list of options. Select box is created using the <select> element
and <option> element.

<select> element defines a drop-down list

To define a pre-selected option, add the selected attribute to the option

<form> <label for="city">City:</label>

<select name="city" id="city">

<option value="sydney">Sydney</option>

<option value="melbourne">Melbourne</option>

<option value="cromwell">Cromwell</option>

</select> </form>

<option value="fiat" selected>Fiat</option>

© Edunet Foundation. All rights reserved .39


Visible Values:

Use the size attribute to specify the number of visible values:

<select name="cars" size="3">


<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>

multiple attribute to allow the user to select more than one value:

<select name="cars" size="4" multiple>

Submit and Reset Buttons

Submit Button

<input type="submit"> defines a button for submitting the form data to a form-
handler.

The form-handler is typically a page on the server with a script for processing input
data.

The form-handler is specified in the form's action attribute.

<form action="/action_page.php">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" value="John"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" value="Doe"><br><br>
<input type="submit" value="Submit">
</form>

A submit button is used to send the form data to a web server. When submit button is
clicked the form data is sent to the file specified in the form's action attribute to process
the submitted data.

A reset button resets all the forms control to default values.

<form action="action.php" method="post">

<label for="first-name">First Name:</label>

<input type="text" name="first-name" id="first-name">

© Edunet Foundation. All rights reserved .40


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

<input type="reset" value="Reset"> </form>

Grouping Form Controls (<fieldset> and <legend>)

The <fieldset> element is used to group related data in a form.

The <legend> element defines a caption for the <fieldset> element.

You also group logically related controls and labels within a web form using
the <legend> element. Grouping form controls into categories makes it easier for
users to locate a control which makes the form more user-friendly.

<form>

<fieldset>

<legend>Contact Details</legend>

<label>Email Address: <input type="email" name="email"></label>

<label>Phone Number: <input type="text" name="phone"></label>

</fieldset> </form>

<datalist> Element

The <datalist> element specifies a list of pre-defined options for an <input> element.

Users will see a drop-down list of the pre-defined options as they input data.

The list attribute of the <input> element, must refer to the id attribute of
the <datalist> element.

<form action="/action_page.php">
<input list="browsers">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</form>
© Edunet Foundation. All rights reserved .41
<output> Element

The <output> element represents the result of a calculation (like one performed by a
script).

<form action="/action_page.php"
oninput="x.value=parseInt(a.value)+parseInt(b.value)">
0
<input type="range" id="a" name="a" value="50">
100 +
<input type="number" id="b" name="b" value="50">
=
<output name="x" for="a b"></output>
<br><br>
<input type="submit">
</form>

Formatting
HTML also defines special elements for defining text with a special meaning.

The formatting tags are divided into two categories:

physical tags, used for text styling (visual appearance of the text)

logical or semantic tags used to add semantic value to the parts of the text (for
example, let the search engines know what keywords should be web page ranked
for).

HTML uses elements like <b> and <i> for formatting output, like bold or italic text.

Formatting elements were designed to display special types of text:

<b> - Bold text

<strong> - Important text

<i> - Italic text

<em> - Emphasized text

<mark> - Marked text

<small> - Small text

<del> - Deleted text

<ins> - Inserted text

© Edunet Foundation. All rights reserved .42


<sub> - Subscript text

<sup> - Superscript text

<b> and <strong> Tags

The <b> tag is a physical tag that stands for bold text, whereas the <strong> tag
being a logical tag is used to emphasize the importance of the text.

<b>This text is bold</b>

<strong>This text is strong</strong>

<i> and <em> Tags

The <i> and <em> tags define italic text. The <i> tag is only responsible for visual
appearance of the enclosed text, without any extra importance. The <em> tag
defines emphasized text, with added semantic importance.

<i>This text is italic</i>

<em>This text is emphasized</em>

<pre> Tag

The <pre> tag is used to define preformatted text. The browsers render the enclosed
text with white spaces and line breaks.

<pre>Spaces

and line breaks

within this element

are shown as typed.

</pre>

<mark> Tag

The <mark> tag is used to present a part of text in one document as marked or
highlighted for reference purposes.

© Edunet Foundation. All rights reserved .43


<small> Tag

The <small> tag decreases the text font size by one size smaller than a document's
base font size (from medium to small, or from x-large to large).

The tag usually contains the items of secondary importance such as copyright
notices, side comments, or legal notices.

<p>The interest rate is only 10%*</p>

<small>* per day</small>

<big> Tag

The <big> tag defines bigger text.

<p><big>Bigger text</big></p>

<del> and <s> Tags

The <del> tag specifies a part of the text that was deleted from the document.
Browsers display this text as a strikethrough.

<p> She likes <del>violets</del> snowdrops․</p>

<p><s>I am studying in high school.</s></p>

The <s> tag defines text that is no longer correct, or relevant.

© Edunet Foundation. All rights reserved .44


The content of both tags is displayed as strikethrough. However, despite the visual
similarity, these tags cannot replace each other.

<ins> and <u> Tags

The <ins> tag defines the text that has been inserted (added) to the document. The
content of the tag is displayed as underlined.

<p>She likes <del>violets</del> <ins>snowdrops</ins>․</p>

The <u> tag specifies text that is stylistically different from normal text, i.e. words or
fragments of text that need to be presented differently. This could be misspelled
words or proper nouns in Chinese.

<p>Here we used <u>the &lt;u&gt; tag</u>.</p>

<sub> and <sup>

The <sub> defines subscript texts. Subscript text is under the baseline of other
symbols of the line and has smaller font. The <sup> tag defines superscript, that is
set slightly above the normal line of type and is relatively smaller than the rest of the
text. The baseline passes through upper or lower edge of the symbols.

<p>The formula of water is H<sub>2</sub>O, and the formula of alcohol is


C<sub>2</sub>H<sub>5</sub>ОН </p>

<p>E = mc<sup>2</sup>, where E — kinetic energy, m — mass, c — the speed


of light. </p>

<dfn> Tag

The <dfn> tag is used to define the term, that is mentioned for the first time. The
content of the tag is displayed in italic.

<p><dfn>HTML</dfn> (HyperText Markup Language ) — The standardized markup


language for documents on the World Wide Web. Most web pages contain a
description of the markup in the language HTML</p>

<p>, <br> and <hr> Tags

The <p> tag defines the paragraph. Browsers automatically add 1em margin before
and after each paragraph.
© Edunet Foundation. All rights reserved .45
<p>The first paragraph</p>

The <br> tag inserts a single line break. Unlike the <p> tag an empty indent is not
added before the line.

<h1>How to use the &lt;br&gt; tag</h1>

<p> We can insert the &lt;br /&gt; tag inside the paragraph, <br /> to transfer a
part of the text to another line if necessary.</p>

In HTML5 the <hr> tag defines a thematic change between paragraph level elements
in an HTML page. In previous versions of HTML it was used to draw a horizontal line
on the page visually separating the content. In HTML5 the element has semantic
meaning.

<h1>Football</h1>

<p>Team sports that involve, to varying degrees, kicking a ball with a foot to score
a goal.</p>

<hr>

<h1>Basketball</h1>

<p>A game played between two teams of five players in which goals are scored
by throwing a ball through a netted hoop fixed at each end of the court.</p>

Block components
HTML Blocks are grouping items of HTML elements. Each HTML element has its own
display based on the its type. However HTML blocks also have display but can group
the other HTML elements also as block.

By default, all block level elements are starts in new line. The elements added after
block level elements will start from new line. Block level elements can contain other
block line elements as nested block line elements. Block level elements can stretch to
the browser full width.

Examples of block-level elements -

Tags Description

<address> Specifies the contact information for a page or document

© Edunet Foundation. All rights reserved .46


<form> A Facility to submit the input data by user

<blockquote> used to define a quote section

<p> Paragraph

<pre> Preformatted text in HTML document

<h1> - <h6> Used to define HTML headings

<dd> Used to specify the term/description/name in a description list

<div> used to create block-level elements

<table> represents a table in an HTML document

<ol> Ordered list in html documents

<ul> Unordered list in HTML document

<nav> Specifies the navigation area

Block elements can be divided into two types.

1. Inline Elements
2. Group Elements

Inline elements

The inline elements do not start at newline. The inline elements always start in the
middle of the line and part of another element. The below list are the inline elements.

Tags Description

<b> used to display the text as bold

<i> Alternate Voice or different quality of text

<u> Unarticulated text/underlined text in HTML document

<p> Paragraph

<address> Specifies the contact information for a page or document

© Edunet Foundation. All rights reserved .47


<form> A Facility to submit the input data by user

<li> used to represent a list item in HTML document

<ins> Editorial Insertion

<del> Used for editorial deletion

<code> Used to define the computer code

Group elements

The Group elements always start with newline. The Group elements used to group
other elements. <div> and <span> are the majorly used Group elements.

<div>

<div> is mostly used to create block-level elements. In other words, <div> tag used to
define a section in HTML documents. Except <div>, all other have its own display.

The tag can be coded like <div></div> with its contents/other HTML tags inserted
between the opening and closing tags. <div> also acts as block-level element that is
used as container for other HTML elements. The <div> element has no additional
attributes by default.

style and class are commonly provided with DIV element. When <div> element used
together with CSS, the style blocks can be used together. All browsers always place
a line break before and after the <div> tag by default.

Syn tax -
<div>.....</div>
Example -
<!DOCTYPE html>
<html>
<head>
<title>div tag text example.. </title>
</head>
<body>
<div style="background-color:green;">
<h2>Heading</h2>
<p>This is paragraph</p>
</div>
</body>

© Edunet Foundation. All rights reserved .48


</html>

Output -

Heading

This is paragraph

<span>

Generic container for text or group inline-elements HTML. The <span> tag used to
specify the generic container for inline elements and content. There no visual change
that can be done by <span> tag.

It doesn’t represent anything other than its children. The tag can be specified like
<span class=""></span> with the content between the opening and closing tags.

Syn tax -
<span>.. text here.. </span>
Example -
<!DOCTYPE html>
<html>
<head>
<title>span tag example.. </title>
</head>
<body>
<p> <span style="color:red;font-weight:bold">Tutorials</span>
objective is to deliver the point to point online content on various
technologies(including technical and non -technical)to encourage the
reader to learn and gain expertise on their desired skills without
any conditions and restrictions. </p>
</body>
</html>

Output

Tutorials objective is to deliver the point to point online content on various


technologies (including technical and non -technical) to encourage the reader to learn
and gain expertise on their desired skills without any conditions and restrictions.

Practical Activity
Lists (30min)

Program:

© Edunet Foundation. All rights reserved .49


<!DOCTYPE html>
<html>
<body>

<h2>A Nested List</h2>

<ul>
<li>Coffee</li>
<li>Tea
<ul>
<li>Black tea</li>
<li>Green tea</li>
</ul>
</li>
<li>Milk</li>
</ul>

</body>
</html>

Output/Results snippet:

Tables (30mins)

Program:

<Html>

<head>

<title>Sample</title>

</head>

© Edunet Foundation. All rights reserved .50


<body bgcolor="#ff88ff">

<table border="4">

<thead>

<tr>

<th>Month</th>

<th>Savings</th>

</tr>

</thead>

<tbody>

<tr style="color:red;">

<td>January</td>

<td>$100</td>

</tr>

<tr>

<td>February</td>

<td>$80</td>

</tr>

</tbody>

<tfoot>

<tr>

<td>Sum</td>

<td>$180</td>

</tr>

</tfoot>

</table>

</body>

</Html>

Output/Results snippet:
© Edunet Foundation. All rights reserved .51
© Edunet Foundation. All rights reserved .52
Formatting(40mins)
Program:

<!DOCTYPE html>

<html>

<body>

<b>This text is bold</b> </br>

<strong>This text is strong</strong></br>

<i>This text is italic</i></br>

<em>This text is emphasized</em></br>

<p>The interest rate is only 10%*</p></br>

<small>* per day</small></br>

<p>She likes <del>violets</del> <ins>snowdrops</ins>․</p></br>

The formula of water is H<sub>2</sub>O</br>

<p>E = mc<sup>2</sup></br>

<pre>

</pre>

</body>

</html>

Output/Results snippet:

© Edunet Foundation. All rights reserved .53


Block-Components (40mins)

Program:

<!DOCTYPE html>

<html>

<head>

<style>

.nav {

background-color: yellow;

list-style-type: none;

text-align: center;

margin: 0;

padding: 0;

.nav li {

display: inline-block;

font-size: 20px;

padding: 20px;

© Edunet Foundation. All rights reserved .54


</style>

</head>

<body>

<h1>Horizontal Navigation Links</h1>

<p>By default, list items are displayed vertically. In this example we use display:
inline-block to display them horizontally (side by side).</p>

<p>Note: If you resize the browser window, the links will automatically break when it
becomes too crowded.</p>

<ul class="nav">

<li><a href="#home">Home</a></li>

<li><a href="#about">About Us</a></li>

<li><a href="#clients">Our Clients</a></li>

<li><a href="#contact">Contact Us</a></li>

</ul>

</body>

</html>

Output/Results snippet:

Forms (30mins)

Program:

© Edunet Foundation. All rights reserved .55


<!DOCTYPE html>

<html>

<head>

<style>

input[type=text] {

width: 100%;

padding: 12px 20px;

margin: 8px 0;

box-sizing: border-box;

</style>

</head>

<body>

<p>Padded text fields:</p>

<form>

<label for="fname">First Name</label>

<input type="text" id="fname" name="fname">

<label for="lname">Last Name</label>

<input type="text" id="lname" name="lname">

<input type="button" value="Click">

</form>

</body>

</html>

Output/Results snippet:

© Edunet Foundation. All rights reserved .56


1.3 - CSS for Page Design

CSS design principles


Forward and backward compatibility. CSS 2.2 user agents will be able to
understand CSS1 style sheets. CSS1 user agents will be able to read CSS 2.2 style
sheets and discard parts they do not understand. Also, user agents with no CSS
support will be able to display style-enhanced documents. Of course, the stylistic
enhancements made possible by CSS will not be rendered, but all content will be
presented.

Complementary to structured documents. Style sheets complement structured


documents (e.g., HTML and XML applications), providing stylistic information for the
marked-up text. It should be easy to change the style sheet with little or no impact on
the markup.

Vendor, platform, and device independence. Style sheets enable documents to


remain vendor, platform, and device independent. Style sheets themselves are also
vendor and platform independent, but CSS 2.2 allows you to target a style sheet for
a group of devices (e.g., printers).

Maintainability. By pointing to style sheets from documents, webmasters can


simplify site maintenance and retain consistent look and feel throughout the site. For
example, if the organization's background color changes, only one file needs to be
changed.

Simplicity. CSS is a simple style language which is human readable and writable.
The CSS properties are kept independent of each other to the largest extent possible
and there is generally only one way to achieve a certain effect.

Network performance. CSS provides for compact encodings of how to present


content. Compared to images or audio files, which are often used by authors to
achieve certain rendering effects, style sheets most often decrease the content size.
Also, fewer network connections have to be opened which further increases network
performance.

© Edunet Foundation. All rights reserved .57


Flexibility. CSS can be applied to content in several ways. The key feature is the
ability to cascade style information specified in the default (user agent) style sheet,
user style sheets, linked style sheets, the document head, and in attributes for the
elements forming the document body.

Richness. Providing authors with a rich set of rendering effects increases the
richness of the Web as a medium of expression. Designers have been longing for
functionality commonly found in desktop publishing and slide-show applications.
Some of the requested rendering effects conflict with device independence, but
CSS 2.2 goes a long way toward granting designers their requests.

Alternative language bindings. The set of CSS properties described in this


specification form a consistent formatting model for visual and aural presentations.
This formatting model can be accessed through the CSS language, but bindings to
other languages are also possible. For example, a JavaScript program may
dynamically change the value of a certain element's 'color' property.

Accessibility. Several CSS features will make the Web more accessible to users with
disabilities:

Properties to control font appearance allow authors to eliminate inaccessible bit-


mapped text images.
Positioning properties allow authors to eliminate mark-up tricks (e.g., invisible
images) to force layout.
The semantics of !important rules mean that users with particular presentation
requirements can override the author's style sheets.
The 'inherit' value for all properties improves cascading generality and allows for
easier and more consistent style tuning.

property:values
Properties
CSS properties are the styles used on specified selectors. They are written before
values in the CSS ruleset and are separated from property values by a colon.
Different HTML selectors and elements have different properties. Some properties
are universal and can be used on every selector. Others work only on specific
selectors and under particular conditions.
An example of that is grid-template-columns, which is used to style the layout of a
page. It works mainly with divs with their display property set to the grid (display:
grid).
There are many properties and their values for HTML selectors. According to CSS
Tricks, there are "520 distinct property names from 66 technical reports and 66
editor's drafts".

© Edunet Foundation. All rights reserved .58


Here are four common properties to work with

• List properties
• Font properties
• Border properties
• Text properties
These properties are common because they are frequently used in all CSS documents
and can be applied to different selectors. One unique thing about properties is that
they have more than one value attached to them. Text-transform, for example, a
property that controls a text's capitalization, can be set to uppercase, lowercase,
capitalize, or none. But this also poses a restraint. You must specify a value to the
right property else nothing happens. If we have 'text-transform: underline;' nothing will
change on the text part because underline is a value for text-decoration.
Below are some properties, their descriptions, and the values they accommodate.

TEXT

Properties Description Values

color Sets the color of a text Hex, RGB, keyword

text-transf orm Sets the capitalization of the text uppercase, lowercase, capitalize, none

text-align Sets the alignment of the text on the right, left, center, justify
screen

letter-spacing Sets the spacing between text characters normal, length

text-decoration Sets the decoration added to the text none, underline, line-through, overline

BORDER

Properties Description Values

border Sets the shorthand combination f or border-width, border-style, border-color


border-width, border-style and border-
color

border-color Sets the color f or the border Keyword, RGB, Hex, transparent, inherit

border-radius Sets the radius of the f our corners of an length, percentage, initial, inherit
element's border

border-style Sets the style f or an element's border none, hidden, dotted, solid, dashed…, i

border-image Sets an image as an element's border border-image-source, border-image-width…

© Edunet Foundation. All rights reserved .59


FONT

Properties Description Values

f ont Sets the shorthand f or all the f ont font-style, font-variant, font-weight, font-size/line-height
specif ications

f ont-weight Sets the weight of a f ont normal, bold, bolder, lighter,


100, 200, 300, 400, 500, 600, 700, 800, 900, inherit

f ont-style Sets the style of a f ont Normal, italic, oblique, initial, inherit

LIST

Properties Description Values

list-style Shorthand combination f or list-style-type, list-style-position, list-style-image, inherit


list-style-type, list-style-
position, and list-style-
image

list-image Sets an image as the list- none, url, initial, inherit


item marker

list-type This sets the type of list- none, disc, circle, square, decimal, decimal-leading-zero……
item marker

Values
Values are written immediately after the colon that separates them from CSS
properties. CSS values aren't just text; they come in different forms - URLs, units,
measurements, integers, strings, inherit, auto, none, etc. We will look at different CSS
values and how to implement them.

TEXT

Text values are prevalent in CSS. They are usually written without quotes, unlike
strings. Every valid CSS property has a text as a value. Margin takes units as values,
but it also has auto, which in this case, is taken as text.

h1 {

© Edunet Foundation. All rights reserved .60


color: red;
text-align: center;
}
Red and center are text values of color and text-align.

INTEGERS

Integers are numbers from one to zero or zero to nine. Some CSS properties make
allowance for their values to be defined as integers, even negative integers. The
values for properties like column-count and z-index are defined using integers.

div {
column-count: 4;
}
div {
z-index: -1;
}

UNITS/MEASUREMENTS

Because CSS must be used to position items on a web page, general layout, and
media queries, many properties take units and measurements as their value. There
are many property-specific units for CSS values, but available units like px, em, fr
and percentages are standard.

h3 {
font-size: 24px;
}
div{
grid-template-columns: 1fr 1fr 1fr 1fr;
}
div {
width: 100%;
font-size: 2em; }
URLS
Properties like background-image take an actual URL as their value. This URL could
be absolute or relative. Meaning, you could copy the address of an image online and
use it as your background image, or you could get images from the project
directory/folder you are working with on your computer.

div{
background-
image:url("https://cdn.pixabay.com/photo/2015/04/23/22/00/tree736885__340.jpg");
}
div{

© Edunet Foundation. All rights reserved .61


background-image: url("./Images/landscape.jpg");
}

STRINGS

Strings are text within quotes. The content property which you can use to insert
generated content allows strings within its parameter.

.div :: after {
content: "This is me";
}

COLORS

The color/background-colors are properties used to set the color of HTML elements.
Their values accept either a hexadecimal color combination value, an RGB
specification, or a defined color.

h2 {
color: red;
}
div{
background-color: #000000;
}

AUTO, NONE, INHERIT

Auto, None, and Inherit are keywords values in CSS. Auto value allows the property
to fill or adjust according to the content of the element.

div {
width: auto;
margin: auto;
}
None adds no value to the specified property.

div{
border: none;
}
Inherit keyword allows the property to inherit the same value from the parent
element. All CSS properties accept inherit.

<div>
<p> this is me </p>
<p id="pickme"> this is not me </p>
© Edunet Foundation. All rights reserved .62
</div>
p{
color: red;
}
#pickme p {
color: inherit;
}
Although all the examples above are of properties with one value, CSS values can
have more than one value, and you can manipulate it to write shorthand. Shorthand
in CSS is a shorter, more compact way of setting values for similar but multiple
properties.

These values,

div{
border-style: solid;
border-color: red;
border-width: 5px;
}
can be rewritten in shorthand as
div{
border: 5px solid red;
}

Other properties with multiple values include, but not limited to

margin: 1px 3px 6px 2px; /* defining the top, left, bottom and left of a margin */
font: italic small-caps bold 12px Georgia, serif; /*defining font-style, font-variant-caps,
font-weight, font-size, and font-family. */
box-shadow: 5px 2px 8px #aaaaaa; /* defining the horizontal offset, vertical offset,
blur, and color values */

Dynamic CSS3
How to create Dynamic CSS?
While writing CSS sometimes we need to declare variables, CSS custom properties
are like CSS’s own implementation of variables.

What are CSS custom properties?


CSS custom properties allow you to assign arbitrary values to a property with a name
of your choice It allow you Use the var() function to use these values in other
properties

© Edunet Foundation. All rights reserved .63


Prerequisites
• Basic knowledge of CSS
• You should have knowledge of currentColor refers to the current color value
of an element

Implement Custom CSS Properties


How to create a pre/postprocessor variables
How to use Variable

How to Create pre/post processor Variables


• CSS pre/postprocessors are allowed to store values in a keyword.
• It also scoped the keyword to a certain selector if required.
• This enables you to store color codes, sizes with all of the known units.
• var() function has been used to get the value of the custom property.
• We can not use var() functions for selectors, property names, or media query
declarations.
• CSS pre/postprocessor variables are only used at compilation -time.
• CSS variables can be used and updated dynamically.
The syntax for CSS custom properties is a bit weird compared to other languages, for
example :
:root {
currentColor: #D3D3D3;
}

.section {
background: var(currentColor);
}
CSS variables can be used and updated dynamically, illustrate with below example
:root {
$value: 10px;
}

.radius {
border-radius: $value;
}

@media screen and (min-width: 600px) {


$value: 50px;
}
This snippet of SASS declarations and rules compiles to CSS as follows:
.radius {
border-radius: 10px;
}

© Edunet Foundation. All rights reserved .64


How to use Variable
Some Basic CSS custom variables we are using in CSS since a long time
is currentColor keyword, It can be used on any declaration that accepts a color
value, and it cascades perfectly.
Example
.section {
color: red;
border: 1px solid currentColor;
}
.section .item {
background: currentColor;
}

.section .item.blue {
color: blue;
}

Explanation of above Example :


Create element with color : red
Sets a red background color for every span child of .element, unless a color property
is declared in this same block

Transform

The transform property applies a 2D or 3D transformation to an element. This


property allows you to rotate, scale, move, skew, etc., elements.
div.a {
transform: rotate(20deg);
}

div.b {
transform: skewY(20deg);
}

div.c {
transform: scaleY(1.5);
}

<style>
div.a {
© Edunet Foundation. All rights reserved .65
width: 150px;
height: 80px;
background-color: yellow;
-ms-transform: rotate(20deg); /* IE 9 */
transform: rotate(20deg);
}

div.b {
width: 150px;
height: 80px;
background-color: yellow;
-ms-transform: skewY(20deg); /* IE 9 */
transform: skewY(20deg);
}

div.c {
width: 150px;
height: 80px;
background-color: yellow;
-ms-transform: scaleY(1.5); /* IE 9 */
transform: scaleY(1.5);
}
</style>

Transitions

CSS transitions allows you to change property values smoothly, over a given
duration.

© Edunet Foundation. All rights reserved .66


How to Use CSS Transitions?

To create a transition effect, you must specify two things:

• the CSS property you want to add an effect to


• the duration of the effect

Note: If the duration part is not specified, the transition will have no effect, because
the default value is 0.

div {
width: 100px;
height: 100px;
background: red;
transition: width 2s;
}

Change Several Property Values

The following example adds a transition effect for both the width and height property,
with a duration of 2 seconds for the width and 4 seconds for the height:

div {
transition: width 2s, height 4s;
}

Animations

CSS allows animation of HTML elements without using JavaScript or Flash!

What are CSS Animations?

An animation lets an element gradually change from one style to another.You can
change as many CSS properties you want, as many times you want.To use CSS
animation, you must first specify some keyframes for the animation.

Keyframes hold what styles the element will have at certain times.

The @keyframes Rule

When you specify CSS styles inside the @keyframes rule, the animation will
gradually change from the current style to the new style at certain times.

To get an animation to work, you must bind the animation to an element.


© Edunet Foundation. All rights reserved .67
The following example binds the "example" animation to the <div> element. The
animation will last for 4 seconds, and it will gradually change the background-color of
the <div> element from "red" to "yellow":

/* The animation code */


@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}

/* The element to apply the animation to */


div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
}

Delay an Animation

The animation-delay property specifies a delay for the start of an animation.

The following example has a 2 seconds delay before starting the animation:

div {
width: 100px;
height: 100px;
position: relative;
background-color: red;
animation-name: example;
animation-duration: 4s;
animation-delay: 2s;
}

CSS Box Model


In CSS, the term "box model" is used when talking about design and layout.

The CSS box model is essentially a box that wraps around every HTML element. It
consists of: margins, borders, padding, and the actual content. The image below
illustrates the box model:

Explanation of the different parts:

• Content - The content of the box, where text and images appear
• Padding - Clears an area around the content. The padding is transparent

© Edunet Foundation. All rights reserved .68


• Border - A border that goes around the padding and content
• Margin - Clears an area outside the border. The margin is transparent

The box model allows us to add a border around elements, and to define space
between elements.

div {
width: 300px;
border: 15px solid green;
padding: 50px;
margin: 20px;
}

Width and Height of an Element

In order to set the width and height of an element correctly in all browsers, you need
to know how the box model works.

Important: When you set the width and height properties of an element with CSS,
you just set the width and height of the content area. To calculate the full size of an
element, you must also add padding, borders and margins.

div {
width: 320px;
padding: 10px;
border: 5px solid gray;
margin: 0;
}

Here is the calculation:

320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px

The total width of an element should be calculated like this:

Total element width = width + left padding + right padding + left border + right border
+ left margin + right margin

The total height of an element should be calculated like this:

© Edunet Foundation. All rights reserved .69


Total element height = height + top padding + bottom padding + top border + bottom
border + top margin + bottom margin

Design layout controls


display

The display property specifies the display behavior (the type of rendering box) of an
element.

Every HTML element has a default display value depending on what type of element
it is. The default display value for most elements is block or inline.

Inline

The default value for elements. Think of elements like <span>, <em>, or <b> and
how wrapping text in those elements within a string of text doesn’t break the flow of
the text.

The <em> element has a 1px red border. Notice it sits right inline with the rest of the
text.

© Edunet Foundation. All rights reserved .70


An inline element will accept margin and padding, but the element still sits inline as
you might expect. Margin and padding will only push other elements horizontally
away, not vertically.

An inline element will not accept height and width. It will just ignore it.

Inline Block

An element set to inline-block is very similar to inline in that it will set inline with the
natural flow of text (on the “baseline”). The difference is that you are able to set
a width and height which will be respected.

Block

A number of elements are set to block by the browser UA stylesheet. They are
usually container elements, like <div>, <section>, and <ul>. Also text “blocks”
like <p> and <h1>. Block level elements do not sit inline but break past them. By
default (without setting a width) they take up as much horizontal space as they can.

© Edunet Foundation. All rights reserved .71


.

Flexbox

The display property is also used for new fangled layout methods like Flexbox.

.header {
display: flex;
}

Grid

Grid layout will also be initially set by the display property.

body {
display: grid;
}

float Property

The float property is used for positioning and formatting content e.g. let an image
float left to the text in a container.

The float property can have one of the following values:

• left - The element floats to the left of its container


• right - The element floats to the right of its container
• none - The element does not float (will be displayed just where it occurs in the
text). This is default
• inherit - The element inherits the float value of its parent

© Edunet Foundation. All rights reserved .72


In its simplest use, the float property can be used to wrap text around images.

Example - float: right;

The following example specifies that an image should float to the right in a text:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.


Phasellus imperdiet, nulla et dictu m interdum, nisi lorem
egestas odio, vitae scelerisque enim ligula venenatis dolor.
Maecenas nisl est, ultrices nec congue eget, auctor vitae
massa. Fusce luctus vestibulum augue ut aliquet. Mauris
ante ligula, facilisis sed ornare eu, lobortis in odio. Praesent
convallis urna a lacus interdum ut hendrerit risus congue.
Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim
ac...

img {
float: right;
}

Positioning techniques

Positioning allows you to move an elemen t from where it would be placed when in
normal flow to another location. Positioning isn’t a method for creating your main
page layouts, it is more about managing and fine-tuning the position of specific items
on the page.

There are however useful techniqu es for certain layout patterns that rely on
the position property. Understanding positioning also helps in understanding normal
flow, and what it is to move an item out of normal flow.

There are five types of positioning you should know about:

• Static positioning is the default that every element gets — it just means "put
the element into its normal position in the document layout flow — nothing
special to see here".

• Relative positioning allows you to modify an element's position on the page,


moving it relative to its position in normal flow — including making it overlap
other elements on the page.

© Edunet Foundation. All rights reserved .73


• Absolute positioning moves an element completely out of the page's normal
layout flow, like it is sitting on its own separate layer. From there, you can fix it
in a position relative to the edges of the page's <html> element (or its nearest
positioned ancestor element). This is useful for creating complex layout effects
such as tabbed boxes where different content panels sit on top of one another
and are shown and hidden as desired, or information panels that sit off screen
by default, but can be made to slide on screen using a control button.

• Fixed positioning is very similar to absolute positioning, except that it fixes an


element relative to the browser viewport, not another element. This is useful
for creating effects such as a persistent navigation menu that always stays in
the same place on the screen as the rest of the content scrolls.

• Sticky positioning is a newer positioning method which makes an element


act like position: static until it hits a defined offset from the viewport, at which
point it acts like position: fixed.

position: static;
HTML elements are positioned static by default.

Static positioned elements are not affected by the top, bottom, left, and right
properties.

An element with position: static; is not positioned in any special way; it is always
positioned according to the normal flow of the page:
div.static {
position: static;
border: 3px solid #73AD21;
}

position: relative;
An element with position: relative; is positioned relative to its normal position.
© Edunet Foundation. All rights reserved .74
Setting the top, right, bottom, and left properties of a relatively-positioned element
will cause it to be adjusted away from its normal position. Other content will not be
adjusted to fit into any gap left by the element.

div.relative {
position: relative;
left: 30px;
border: 3px solid #73AD21;
}

position: fixed;
An element with position: fixed; is positioned relative to the viewport, which means it
always stays in the same place even if the page is scrolled. The top, right, bottom,
and left properties are used to position the element.

A fixed element does not leave a gap in the page where it would normally have been
located.

div.fixed {
position: fixed;
bottom: 0;
right: 0;
width: 300px;
border: 3px solid #73AD21;
}

position: absolute;

© Edunet Foundation. All rights reserved .75


An element with position: absolute; is positioned relative to the nearest positioned
ancestor (instead of positioned relative to the viewport, like fixed).

However; if an absolute positioned element has no positioned ancestors, it uses the


document body, and moves along with page scrolling.

Note: A "positioned" element is one whose position is anything except static.

div.relative {
position: relative;
width: 400px;
height: 200px;
border: 3px solid #73AD21;
}

div.absolute {
position: absolute;
top: 80px;
right: 0;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}

position: sticky;
An element with position: sticky; is positioned based on the user's scroll position.

A sticky element toggles between relative and fixed, depending on the scroll position.
It is positioned relative until a given offset position is met in the viewport - then it
"sticks" in place (like position:fixed).

© Edunet Foundation. All rights reserved .76


div.sticky {
position: -webkit-sticky; /* Safari */
position: sticky;
top: 0;
background-color: green;
border: 2px solid #4CAF50;
}

Practical Activities
Program:

Create Web-Layout Page Design(90mins)

<!DOCTYPE html>

<html>

<head>

<link href="style.css" rel="stylesheet">

</head>

<body>

<header>

<h1>Tourist Places in India</h1>

</header>

© Edunet Foundation. All rights reserved .77


<nav>

<a href="#">Ooty</a><br>

<a href="#">Simla</a><br>

<a href="#">kodaikkanal</a></br>

</nav>

<main>

<section>

<h1>Ooty</h1>

<p>Ooty is most famous for its tea plantations. Connoisseurs will find plenty to
choose from: dust and leaf; black, green, black and white varieties; and flavours
such as masala, jasmine, cardamom and even chocolate.</p>

<p>The top places near to Ooty are Wayanad which is 73 km from Ooty, Coonoor
which is located 12 km from Ooty, Bandipur national park which is located 29 km
from Ooty, Munnar which is located 152 km from Ooty, Coorg which is located 153
km from Ooty.</p>

</section>

<section>

<h1>Ooty</h1>

<p>Ooty is most famous for its tea plantations. Connoisseurs will find plenty to
choose from: dust and leaf; black, green, black and white varieties; and flavours
such as masala, jasmine, cardamom and even chocolate.</p>

<p>The top places near to Ooty are Wayanad which is 73 km from Ooty, Coonoor
which is located 12 km from Ooty, Bandipur national park which is located 29 km
from Ooty, Munnar which is located 152 km from Ooty, Coorg which is located 153
km from Ooty.</p>

</section>

</main>

<footer>

Copyright All rights &#169; Reserved

</footer>

</body>

© Edunet Foundation. All rights reserved .78


</html>

CSS

<style>

body

font-size:20px;

header {

background-color:black;

color:white;

text-align:center;

padding:5px;

nav {

line-height:30px;

background-color:white;

height:300px;

width:300px;

float:left;

padding:5px;

section {

width:350px;

float:left;

padding:10px;

footer {
© Edunet Foundation. All rights reserved .79
background-color:black;

color:white;

clear:both;

text-align:center;

padding:5px;

</style>

Output/Results snippet:

Animation(40mins)

Program:

<!DOCTYPE html>

<html>

<head>

<style>

div {

width: 100px;

height: 100px;

© Edunet Foundation. All rights reserved .80


background-color: red;

animation-name: example;

animation-duration: 4s;

@keyframes example {

from {background-color: red;}

to {background-color: yellow;}

</style>

</head>

<body>

<div></div>

</body>

</html>

Output/Results snippet:

Box Model(40mins)

Program:

<!DOCTYPE html>

© Edunet Foundation. All rights reserved .81


<html lang="en">

<head>

<meta charset="utf-8">

<title>CSS Box Formatting Model</title>

<style>

div {

width: 300px;

height: 200px;

padding: 15px;

border: 10px solid black;

margin: 20px auto;

</style>

</head>

<body>

<div>Web design refers to the design of websites that are displayed on the
internet. It usually refers to the user experience aspects of website development
rather than software development..</div>

</body>

</html>

Output/Results snippet:

© Edunet Foundation. All rights reserved .82


Float (40mins)

Program:

<!DOCTYPE html>
<html>
<head>
<style>
img {
float: right;
}
</style>
</head>
<body>

<h2>Float Right</h2>

<p>In this example, the image will float to the right in the paragraph, and the text in
the paragraph will wrap around the image.</p>

<p><img src="pineapple.jpg" alt="Pineapple"


style="width:170px;height:170px;margin -left:15px;">
Web design refers to the design of websites that are displayed on the internet. It
usually refers to the user experience aspects of website development rather than
software development..Klientboost. This is another fantastic example of mobile
© Edunet Foundation. All rights reserved .83
responsive web design. Their website loads remarkably fast at four seconds using 3G
connections. More importantly, the look and feel of Klientboost's website stays
consistent across all devices, yet they've managed to tailor their user experience to
each device.</p>

</body>
</html>

Output/Results snippet:

1.4 - JS for Client-side scripting

Handling HTML Events

What is an Event?
JavaScript's interaction with HTML is handled through events that occur when the
user or the browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click
too is an event. Other examples include events like pressing any key, closing a
window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which
cause buttons to close windows, messages to be displayed to users, data to be
validated, and virtually any other type of response imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML
element contains a set of events which can trigger JavaScript Code.

<body> and <frameset> Level Events

There are only two attributes which can be used to trigger any javascript or vbscript
code when there is any event occurs on document level.

Attribute Value Description

© Edunet Foundation. All rights reserved .84


onload script Script runs when a HTML document loads

onunload script Script runs when a HTML document unloads

NOTE − Here script refer to any VBScript or JavaScript function or piece of code.

<form> Level Events

There are following six attributes which can be used to trigger any javascript or
vbscript code when there is any event occurs on form level.

Attribute Value Description

onchange script Script runs when the element changes

onsubmit script Script runs when the form is submitted

onreset script Script runs when the form is reset

onselect script Script runs when the element is selected

onblur script Script runs when the element loses focus

onfocus script Script runs when the element gets focus

Keyboard Events

There are following three events which are generated by keyboard. These events are
not valid in base, bdo, br, frame, frameset, head, html, iframe, meta, param, script,
style, and title elements.

Attribute Value Description

onkeydown script Script runs when key is pressed

© Edunet Foundation. All rights reserved .85


onkeypress script Script runs when key is pressed and released

onkeyup script Script runs when key is released

Other Events

There following other 7 events which are generated by mouse when it comes in
contact of any HTML tag. These events are not valid in base, bdo, br, frame,
frameset, head, html, iframe, meta, param, script, style, title elements.

Attribute Value Description

onclick script Script runs when a mouse click

ondblclick script Script runs when a mouse double-click

onmousedown script Script runs when mouse button is pressed

onmousemove script Script runs when mouse pointer moves

onmouseout script Script runs when mouse pointer moves out of an element

onmouseover script Script runs when mouse pointer moves over an element

onmouseup script Script runs when mouse button is released

onclick Event Type

© Edunet Foundation. All rights reserved .86


Animations
JavaScript animations are done by programming gradual changes in an
element's style.

The changes are called by a timer. When the timer interval is small, the
animation looks continuous.

<!DOCTYPE html>
<html>
<body>

<h1>My First JavaScript Animation</h1>

<div id ="myContainer">
<div id ="myAnimation">My animation will go here</div>
</div>

</body>
<html>

Styling the Elements


To make an animation possible, the animated element must be animated relative to a
"parent container".

The container element should be created with style = "position: relative".

The animation element should be created with style = "position: absolute".

#myContainer {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}

#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background: red;
}

Create the Animation Using JavaScript

© Edunet Foundation. All rights reserved .87


Reading element state & data
What is DOM in JavaScript?

JavaScript can access all the elements in a webpage making use of Document
Object Model (DOM). In fact, the web browser creates a DOM of the webpage when
the page is loaded. The DOM model is created as a tree of objects like this:

© Edunet Foundation. All rights reserved .88


Image: DOM in Javascript
Reference: https://www.guru99.com/images/JavaScript/javascript8_1.png

How to use DOM and Events

Using DOM, JavaScript can perform multiple tasks. It can create new elements and
attributes, change the existing elements and attributes and even remove existing
elements and attributes. JavaScript can also react to existing events and create new
events in the page.

getElementById, innerHTML Example

1. getElementById: To access elements and attributes whose id is set.


2. innerHTML: To access the content of an element.

Finding HTML Elements


Often, with JavaScript, you want to manipulate HTML elements.
To do so, you have to find the elements first. There are several ways to do this:
• Finding HTML elements by id
• Finding HTML elements by tag name
• Finding HTML elements by class name
• Finding HTML elements by CSS selectors
Finding HTML Element by Id
The easiest way to find an HTML element in the DOM, is by using the element id.
This example finds the element with id="intro":
© Edunet Foundation. All rights reserved .89
var myElement = document.getElementById("intro");
If the element is found, the method will return the element as an object (in
myElement).
If the element is not found, myElement will contain null.

Finding HTML Elements by Tag Name


This example finds all <p> elements:
var x = document.getElementsByTagName("p");
This example finds the element with id="main", and then finds all <p> elements
inside "main":
var x = document.getElementById("main");
var y = x.getElementsByTagName("p");

Finding HTML Elements by Class Name


If you want to find all HTML elements with the same class name,
use getElementsByClassName().
This example returns a list of all elements with class="intro".
var x = document.getElementsByClassName("intro");
Finding elements by class name does not work in Internet Explorer 8 and earlier
versions.

Finding HTML Elements by CSS Selectors


If you want to find all HTML elements that match a specified CSS selector (id, class
names, types, attributes, values of attributes, etc), use
the querySelectorAll() method.
This example returns a list of all <p> elements with class="intro".
var x = document.querySelectorAll("p.intro");

<html>
<head>
<title>DOM!!!</title>
</head>
<body>
<h1 id="one">Welcome</h1>
<p>This is the welcome message.</p>
<h2>Technology</h2>
<p>This is the technology section.</p>
<script type="text/javascript">
var text = document.getElementById("one").innerHTML;
alert("The first heading is " + text);
</script>
</body>
</html>

© Edunet Foundation. All rights reserved .90


Form handling and validations
Form handling

Forms are an extremely important part of HTML and the Web Platform. They allow
users can interact with the page and search something on the site trigger filters to
trim result pages send information and much much more.

By default, forms submit their content to a server-side endpoint, which by default is


the page URL itself:

<form>

<input type="submit">

</form>

We can override this behavior by setting the action attribute of the form element,
using the HTML method defined by the method attribute, which defaults to GET:

<form action="/contact" method="POST">

<input type="submit">

</form>

Upon clicking the submit input element, the browser makes a POST request to
the /contact URL on the same origin (protocol, domain and port).

Using JavaScript we can intercept this event, submit the form asynchronously
(with XHR and Fetch), and we can also react to events happening on individual form
elements.

Working with input element events

We have a number of events we can listen for in form elements

• input fired on form elements when the element value is changed

• change fired on form elements when the element value is changed. In the
case of text input elements and textarea, it’s fired only once when the element
loses focus (not for every single character typed)

• cut fired when the user cuts text from the form element

• copy fired when the user copies text from the form element

• paste fired when the user pastes text into the form element

© Edunet Foundation. All rights reserved .91


• focus fired when the form element gains focus

• blur fired when the form element loses focus

Validation
HTML form validation can be done by JavaScript.

If a form field (fname) is empty, this function alerts a message, and returns false, to
prevent the form from being submitted:

function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}

The function can be called when the form is submitted:

<form name="myForm" action="/action_page.php" onsubmit="return


validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>

Automatic HTML Form Validation

HTML form validation can be performed automatically by the browser:

If a form field (fname) is empty, the required attribute prevents this form from being
submitted:

<form action="/action_page.php" method="post">


<input type="text" name="fname" required>
<input type="submit" value="Submit">
</form>

© Edunet Foundation. All rights reserved .92


Data Validation

Data validation is the process of ensuring that user input is clean, correct, and
useful.

Typical validation tasks are:

• has the user filled in all required fields?

• has the user entered a valid date?

• has the user entered text in a numeric field?

• Most often, the purpose of data validation is to ensure correct user input.

Validation can be defined by many different methods, and deployed in many different
ways.

Server side validation is performed by a web server, after input has been sent to
the server.

Client side validation is performed by a web browser, before input is sent to a web
server.

Handling Cookies and Session Data


Cookies in JavaScript
What are Cookies?

A cookie is a piece of data that is stored on your computer to be accessed by your


browser. You also might have enjoyed the benefits of cookies knowingly or
unknowingly. Have you ever saved your Facebook password so that you do not have
to type it each and every time you try to login? If yes, then you are using cookies.
Cookies are saved as key/value pairs.

Why do you need a Cookie?

The communication between a web browser and server happens using a stateless
protocol named HTTP. Stateless protocol treats each request independent. So, the
server does not keep the data after sending it to the browser. But in many situations,
the data will be required again. Here come cookies into a picture. With cookies, the
web browser will not have to communicate with the server each time the data is
required. Instead, it can be fetched directly from the computer.

Cookies are a plain text data record of 5 variable-length fields −

Expires − The date the cookie will expire. If this is blank, the cookie will expire when
the visitor quits the browser.

Domain − The domain name of your site.

© Edunet Foundation. All rights reserved .93


Path − The path to the directory or web page that set the cookie. This may be blank
if you want to retrieve the cookie from any directory or page.

Secure − If this field contains the word "secure", then the cookie may only be
retrieved with a secure server. If this field is blank, no such restriction exists.

Name=Value − Cookies are set and retrieved in the form of key-value pairs

Javascript Set Cookie

You can create cookies using document. cookie property like this.

document.cookie = "cookiename=cookievalue"

You can even add expiry date to your cookie so that the particular cookie will be
removed from the computer on the specified date. The expiry date should be set in
the UTC/GMT format. If you do not set the expiry date, the cookie will be removed
when the user closes the browser.

document.cookie = "cookiename=cookievalue; expires= Thu, 21 Aug 2014 20:00:00


UTC"

You can also set the domain and path to specify to which domain and to which
directories in the specific domain the cookie belongs to. By default, a cookie belongs
to the page that sets the cookie.

document.cookie = "cookiename=cookievalue; expires= Thu, 21 Aug 2014 20:00:00


UTC; path=/ "

//create a cookie with a domain to the current page and path to the entire domain.

JavaScript get Cookie

You can access the cookie like this which will return all the cookies saved for the
current domain.

var x = document.cookie

JavaScript Delete Cookie

To delete a cookie, you just need to set the value of the cookie to empty and set the
value of expires to a passed date.

document.cookie = "cookiename= ; expires = Thu, 01 Jan 1970 00:00:00 GMT"

<html>

<head>
© Edunet Foundation. All rights reserved .94
<title>Cookie!!!</title>

<script type="text/javascript">

function createCookie(cookieName,cookieValue,daysToExpire)

var date = new Date();

date.setTime(date.getTime()+(daysToExpire*24*60*60*1000));

document.cookie = cookieName + "=" + cookieValue + "; expires=" +


date.toGMTString();

function accessCookie(cookieName)

var name = cookieName + "=";

var allCookieArray = document.cookie.split(';');

for(var i=0; i<allCookieArray.length; i++)

var temp = allCookieArray[i].trim();

if (temp.indexOf(name)==0)

return temp.substring(name.length,temp.length);

return "";

function checkCookie()

var user = accessCookie("testCookie");

if (user!="")

alert("Welcome Back " + user + "!!!");

else

© Edunet Foundation. All rights reserved .95


user = prompt("Please enter your name");

num = prompt("How many days you want to store your name on your
computer?");

if (user!="" && user!=null)

createCookie("testCookie", user, num);

</script>

</head>

<body onload="checkCookie()"></body>

</html>

SessionStorage
The sessionStorage object stores data for only one session (the data is deleted
when the browser tab is closed).

Tip: Also look at the localStorage property which stores data with no expiration date.
The data will not be deleted when the browser is closed, and will be available the
next day, week, or year.

Syntax for SAVING data to sessionStorage:

© Edunet Foundation. All rights reserved .96


sessionStorage.setItem("key", "value");

Syntax for READING data from sessionStorage:

var lastname = sessionStorage.getItem("key");

Syntax for REMOVING saved data from sessionStorage:

sessionStorage.removeItem("key");

Syntax for REMOVING ALL saved data from sessionStorage:

sessionStorage.clear();

if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
sessionStorage.clickcount = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";

© Edunet Foundation. All rights reserved .97


© Edunet Foundation. All rights reserved .98
Practical Activities
Event Handling(40mins)

Program:

<html>

<head>

<script type = "text/javascript">

<!--

function over() {

document.write ("Mouse Over");

function out() {

document.write ("Mouse Out");

//-->

</script>

</head>

<body>

<p>Bring your mouse inside the division to see the result:</p>

<div onmouseover = "over()" onmouseout = "out()">

<h2> This is inside the division </h2>

</div>

</body>

</html>

Output/Results snippet:
© Edunet Foundation. All rights reserved .99
DOM (40mins)

Program:

<!DOCTYPE html>
<html>
<body>

<p id="demo" onclick="myFunction()">Click me to change my HTML content


(innerHTML).</p>

<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed!";
}
</script>

</body>
</html>

Output/Results snippet:

Animations(50mins)

Program:

<!DOCTYPE HTML>
<html>

© Edunet Foundation. All rights reserved .100


<head>
<style>
#train {
position: relative;
cursor: pointer;
}
</style>
</head>

<body>

<img id="train" src="https://js.cx/clipart/train.gif">

<script>
train.onclick = function() {
let start = Date.now();

let timer = setInterval(function() {


let timePassed = Date.now() - start;

train.style.left = timePassed / 5 + 'px';

if (timePassed > 2000) clearInterval(timer);

}, 20);
}
</script>

</body>

</html>

Output/Results snippet:

© Edunet Foundation. All rights reserved .101


Cookies & Session Handling(80mins)

Program:

<!DOCTYPE html>

<html>

<head>

<script>

function setCookie(cname,cvalue,exdays) {

var d = new Date();

d.setTime(d.getTime() + (exdays*24*60*60*1000));

var expires = "expires=" + d.toGMTString();

document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";

function getCookie(cname) {

var name = cname + "=";

var decodedCookie = decodeURIComponent(document.cookie);

var ca = decodedCookie.split(';');

for(var i = 0; i < ca.length; i++) {

var c = ca[i];

while (c.charAt(0) == ' ') {


© Edunet Foundation. All rights reserved .102
c = c.substring(1);

if (c.indexOf(name) == 0) {

return c.substring(name.length, c.length);

return "";

function checkCookie() {

var user=getCookie("username");

if (user != "") {

alert("Welcome again " + user);

} else {

user = prompt("Please enter your name:","");

if (user != "" && user != null) {

setCookie("username", user, 30);

</script>

</head>

<body onload="checkCookie()"></body>

</html>

Output/Results snippet:

© Edunet Foundation. All rights reserved .103


Session

Program:

<!DOCTYPE html>

<html>

<head>

<script>

function clickCounter() {

if(typeof(Storage) !== "undefined") {

if (sessionStorage.clickcount) {

sessionStorage.clickcount = Number(sessionStorage.clickcount)+1;

} else {

sessionStorage.clickcount = 1;

document.getElementById("result").innerHTML = "You have clicked the button " +


sessionStorage.clickcount + " time(s) in this session.";

} else {

document.getElementById("result").innerHTML = "Sorry, your browser does not


support web storage...";

© Edunet Foundation. All rights reserved .104


}

</script>

</head>

<body>

<p><button onclick="clickCounter()" type="button">Click me!</button></p>

<div id="result"></div>

<p>Click the button to see the counter increase.</p>

<p>Close the browser tab (or window), and try again, and the counter is reset.</p>

</body>

</html>

Output/Results snippet:

1.5 - Building Dynamic web pages using HTML 5, CSS3 and


JS

Dynamic Web Page:


A dynamic web page is a web page that displays different content each time it's
viewed. For example, the page may change with the time of day, the user that
accesses the webpage, or the type of user interaction.

© Edunet Foundation. All rights reserved .105


Image: Dynamic Web Page
Reference:https://www.geeksforgeeks.org/difference-between-static-and-dynamic-web-pages/

Our first empty web page will look much like this:

Sample.html
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<body>
<!-- Content will go here -->

</body>
</html>

Creating Page Content

Inside the <body> element of our web site we will use our "Layout Picture" and
create:

• A navigation bar
• A slide show
• A header
• Some sections
• A footer

© Edunet Foundation. All rights reserved .106


Semantic Elements

• HTML5 introduced several new semantic elements. Semantic elements are


important to use because they define the structure of web pages and helps
screen readers and search engines to read the page correctly.
• These are some of the most common semantic HTML elements:
• The <section> element can be used to define a part of a website with related
content.
• The <header> element can be used to define a header (in a document, a
section, or an article).
• The <footer> element can be used to define a footer (in a document, a
section, or an article).
• The <nav> element can be used to define a container of navigation links.

The Navigation Bar

On our "Layout Draft" we have a "Navigation bar".

<!-- Navigation -->


<nav class="menu">
<a href="#home">Home</a>
<a href="#band">Band</a>
<a href="#tour">Tour</a>
<a href="#contact">Contact</a>
</nav>

Slide Show

For the slide show we can use a <section> or <div> element as a picture container:

<!-- Slide Show -->


<section>
<img class="mySlides" src="img1.jpg" style="width:100%">
<img class="mySlides" src="img2.jpg" style="width:100%">
</section>

We need to add a little JavaScript to change the images every 3 seconds:

// Automatic Slideshow - change image every 3 seconds


var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("mySlides");
for (i = 0; i < x.length; i++) {

© Edunet Foundation. All rights reserved .107


x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1}
x[myIndex-1].style.display = "block";
setTimeout(carousel, 3000);
}

Sections

Looking at the "Layout Draft" we can see that the next step is to create articles.

First we will create a <section> or <div> element containing band information:

<section style="max-width:600px">
<h2>THE BAND</h2>
<p><i>We love music</i></p>
</section>

Then we will add a paragraph describing the band:

<section style="max-width:600px">
<p>
We have created a fictional band website. Lorem ipsum dolor sit amet, consectetur
adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua.</p>
</section>

Footer
Finally we will use a <footer> or <div> to create a footer:
<footer class="footer">
<p> This is a Footer</p>
</footer>

Finally we need to apply the styles for the entire web page ,we can do this by
creating a external css file. The following is the CSS file.

styles.css
/* Add a black background color to the top navigation */
.topnav {
© Edunet Foundation. All rights reserved .108
background-color: #333;
overflow: hidden;
}

/* Style the links inside the navigation bar */


.topnav a {
float: left;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}

/* Change the color of links on hover */


.topnav a:hover {
background-color: #ddd;
color: black;
}

/* Add a color to the active/current link */

.topnav a.active {

background-color: #4CAF50;
color: white;
}
.footer {
position: fixed;
left: 0;
bottom: 0;
width: 100%;
background-color: black;
color: white;
text-align: center;
}

Now we need to add this external css file in our web page .After adding the external
css file ,the sample.html file will look like this:

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="styles.css">

© Edunet Foundation. All rights reserved .109


<body>
<!-- Content will go here -->
<!—nav bar, section and footer will come here -->
</body>
</html>
Output

Image: Dynamic Web Page using HTML5, CSS3 and JS

Here the image slideshow repeats after every 3 seconds. The images will be
frequently changing with 3 second delay .

Bootstrap-Front end Framework -Mobile first site and application

Design

After completing this module, you will be able to

❑ Create mobile-first website


❑ Work with basic elements of bootstrap

❑ Create various types of images with class

© Edunet Foundation. All rights reserved .110


❑ Create different types of buttons, Badges, Progress bar

❑ Create Pagination and dropdowns


❑ Create Forms and Utilities

Plan
❑ Download compiled and minified CSS bundles and JavaScript Plugin
❑ (Or) Download source SaaS, JavaScript and documentation files

❑ (Or) Download with CDN

❑ Latest Bootstrap version 5

❑ Internet Explorer 11 and down is not supported


❑ jQuery is replaced with Vanilla JavaScript

Bootstrap
Guide
What is Bootstrap?
❑ Bootstrap helps in building websites and web quickly. It is the world's most
popular framework for building the responsive, mobile-first app on the web.
❑ Ideally Bootstrap saves time from writing a lot of CSS code and gives us more time
to spend on designing web pages.
❑ It was officially released on 16 June 2020 after several months of redefining its
features.

BOOTSTRAP VERSION

Why we use Bootstrap?

❑ Easy to use: Anybody with just basic knowledge of HTML and CSS can start using
Bootstrap

© Edunet Foundation. All rights reserved .111


❑ Responsive features: Bootstrap's responsive CSS adjusts to phones, tablets, and
desktops
❑ Mobile-first approach: In Bootstrap, mobile-first styles are part of the core
framework
❑ Browser compatibility: Bootstrap 5 is compatible with all modern browsers
(Chrome, Firefox, Edge, Safari, and Opera). Note that if you need support for IE11
and down, you must use either BS4 or BS3.

Difference between Bootstrap3 and Bootstrap 4?

Difference between Bootstrap 4 and Bootstrap 5

Starter Template BS5

<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">

© Edunet Foundation. All rights reserved .112


<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css"
rel="stylesheet" integrity="sha384-
EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
crossorigin="anonymous">
<title>Hello, world!</title>
</head>
<body>
<h1>Hello, world!</h1>
<!-- Optional JavaScript; choose one of the two! -->
<!-- Option 1: Bootstrap Bundle with Popper -->
<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-
MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
crossorigin="anonymous"></script>
<!-- Option 2: Separate Popper and Bootstrap JS -->
<!--
<script
src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"
integrity="sha384-
IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js"
integrity="sha384-
cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF"
crossorigin="anonymous"></script>
-->
</body>
</html>

BS5 Colors

© Edunet Foundation. All rights reserved .113


The classes for text colors are: The classes for background colors are:

.text-muted, .text-primary, .text-success, .bg-primary, .bg-success, .bg-info, .bg-


.text-info, .text-warning, .text-danger, warning, .bg-danger, .bg-secondary, .bg-
.text-secondary, .text-white, .text-dark, dark and .bg-light.
.text-body (default body color/often black)
and .text-light:

Example: Example:

<p class="text-primary">.text-primary</p> <p class=“bg-primary">.text-primary</p>

<p class="text-secondary">.text- <p class=“bg-secondary">.text-


secondary</p> secondary</p>

<p class="text-success">.text-success</p> <p class=“bg-success">.text-success</p>

<p class="text-danger">.text-danger</p> <p class=“bg-danger">.text-danger</p>

BS5 Alerts and Buttons

BS5 ALERTS AND BADGES O/P

© Edunet Foundation. All rights reserved .114


BS5 Breadcrumbs and Pagination

Breadcrumbs Pagination

Indicate the current page’s location within Documentation and examples for showing
a navigational hierarchy that pagination to indicate a series of
automatically adds separators via CSS. related content exists across multiple
pages.

Example: Example:

<ul class="breadcrumb"> <ul class="pagination">


<li class="breadcrumb-item"><a <li class="page-item"><a class="page-
href="#">Photos</a></li> link" href="#">Previous</a></li>
<li class="breadcrumb-item"><a <li class="page-item"><a class="page-
href="#">Summer 2017</a></li> link" href="#">1</a></li>
<li class="breadcrumb-item"><a <li class="page-item"><a class="page-
href="#">Italy</a></li> link" href="#">2</a></li>
<li class="breadcrumb-item <li class="page-item"><a class="page-
active">Rome</li> link" href="#">3</a></li>
</ul> <li class="page-item"><a class="page-
link" href="#">Next</a></li>
</ul>

BS5 BREADCRUMBS AND PAGINATION O/P

© Edunet Foundation. All rights reserved .115


BS5 ToolTips and Popovers

ToolTips PopOvers

qDocumentation and examples for adding qDocumentation and examples for adding
custom Bootstrap tooltips with CSS Bootstrap popovers, like those found
and JavaScript using CSS3 for in iOS, to any element on your site.
animations and data-bs-attributes for
local title storage.

Example: Example:

<button type="button" class="btn btn- <button type="button" class="btn btn-


secondary" data-bs-toggle="tooltip" data- secondary" data-bs-container="body"
bs-placement="top" data-bs-custom- data-bs-toggle="popover" data-bs-
class="custom-tooltip" data-bs-title="This placement="top" data-bs-content="Top
top tooltip is themed via CSS variables."> popover"> Popover on top </button>
Custom tooltip </button> <button type="button" class="btn btn-
secondary" data-bs-container="body"
data-bs-toggle="popover" data-bs-
placement="right" data-bs-content="Right
popover"> Popover on right </button>

BS5 ToolTips AND Popovers O/P

© Edunet Foundation. All rights reserved .116


BS5 Cards and Modals

Cards Modals

Bootstrap’s cards provide a flexible and Use Bootstrap’s JavaScript modal plugin to
extensible content container with add dialogs to your site for lightboxes,
multiple variants and options. user notifications, or completely
custom content.

Example: Example:

<div class="card" style="width:400px"> <div class="modal" tabindex="-1">


<img class="card-img-top"
<div class="modal-dialog"> <div
src="img_avatar1.png" alt="Card image">
class="modal-content"> <div
<div class="card-body">
class="modal-header"> <h5 class="modal-
<h4 class="card-title">John Doe</h4>
title">Modal title</h5> <button
<p class="card-text">Some example
type="button" class="btn-close" data-bs-
text.</p>
dismiss="modal" aria-
<a href="#" class="btn btn-
label="Close"></button> </div> <div
primary">See Profile</a>
class="modal-body"> <p>Modal body text
</div>
goes here.</p> </div> <div class="modal-
</div>
footer"> <button type="button"
class="btn btn-secondary" data-bs-
dismiss="modal">Close</button> <button
type="button" class="btn btn-
primary">Save changes</button> </div>
</div> </div> </div>

BS5 Cards and Modals O/P

© Edunet Foundation. All rights reserved .117


BS5 Scrollspy and Form controls

Scrollspy Form Controls

qAutomatically update Bootstrap qGive textual form controls like <input>s


navigation or list group components and <textarea>s an upgrade with
based on scroll position to indicate custom styles, sizing, focus states, and
which link is currently active in the more.
viewport.

Example: Example:

<body data-bs-spy="scroll" data-bs- <div class="mb-3"> <label


target=".navbar" data-bs-offset="50"> for="exampleFormControlInput1"
class="form-label">Email address</label>
<!-- The navbar - The <a> elements are
<input type="email" class="form-control"
used to jump to a section in the scrollable
id="exampleFormControlInput1"
area -->
placeholder="name@example.com">
<nav class="navbar navbar-expand-sm bg-
</div> <div class="mb-3"> <label
dark navbar-dark fixed-top">
for="exampleFormControlTextarea1"
<ul class="navbar-nav">
class="form-label">Example
<li><a href="#section1">Section
textarea</label> <textarea class="form-
1</a></li></nav>
control"
<!-- Section 1 -->
id="exampleFormControlTextarea1"
<div id="section1">
rows="3"></textarea> </div>
<h1>Section 1</h1>
<p>Try to scroll this page and look at the
navigation bar while scrolling!</p></div>

© Edunet Foundation. All rights reserved .118


BS5 Scrollspy and Form Controls O/P

Bootstrap 5 Grid System

Why we use BS grid?

❑ Bootstrap's grid system is built with flexbox and allows up to 12 columns across
the page.

❑ If you do not want to use all 12 columns individually, you can group the columns
together to create wider columns:

❑ The classes above can be combined to create more dynamic and flexible layouts.

Grid Classes:

The Bootstrap 5 grid system has six classes:

❑ . col- (extra small devices - screen width less than 576px)

❑ . col-sm- (small devices - screen width equal to or greater than 576px)

© Edunet Foundation. All rights reserved .119


❑ . col-md- (medium devices - screen width equal to or greater than 768px)

❑ . col-lg- (large devices - screen width equal to or greater than 992px)

❑ . col-xl- (xlarge devices - screen width equal to or greater than 1200px)

❑ . col-xxl- (xxlarge devices - screen width equal to or greater than 1400px)

Basic Structure of a Bootstrap 5 Grid


<!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 href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
rel="stylesheet">

<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></s
cript>

</head>

<body>

<div class="container-fluid mt-3">

<h1>Basic Grid Structure</h1>

<p>Resize the browser window to see the effect.</p>

<p>The first, second and third row will automatically stack on top of each other when the
screen is less than 576px wide.</p>

<!-- Control the column width, and how they should appear on different devices -->

<div class="row">

<div class="col-sm-6 bg-primary text-white">50%</div>

<div class="col-sm-6 bg-dark text-white">50%</div>

© Edunet Foundation. All rights reserved .120


</div>

<br>

<div class="row">

<div class="col-sm-4 bg-primary text-white">33.33%</div>

<div class="col-sm-4 bg-dark text-white">33.33%</div>

<div class="col-sm-4 bg-primary text-white">33.33%</div>

</div>

<br>

<!-- Or let Bootstrap automatically handle the layout -->

<div class="row">

<div class="col-sm bg-primary text-white">25%</div>

<div class="col-sm bg-dark text-white">25%</div>

<div class="col-sm bg-primary text-white">25%</div>

<div class="col-sm bg-dark text-white">25%</div>

</div>

<br>

<div class="row">

<div class="col bg-primary text-white">25%</div>

<div class="col bg-dark text-white">25%</div>

<div class="col bg-primary text-white">25%</div>

<div class="col bg-dark text-white">25%</div>

</div>

</div>

</body>

</html>

BS GRID O/P:
© Edunet Foundation. All rights reserved .121
Portfolio Project

Code Implementation
<!DOCTYPE html>

<html lang="en">

<head>

<title>Bootstrap 5 Website Example</title>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
rel="stylesheet">

<script
src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></s
cript>

<style>

.fakeimg {
© Edunet Foundation. All rights reserved .122
height: 200px;

background: #aaa;

</style>

</head>

<body>

<div class="p-5 bg-primary text-white text-center">

<h1>My First Bootstrap 5 Page</h1>

<p>Resize this responsive page to see the effect!</p>

</div>

Navigation
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">

<div class="container-fluid">

<ul class="navbar-nav">

<li class="nav-item">

<a class="nav-link active" href="#">Active</a>

</li>

<li class="nav-item">

<a class="nav-link" href="#">Link</a>

</li>

<li class="nav-item">

<a class="nav-link" href="#">Link</a>

</li>

<li class="nav-item">

<a class="nav-link disabled" href="#">Disabled</a>

</li>

</ul>
© Edunet Foundation. All rights reserved .123
</div>

</nav>

<div class="container mt-5">

<div class="row">

<div class="col-sm-4">

<h2>About Me</h2>

<h5>Photo of me:</h5>

<div class="fakeimg">Fake Image</div>

<p>Some text about me in culpa qui officia deserunt mollit anim..</p>

<h3 class="mt-4">Some Links</h3>

<p>Lorem ipsum dolor sit ame.</p>

<ul class="nav nav-pills flex-column">

<li class="nav-item">

<a class="nav-link active" href="#">Active</a>

</li>

<li class="nav-item">

<a class="nav-link" href="#">Link</a>

</li>

<li class="nav-item">

<a class="nav-link" href="#">Link</a>

</li>

<li class="nav-item">

<a class="nav-link disabled" href="#">Disabled</a>

</li>

</ul>

<hr class="d-sm-none">

</div>
© Edunet Foundation. All rights reserved .124
Column Layout

<div class="col-sm-8">
<h2>TITLE HEADING</h2>
<h5>Title description, Dec 7, 2020</h5>
<div class="fakeimg">Fake Image</div>
<p>Some text..</p>
<p>Sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco.</p>
<h2 class="mt-5">TITLE HEADING</h2>
<h5>Title description, Sep 2, 2020</h5>
<div class="fakeimg">Fake Image</div>
<p>Some text..</p>
<p>Sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad
minim veniam, quis nostrud exercitation ullamco.</p>
</div>
</div>
</div>
<div class="mt-5 p-4 bg-dark text-white text-center">
<p>Footer</p>
</div></body>

</html>

Chapter 2 – Revisiting Java Object


Oriented Paradigms

Learning Outcomes:

• Core JAVA (J2SE) Programming and Coding Skills


• Work with most popular web development technologies

© Edunet Foundation. All rights reserved .125


2.1 - Understanding OOP concepts through core Java

Java Class and Objects

An object is any entity that has a state and behavior.

Java Class
A class is a blueprint for the object. We can think of the class as a sketch (prototype)
of a house. It contains all the details about the floors, doors, windows, etc. Based on
these descriptions we build the house. House is the object.

Since many houses can be made from the same description, we can create many
objects from a class.

Create a class in Java


We can create a class in Java using the class keyword. For example,

class ClassName {

// fields

// methods

Here, fields (variables) and methods represent the state and behavior of the object
respectively.

fields are used to store data

methods are used to perform some operations

For our bicycle object, we can create the class as

class Bicycle {

// state or field

private int gear = 5;

// behavior or method

public void braking() {

© Edunet Foundation. All rights reserved .126


System.out.println("Working of Braking");

In the above example, we have created a class named Bicycle. It contains a field
named gear and a method named braking().

Here, Bicycle is a prototype. Now, we can create any number of bicycles using the
prototype. And, all the bicycles will share the fields and methods of the prototype.

Java Objects
An object is called an instance of a class. For example, suppose Bicycle is a class
then MountainBicycle, SportsBicycle, TouringBicycle, etc can be considered as
objects of the class.

Creating an Object in Java


Here is how we can create an object of a class.

className object = new className();

// for Bicycle class

Bicycle sportsBicycle = new Bicycle();

Bicycle touringBicycle = new Bicycle();

We have used the new keyword along with the constructor of the class to create an
object. Constructors are similar to methods and have the same name as the class. For
example, Bicycle() is the constructor of the Bicycle class.

Here, sportsBicycle and touringBicycle are the names of objects. We can use them to
access fields and methods of the class.

We have created two objects of the class. We can create multiple objects of a single
class in Java.

Access Members of a Class


We can use the name of objects along with the . operator to access members of a
class.

class Bicycle {

// field of class

© Edunet Foundation. All rights reserved .127


int gear = 5;

// method of class

void braking() {

...

// create object

Bicycle sportsBicycle = new Bicycle();

// access field and method

sportsBicycle.gear;

sportsBicycle.braking();

In the above example, we have created a class named Bicycle. It includes a field
named gear and a method named braking().

Example: Java Class and Objects

class Lamp {

// stores the value for light

// true if light is on

// false if light is off

boolean isOn;

// method to turn on the light

void turnOn() {

isOn = true;

System.out.println("Light on? " + isOn);

© Edunet Foundation. All rights reserved .128


}

// method to turnoff the light

void turnOff() {

isOn = false;

System.out.println("Light on? " + isOn);

class Main {

public static void main(String[] args) {

// create objects led and halogen

Lamp led = new Lamp();

Lamp halogen = new Lamp();

// turn on the light by

// calling method turnOn()

led.turnOn();

// turn off the light by

// calling method turnOff()

halogen.turnOff();

© Edunet Foundation. All rights reserved .129


Example: Create objects inside the same class

class Lamp {

// stores the value for light

// true if light is on

// false if light is off

boolean isOn;

// method to turn on the light

void turnOn() {

isOn = true;

System.out.println("Light on? " + isOn);

public static void main(String[] args) {

// create an object of Lamp

Lamp led = new Lamp();

// access method using object

led.turnOn();

Java Methods
A method is a block of code that performs a specific task.

© Edunet Foundation. All rights reserved .130


In Java, there are two types of methods:

1. User-defined Methods: We can create our own method based on our


requirements.
2. Standard Library Methods: These are built-in methods in Java that are available
to use.

Declaring a Java Method


The syntax to declare a method is:

returnType methodName() {

// method body

Here,

returnType - It specifies what type of value a method returns For example if a method
has an int return type then it returns an integer value.

If the method does not return a value, its return type is void.

methodName - It is an identifier that is used to refer to the particular method in a


program.

method body - It includes the programming statements that are used to perform some
tasks. The method body is enclosed inside the curly braces { }.

Calling a Method in Java


Example: Java Methods

class Main {

// create a method

public int addNumbers(int a, int b) {

int sum = a + b;

// return value

return sum;

© Edunet Foundation. All rights reserved .131


public static void main(String[] args) {

int num1 = 25;

int num2 = 15;

// create an object of Main

Main obj = new Main();

// calling method

int result = obj.addNumbers(num1, num2);

System.out.println("Sum is: " + result);

The method takes two parameters a and b. Notice the line,

int result = obj.addNumbers(num1, num2);

Here, we have called the method by passing two arguments num1 and num2. Since
the method is returning some value, we have stored the value in the result variable.

Java Method Return Type


A Java method may or may not return a value to the function call. We use the return
statement to return any value. For example,

int addNumbers() {

...

return sum;

Here, we are returning the variable sum. Since the return type of the function is int.
The sum variable should be of int type. Otherwise, it will generate an error.

© Edunet Foundation. All rights reserved .132


Example: Method Return Type

class Main {

// create a method

public static int square(int num) {

// return statement

return num * num;

public static void main(String[] args) {

int result;

// call the method

// store returned value to result

result = square(10);

System.out.println("Squared value of 10 is: " + result);

© Edunet Foundation. All rights reserved .133


Figure

Figure: Representation of the Java method returning a value


Source: https://www.programiz.com/java-programming/methods

Method Parameters in Java


A method parameter is a value accepted by the method.

Example: Method Parameters

class Main {

// method with no parameter

public void display1() {

System.out.println("Method without parameter");

// method with single parameter

public void display2(int a) {

© Edunet Foundation. All rights reserved .134


System.out.println("Method with a single parameter: " + a);

public static void main(String[] args) {

// create an object of Main

Main obj = new Main();

// calling method with no parameter

obj.display1();

// calling method with the single parameter

obj.display2(24);

Here, the parameter of the method is int. Hence, if we pass any other data type instead
of int, the compiler will throw an error. It is because Java is a strongly typed language.

Standard Library Methods


The standard library methods are built-in methods in Java that are readily available for
use. These standard libraries come along with the Java Class Library (JCL) in a Java
archive (*.jar) file with JVM and JRE.

For example,

print() is a method of java.io.PrintSteam. The print("...") method prints the string inside
quotation marks.

sqrt() is a method of Math class. It returns the square root of a number.

Example: Java Standard Library Method

public class Main {

© Edunet Foundation. All rights reserved .135


public static void main(String[] args) {

// using the sqrt() method

System.out.print("Square root of 4 is: " + Math.sqrt(4));

Advantages of using methods


1. Code reusability
2. More readable and easier to debug
Example: Java Method for Code Reusability

public class Main {

// method defined

private static int getSquare(int x){

return x * x;

public static void main(String[] args) {

for (int i = 1; i <= 5; i++) {

// method call

int result = getSquare(i);

System.out.println("Square of " + i + " is: " + result);

© Edunet Foundation. All rights reserved .136


Java Method Overloading
In Java, two or more methods may have the same name if they differ in parameters
(different number of parameters, different types of parameters, or both). These
methods are called overloaded methods and this feature is called method overloading.
For example:

void func() { ... }

void func(int a) { ... }

float func(double a) { ... }

float func(int a, float b) { ... }

Here, the func() method is overloaded. These methods have the same name but
accept different arguments.

Note: The return types of the above methods are not the same. It is because method
overloading is not associated with return types. Overloaded methods may have the
same or different return types, but they must differ in parameters.

Why method overloading?


Suppose, you have to perform the addition of given numbers but there can be any
number of arguments (let’s say either 2 or 3 arguments for simplicity).

In order to accomplish the task, you can create two methods sum2num(int, int) and
sum3num(int, int, int) for two and three parameters respectively. However, other
programmers, as well as you in the future may get confused as the behavior of both
methods are the same but they differ by name.

The better way to accomplish this task is by overloading methods. And, depending
upon the argument passed, one of the overloaded methods is called. This helps to
increase the readability of the program.

How to perform method overloading in Java?


Here are different ways to perform method overloading:

1. Overloading by changing the number of parameters

class MethodOverloading {

private static void display(int a){

System.out.println("Arguments: " + a);

}
© Edunet Foundation. All rights reserved .137
private static void display(int a, int b){

System.out.println("Arguments: " + a + " and " + b);

public static void main(String[] args) {

display(1);

display(1, 4);

2. Method Overloading by changing the data type of parameters


class MethodOverloading {

// this method accepts int

private static void display(int a){

System.out.println("Got Integer data.");

// this method accepts String object

private static void display(String a){

System.out.println("Got String object.");

public static void main(String[] args) {

display(1);

display("Hello");

}
© Edunet Foundation. All rights reserved .138
Here, both overloaded methods accept one argument. However, one accepts the
argument of type int whereas other accepts String object.

Example:

class HelperService {

private String formatNumber(int value) {

return String.format("%d", value);

private String formatNumber(double value) {

return String.format("%.3f", value);

private String formatNumber(String value) {

return String.format("%.2f", Double.parseDouble(value));

public static void main(String[] args) {

HelperService hs = new HelperService();

System.out.println(hs.formatNumber(500));

System.out.println(hs.formatNumber(89.9934));

System.out.println(hs.formatNumber("550"));

Important Points
• Two or more methods can have the same name inside the same class if they
accept different arguments. This feature is known as method overloading.
• Method overloading is achieved by either:
© Edunet Foundation. All rights reserved .139
• changing the number of arguments.
• or changing the data type of arguments.
• It is not method overloading if we only change the return type of methods. There
must be differences in the number of parameters.

Java Constructors
What is a Constructor?

A constructor in Java is similar to a method that is invoked when an object of the class
is created.

Unlike Java methods, a constructor has the same name as that of the class and does
not have any return type.

For example,

class Test {

Test() {

// constructor body

Here, Test() is a constructor. It has the same name as that of the class and doesn't
have a return type.

Example: Java Constructor

class Main {

private String name;

// constructor

Main() {

System.out.println("Constructor Called:");

name = "Jack";
© Edunet Foundation. All rights reserved .140
}

public static void main(String[] args) {

// constructor is invoked while

// creating an object of the Main class

Main obj = new Main();

System.out.println("The name is " + obj.name);

Notice the statement of creating an object of the Main class.

Main obj = new Main();

Here, when the object is created, the Main() constructor is called. And, the value of
the name variable is initialized.

Hence, the program prints the value of the name variables as Jack.

Types of Constructor
In Java, constructors can be divided into 3 types:

1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor

1. Java No-Arg Constructors


Similar to methods, a Java constructor may or may not have any parameters
(arguments).

If a constructor does not accept any parameters, it is known as a no-argument


constructor. For example,

private Constructor() {
© Edunet Foundation. All rights reserved .141
// body of the constructor

Example: Java private no-arg constructor

class Main {

int i;

// constructor with no parameter

private Main() {

i = 5;

System.out.println("Constructor is called");

public static void main(String[] args) {

// calling the constructor without any parameter

Main obj = new Main();

System.out.println("Value of i: " + obj.i);

We have created a constructor Main(). Here, the constructor does not accept any
parameters. Hence, it is known as a no-arg constructor.

Notice that we have declared the constructor as private.

Once a constructor is declared private, it cannot be accessed from outside the class.
So, creating objects from outside the class is prohibited using the private constructor.

Here, we are creating the object inside the same class. Hence, the program is able to
access the constructor.
© Edunet Foundation. All rights reserved .142
Example: Java public no-arg constructors

class Company {

String name;

// public constructor

public Company() {

name = "Programiz";

class Main {

public static void main(String[] args) {

// object is created in another class

Company obj = new Company();

System.out.println("Company name = " + obj.name);

2. Java Parameterized Constructor


A Java constructor can also accept one or more parameters. Such constructors are
known as parameterized constructors (constructor with parameters).

Example: Parameterized constructor

class Main {

String languages;

// constructor accepting single value

© Edunet Foundation. All rights reserved .143


Main(String lang) {

languages = lang;

System.out.println(languages + " Programming Language");

public static void main(String[] args) {

// call constructor by passing a single value

Main obj1 = new Main("Java");

Main obj2 = new Main("Python");

Main obj3 = new Main("C");

We have created a constructor named Main(). Here, the constructor takes a single
parameter. Notice the expression,

Main obj1 = new Main("Java");

Here, we are passing the single value to the constructor. Based on the argument
passed, the language variable is initialized inside the constructor.

3. Java Default Constructor


If we do not create any constructor, the Java compiler automatically create a no-arg
constructor during the execution of the program. This constructor is called default
constructor.

Example: Default Constructor

class Main {

int a;

boolean b;

public static void main(String[] args) {

© Edunet Foundation. All rights reserved .144


// A default constructor is called

Main obj = new Main();

System.out.println("Default Value:");

System.out.println("a = " + obj.a);

System.out.println("b = " + obj.b);

}}

Here, we haven't created any constructors. Hence, the Java compiler automatically
creates the default constructor.

The default constructor initializes any uninitialized instance variables with default
values.

Important Notes on Java Constructors


• Constructors are invoked implicitly when you instantiate objects.
• The two rules for creating a constructor are:
• The name of the constructor should be the same as the class.
• A Java constructor must not have a return type.
• If a class doesn't have a constructor, the Java compiler automatically creates a
default constructor during run-time. The default constructor initializes instance
variables with default values. For example, the int variable will be initialized to
0
• Constructor types:
• No-Arg Constructor - a constructor that does not accept any arguments
• Parameterized constructor - a constructor that accepts arguments
• Default Constructor - a constructor that is automatically created by the Java
compiler if it is not explicitly defined.
• A constructor cannot be abstract or static or final.
• A constructor can be overloaded but can not be overridden.

Constructors Overloading in Java


Similar to Java method overloading, we can also create two or more constructors with
different parameters. This is called constructors overloading.

Example: Java Constructor Overloading

© Edunet Foundation. All rights reserved .145


class Main {

String language;

// constructor with no parameter

Main() {

this.language = "Java";

// constructor with a single parameter

Main(String language) {

this.language = language;

public void getName() {

System.out.println("Programming Langauage: " + this.language);

public static void main(String[] args) {

// call constructor with no parameter

Main obj1 = new Main();

// call constructor with a single parameter

Main obj2 = new Main("Python");

obj1.getName();

obj2.getName();
© Edunet Foundation. All rights reserved .146
}

We have two constructors: Main() and Main(String language). Here, both the
constructor initialize the value of the variable language with different values.

Based on the parameter passed during object creation, different constructors are
called and different values are assigned.

It is also possible to call one constructor from another constructor.

Java Strings
In Java, a string is a sequence of characters. For example, "hello" is a string containing
a sequence of characters 'h', 'e', 'l', 'l', and 'o'.

We use double quotes to represent a string in Java. For example,

// create a string

String type = "Java programming";

Here, we have created a string variable named type. The variable is initialized with the
string Java Programming.

Example: Create a String in Java

class Main {

public static void main(String[] args) {

// create strings

String first = "Java";

String second = "Python";

String third = "JavaScript";

// print strings

System.out.println(first); // print Java

System.out.println(second); // print Python

System.out.println(third); // print JavaScript

© Edunet Foundation. All rights reserved .147


}

We have created three strings named first, second, and third. Here, we are directly
creating strings like primitive types.

Note: Strings in Java are not primitive types (like int, char, etc). Instead, all strings are
objects of a predefined class named String.

And, all string variables are instances of the String class.

Java String Operations


Java String provides various methods to perform different operations on strings. We
will look into some of the commonly used string operations.

1. Get length of a String


To find the length of a string, we u se the length() method of the String. For example,

class Main {

public static void main(String[] args) {

// create a string

String greet = "Hello! World";

System.out.println("String: " + greet);

// get the length of greet

int length = greet.length();

System.out.println("Length: " + length);

In the above example, the length() method calculates the total number of characters
in the string and returns it.

2. Join Two Java Strings


We can join two strings in Java using the concat() method. For example,

class Main {

© Edunet Foundation. All rights reserved .148


public static void main(String[] args) {

// create first string

String first = "Java ";

System.out.println("First String: " + first);

// create second

String second = "Programming";

System.out.println("Second String: " + second);

// join two strings

String joinedString = first.concat(second);

System.out.println("Joined String: " + joinedString);

We have created two strings named first and second. Notice the statement,

String joinedString = first.concat(second);

Here, the concat() method joins the second string to the first string and assigns it to
the joinedString variable.

We can also join two strings using the + operator in Java.

3. Compare two Strings


In Java, we can make comparisons between two strings using the equals() method.
For example,

class Main {

public static void main(String[] args) {

// create 3 strings

© Edunet Foundation. All rights reserved .149


String first = "java programming";

String second = "java programming";

String third = "python programming";

// compare first and second strings

boolean result1 = first.equals(second);

System.out.println("Strings first and second are equal: " + result1);

// compare first and third strings

boolean result2 = first.equals(third);

System.out.println("Strings first and third are equal: " + result2);

We have created 3 strings named first, second, and third. Here, we are using the
equal() method to check if one string is equal to another.

The equals() method checks the conten t of strings while comparing them.

Escape character in Java Strings


The escape character is used to escape some of the characters present inside a string.

Suppose we need to include double quotes inside a string.

// include double quote

String example = "This is the "String" class";

Since strings are represented by double quotes, the compiler will treat "This is the " as
the string. Hence, the above code will cause an error.

To solve this issue, we use the escape character \ in Java. For example,

// use the escape character

String example = "This is the \"String\" class.";

Now escape characters tell the compiler to escape double quotes and read the whole
text.

© Edunet Foundation. All rights reserved .150


Java Strings are Immutable
In Java, strings are immutable. This means, once we create a string, we cannot
change that string.

To understand it more deeply, consider an example:

// create a string

String example = "Hello! ";

Here, we have created a string variable named example. The variable holds the string
"Hello! ".

Now suppose we want to change the string.

// add another string "World"

// to the previous tring example

example = example.concat(" World");

Here, we are using the concat() method to add another string World to the previous
string.

It looks like we are able to change the value of the previous string. However, this is
not true.

Here is what has happened,

• JVM takes the first string "Hello! "


• creates a new string by adding "World" to the first string
• assign the new string "Hello! World" to the example variable
• the first string "Hello! " remains unchanged

Creating strings using the new keyword


So far we have created strings like primitive types in Java.

Since strings in Java are objects, we can create strings using the new keyword as
well. For example,

// create a string using the new keyword

String name = new String("Java String");

In the above example, we have created a string name using the new keyword.

Here, when we create a string object, the String() constructor is invoked.

© Edunet Foundation. All rights reserved .151


Example: Create Java Strings using the new keyword

class Main {

public static void main(String[] args) {

// create a string using new

String name = new String("Java String");

System.out.println(name); // print Java String

Create String using literals vs new keyword


Now that we know how strings are created using string literals and the new keyword,
let's see what is the major difference between them.

In Java, the JVM maintains a string pool to store all of its strings inside the memory.
The string pool helps in reusing the strings.

1. While creating strings using string literals,

String example = "Java";

Here, we are directly providing the value of the string (Java). Hence, the compiler first
checks the string pool to see if the string already exists.

If the string already exists, the new string is not created. Instead, the new reference,
example points to the already existed string (Java).

If the string doesn't exist, the new string (Java is created.

2. While creating strings using the new keyword,

String example = new String("Java");

Here, the value of the string is not directly provided. Hence, a new "Java" string is
created even though "Java" is already present inside the memory pool.

Methods of Java String


Besides those mentioned above, there are various string methods present in Java.
Here are some of those methods:

© Edunet Foundation. All rights reserved .152


Methods Description

contains() checks whether the string contains a substring

substring() returns the substring of the string

join() join the given strings using the delimiter

replace() replaces the specified old character with the specified new
character

replaceAll() replaces all substrings matching the regex pattern

replaceFirst() replace the first matching substring

charAt() returns the character present in the specified location

getBytes() converts the string to an array of bytes

indexOf() returns the position of the specified character in the string

compareTo() compares two strings in the dictionary order

compareToIgnoreCase() compares two strings ignoring case differences

trim() removes any leading and trailing whitespaces

format() returns a formatted string

split() breaks the string into an array of strings

toLowerCase() converts the string to lowercase

toUpperCase() converts the string to uppercase

valueOf() returns the string representation of the specified argument

toCharArray() converts the string to a char array

matches() checks whether the string matches the given regex

startsWith() checks if the string begins with the given string

endsWith() checks if the string ends with the given string

isEmpty() checks whether a string is empty of not

intern() returns the canonical representation of th e string

contentEquals() checks whether the string is equal to charSequence

hashCode() returns a hash code for the string

subSequence() returns a subsequence from the string

© Edunet Foundation. All rights reserved .153


Java Access Modifiers
What are Access Modifiers?

In Java, access modifiers are used to set the accessibility (visibility) of classes,
interfaces, variables, methods, constructors, data members, and the setter methods.
For example,

class Animal {

public void method1() {...}

private void method2() {...}

In the above example, we have declared 2 methods: method1() and method2(). Here,

method1 is public - This means it can be accessed by other classes.

method2 is private - This means it can not be accessed by other classes.

Types of Access Modifier

There are four access modifiers keywords in Java and they are:

Modifier Description

1. Default declarations are visible only within the package (package private)
2. Private declarations are visible within the class only
3. Protected declarations are visible within the package or all subclasses
4. Public declarations are visible everywhere

Default Access Modifier


If we do not explicitly specify any access modifier for classes, methods, variables, etc,
then by default the default access modifier is considered.

Private Access Modifier

When variables and methods are declared private, they cannot be accessed outside
of the class. For example,

class Data {

© Edunet Foundation. All rights reserved .154


// private variable

private String name;

public class Main {

public static void main(String[] main){

// create an object of Data

Data d = new Data();

// access private variable and field from another class

d.name = "Programiz";

Protected Access Modifier

When methods and data members are declared protected, we can access them within
the same package as well as from subclasses. For example,

class Animal {

// protected method

protected void display() {

System.out.println("I am an animal");

class Dog extends Animal {

public static void main(String[] args) {

// create an object of Dog class

© Edunet Foundation. All rights reserved .155


Dog dog = new Dog();

// access protected method

dog.display();

Public Access Modifier


When methods, variables, classes, and so on are declared public, then we can access
them from anywhere. The public access modifier has no scope restriction. For
example,

// Animal.java file

// public class

public class Animal {

// public variable

public int legCount;

// public method

public void display() {

System.out.println("I am an animal.");

System.out.println("I have " + legCount + " legs.");

// Main.java

public class Main {

public static void main( String[] args ) {

// accessing the public class

Animal animal = new Animal();

© Edunet Foundation. All rights reserved .156


// accessing the public variable

animal.legCount = 4;

// accessing the public method

animal.display();

Figure: Accessibility of all access modifiers in Java


Source: https://www.programiz.com/java-programming/access-modifiers

Java this Keyword


this Keyword

© Edunet Foundation. All rights reserved .157


In Java, this keyword is used to refer to the current object inside a method or a
constructor. For example,

class Main {

int instVar;

Main(int instVar){

this.instVar = instVar;

System.out.println("this reference = " + this);

public static void main(String[] args) {

Main obj = new Main(8);

System.out.println("object reference = " + obj);

Output:

this reference = Main@23fc625e

object reference = Main@23fc625e

Here, we can see that the reference of both obj and this is the same. It means this is
nothing but the reference to the current object.

Use of this Keyword


1. Using this for Ambiguity Variable Names
In Java, it is not allowed to declare two or more variables having the same name inside
a scope (class scope or method scope). However, instance variables and parameters
may have the same name.

2. Using this in Constructor Overloading

© Edunet Foundation. All rights reserved .158


While working with constructor overloading, we might have to invoke one constructor
from another constructor. In such a case, we cannot call the constructor explicitly.
Instead, we have to use this keyword.

While working with constructor overloading, we might have to invoke one constructor
from another constructor. In such a case, we cannot call the constructor explicitly.
Instead, we have to use this keyword.

Java final keyword


In Java, the final keyword is used to denote constants. It can be used with variables,
methods, and classes.

Once any entity (variable, method or class) is declared final, it can be assigned only
once. That is,

1. the final variable cannot be reinitialized with another value


2. the final method cannot be overridden
3. the final class cannot be extended

1. Java final Variable


In Java, we cannot change the value of a final variable. For example,

class Main {

public static void main(String[] args) {

// create a final variable

final int AGE = 32;

// try to change the final variable

AGE = 45;

System.out.println("Age: " + AGE);

When we run the program, we will get a compilation error with the following message.

cannot assign a value to final variable AGE

AGE = 45;
© Edunet Foundation. All rights reserved .159
^

Note: It is recommended to use uppercase to declare final variables in Java.

2. Java final Method


Before you learn about final methods and final classes, make sure you know about the
Java Inheritance.

In Java, the final method cannot be overridden by the child class. For example,

class FinalDemo {

// create a final method

public final void display() {

System.out.println("This is a final method.");

class Main extends FinalDemo {

// try to override final method

public final void display() {

System.out.println("The final method is overridden.");

public static void main(String[] args) {

Main obj = new Main();

obj.display();

When we run the program, we will get a compilation error with the following message.

display() in Main cannot override display() in FinalDemo

public final void display() {

© Edunet Foundation. All rights reserved .160


overridden method is final

3. Java final Class


In Java, the final class cannot be inherited by another class. For example,

// create a final class

final class FinalClass {

public void display() {

System.out.println("This is a final method.");

// try to extend the final class

class Main extends FinalClass {

public void display() {

System.out.println("The final method is overridden.");

public static void main(String[] args) {

Main obj = new Main();

obj.display();

When we run the program, we will get a compilation error with the following message.

cannot inherit from final FinalClass

class Main extends FinalClass {

Java instanceof Operator

© Edunet Foundation. All rights reserved .161


The instanceof operator in Java is used to check whether an object is an instance of
a particular class or not.

Its syntax is

objectName instanceOf className;

Here, if objectName is an instance of className, the operator returns true. Otherwise,


it returns false.

Example: Java instanceof

class Main {

public static void main(String[] args) {

// create a variable of string type

String name = "Programiz";

// checks if name is instance of String

boolean result1 = name instanceof String;

System.out.println("name is an instance of String: " + result1);

// create an object of Main

Main obj = new Main();

// checks if obj is an instance of Main

boolean result2 = obj instanceof Main;

System.out.println("obj is an instance of Main: " + result2);

© Edunet Foundation. All rights reserved .162


Output

name is an instance of String: true

obj is an instance of Main: true

In the above example, we have created a variable name of the String type and an
object obj of the Main class.

Here, we have used the instanceof operator to check whether name and obj are
instances of the String and Main class respectively. And, the operator returns true in
both cases.

Java Inheritance
Inheritance is one of the key features of OOP that allows us to create a new class from
an existing class.

The new class that is created is known as subclass (child or derived class) and the
existing class from where the child class is derived is known as superclass (parent or
base class).

The extends keyword is used to perform inheritance in Java. For example,

class Animal {

// methods and fields

// use of extends keyword

// to perform inheritance

class Dog extends Animal {

// methods and fields of Animal

// methods and fields of Dog

In the above example, the Dog class is created by inheriting the methods and fields
from the Animal class.

© Edunet Foundation. All rights reserved .163


Here, Dog is the subclass and Animal is the superclass.

Example: Java Inheritance

class Animal {

// field and method of the parent class

String name;

public void eat() {

System.out.println("I can eat");

// inherit from Animal

class Dog extends Animal {

// new method in subclass

public void display() {

System.out.println("My name is " + name);

class Main {

public static void main(String[] args) {

// create an object of the subclass

Dog labrador = new Dog();

// access field of superclass

labrador.name = "Rohu";

© Edunet Foundation. All rights reserved .164


labrador.display();

// call method of superclass

// using object of subclass

labrador.eat();

Output

My name is Rohu

I can eat

In the above example, we have derived a subclass Dog from superclass Animal.

Notice the statements,

labrador.name = "Rohu";

labrador.eat();

Here, labrador is an object of Dog. However, name and eat() are the members of the
Animal class.

Since Dog inherits the field and method from Animal, we are able to access the field
and method using the object of the Dog.

© Edunet Foundation. All rights reserved .165


Figure: Inheritance in Java
Source: https://www.programiz.com/java-programming/inheritance

Method Overriding in Java Inheritance


If the same method is present in both the superclass and subclass the method in the
subclass overrides the method in the superclass. This concept is known as method
overriding in Java.

Example: Method overriding in Java Inheritance

class Animal {

// method in the superclass

public void eat() {

System.out.println("I can eat");

// Dog inherits Animal

class Dog extends Animal {

© Edunet Foundation. All rights reserved .166


// overriding the eat() method

@Override

public void eat() {

System.out.println("I eat dog food");

// new method in subclass

public void bark() {

System.out.println("I can bark");

class Main {

public static void main(String[] args) {

// create an object of the subclass

Dog labrador = new Dog();

// call the eat() method

labrador.eat();

labrador.bark();

Output

I eat dog food

I can bark

© Edunet Foundation. All rights reserved .167


In the above example, the eat() method is present in both the superclass Animal and
the subclass Dog.

Here, we have created an object labrador of Dog.

Now when we call eat() using the object labrador, the method inside Dog is called.
This is because the method inside the derived class overrides the method inside the
base class.

This is called method overriding.

super Keyword in Java Inheritance

Previously we saw that the same method in the subclass overrides the method in
superclass.

In such a situation, the super keyword is used to call the method of the parent class
from the method of the child class.

Example: super Keyword in Inheritance

class Animal {

// method in the superclass

public void eat() {

System.out.println("I can eat");

// Dog inherits Animal

class Dog extends Animal {

// overriding the eat() method

@Override

public void eat() {

// call method of superclass


© Edunet Foundation. All rights reserved .168
super.eat();

System.out.println("I eat dog food");

// new method in subclass

public void bark() {

System.out.println("I can bark");

class Main {

public static void main(String[] args) {

// create an object of the subclass

Dog labrador = new Dog();

// call the eat() method

labrador.eat();

labrador.bark();

Output

I can eat

I eat dog food

I can bark

In the above example, the eat() method is present in both the base class Animal and
the derived class Dog. Notice the statement,

© Edunet Foundation. All rights reserved .169


super.eat();

Here, the super keyword is used to call the eat() method present in the superclass.

We can also use the super keyword to call the constructor of the superclass from the
constructor of the subclass.

Why use inheritance?


The most important use of inheritance in Java is code reusability. The code that is
present in the parent class can be directly used by the child class.

Method overriding is also known as runtime polymorphism. Hence, we can achieve


Polymorphism in Java with the help of inheritance.

Types of inheritance
There are five types of inheritance.

1. Single Inheritance
In single inheritance, a single subclass extends from a single superclass. For example,

Figure: Single Inheritance in Java


Source: https://www.programiz.com/java-programming/inheritance

2. Multilevel Inheritance
In multilevel inheritance, a subclass extends from a superclass and then the same
subclass acts as a superclass for another class. For example,

© Edunet Foundation. All rights reserved .170


Figure: Multilevel Inheritance in Java
Source: https://www.programiz.com/java-programming/inheritance

3. Hierarchical Inheritance
In hierarchical inheritance, multiple subclasses extend from a single superclass. For
example,

Figure: Hierarchical Inheritance in Java


Source: https://www.programiz.com/java-programming/inheritance

4. Multiple Inheritance
In multiple inheritance, a single subclass extends from multiple superclasses. For
example,

Figure: Multiple Inheritance in Java


Source: https://www.programiz.com/java-programming/inheritance

© Edunet Foundation. All rights reserved .171


Note: Java doesn't support multiple inheritance. However, we can achieve multiple
inheritance using interfaces.

5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance. For example,

Figure: Hybrid Inheritance in Java


Source: https://www.programiz.com/java-programming/inheritance

Here, we have combined hierarchical and multiple inheritance to form a hybrid


inheritance.

Java Method Overriding


If the same method is defined in both the superclass and the subclass, then the
method of the subclass class overrides the method of the superclass. This is known
as method overriding.

Example: Method Overriding

class Animal {

public void displayInfo() {

System.out.println("I am an animal.");

class Dog extends Animal {

© Edunet Foundation. All rights reserved .172


@Override

public void displayInfo() {

System.out.println("I am a dog.");

class Main {

public static void main(String[] args) {

Dog d1 = new Dog();

d1.displayInfo();

Output:

I am a dog.

In the above program, the displayInfo() method is present in both the Animal
superclass and the Dog subclass.

When we call displayInfo() using the d1 object (object of the subclass), the method
inside the subclass Dog is called. The displayInfo() method of the subclass overrides
the same method of the superclass.

Figure: Overriding in Java


Source: https://www.programiz.com/java-programming/method -overriding

© Edunet Foundation. All rights reserved .173


Java Overriding Rules
Both the superclass and the subclass must have the same method name, the same
return type and the same parameter list.

We cannot override the method declared as final and static.

We should always override abstract methods of the superclass super Keyword in Java
Overriding

To access the method of the superclass from the subclass, we use the super keyword.

Example: Use of super Keyword

class Animal {

public void displayInfo() {

System.out.println("I am an animal.");

class Dog extends Animal {

public void displayInfo() {

super.displayInfo();

System.out.println("I am a dog.");

class Main {

public static void main(String[] args) {

Dog d1 = new Dog();

d1.displayInfo();

© Edunet Foundation. All rights reserved .174


Output:

I am an animal.

I am a dog.

In the above example, the subclass Dog overrides the method displayInfo() of the
superclass Animal.

When we call the method displayInfo() using the d1 object of the Dog subclass, the
method inside the Dog subclass is called; the method inside the superclass is not
called.

Inside displayInfo() of the Dog subclass, we have used super.displayInfo() to call


displayInfo() of the superclass.

Java super keyword


The super keyword in Java is used in subclasses to access superclass members
(attributes, constructors and methods).

Before we learn about the super keyword, make sure to know about Java inheritance.

Uses of super keyword

1. To call methods of the superclass that is overridden in the subclass.


2. To access attributes (fields) of the superclass if both superclass and subclass
have attributes with the same name.
3. To explicitly call superclass no-arg (default) or parameterized constructor from
the subclass constructor.

1. Access Overridden Methods of the superclass


If methods with the same name are defined in both superclass and subclass, the
method in the subclass overrides the method in th e superclass. This is called method
overriding.

Example: Method overriding

class Animal {

// overridden method

public void display(){

© Edunet Foundation. All rights reserved .175


System.out.println("I am an animal");

class Dog extends Animal {

// overriding method

@Override

public void display(){

System.out.println("I have a dog");

public void printMessage(){

display();

class Main {

public static void main(String[] args) {

Dog dog1 = new Dog();

dog1.printMessage();

}}

Output

I have a dog

In this example, by making an object dog1 of Dog class, we can call its method
printMessage() which then executes the display() statement.

© Edunet Foundation. All rights reserved .176


Since display() is defined in both the classes, the method of subclass Dog overrides
the method of superclass Animal. Hence, the display() of the subclass is called.

Figure: super keyword in Java


Source: https://www.programiz.com/java-programming/super-keyword

What if the overridden method of the superclass has to be called?


We use super.display() if the overridden method display() of superclass Animal needs
to be called.

Example: super to Call Superclass Method

class Animal {

// overridden method

public void display(){

System.out.println("I am an animal");

class Dog extends Animal {

© Edunet Foundation. All rights reserved .177


// overriding method

@Override

public void display(){

System.out.println("I am a dog");

public void printMessage(){

// this calls overriding method

display();

// this calls overridden method

super.display();

class Main {

public static void main(String[] args) {

Dog dog1 = new Dog();

dog1.printMessage();

Output

I am a dog

I am an animal

Here, how the above program works.


© Edunet Foundation. All rights reserved .178
Figure: super keyword in Java
Source: https://www.programiz.com/java-programming/super-keyword

2. Access Attributes of the Superclass


The superclass and subclass can have attributes with the same name. We use the
super keyword to access the attribute of the superclass.

Example: Access superclass attribute

class Animal {

protected String type="animal";

class Dog extends Animal {

public String type="mammal";

public void printType() {

System.out.println("I am a " + type);

System.out.println("I am an " + super.type);

© Edunet Foundation. All rights reserved .179


class Main {

public static void main(String[] args) {

Dog dog1 = new Dog();

dog1.printType();

Output:

I am a mammal

I am an animal

In this example, we have defined the same instance field type in both the superclass
Animal and the subclass Dog.

We then created an object dog1 of the Dog class. Then, the printType() method is
called using this object.

Inside the printType() function,

type refers to the attribute of the subclass Dog.

super.type refers to the attribute of the superclass Animal.

3. Use of super() to access superclass constructor


As we know, when an object of a class is created, its default constructor is
automatically called.

To explicitly call the superclass constructor from the subclass constructor, we use
super(). It's a special form of the super keyword.

super() can be used only inside the subclass constructor and must be the first
statement.

Example: Use of super()

class Animal {

// default or no-arg constructor of class Animal


© Edunet Foundation. All rights reserved .180
Animal() {

System.out.println("I am an animal");

class Dog extends Animal {

// default or no-arg constructor of class Dog

Dog() {

// calling default constructor of the superclass

super();

System.out.println("I am a dog");

class Main {

public static void main(String[] args) {

Dog dog1 = new Dog();

Output

I am an animal

I am a dog

Here, when an object dog1 of Dog class is created, it automatically calls the default or
no-arg constructor of that class.

© Edunet Foundation. All rights reserved .181


Inside the subclass constructor, the super() statement calls the constructor of the
superclass and executes the statements inside it. Hence, we get the output I am an
animal.

Figure: super keyword in Java


Source: https://www.programiz.com/java-programming/super-keyword

Java Abstract Class and Abstract Methods


Java Abstract Class

The abstract class in Java cannot be instantiated (we cannot create objects of abstract
classes). We use the abstract keyword to declare an abstract class. For example,

// create an abstract class

abstract class Language {

// fields and methods

...

// try to create an object Language

// throws an error

Language obj = new Language();

An abstract class can have both the regular methods and abstract methods. For
example,

© Edunet Foundation. All rights reserved .182


abstract class Language {

// abstract method

abstract void method1();

// regular method

void method2() {

System.out.println("This is regular method");

Java Abstract Method


A method that doesn't have its body is known as an abstract method. We use the same
abstract keyword to create abstract methods. For example,

abstract void display();

Here, display() is an abstract method. The body of display() is replaced by ;.

If a class contains an abstract method, then the class should be declared abstract.
Otherwise, it will generate an error. For example,

// error

// class should be abstract

class Language {

// abstract method

abstract void method1();

Example: Java Abstract Class and Method

Though abstract classes cannot be instantiated, we can create subclasses from it. We
can then access members of the abstract class using the object of the subclass. For
example,

abstract class Language {


© Edunet Foundation. All rights reserved .183
// method of abstract class

public void display() {

System.out.println("This is Java Programming");

class Main extends Language {

public static void main(String[] args) {

// create an object of Main

Main obj = new Main();

// access method of abstract class

// using object of Main class

obj.display();

Output

This is Java programming

In the above example, we have created an abstract class named Language. The class
contains a regular method display().

We have created the Main class that inherits the abstract class. Notice the statement,

obj.display();

Here, obj is the object of the child class Main. We are calling the method of the abstract
class using the object obj.

© Edunet Foundation. All rights reserved .184


Implementing Abstract Methods
If the abstract class includes any abstract method, then all the child classes inherited
from the abstract superclass must provide the implementation of the abstract method.
For example,

abstract class Animal {

abstract void makeSound();

public void eat() {

System.out.println("I can eat.");

class Dog extends Animal {

// provide implementation of abstract method

public void makeSound() {

System.out.println("Bark bark");

class Main {

public static void main(String[] args) {

// create an object of Dog class

Dog d1 = new Dog();

d1.makeSound();

© Edunet Foundation. All rights reserved .185


d1.eat();

Output

Bark bark

I can eat.

In the above example, we have created an abstract class Animal. The class contains
an abstract method makeSound() and a non -abstract method eat().

We have inherited a subclass Dog from the superclass Animal. Here, the subclass
Dog provides the implementation for the abstract method makeSound().

We then used the object d1 of the Dog class to call methods makeSound() and eat().

Note: If the Dog class doesn't provide the implementation of the abstract method
makeSound(), Dog should also be declared as abstract. This is because the subclass
Dog inherits makeSound() from Animal.

Java Abstraction
The major use of abstract classes and methods is to achieve abstraction in Java.

Abstraction is an important concept of object-oriented programming that allows us to


hide unnecessary details and only show the needed information.

This allows us to manage complexity by omitting or hiding details with a simpler,


higher-level idea.

A practical example of abstraction can be motorbike brakes. We know what brake


does. When we apply the brake, the motorbike will stop. However, the working of the
brake is kept hidden from us.

The major advantage of hiding the working of the brake is that now the manufacturer
can implement brake differently for different motorbikes, however, what brake does
will be the same.

Example: Java Abstraction

abstract class MotorBike {

abstract void brake();

© Edunet Foundation. All rights reserved .186


class SportsBike extends MotorBike {

// implementation of abstract method

public void brake() {

System.out.println("SportsBike Brake");

class MountainBike extends MotorBike {

// implementation of abstract method

public void brake() {

System.out.println("MountainBike Brake");

class Main {

public static void main(String[] args) {

MountainBike m1 = new MountainBike();

m1.brake();

SportsBike s1 = new SportsBike();

s1.brake();

Output:

MountainBike Brake

SportsBike Brake

© Edunet Foundation. All rights reserved .187


In the above example, we have created an abstract super class MotorBike. The
superclass MotorBike has an abstract method brake().

The brake() method cannot be implemented inside MotorBike. It is because every bike
has different implementation of brakes. So, all the subclasses of MotorBike would have
different implementation of brake().

So, the implementation of brake() in MotorBike is kept hidden.

Here, MountainBike makes its own implementation of brake() and SportsBike makes
its own implementation of brake().

Key Points to Remember


• We use the abstract keyword to create abstract classes and methods.
• An abstract method doesn't have any implementation (method body).
• A class containing abstract methods should also be abstract.
• We cannot create objects of an abstract class.
• To implement features of an abstract class, we inherit subclasses from it and
create objects of the subclass.
• A subclass must override all abstract methods of an abstract class. However, if
the subclass is declared abstract, it's not mandatory to override abstract
methods.
• We can access the static attributes and methods of an abstract class using the
reference of the abstract class. For example,
Animal.staticMethod();

Java Interface
An interface is a fully abstract class. It includes a group of abstract methods (methods
without a body).

We use the interface keyword to create an interface in Java. For example,

interface Language {

public void getType();

public void getVersion();

Here,

• Language is an interface.
• It includes abstract methods: getType() and getVersion().
© Edunet Foundation. All rights reserved .188
Implementing an Interface
Like abstract classes, we cannot create objects of interfaces.

To use an interface, other classes must implement it. We use the implements keyword
to implement an interface.

Example: Java Interface

interface Polygon {

void getArea(int length, int breadth);

// implement the Polygon interface

class Rectangle implements Polygon {

// implementation of abstract method

public void getArea(int length, int breadth) {

System.out.println("The area of the rectangle is " + (length * breadth));

class Main {

public static void main(String[] args) {

Rectangle r1 = new Rectangle();

r1.getArea(5, 6);

Output

The area of the rectangle is 30

© Edunet Foundation. All rights reserved .189


In the above example, we have created an interface named Polygon. The interface
contains an abstract method getArea().

Here, the Rectangle class implements Polygon. And, provides the implementation of
the getArea() method.

Implementing Multiple Interfaces


In Java, a class can also implement multiple interfaces. For example,

interface A {

// members of A

interface B {

// members of B

class C implements A, B {

// abstract members of A

// abstract members of B

Extending an Interface
Similar to classes, interfaces can extend other interfaces. The extends keyword is
used for extending interfaces. For example,

interface Line {

// members of Line interface

// extending interface

interface Polygon extends Line {

// members of Polygon interface

© Edunet Foundation. All rights reserved .190


// members of Line interface

Here, the Polygon interface extends the Line interface. Now, if any class implements
Polygon, it should provide implementations for all the abstract methods of both Line
and Polygon.

Extending Multiple Interfaces


An interface can extend multiple interfaces. For example,

interface A {

...

interface B {

...

interface C extends A, B {

...

Advantages of Interface in Java


• Similar to abstract classes, interfaces help us to achieve abstraction in Java.
• Interfaces provide specifications that a class (which implements it) must follow.
• Interfaces are also used to achieve multiple in heritance in Java.
default methods in Java Interfaces

With the release of Java 8, we can now add methods with implementation inside an
interface. These methods are called default methods.

To declare default methods inside interfaces, we use the default keyword. For
example,

public default void getSides() {

// body of getSides()

}
© Edunet Foundation. All rights reserved .191
Why default methods?
Let's take a scenario to understand why default methods are introduced in Java.

Suppose, we need to add a new method in an interface.

We can add the method in our interface easily without implementation. However, that's
not the end of the story. All our classes that implement that interface must provide an
implementation for the method.

If a large number of classes were implementing this interface, we need to track all
these classes and make changes to them. This is not only tedious but error-prone as
well.

To resolve this, Java introduced default methods. Default methods are inherited like
ordinary methods.

Example: Default Method in Java Interface

interface Polygon {

void getArea();

// default method

default void getSides() {

System.out.println("I can get sides of a polygon.");

// implements the interface

class Rectangle implements Polygon {

public void getArea() {

int length = 6;

int breadth = 5;

int area = length * breadth;

System.out.println("The area of the rectangle is " + area);

© Edunet Foundation. All rights reserved .192


// overrides the getSides()

public void getSides() {

System.out.println("I have 4 sides.");

// implements the interface

class Square implements Polygon {

public void getArea() {

int length = 5;

int area = length * length;

System.out.println("The area of the square is " + area);

class Main {

public static void main(String[] args) {

// create an object of Rectangle

Rectangle r1 = new Rectangle();

r1.getArea();

r1.getSides();

// create an object of Square

Square s1 = new Square();

s1.getArea();

s1.getSides();
© Edunet Foundation. All rights reserved .193
}

Output

The area of the rectangle is 30

I have 4 sides.

The area of the square is 25

I can get sides of a polygon.

In the above example, we have created an interface named Polygon. It has a default
method getSides() and an abstract method getArea().

Here, we have created two classes Rectangle and Square that implement Polygon.

The Rectangle class provides the implementation of the getArea() method and
overrides the getSides() method. However, the Square class only provides the
implementation of the getArea() method.

Now, while calling the getSides() method using the Rectangle object, the overridden
method is called. However, in the case of the Square object, the default method is
called.

Practical Example of Interface


Let's see a more practical example of Java Interface.

// To use the sqrt function

import java.lang.Math;

interface Polygon {

void getArea();

// calculate the perimeter of a Polygon

default void getPerimeter(int... sides) {

int perimeter = 0;

for (int side: sides) {

© Edunet Foundation. All rights reserved .194


perimeter += side;

System.out.println("Perimeter: " + perimeter);

class Triangle implements Polygon {

private int a, b, c;

private double s, area;

// initializing sides of a triangle

Triangle(int a, int b, int c) {

this.a = a;

this.b = b;

this.c = c;

s = 0;

// calculate the area of a triangle

public void getArea() {

s = (double) (a + b + c)/2;

area = Math.sqrt(s*(s-a)*(s-b)*(s-c));

System.out.println("Area: " + area);

class Main {
© Edunet Foundation. All rights reserved .195
public static void main(String[] args) {

Triangle t1 = new Triangle(2, 3, 4);

// calls the method of the Triangle class

t1.getArea();

// calls the method of Polygon

t1.getPerimeter(2, 3, 4);

Output

Area: 2.9047375096555625

Perimeter: 9

In the above program, we have created an interface named Polygon. It includes a


default method getPerimeter() and an abstract method getArea().

We can calculate the perimeter of all polygons in the same manner so we implemented
the body of getPerimeter() in Polygon.

Now, all polygons that implement Polygon can use getPerimeter() to calculate
perimeter.

However, the rule for calculating the area is different for different polygons. Hence,
getArea() is included without implementation.

Any class that implements Polygon must provide an implementation of getArea().

Java Polymorphism
Polymorphism is an important concept of object-oriented programming. It simply
means more than one form.

That is, the same entity (method or operator or object) can perform different operations
in different scenarios.

Example: Java Polymorphism


© Edunet Foundation. All rights reserved .196
class Polygon {

// method to render a shape

public void render() {

System.out.println("Rendering Polygon...");

class Square extends Polygon {

// renders Square

public void render() {

System.out.println("Rendering Square...");

class Circle extends Polygon {

// renders circle

public void render() {

System.out.println("Rendering Circle...");

class Main {

public static void main(String[] args) {

// create an object of Square

Square s1 = new Square();


© Edunet Foundation. All rights reserved .197
s1.render();

// create an object of Circle

Circle c1 = new Circle();

c1.render();

Java Encapsulation
Encapsulation is one of the key features of object-oriented programming.
Encapsulation refers to the bundling of fields and methods inside a single class.

It prevents outer classes from accessing and changing fields and methods of a class.
This also helps to achieve data hiding.

Example: Java Encapsulation

class Area {

// fields to calculate area

int length;

int breadth;

// constructor to initialize values

Area(int length, int breadth) {

this.length = length;

this.breadth = breadth;

// method to calculate area

© Edunet Foundation. All rights reserved .198


public void getArea() {

int area = length * breadth;

System.out.println("Area: " + area);

class Main {

public static void main(String[] args) {

// create object of Area

// pass value of length and breadth

Area rectangle = new Area(5, 6);

rectangle.getArea();

In the above example, we have created a class named Area. The main purpose of this
class is to calculate the area.

To calculate an area, we need two variables: length and breadth and a method:
getArea(). Hence, we bundled these fields and methods inside a single class.

Here, the fields and methods can be accessed from other classes as well. Hence, this
is not data hiding.

This is only encapsulation. We are just keeping similar codes together.

Why Encapsulation?

In Java, encapsulation helps us to keep related fields and methods together, which
makes our code cleaner and easy to read.

It helps to control the values of our data fields. For example,

class Person {

private int age;

© Edunet Foundation. All rights reserved .199


public void setAge(int age) {

if (age >= 0) {

this.age = age;

Here, we are making the age variable private and applying logic inside the setAge()
method. Now, age cannot be negative.

Data Hiding
Data hiding is a way of restricting the access of our data members by hiding the
implementation details. Encapsulation also provides a way for data hiding.

Java Exceptions
An exception is an unexpected event that occurs during program execution. It affects
the flow of the program instructions which can cause the program to terminate
abnormally.

An exception can occur for many reasons. Some of them are:

• Invalid user input


• Device failure
• Loss of network connection
• Physical limitations (out of disk memory)
• Code errors
• Opening an unavailable file

Java Exception hierarchy


Here is a simplified diagram of the exception hierarchy in Java.

© Edunet Foundation. All rights reserved .200


Figure: Java Exception hierarchy
Source: https://www.programiz.com/java-programming/exceptions

Errors
Errors represent irrecoverable conditions such as Java virtual machine (JVM) running
out of memory, memory leaks, stack overflow errors, library incompatibility, infinite
recursion, etc.

Errors are usually beyond the control of the programmer and we should not try to
handle errors.

Exceptions
Exceptions can be caught and handled by the program.

When an exception occurs within a method, it creates an object. This object is called
the exception object.

It contains information about the exception such as the name and description of the
exception and state of the program when the exception occurred.

Java Exception Types


The exception hierarchy also has two branches: RuntimeException and IOException.

1. RuntimeException

© Edunet Foundation. All rights reserved .201


A runtime exception happens due to a programming error. They are also known as
unchecked exceptions.

These exceptions are not checked at compile-time but run-time. Some of the common
runtime exceptions are:

• Improper use of an API - IllegalArgumentException


• Null pointer access (missing the initialization of a variable) -
NullPointerException
• Out-of-bounds array access - ArrayIndexOutOfBoundsException
• Dividing a number by 0 - ArithmeticException
• You can think about it in this way. “If it is a runtime exception, it is your fault”.

The NullPointerException would not have occurred if you had checked whether the
variable was initialized or not before using it.

An ArrayIndexOutOfBoundsException would not have occurred if you tested the array


index against the array bounds.

2. IOException
An IOException is also known as a checked exception. They are checked by the
compiler at the compile-time and the programmer is prompted to handle these
exceptions.

Some of the examples of checked exceptions are:

• Trying to open a file that doesn’t exist results in FileNotFoundException


• Trying to read past the end of a file

Java Exception Handling


Different approaches to handle exceptions in Java.

1. try...catch block
2. finally block
3. throw and throws keyword

1. Java try...catch block


The try-catch block is used to handle exceptions in Java. Here's the syntax of
try...catch block:

try {

// code

© Edunet Foundation. All rights reserved .202


}

catch(Exception e) {

// code

Here, we have placed the code that might generate an exception inside the try block.
Every try block is followed by a catch block.

When an exception occurs, it is caught by the catch block. The catch block cannot be
used without the try block.

Example: Exception handling using try...catch

class Main {

public static void main(String[] args) {

try {

// code that generate exception

int divideByZero = 5 / 0;

System.out.println("Rest of code in try block");

catch (ArithmeticException e) {

System.out.println("ArithmeticException => " + e.getMessage());

Output

ArithmeticException => / by zero

In the example, we are trying to divide a number by 0. Here, this code generates an
exception.

© Edunet Foundation. All rights reserved .203


To handle the exception, we have put the code, 5 / 0 inside the try block. Now when
an exception occurs, the rest of the code inside the try block is skipped.

The catch block catches the exception and statements inside the catch block is
executed.

If none of the statements in the try block generates an exception, the catch block is
skipped.

2. Java finally block


In Java, the finally block is always executed no matter whether there is an exception
or not.

The finally block is optional. And, for each try block, there can be only one finally block.

The basic syntax of finally block is:

try {

//code

catch (ExceptionType1 e1) {

// catch block

finally {

// finally block always executes

If an exception occurs, the finally block is executed after the try...catch block.
Otherwise, it is executed after the try block. For each try block, there can be only one
finally block.

Example: Java Exception Handling using finally block

class Main {

public static void main(String[] args) {

try {

// code that generates exception

© Edunet Foundation. All rights reserved .204


int divideByZero = 5 / 0;

catch (ArithmeticException e) {

System.out.println("ArithmeticException => " + e.getMessage());

finally {

System.out.println("This is the finally block");

Output

ArithmeticException => / by zero

This is the finally block

In the above example, we are dividing a number by 0 inside the try block. Here, this
code generates an ArithmeticException.

The exception is caught by the catch block. And, then the finally block is executed.

3. Java throw and throws keyword


The Java throw keyword is used to explicitly throw a single exception.

When we throw an exception, the flow of the program moves from the try block to the
catch block.

Example: Exception handling using Java throw

class Main {

public static void divideByZero() {

© Edunet Foundation. All rights reserved .205


// throw an exception

throw new ArithmeticException("Trying to divide by 0");

public static void main(String[] args) {

divideByZero();

Output

Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0

at Main.divideByZero(Main.java:5)

at Main.main(Main.java:9)

In the above example, we are explicitly throwing the ArithmeticException using the
throw keyword.

Similarly, the throws keyword is used to declare the type of exceptions that might occur
within the method. It is used in the method declaration.

Example: Java throws keyword

import java.io.*;

class Main {

// declareing the type of exception

public static void findFile() throws IOException {

// code that may generate IOException

File newFile = new File("test.txt");

FileInputStream stream = new FileInputStream(newFile);

© Edunet Foundation. All rights reserved .206


public static void main(String[] args) {

try {

findFile();

catch (IOException e) {

System.out.println(e);

Output

java.io.FileNotFoundException: test.txt (The system cannot find the file


specified)

When we run this program, if the file test.txt does not exist, FileInputStream throws a
FileNotFoundException which extends the IOException class.

The findFile() method specifies that an IOException can be thrown. The main() method
calls this method and handles the exception if it is thrown.

If a method does not handle exceptions, the type of exceptions that may occur within
it must be specified in the throws clause.

Java try...catch
The try...catch block in Java is used to handle exceptions and prevents the abnormal
termination of the program.

Here's the syntax of a try...catch block in Java.

try{

// code

catch(exception) {

// code

© Edunet Foundation. All rights reserved .207


The try block includes the code that might generate an exception.

The catch block includes the code that is executed when there occurs an exception
inside the try block.

Example: Java try...catch block

class Main {

public static void main(String[] args) {

try {

int divideByZero = 5 / 0;

System.out.println("Rest of code in try block");

catch (ArithmeticException e) {

System.out.println("ArithmeticException => " + e.getMessage());

Output

ArithmeticException => / by zero

In the above example, notice the line,

int divideByZero = 5 / 0;

Here, we are trying to divide a number by zero. In this case, an exception occurs.
Hence, we have enclosed this code inside the try block.

When the program encounters this code, ArithmeticException occurs. And, the
exception is caught by the catch block and executes the code inside the catch block.

The catch block is only executed if there exists an exception inside the try block.

© Edunet Foundation. All rights reserved .208


Java throw and throws
In Java, exceptions can be categorized into two types:

• Unchecked Exceptions: They are not checked at compile-time but at run-


time.For example: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException, exceptions under Error class, etc.
• Checked Exceptions: They are checked at compile-time. For example,
IOException, InterruptedException, etc.
Java throws keyword

We use the throws keyword in the method declaration to declare the type of exceptions
that might occur within it.

Its syntax is:

accessModifier returnType methodName() throws ExceptionType1,


ExceptionType2 … {

// code

As you can see from the above syntax, we can use throws to declare multiple
exceptions.

Example: Java throws Keyword

import java.io.*;

class Main {

public static void findFile() throws IOException {

// code that may produce IOException

File newFile=new File("test.txt");

FileInputStream stream=new FileInputStream(newFile);

public static void main(String[] args) {

try{

findFile();

} catch(IOException e){

© Edunet Foundation. All rights reserved .209


System.out.println(e);

Output

java.io.FileNotFoundException: test.txt (No such file or directory)

When we run this program, if the file test.txt does not exist, FileInputStream throws a
FileNotFoundException which extends the IOException class.

If a method does not handle exceptions, the type of exceptions that may occur within
it must be specified in the throws clause so that methods further up in the call stack
can handle them or specify them using throws keyword themselves.

The findFile() method specifies that an IOException can be thrown. The main() method
calls this method and handles the exception if it is thrown.

Java throw keyword


The throw keyword is used to explicitly throw a single exception.

When an exception is thrown, the flow of program execution transfers from the try
block to the catch block. We use the throw keyword within a method.

Its syntax is:

throw throwableObject;

A throwable object is an instance of class Throwable or subclass of the Throwable


class.

Example: Java throw keyword

class Main {

public static void divideByZero() {

throw new ArithmeticException("Trying to divide by 0");

public static void main(String[] args) {


© Edunet Foundation. All rights reserved .210
divideByZero();

Output

Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0

at Main.divideByZero(Main.java:3)

at Main.main(Main.java:7)

exit status 1

In this example, we are explicitly throwing an ArithmeticException.

Note: ArithmeticException is an unchecked exception. It's usually not necessary to


handle unchecked exceptions.

2.2 - Java Annotations


Java annotations are metadata (data about data) for our program source code.

They provide additional information about the program to the compiler but are not part
of the program itself. These annotations do not affect the execution of the compiled
program.

Annotations start with @. Its syntax is:

@AnnotationName

Let's take an example of @Override annotation.

The @Override annotation specifies that the method that has been marked with this
annotation overrides the method of the superclass with the same method name, return
type, and parameter list.

It is not mandatory to use @Override when overriding a method. However, if we use


it, the compiler gives an error if something is wrong (such as wrong parameter type)
while overriding the method.

Example: @Override Annotation Example

class Animal {

public void displayInfo() {

System.out.println("I am an animal.");

© Edunet Foundation. All rights reserved .211


}

class Dog extends Animal {

@Override

public void displayInfo() {

System.out.println("I am a dog.");

class Main {

public static void main(String[] args) {

Dog d1 = new Dog();

d1.displayInfo();

Output

I am a dog.

In this example, the method displayInfo() is present in both the superclass Animal and
subclass Dog. When this method is called, the method of the subclass is called instead
of the method in the superclass.

Annotation formats
Annotations may also include elements (members/attributes/parameters).

1. Marker Annotations
Marker annotations do not contain members/elements. It is only used for marking a
declaration.

Its syntax is:

@AnnotationName()
© Edunet Foundation. All rights reserved .212
Since these annotations do not contain elements, parentheses can be excluded. For
example,

@Override

2. Single element Annotations


A single element annotation contains only one element.

Its syntax is:

@AnnotationName(elementName = "elementValue")

If there is only one element, it is a convention to name that element as value.

@AnnotationName(value = "elementValue")

In this case, the element name can be excluded as well. The element name will be
value by default.

@AnnotationName("elementValue")

3. Multiple element Annotations


These annotations contain multiple elements separated by commas.

Its syntax is:

@AnnotationName(element1 = "value1", element2 = "value2")

Annotation placement
Any declaration can be marked with annotation by placing it above that declaration.
As of Java 8, annotations can also be placed before a type.

1. Above declarations
As mentioned above, Java annotations can be placed above class, method, interface,
field, and other program element declarations.

Example: @SuppressWarnings Annotation Example

import java.util.*;

class Main {

© Edunet Foundation. All rights reserved .213


@SuppressWarnings("unchecked")

static void wordsList() {

ArrayList wordList = new ArrayList<>();

// This causes an unchecked warning

wordList.add("MS-SAP");

System.out.println("Word list => " + wordList);

public static void main(String args[]) {

wordsList();

Output

Word list => [MS-SAP]

If the above program is compiled without using the


@SuppressWarnings("unchecked") annotation, the compiler will still compile the
program but it will give warnings like:

Main.java uses unchecked or unsafe operations.

Word list => [MS-SAP]

We are getting the warning

Main.java uses unchecked or unsafe operations

because of the following statement.

ArrayList wordList = new ArrayList<>();

© Edunet Foundation. All rights reserved .214


This is because we haven't defined the generic type of the array list. We can fix this
warning by specifying generics inside angle brackets <>.

ArrayList<String> wordList = new ArrayList<>();

2. Type annotations
Before Java 8, annotations could be applied to declarations only. Now, type
annotations can be used as well. This means that we can place annotations wherever
we use a type.

Constructor invocations

new @Readonly ArrayList<>()

Type definitions

@NonNull String str;

This declaration specifies non-null variable str of type String to avoid


NullPointerException.

@NonNull List<String> newList;

This declaration specifies a non -null list of type String.

List<@NonNull String> newList;

This declaration specifies a list of non -null values of type String.

Type casts

newStr = (@NonNull String) str;

extends and implements clause

class Warning extends @Localized Message

throws clause

public String readMethod() throws @Localized IOException

© Edunet Foundation. All rights reserved .215


Type annotations enable Java code to be analyzed better and provide even stronger
type checks.

Types of Annotations
1. Predefined annotations

@Deprecated

@Override

@SuppressWarnings

@SafeVarargs

@FunctionalInterface

2. Meta-annotations

@Retention

@Documented

@Target

@Inherited

@Repeatable

3. Custom annotations

Use of Annotations
• Compiler instructions - Annotations can be used for giving instructions to the
compiler, detect errors or suppress warnings. The built-in annotations
@Deprecated, @Override,@SuppressWarnings are used for these purposes.
• Compile-time instructions - Compile-time instructions provided by these
annotations help the software build tools to generate code, XML files and many
more.
• Runtime instructions - Some annotations can be defined to give instructions to
the program at runtime. These annotations are accessed using Java Reflection.

Java Annotation Types

© Edunet Foundation. All rights reserved .216


Java annotations are metadata (data about data) for our program source code. There
are several predefined annotations provided by the Java SE. Moreover, we can also
create custom annotations as per our needs.

These annotations can be categorized as:

1. Predefined annotations

@Deprecated

@Override

@SuppressWarnings

@SafeVarargs

@FunctionalInterface

2. Custom annotations

3. Meta-annotations

@Retention

@Documented

@Target

@Inherited

@Repeatable

Predefined Annotation Types


1. @Deprecated
The@Deprecated annotation is a marker annotation that indicates the element (class,
method, field, etc) is deprecated and has been replaced by a newer element.

Its syntax is:

@Deprecated

accessModifier returnType deprecatedMethodName() { ... }

When a program uses the element that has been declared deprecated, the compiler
generates a warning.
© Edunet Foundation. All rights reserved .217
We use Javadoc @deprecated tag for documenting the deprecated element.

/**

* @deprecated

* why it was deprecated

*/

@Deprecated

accessModifier returnType deprecatedMethodName() { ... }

Example: @Deprecated annotation example

class Main {

/**

* @deprecated

* This method is deprecated and has been replaced by newMethod()

*/

@Deprecated

public static void deprecatedMethod() {

System.out.println("Deprecated method");

public static void main(String args[]) {

deprecatedMethod();

Output

Deprecated method

© Edunet Foundation. All rights reserved .218


2. @Override
The @Override annotation specifies that a method of a subclass overrides the method
of the superclass with the same method name, return type, and parameter list.

It is not mandatory to use @Override when overriding a method. However, if we use


it, the compiler gives an error if something is wrong (such as wrong parameter type)
while overriding the method.

Example: @Override annotation example

class Animal {

// overridden method

public void display(){

System.out.println("I am an animal");

class Dog extends Animal {

// overriding method

@Override

public void display(){

System.out.println("I am a dog");

public void printMessage(){

display();

© Edunet Foundation. All rights reserved .219


class Main {

public static void main(String[] args) {

Dog dog1 = new Dog();

dog1.printMessage();

Output

I am a dog

In this example, by making an object dog1 of Dog class, we can call its method
printMessage() which then executes the display() statement.

Since display() is defined in both the classes, the method of subclass Dog overrides
the method of superclass Animal. Hence, the display() of the subclass is called.

3. @SuppressWarnings
As the name suggests, the @SuppressWarnings annotation instructs the compiler to
suppress warnings that are generated while the program executes.

We can specify the type of warnings to be suppressed. The warnings that can be
suppressed are compiler-specific but there are two categories of warnings:
deprecation and unchecked.

To suppress a particular category of warning, we use:

@SuppressWarnings("warningCategory")

For example,

@SuppressWarnings("deprecated")

To suppress multiple categories of warnings, we use:

@SuppressWarnings({"warningCategory1", "warningCategory2"})

For example,

@SuppressWarnings({"deprecated", "unchecked"})

Category deprecated instructs the compiler to suppress warnings when we use a


deprecated element.

© Edunet Foundation. All rights reserved .220


Category unchecked instructs the compiler to suppress warnings when we use raw
types.

And, undefined warnings are ignored. For example,

@SuppressWarnings("someundefinedwarning")

Example: @SuppressWarnings annotation example

class Main {

@Deprecated

public static void deprecatedMethod() {

System.out.println("Deprecated method");

@SuppressWarnings("deprecated")

public static void main(String args[]) {

Main depObj = new Main();

depObj. deprecatedMethod();

Output

Deprecated method

Here, deprecatedMethod() has been marked as deprecated and will give compiler
warnings when used. By using the @SuppressWarnings("deprecated") annotation, we
can avoid compiler warnings.

© Edunet Foundation. All rights reserved .221


2.3 - Understanding Server-Side Scripting

What is Server-Side Scripting?

Web servers are used to execute server-side scripting. They are basically used to
create dynamic pages. It can also access the file system residing at the webserver. A
server-side environment that runs on a scripting language is a web server.

Scripts can be written in any of a number of server-side scripting languages available.


It is used to retrieve and generate content for dynamic pages. It is used to require to
download plugins. In this load times are generally faster than client-side scripting.
When you need to store and retrieve information a database will be used to contain
data. It can use huge resources of the server. It reduces client-side computation
overhead. The server sends pages to the request of the user/client.

© Edunet Foundation. All rights reserved .222


Advantage of Server side Scripting
There are several advantages of using server side scripting languages that are as
follows:

1. The main advantage of using server side scripting is that all the processing of
data takes place before a web page is sent to the browser. As a result, server
side script code remains hidden from users.
2. Server side scripting is an independent of browser. That is, browser does not
impact on the processing of script code because all the data processing takes
place on the server end.
3. It allows database interactivity with web pages.
4. Furthermore, it allows the use of templates for creating HTML web pages. A
template is a file that contains HTML code to which contents from a text file,
database, and other data retrieves dynamically before displaying the web page
to the user.
5. Server side script cannot be disabled at the client side.
6. Server side scripting is more secure than client side scripting.
7. It can access files and database that do not normally be available to the client
or user.
8. It provides code reusability.

Disadvantage of Server side Scripting


There are also a few disadvantages of using server side scripts that are as follows:

1. We need a high configuration server to use server side scripting.


2. We require a lot of processing speed for running complex tasks. It possibly
slows down the website if the server speed is not good.
3. Server side scripting is slower than client side scripting. It takes too much time
because it requires request from the client.

What is Server side Script?


A server-side script is a program that is executed on the server side when the user
requests information. The script do not download at the client side.

When the client or visitor requests the page, the web server reads it first. After reading,
the web server locates the page file on the disk, loads into memory and asks the script
engines (or interpreter) to process the script code.

After processing, web server generates the HTML page and pass back to the server.
The browser processes the client side script along with the HTML web page from the
server and display the web page on the client’s computer screen.

© Edunet Foundation. All rights reserved .223


Figure: Server side and client side scripts processing
Source: https://www.scientecheasy.com/2021/12/server-side-scripting.html/

Thus, the client receives a pure HTML web page (possibly even client code) without
any trace of server code. In this way, the server code secure enormously.

So, we can say that in the server side, all the tasks are carried out at a server end
instead of on the client end, and then the result is sent back to the client end.

Server side Scripting Language Example


The language in which server side script or program is written using syntax is called
server side scripting language or server side programming language.

These kinds of scripts are always executed before a web page is loaded on the
browser. Some common examples of server-side scripting languages are:

• PHP,
• Python,
• Ruby,
• ASP.NET,
• Perl,
• Go,
• JavaScript
• Java
These scripting languages execute like programming languages at the server end.

Application of Server side Scripting


© Edunet Foundation. All rights reserved .224
The server side scripting is used to send the information to the web server to execute
the script on the web server. Some common use of server-side scripting are listed, as
below:

1. Server side scripting is used to protect the credential (username and password).
When the user signs up any login web page first time, username and password are
saved in the server.

Whenever a user wishes to log in, the web server verifies the credential (username
and password) of the user with the username and password stored in the server. If
they are matched, the user will be allowed to access the server side resources.

2. Whenever we submit an online application, the data or information entered in the


form is stored in the database of the server.

Once the information is successfully submitted to the server via online forms, the
information from the server can be accessed and represented in the form of report,
forms, etc.

3. At server side, we can dynamically edit, add, remove, or update the content of web
page at any moment.

4. It is used at backend, where the source code is not visible to the client.

5. Server side script can be used for creating and applying complex business logics.

6. It can be used to customize a web page to make it more useful for individual clients.

Introduction to Servlets and JSP

Why to Learn Servlet?


• Using Servlets, you can collect input from users through web page forms,
present records from a database or another source, and create web pages
dynamically.
• Java Servlets often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI). But Servlets offer several advantages
in comparison with the CGI.
• Performance is significantly better.
• Servlets execute within the address space of a Web server. It is not necessary
to create a separate process to handle each client request.
• Servlets are platform-independent because they are written in Java.
• Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine. So servlets are trusted.

© Edunet Foundation. All rights reserved .225


• The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and
RMI mechanisms that you have seen already.

Applications of Servlet
• Read the explicit data sent by the clients (browsers). This includes an HTML
form on a Web page or it could also come from an applet or a custom HTTP
client program.
• Read the implicit HTTP request data sent by the clients (browsers). This
includes cookies, media types and compression schemes the browser
understands, and so forth.
• Process the data and generate the results. This process may require talking to
a database, executing an RMI or CORBA call, invoking a Web service, or
computing the response directly.
• Send the explicit data (i.e., the document) to the clients (browsers). This
document can be sent in a variety of formats, including text (HTML or XML),
binary (GIF images), Excel, etc.
• Send the implicit HTTP response to the clients (browsers). This includes telling
the browsers or other clients what type of document is being returned (e.g.,
HTML), setting cookies and caching parameters, and other such tasks.

What are Servlets?


Java Servlets are programs that run on a Web or Application server and act as a
middle layer between a requests coming from a Web browser or other HTTP client
and databases or applications on the HTTP server.

Using Servlets, you can collect input from users through web page forms, present
records from a database or another source, and create web pages dynamically.

Java Servlets often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But Servlets offer several advantages in
comparison with the CGI.

• Performance is significantly better.


• Servlets execute within the address space of a Web server. It is not necessary
to create a separate process to handle each client request.
• Servlets are platform-independent because they are written in Java.
• Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine. So servlets are trusted.
• The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and
RMI mechanisms that you have seen already.

© Edunet Foundation. All rights reserved .226


Servlets Architecture
The following diagram shows the position of Servlets in a Web Application.

Figure: Servlet architecture


Source: https://www.tutorialspoint.com/servlets/servlets_overview.htm

Servlets Tasks
Servlets perform the following major tasks −

• Read the explicit data sent by the clients (browsers). This includes an HTML
form on a Web page or it could also come from an applet or a custom HTTP
client program.
• Read the implicit HTTP request data sent by the clients (browsers). This
includes cookies, media types and compression schemes the browser
understands, and so forth.
• Process the data and generate the results. This process may require talking to
a database, executing an RMI or CORBA call, invoking a Web service, or
computing the response directly.
• Send the explicit data (i.e., the document) to the clients (browsers). This
document can be sent in a variety of formats, including text (HTML or XML),
binary (GIF images), Excel, etc.
• Send the implicit HTTP response to the clients (browsers). This includes telling
the browsers or other clients what type of document is being returned (e.g.,
HTML), setting cookies and caching parameters, and other such tasks.

Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that
supports the Java Servlet specification.

Servlets can be created using the javax.servlet and javax.servlet.http packages,


which are a standard part of the Java's enterprise edition, an expanded version of the
Java class library that supports large-scale development projects.

© Edunet Foundation. All rights reserved .227


These classes implement the Java Servlet and JSP specifications. At the time of
writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.

Java servlets have been created and compiled just like any other Java class. After you
install the servlet packages and add them to your computer's Classpath, you can
compile servlets with the JDK's Java compiler or any other current compiler.

Servlets - Life Cycle


A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet.

1. The servlet is initialized by calling the init() method.


2. The servlet calls service() method to process a client's request.
3. The servlet is terminated by calling the destroy() method.
4. Finally, servlet is garbage collected by the garbage collector of the JVM.

Now let us discuss the life cycle methods in detail.

The init() Method


The init method is called only once. It is called only when the servlet is created, and
not called for any user requests afterwards. So, it is used for one-time initializations,
just as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first
started.

When a user invokes a servlet, a single instance of each servlet gets created, with
each user request resulting in a new thread that is handed off to doGet or doPost as
appropriate. The init() method simply creates or loads some data that will be used
throughout the life of the servlet.

The init method definition looks like this −

public void init() throws ServletException {

// Initialization code...

The service() Method


© Edunet Foundation. All rights reserved .228
The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming from
the client( browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread
and calls service. The service() method checks the HTTP request type (GET, POST,
PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as
appropriate.

Here is the signature of this method −

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

The service () method is called by the container and service method invokes doGet,
doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do
with service() method but you override either doGet() or doPost() depending on what
type of request you receive from the client.

The doGet() and doPost() are most frequently used methods with in each service
request. Here is the signature of these two methods.

The doGet() Method


A GET request results from a normal request for a URL or from an HTML form that
has no METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Servlet code

The doPost() Method

A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException {

// Servlet code

© Edunet Foundation. All rights reserved .229


}

The destroy() Method


The destroy() method is called only once at the end of the life cycle of a servlet. This
method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup
activities.

After the destroy() method is called, the servlet object is marked for garbage collection.
The destroy method definition looks like this −

public void destroy() {

// Finalization code...

Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.

1. First the HTTP requests coming to the server are delegated to the servlet
container.
2. The servlet container loads the servlet before invoking the service() method.
3. Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of the
servlet.

Figure: Servlet architecture diagran


Source: https://www.tutorialspoint.com/servlets/servlets -life-cycle.htm

© Edunet Foundation. All rights reserved .230


Servlets – Examples

Servlets are Java classes which service HTTP requests and implement the
javax.servlet.Servlet interface. Web application developers typically write servlets that
extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet
interface and is specially designed to handle HTTP requests.

Sample Code
Following is the sample source code structure of a servlet example to show Hello
World −

// Import required java libraries

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

// Extend HttpServlet class

public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {

// Do required initialization

message = "Hello World";

public void doGet(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException {

© Edunet Foundation. All rights reserved .231


// Set response content type

response.setContentType("text/html");

// Actual logic goes here.

PrintWriter out = response.getWriter();

out.println("<h1>" + message + "</h1>");

public void destroy() {

// do nothing.

Compiling a Servlet
Let us create a file with name HelloWorld.java with the code shown above. Place this
file at C:\ServletDevel (in Windows) or at /usr/ServletDevel (in Unix). This path location
must be added to CLASSPATH before proceeding further.

Assuming your environment is setup properly, go in ServletDevel directory and


compile HelloWorld.java as follows −

$ javac HelloWorld.java

If the servlet depends on any other libraries, you have to include those JAR fi les on
your CLASSPATH as well. We have included only servlet-api.jar JAR file because we
are not using any other library in Hello World program.

This command line uses the built-in javac compiler that comes with the Sun
Microsystems Java Software Development Kit (JDK). For this command to work
properly, you have to include the location of the Java SDK that you are using in the
PATH environment variable.

If everything goes fine, above compilation would produce HelloWorld.class file in the
same directory. Next section would explain how a compiled servlet would be deployed
in production.

Servlet Deployment

© Edunet Foundation. All rights reserved .232


By default, a servlet application is located at the path <Tomcat-
installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-
installationdirectory>/webapps/ROOT/WEB-INF/classes.

If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class
must be located in WEB-INF/classes/com/myorg/MyServlet.class.

For now, let us copy HelloWorld.class into <Tomcat-


installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries
in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/

<servlet>

<servlet-name>HelloWorld</servlet-name>

<servlet-class>HelloWorld</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloWorld</servlet-name>

<url-pattern>/HelloWorld</url-pattern>

</servlet-mapping>

Above entries to be created inside <web-app>...</web-app> tags available in web.xml


file. There could be various entries in this table already available, but never mind.

We are almost done, now let us start tomcat server using <Tomcat-
installationdirectory>\bin\startup.bat (on Windows) or <Tomcat-
installationdirectory>/bin/startup.sh (on Linux/Solaris etc.) and finally type
http://localhost:8080/HelloWorld in the browser's address box. If everything goes fine,
you would get the following result

© Edunet Foundation. All rights reserved .233


2.4 - Java Server Pages (JSP)
Java Server Pages (JSP) is a server-side programming technology that enables the
creation of dynamic, platform-independent method for building Web-based
applications. JSP have access to the entire family of Java APIs, including the JDBC
API to access enterprise databases.

Why to Learn JSP?


JavaServer Pages often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But JSP offers several advantages in comparison
with the CGI.

• Performance is significantly better because JSP allows embedding Dynamic


Elements in HTML Pages itself instead of having separate CGI files.

© Edunet Foundation. All rights reserved .234


• JSP are always compiled before they are processed by the server unlike
CGI/Perl which requires the server to load an interpreter and the target script
each time the page is requested.
• JavaServer Pages are built on top of the Java Servlets API, so like Servlets,
JSP also has access to all the powerful Enterprise Java APIs, including JDBC,
JNDI, EJB, JAXP, etc.
• JSP pages can be used in combination with servlets that handle the business
logic, the model supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the
most complex and demanding.

Applications of JSP
As mentioned before, JSP is one of the most widely used language over the web. I'm
going to list few of them here:

JSP vs. Active Server Pages (ASP)

The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual
Basic or other MS specific language, so it is more powerful and easier to use. Second,
it is portable to other operating systems and non-Microsoft Web servers.

JSP vs. Pure Servlets

It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.

What is JavaServer Pages?


JavaServer Pages (JSP) is a technology for developing Webpages that supports
dynamic content. This helps developers insert java code in HTML pages by making
use of special JSP tags, most of which start with <% and end with %>.

A JavaServer Pages component is a type of Java servlet th at is designed to fulfill the


role of a user interface for a Java web application. Web developers write JSPs as text
files that combine HTML or XHTML code, XML elements, and embedded JSP actions
and commands.

© Edunet Foundation. All rights reserved .235


Using JSP, you can collect input from users through Webpage forms, present records
from a database or another source, and create Webpages dynamically.

JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing
control between pages, and sharing information between requests, pages etc.

JSP – Architecture
The web server needs a JSP engine, i.e, a container to process JSP pages. The JSP
container is responsible for intercepting requests for JSP pages. This tutorial makes
use of Apache which has built-in JSP container to support JSP pages development.

A JSP container works with the Web server to provide the runtime environment and
other services a JSP needs. It knows how to understand the special elements that are
part of JSPs.

Following diagram shows the position of JSP container and JSP files in a Web
application.

Figure: JSP architecture


Source: https://www.tutorialspoint.com/jsp/jsp_architecture.htm

JSP Processing
The following steps explain how the web server creates the Webpage using JSP −

1. As with a normal page, your browser sends an HTTP request to the web server.
2. The web server recognizes that the HTTP request is for a JSP page and
forwards it to a JSP engine. This is done by using the URL or JSP page which
ends with .jsp instead of .html.
3. The JSP engine loads the JSP page from disk and converts it into a servlet
content. This conversion is very simple in which all template text is converted

© Edunet Foundation. All rights reserved .236


to println( ) statements and all JSP elements are converted to Java code. This
code implements the corresponding dynamic behavior of the page.
4. The JSP engine compiles the servlet into an execu table class and forwards the
original request to a servlet engine.
5. A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML format.
The output is furthur passed on to the web server by the servlet engine inside
an HTTP response.
6. The web server forwards the HTTP response to your browser in terms of static
HTML content.
7. Finally, the web browser handles the dynamically-generated HTML page inside
the HTTP response exactly as if it were a static page.

All the above mentioned steps can be seen in the following diagram −

Figure: JSP Processing


Source: https://www.tutorialspoint.com/jsp/jsp_architecture.htm

Typically, the JSP engine checks to see whether a servlet for a JSP file already exists
and whether the modification date on the JSP is older than the servlet. If the JSP is
older than its generated servlet, the JSP container assumes that the JSP hasn't
changed and that the generated servlet still matches the JSP's contents. This makes
the process more efficient than with the other scripting languages (such as PHP) and
therefore faster.

So in a way, a JSP page is really just another way to write a servlet without having to
be a Java programming wiz. Except for the translation phase, a JSP page is handled
exactly like a regular servlet.

JSP – Lifecycle
A JSP life cycle is defined as the process from its creation till the destruction. This is
similar to a servlet life cycle with an additional step which is required to compile a JSP
into servlet.

© Edunet Foundation. All rights reserved .237


Paths Followed By JSP

The following are the paths followed by a JSP −

1. Compilation
2. Initialization
3. Execution
4. Cleanup
The four major phases of a JSP life cycle are very similar to the Servlet Life Cycle.
The four phases have been described below –

Figure: JSP Processing


Source: https://www.tutorialspoint.com/jsp/jsp_life_cycle.htm

JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it needs
to compile the page. If the page has never been compiled, or if the JSP has been
modified since it was last compiled, the JSP engine compiles the page.

The compilation process involves three steps −

1. Parsing the JSP.


2. Turning the JSP into a servlet.
3. Compiling the servlet.

JSP Initialization

© Edunet Foundation. All rights reserved .238


When a container loads a JSP it invokes the jspInit() method before servicing any
requests. If you need to perform JSP-specific initialization, override the jspInit()
method −

public void jspInit(){

// Initialization code...

Typically, initialization is performed only once and as with the servlet init method, you
generally initialize database connections, open files, and create lookup tables in the
jspInit method.

JSP Execution
This phase of the JSP life cycle represents all interactions with requests until the JSP
is destroyed.

Whenever a browser requests a JSP and the page has been loaded and initialized,
the JSP engine invokes the _jspService() method in the JSP.

The _jspService() method takes an HttpServletRequest and an


HttpServletResponse as its parameters as follows −

void _jspService(HttpServletRequest request, HttpServletResponse response) {

// Service handling code...

The _jspService() method of a JSP is invoked on request basis. This is responsible


for generating the response for that request and this method is also responsible for
generating responses to all seven of the HTTP methods, i.e, GET, POST, DELETE,
etc.

JSP Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being removed
from use by a container.

The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
Override jspDestroy when you need to perform any cleanup, such as releasing
database connections or closing open files.

© Edunet Foundation. All rights reserved .239


The jspDestroy() method has the following form −

public void jspDestroy() {

// Your cleanup code goes here.

JSP – Syntax

Elements of JSP

The elements of JSP have been described below −

The Scriptlet
A scriptlet can contain any number of JAVA language statements, variable or method
declarations, or expressions that are valid in the page scripting language.

Following is the syntax of Scriptlet −

<% code fragment %>

You can write the XML equivalent of the above syntax as follows −

<jsp:scriptlet>

code fragment

</jsp:scriptlet>

Any text, HTML tags, or JSP elements you write must be outside the scriptlet.
Following is the simple and first example for JSP −

<html>

<head><title>Hello World</title></head>

<body>

Hello World!<br/>

<%

out.println("Your IP address is " + request.getRemoteAddr());

%>

© Edunet Foundation. All rights reserved .240


</body>

</html>

NOTE − Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and


your environment is setup.

Let us keep the above code in JSP file hello.jsp and put this file in C:\apache-
tomcat7.0.2\webapps\ROOT directory. Browse through the same using URL
http://localhost:8080/hello.jsp. The above code will generate the following result –

JSP Declarations
A declaration declares one or more variables or methods that you can use in Java
code later in the JSP file. You must declare the variable or method before you use it
in the JSP file.

Following is the syntax for JSP Declarations −

<%! declaration; [ declaration; ]+ ... %>

You can write the XML equivalent of the above syntax as follows −

<jsp:declaration>

code fragment

</jsp:declaration>

Following is an example for JSP Declarations −

<%! int i = 0; %>

<%! int a, b, c; %>

<%! Circle a = new Circle(2.0); %>

© Edunet Foundation. All rights reserved .241


JSP Expression
A JSP expression element contains a scripting language expression that is evaluated,
converted to a String, and inserted where the expression appears in the JSP file.

Because the value of an expression is converted to a String, you can use an


expression within a line of text, whether or not it is tagged with HTML, in a JSP file.

The expression element can contain any expression that is valid according to the Java
Language Specification but you cannot use a semicolon to end an expression.

Following is the syntax of JSP Expression −

<%= expression %>

You can write the XML equivalent of the above syntax as follows −

<jsp:expression>

expression

</jsp:expression>

Following example shows a JSP Expression −

<html>

<head><title>A Comment Test</title></head>

<body>

<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>

</body>

</html>

The above code will generate the following result −

Today's date: 11-Sep-2010 21:24:25

JSP Comments
JSP comment marks text or statements that the JSP container should ignore. A JSP
comment is useful when you want to hide or "comment out", a part of your JSP page.
© Edunet Foundation. All rights reserved .242
Following is the syntax of the JSP comments −

<%-- This is JSP comment --%>

Following example shows the JSP Comments −

<html>

<head><title>A Comment Test</title></head>

<body>

<h2>A Test of Comments</h2>

<%-- This comment will not be visible in the page source --%>

</body>

</html>

There are a small number of special constructs you can use in various cases to insert
comments or characters that would otherwise be treated specially. Here's a summary

S.No. Syntax & Purpose

1 <%-- comment --%>

A JSP comment. Ignored by the JSP engine.

2 <!-- comment -->

An HTML comment. Ignored by the browser.

3 <\%

Represents static <% literal.

4 %\>

Represents static %> literal.

5 \'
© Edunet Foundation. All rights reserved .243
A single quote in an attribute that uses single quotes.

6 \"

A double quote in an attribute that uses double quotes.

JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the
following form −

<%@ directive attribute="value" %>

There are three types of directive tag –

S.No. Directive & Description

1 <%@ page ... %>

Defines page-dependent attributes, such as scripting


language, error page, and buffering requirements.

2 <%@ include ... %>

Includes a file during the translation phase.

3 <%@ taglib ... %>

Declares a tag library, containing custom actions, used in


the page

JSP Actions
JSP actions use constructs in XML syntax to control the behavior of the servlet engine.
You can dynamically insert a file, reuse JavaBeans components, forward the user to
another page, or generate HTML for the Java plugin.

There is only one syntax for the Action element, as it conforms to the XML standard −

<jsp:action_name attribute="value" />

© Edunet Foundation. All rights reserved .244


Action elements are basically predefin ed functions. Following table lists out the
available JSP Actions –

1. jsp:include Includes a file at the time the page is requested.

2. jsp:useBean Finds or instantiates a JavaBean.

3. jsp:setProperty Sets the property of a JavaBean.

4. jsp:getProperty Inserts the property of a JavaBean into the output.

5. jsp:forward Forwards the requester to a new page.

6. jsp:plugin Generates browser-specific code that makes an OBJECT


or EMBED tag for the Java plugin.

7. jsp:element Defines XML elements dynamically.

8. jsp:attribute Defines dynamically-defined XML element's attribute.


9. jsp:body Defines dynamically-defined XML element's body.

10. jsp:text Used to write template text in JSP pages and documents.

JSP Implicit Objects


JSP supports nine automatically defined variables, which are also called implicit
objects. These variables are –

S.No. Object & Description

1 request

This is the HttpServletRequest object associated with the request.

2 response
© Edunet Foundation. All rights reserved .245
This is the HttpServletResponse object associated with the response to
the client.

3 out

This is the PrintWriter object used to send output to the client.

4 session

This is the HttpSession object associated with the request.

5 application

This is the ServletContext object associated with the application


context.

6 config

This is the ServletConfig object associated with the page.

7 pageContext

This encapsulates use of server-specific features like higher


performance JspWriters.

8 page

This is simply a synonym for this, and is used to call the methods
defined by the translated servlet class.

9 Exception

The Exception object allows the exception data to be accessed


by designated JSP.

2.5 - Handling Client-side data


© Edunet Foundation. All rights reserved .246
JSP - Form Processing

When you need to pass some information from your browser to the web server and
ultimately to your backend program. The browser uses two methods to pass this
information to the web server. These methods are the GET Method and the POST
Method.

The Methods in Form Processing


Let us now discuss the methods in Form Processing.

GET method

The GET method sends the encoded user information appended to the page request.
The page and the encoded information are separated by the ? character as follows −

http://www.test.com/hello?key1=value1&key2=value2

The GET method is the default method to pass information from the browser to the
web server and it produces a long string that appears in your browser's Location:box.
It is recommended that the GET method is better not used. if you have password or
other sensitive information to pass to the server.

The GET method has size limitation: only 1024 characters can be in a request string.

This information is passed using QUERY_STRING header and will be accessible


through QUERY_STRING environment variable which can be handled using
getQueryString() and getParameter() methods of request object.

POST method

A generally more reliable method of passing information to a backend program is the


POST method.

This method packages the information in exactly the same way as the GET method,
but instead of sending it as a text string after a ? in the URL it sends it as a separate
message. This message comes to the backend program in the form of the standard
input which you can parse and use for your processing.

JSP handles this type of requests using getParameter() method to read simple
parameters and getInputStream() method to read binary data stream coming from the
client.

© Edunet Foundation. All rights reserved .247


Reading Form Data using JSP
JSP handles form data parsing automatically using the following methods depending
on the situation −

• getParameter() − You call request.getParameter() method to get the value of a


form parameter.

• getParameterValues() − Call this method if the parameter appears more than


once and returns multiple values, for example checkbox.

• getParameterNames() − Call this method if you want a complete list of all


parameters in the current request.

• getInputStream() − Call this method to read binary data stream coming from
the client.

GET Method Example Using URL


The following URL will pass two values to HelloForm program using the GET method.

http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI

Below is the main.jsp JSP program to handle input given by web browser. We are
going to use the getParameter() method which makes it very easy to access the
passed information −

<html>

<head>

<title>Using GET Method to Read Form Data</title>

</head>

<body>

<h1>Using GET Method to Read Form Data</h1>


© Edunet Foundation. All rights reserved .248
<ul>

<li><p><b>First Name:</b>

<%= request.getParameter("first_name")%>

</p></li>

<li><p><b>Last Name:</b>

<%= request.getParameter("last_name")%>

</p></li>

</ul>

</body>

</html>

Now type http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI in your


browser's Location:box.

GET Method Example Using Form


Following is an example that passes two values using the HTML FORM and the submit
button. We are going to use the same JSP main.jsp to handle this input.

<html>

<body>

<form action = "main.jsp" method = "GET">

First Name: <input type = "text" name = "first_name">

<br />

Last Name: <input type = "text" name = "last_name" />

<input type = "submit" value = "Submit" />

</form>

© Edunet Foundation. All rights reserved .249


</body>

</html>

Keep this HTML in a file Hello.htm and put it in <Tomcat-installation-


directory>/webapps/ROOT directory. When you would access
http://localhost:8080/Hello.htm

POST Method Example Using Form


Let us do a little modification in the above JSP to handle both the GET and the POST
method. Below is the main.jsp JSP program to handle the input given by web browser
using the GET or the POST methods.

Infact there is no change in the above JSP because the only way of passing
parameters is changed and no binary data is being passed to the JSP program. File
handling related concepts will be explained in separate chapter where we need to read
the binary data stream.

<html>

<head>

<title>Using GET and POST Method to Read Form Data</title>

</head>

<body>

<center>

<h1>Using POST Method to Read Form Data</h1>

<ul>

<li><p><b>First Name:</b>

<%= request.getParameter("first_name")%>

</p></li>

<li><p><b>Last Name:</b>

<%= request.getParameter("last_name")%>

</p></li>

© Edunet Foundation. All rights reserved .250


</ul>

</body>

</html>

Following is the content of the Hello.htm file −

<html>

<body>

<form action = "main.jsp" method = "POST">

First Name: <input type = "text" name = "first_name">

<br />

Last Name: <input type = "text" name = "last_name" />

<input type = "submit" value = "Submit" />

</form>

</body>

</html>

Let us now keep main.jsp and hello.htm in <Tomcat-


installationdirectory>/webapps/ROOT directory. When you access
http://localhost:8080/Hello.htm

Passing Checkbox Data to JSP Program


Checkboxes are used when more than one option is required to be selected.

Following is an example HTML code, CheckBox.htm, for a form with two checkboxes.

© Edunet Foundation. All rights reserved .251


<html>

<body>

<form action = "main.jsp" method = "POST" target = "_blank">

<input type = "checkbox" name = "maths" checked = "checked" /> Maths

<input type = "checkbox" name = "physics" /> Physics

<input type = "checkbox" name = "chemistry" checked = "checked" />


Chemistry

<input type = "submit" value = "Select Subject" />

</form>

</body>

</html>

Following is main.jsp JSP program to handle the input given by the web browser for
the checkbox button.

<html>

<head>

<title>Reading Checkbox Data</title>

</head>

<body>

<h1>Reading Checkbox Data</h1>

<ul>

<li><p><b>Maths Flag:</b>

<%= request.getParameter("maths")%>

</p></li>

© Edunet Foundation. All rights reserved .252


<li><p><b>Physics Flag:</b>

<%= request.getParameter("physics")%>

</p></li>

<li><p><b>Chemistry Flag:</b>

<%= request.getParameter("chemistry")%>

</p></li>

</ul>

</body>

</html>

Reading All Form Parameters


Following is a generic example which uses getParameterNames() method of
HttpServletRequest to read all the available form parameters. This method returns an
Enumeration that contains the parameter names in an unspecified order.

Once we have an Enumeration, we can loop down the Enumeration in the standard
manner, using the hasMoreElements() method to determine when to stop and using
the nextElement() method to get each parameter name.

<%@ page import = "java.io.*,java.util.*" %>

<html>

<head>

<title>HTTP Header Request Example</title>

</head>

<body>

© Edunet Foundation. All rights reserved .253


<center>

<h2>HTTP Header Request Example</h2>

<table width = "100%" border = "1" align = "center">

<tr bgcolor = "#949494">

<th>Param Name</th>

<th>Param Value(s)</th>

</tr>

<%

Enumeration paramNames = request.getParameterNames();

while(paramNames.hasMoreElements()) {

String paramName = (String)paramNames.nextElement();

out.print("<tr><td>" + paramName + "</td>\n");

String paramValue = request.getHeader(paramName);

out.println("<td> " + paramValue + "</td></tr>\n");

%>

</table>

</center>

</body>

</html>

Following is the content of the Hello.htm −

<html>

<body>

<form action = "main.jsp" method = "POST" target = "_blank">

<input type = "checkbox" name = "maths" checked = "checked" /> Maths


© Edunet Foundation. All rights reserved .254
<input type = "checkbox" name = "physics" /> Physics

<input type = "checkbox" name = "chemistry" checked = "checked" />


Chem

<input type = "submit" value = "Select Subject" />

</form>

</body>

</html>

Now try calling JSP using the above Hello.htm

2.6 - Managing Sessions at Server and Cookies at Client

HTTP is a "stateless" protocol which means each time a client retrieves a Webpage,
the client opens a separate connection to the Web server and the server automatically
does not keep any record of previous client request.

Maintaining Session Between Web Client And Server


Let us now discuss a few options to maintain the session between the Web Client and
the Web Server −

Cookies
A webserver can assign a unique session ID as a cookie to each web client and for
subsequent requests from the client they can be recognized using the received cookie.

© Edunet Foundation. All rights reserved .255


This may not be an effective way as the browser at times does not support a cookie.
It is not recommended to use this procedure to maintain the sessions.

Hidden Form Fields


A web server can send a hidden HTML form field along with a unique session ID as
follows −

<input type = "hidden" name = "sessionid" value = "12345">

This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or the POST data. Each time the web browser sends
the request back, the session_id value can be used to keep the track of different web
browsers.

This can be an effective way of keeping track of the session but clicking on a regular
(<A HREF...>) hypertext link does not result in a form submission, so hidden form
fields also cannot support general session tracking.

URL Rewriting
You can append some extra data at the end of each URL. This data identifies the
session; the server can associate that session identifier with the data it has stored
about that session.

For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session


identifier is attached as sessionid = 12345 which can be accessed at the web server
to identify the client.

URL rewriting is a better way to maintain sessions and works for the browsers when
they don't support cookies. The drawback here is that you will have to generate every
URL dynamically to assign a session ID though page is a simple static HTML page.

The session Object


Apart from the above mentioned options, JSP makes use of the servlet provided
HttpSession Interface. This interface provides a way to identify a user across.

• a one page request or


• visit to a website or
• store information about that user
By default, JSPs have session tracking enabled and a new HttpSession object is
instantiated for each new client automatically. Disabling session tracking requires
explicitly turning it off by setting the page directive session attribute to false as follows

© Edunet Foundation. All rights reserved .256
<%@ page session = "false" %>

The JSP engine exposes the HttpSession object to the JSP author through the implicit
session object. Since session object is already provided to the JSP programmer, the
programmer can immediately begin storing and retrieving data from the object without
any initialization or getSession().

Session Tracking Example

This example describes how to use the HttpSession object to find out the creation time
and the last-accessed time for a session. We would associate a new session with the
request if one does not already exist.

<%@ page import = "java.io.*,java.util.*" %>

<%

// Get session creation time.

Date createTime = new Date(session.getCreationTime());

// Get last access time of this Webpage.

Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";

Integer visitCount = new Integer(0);

String visitCountKey = new String("visitCount");

String userIDKey = new String("userID");

String userID = new String("ABCD");

// Check if this is new comer on your Webpage.

if (session.isNew() ){

title = "Welcome to my website";

session.setAttribute(userIDKey, userID);

© Edunet Foundation. All rights reserved .257


session.setAttribute(visitCountKey, visitCount);

visitCount = (Integer)session.getAttribute(visitCountKey);

visitCount = visitCount + 1;

userID = (String)session.getAttribute(userIDKey);

session.setAttribute(visitCountKey, visitCount);

%>

<html>

<head>

<title>Session Tracking</title>

</head>

<body>

<center>

<h1>Session Tracking</h1>

</center>

<table border = "1" align = "center">

<tr bgcolor = "#949494">

<th>Session info</th>

<th>Value</th>

</tr>

<tr>

<td>id</td>

<td><% out.print( session.getId()); %></td>

</tr>

<tr>
© Edunet Foundation. All rights reserved .258
<td>Creation Time</td>

<td><% out.print(createTime); %></td>

</tr>

<tr>

<td>Time of Last Access</td>

<td><% out.print(lastAccessTime); %></td>

</tr>

<tr>

<td>User ID</td>

<td><% out.print(userID); %></td>

</tr>

<tr>

<td>Number of visits</td>

<td><% out.print(visitCount); %></td>

</tr>

</table>

</body>

</html>

Now put the above code in main.jsp and try to access http://localhost:8080/main.jsp.
Once you run the URL, you will receive the following result –

© Edunet Foundation. All rights reserved .259


Now try to run the same JSP for the second time, you will receive the following result.

Deleting Session Data


When you are done with a user's session data, you have several options −

• Remove a particular attribute − You can call the public void


removeAttribute(String name) method to delete the value associated with the a
particular key.
• Delete the whole session − You can call the public void invalidate() method
to discard an entire session.
• Setting Session timeout − You can call the public void
setMaxInactiveInterval(int interval) method to set the timeout for a session
individually.

© Edunet Foundation. All rights reserved .260


• Log the user out − The servers that support servlets 2.4, you can call logout
to log the client out of the Web server and invalidate all sessions belonging to
all the users.
• web.xml Configuration − If you are using Tomcat, apart from the above
mentioned methods, you can configure the session time out in web.xml file as
follows.

<session-config>

<session-timeout>15</session-timeout>

</session-config>

The timeout is expressed as minutes, and overrides the default timeout which is 30
minutes in Tomcat.

The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that
session in seconds. So if your session is configured in web.xml for 15 minutes,
getMaxInactiveInterval( ) returns 900.

JSP - Cookies Handling


Cookies are text files stored on the client computer and they are kept for various
information tracking purposes. JSP transparently supports HTTP cookies using
underlying servlet technology.

There are three steps involved in identifying and returning users −

1. Server script sends a set of cookies to the browser. For example, name, age,
or identification number, etc.
2. Browser stores this information on the local machine for future use.
3. When the next time the browser sends any request to the web server then it
sends those cookies information to the server and server uses that information
to identify the user or may be for some other purpose as well.

The Anatomy of a Cookie


Cookies are usually set in an HTTP header (although JavaScript can also set a cookie
directly on a browser). A JSP that sets a cookie might send headers that look
something like this −

HTTP/1.1 200 OK

© Edunet Foundation. All rights reserved .261


Date: Fri, 04 Feb 2000 21:03:38 GMT

Server: Apache/1.3.9 (UNIX) PHP/4.0b3

Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT;

path = /; domain = tutorialspoint.com

Connection: close

Content-Type: text/html

As you can see, the Set-Cookie header contains a name value pair, a GMT date, a
path and a domain. The name and value will be URL encoded. The expires field is an
instruction to the browser to "forget" the cookie after the given time and date.

If the browser is configured to store cookies, it will then keep this information until the
expiry date. If the user points the browser at any page that matches the path and
domain of the cookie, it will resend the cookie to the server. The browser's headers
might look something like this −

GET / HTTP/1.0

Connection: Keep-Alive

User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)

Host: zink.demon.co.uk:1126

Accept: image/gif, */*

Accept-Encoding: gzip

Accept-Language: en

Accept-Charset: iso-8859-1,*,utf-8

Cookie: name = xyz

A JSP script will then have access to the cookies through the request method
request.getCookies() which returns an array of Cookie objects.

Setting Cookies with JSP


Setting cookies with JSP involves three steps −

© Edunet Foundation. All rights reserved .262


Step 1: Creating a Cookie object

You call the Cookie constructor with a cookie name and a cookie value, both of which
are strings.

Cookie cookie = new Cookie("key","value");

Neither the name nor the value should contain white space or any of the following
characters −

[]()=,"/?@:;

Step 2: Setting the maximum age

You use setMaxAge to specify how long (in seconds) the cookie should be valid. The
following code will set up a cookie for 24 hours.

cookie.setMaxAge(60*60*24);

Step 3: Sending the Cookie into the HTTP response headers

You use response.addCookie to add cookies in the HTTP response header as follows

response.addCookie(cookie);

Example

Let us modify our Form Example to set the cookies for the first and the last name.

<%

// Create cookies for first and last names.

Cookie firstName = new Cookie("first_name",


request.getParameter("first_name"));

Cookie lastName = new Cookie("last_name",


request.getParameter("last_name"));

// Set expiry date after 24 Hrs for both the cookies.


© Edunet Foundation. All rights reserved .263
firstName.setMaxAge(60*60*24);

lastName.setMaxAge(60*60*24);

// Add both the cookies in the response header.

response.addCookie( firstName );

response.addCookie( lastName );

%>

<html>

<head>

<title>Setting Cookies</title>

</head>

<body>

<center>

<h1>Setting Cookies</h1>

</center>

<ul>

<li><p><b>First Name:</b>

<%= request.getParameter("first_name")%>

</p></li>

<li><p><b>Last Name:</b>

<%= request.getParameter("last_name")%>

</p></li>

</ul>

</body>

</html>
© Edunet Foundation. All rights reserved .264
Let us put the above code in main.jsp file and use it in the following HTML page −

<html>

<body>

<form action = "main.jsp" method = "GET">

First Name: <input type = "text" name = "first_name">

<br />

Last Name: <input type = "text" name = "last_name" />

<input type = "submit" value = "Submit" />

</form>

</body>

</html>

Keep the above HTML content in a file hello.jsp and put hello.jsp and main.jsp in
<Tomcat-installation-directory>/webapps/ROOT directory. When you will access
http://localhost:8080/hello.jsp

Reading Cookies with JSP


To read cookies, you need to create an array of javax.servlet.http.Cookie objects by
calling the getCookies( ) method of HttpServletRequest. Then cycle through the array,
and use getName() and getValue() methods to access each cookie and associated
value.

Example

Let us now read cookies that were set in the previous example −

<html>

<head>

<title>Reading Cookies</title>

© Edunet Foundation. All rights reserved .265


</head>

<body>

<center>

<h1>Reading Cookies</h1>

</center>

<%

Cookie cookie = null;

Cookie[] cookies = null;

// Get an array of Cookies associated with the this domain

cookies = request.getCookies();

if( cookies != null ) {

out.println("<h2> Found Cookies Name and Value</h2>");

for (int i = 0; i < cookies.length; i++) {

cookie = cookies[i];

out.print("Name : " + cookie.getName( ) + ", ");

out.print("Value: " + cookie.getValue( )+" <br/>");

} else {

out.println("<h2>No cookies founds</h2>");

%>

</body>

</html>
© Edunet Foundation. All rights reserved .266
Let us now put the above code in main.jsp file and try to access it. If you set the
first_name cookie as "John" and the last_name cookie as "Player" then running
http://localhost:8080/main.jsp will display the following result −

Delete Cookies with JSP


To delete cookies is very simple. If you want to delete a cookie, then you simply need
to follow these three steps −

1. Read an already existing cookie and store it in Cookie object.


2. Set cookie age as zero using the setMaxAge() method to delete an existing
cookie.
3. Add this cookie back into the response header.
Example

Following example will show you how to delete an existing cookie named "first_name"
and when you run main.jsp JSP next time, it will return null value for first_name.

<html>

<head>

<title>Reading Cookies</title>

</head>

<body>

<center>
© Edunet Foundation. All rights reserved .267
<h1>Reading Cookies</h1>

</center>

<%

Cookie cookie = null;

Cookie[] cookies = null;

// Get an array of Cookies associated with the this domain

cookies = request.getCookies();

if( cookies != null ) {

out.println("<h2> Found Cookies Name and Value</h2>");

for (int i = 0; i < cookies.length; i++) {

cookie = cookies[i];

if((cookie.getName( )).compareTo("first_name") == 0 ) {

cookie.setMaxAge(0);

response.addCookie(cookie);

out.print("Deleted cookie: " +

cookie.getName( ) + "<br/>");

out.print("Name : " + cookie.getName( ) + ", ");

out.print("Value: " + cookie.getValue( )+" <br/>");

} else {

out.println(

"<h2>No cookies founds</h2>");

}
© Edunet Foundation. All rights reserved .268
%>

</body>

</html>

Let us now put the above code in the main.jsp file and try to access it. It will display
the following result −

Now run http://localhost:8080/main.jsp once again and it should display only one
cookie as follows –

You can delete your cookies in the Internet Explorer manually. Start at the Tools menu
and select the Internet Options. To delete all cookies, click the Delete Cookies button.

© Edunet Foundation. All rights reserved .269


2.7 - JSP - Expression Language (EL)

JSP Expression Language (EL) makes it possible to easily access application data
stored in JavaBeans components. JSP EL allows you to create expressions both (a)
arithmetic and (b) logical. Within a JSP EL expression, you can use integers, floating
point numbers, strings, the built-in constants true and false for boolean values, and
null.

Simple Syntax

Typically, when you specify an attribute value in a JSP tag, you simply use a stri ng.
For example −

<jsp:setProperty name = "box" property = "perimeter" value = "100"/>

JSP EL allows you to specify an expression for any of these attribute values. A simple
syntax for JSP EL is as follows −

${expr}

Here expr specifies the expression itself. The most common operators in JSP EL are
. and []. These two operators allow you to access various attributes of Java Beans and
built-in JSP objects.

For example, the above syntax <jsp:setProperty> tag can be written with an
expression like −

<jsp:setProperty name = "box" property = "perimeter"

value = "${2*box.width+2*box.height}"/>

When the JSP compiler sees the ${} form in an attribute, it generates code to evaluate
the expression and substitues the value of expresson.

© Edunet Foundation. All rights reserved .270


You can also use the JSP EL expressions within template text for a tag. For example,
the <jsp:text> tag simply inserts its content within the body of a JSP. The following
<jsp:text> declaration inserts <h1>Hello JSP!</h1> into the JSP output −

<jsp:text>

<h1>Hello JSP!</h1>

</jsp:text>

You can now include a JSP EL expression in the body of a <jsp:text> tag (or any other
tag) with the same ${} syntax you use for attributes. For example −

<jsp:text>

Box Perimeter is: ${2*box.width + 2*box.height}

</jsp:text>

EL expressions can use parentheses to group subexpressions. For example, ${(1 +


2) * 3} equals 9, but ${1 + (2 * 3)} equals 7.

To deactivate the evaluation of EL expressions, we specify the isELIgnored attribute


of the page directive as below −

<%@ page isELIgnored = "true|false" %>

The valid values of this attribute are true and false. If it is true, EL expressions are
ignored when they appear in static text or tag attributes. If it is false, EL expressions
are evaluated by the container.

Functions in JSP EL
JSP EL allows you to use functions in expressions as well. These functions must be
defined in the custom tag libraries. A function usage has the following syntax −

${ns:func(param1, param2, ...)}

Where ns is the namespace of the function, func is the name of the function and
param1 is the first parameter value. For example, the function fn:length, which is part
of the JSTL library. This function can be used as follows to get the length of a string.

${fn:length("Get my length")}

© Edunet Foundation. All rights reserved .271


To use a function from any tag library (standard or custom), you must install that library
on your server and must include the library in your JSP using the <taglib> directive.

The pageContext Object


The pageContext object gives you access to the pageContext JSP object. Through
the pageContext object, you can access the request object. For example, to access
the incoming query string for a request, you can use the following expression −

${pageContext.request.queryString}

The Scope Objects


The pageScope, requestScope, sessionScope, and applicationScope variables
provide access to variables stored at each scope level.

For example, if you need to explicitly access the box variable in the application scope,
you can access it through the applicationScope variable as applicationScope.box.

The param and paramValues Objects


The param and paramValues objects give you access to the parameter values
normally available through the request.getParameter and
request.getParameterValues methods.

For example, to access a parameter named order, use the expression ${param.order}
or ${param["order"]}.

Following is the example to access a request parameter named username −

<%@ page import = "java.io.*,java.util.*" %>

<%String title = "Accessing Request Param";%>

<html>

<head>

<title><% out.print(title); %></title>

© Edunet Foundation. All rights reserved .272


</head>

<body>

<center>

<h1><% out.print(title); %></h1>

</center>

<div align = "center">

<p>${param["username"]}</p>

</div>

</body>

</html>

The param object returns single string values, whereas the paramValues object
returns string arrays.

header and headerValues Objects


The header and headerValues objects give you access to the header values normally
available through the request.getHeader and the request.getHeaders methods.

For example, to access a header named user-agent, use the expression


${header.user-agent} or ${header["user-agent"]}.

Following is the example to access a header parameter named user-agent −

<%@ page import = "java.io.*,java.util.*" %>

<%String title = "User Agent Example";%>

<html>

<head>

<title><% out.print(title); %></title>

</head>

© Edunet Foundation. All rights reserved .273


<body>

<center>

<h1><% out.print(title); %></h1>

</center>

<div align = "center">

<p>${header["user-agent"]}</p>

</div>

</body>

</html>

The output will somewhat be like the following –

The header object returns single string values, whereas the headerValues object
returns string arrays.

© Edunet Foundation. All rights reserved .274


2.8 - JSP - Standard Tag Library (JSTL)

The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags
which encapsulates the core functionality common to many JSP applications.

JSTL has support for common, structural tasks such as iteration and conditionals, tags
for manipulating XML documents, internationalization tags, and SQL tags. It also
provides a framework for integrating the existing custom tags with the JSTL tags.

Install JSTL Library


To begin working with JSP tages you need to first install the JSTL library. If you are
using the Apache Tomcat container, then follow these two steps −

Step 1 − Download the binary distribution from Apache Standard Taglib and unpack
the compressed file.

Step 2 − To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy
the JAR files in the distribution's 'lib' directory to your application's
webapps\ROOT\WEB-INF\lib directory.

To use any of the libraries, you must include a <taglib> directive at the top of each
JSP that uses the library.

Classification of The JSTL Tags


The JSTL tags can be classified, according to their functions, into the following JSTL
tag library groups that can be used when creating a JSP page −

• Core Tags
• Formatting tags
• SQL tags
• XML tags
• JSTL Functions

© Edunet Foundation. All rights reserved .275


Core Tags
The core group of tags are the most commonly used JSTL tags. Following is the syntax
to include the JSTL Core library in your JSP −

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>

Formatting Tags
The JSTL formatting tags are used to format and display text, the date, the time, and
numbers for internationalized Websites. Following is the syntax to include Formatting
library in your JSP −

<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>

SQL Tags
The JSTL SQL tag library provides tags for interacting with relational databases
(RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server.

Following is the syntax to include JSTL SQL library in your JSP −

<%@ taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql" %>

XML tags
The JSTL XML tags provide a JSP-centric way of creating and manipulating the XML
documents. Following is the syntax to include the JSTL XML library in your JSP.

The JSTL XML tag library has custom tags for interacting with the XML data. This
includes parsing the XML, transforming the XML data, and the flow control based on
the XPath expressions.

<%@ taglib prefix = "x"

uri = "http://java.sun.com/jsp/jstl/xml" %>

Before you proceed with the examples, you will need to copy the following two XML
and XPath related libraries into your <Tomcat Installation Directory>\lib −

• XercesImpl.jar − Download it from https://www.apache.org/dist/xerces/j/


• xalan.jar − Download it from https://xml.apache.org/xalan-j/index.html
© Edunet Foundation. All rights reserved .276
JSTL Functions
JSTL includes a number of standard functions, most of which are common string
manipulation functions. Following is the syntax to include JSTL Functions library in
your JSP −

<%@ taglib prefix = "fn"

uri = "http://java.sun.com/jsp/jstl/functions" %>

© Edunet Foundation. All rights reserved .277


Chapter 3 – Connecting End-
to-End
Learning Outcomes:

• Introduction to relational databases- MySQL

• Managing data in databases using JSP & Servlet

3.1 Introduction to relational databases- MySQL

Introducing relational databases, need for database, persistent


storage benefits, MySQL basics, commands
Introducing relational database

What is a database?

A database is a collection of related information. Modern databases contain millions


or even trillions of pieces of information. Databases provide convenience for easy
storage and access to data.

The word ‘datum’ means a single piece of information. The word data is the plural form
of datum. One of the most important aspects of a database is to easily manage and
operate large amounts of data.

What is a Database Management System?

A Relational Database Management System is a tabular based collection of programs


and capabilities that provides an interface between users and applications and the
database, offering a systematic way to create, update, delete, manage, and retrieve
data. Most relational database management systems use the SQL programming
language to access the database and many follow the ACID (Atomicity, Consistency,
Isolation, Durability) properties of the database:

• Atomicity: If any statement in the transaction fails, the entire transaction fails
and the database is left unchanged.
• Consistency: The transaction must meet all protocols defined by the system --
no partially completed transactions.
© Edunet Foundation. All rights reserved .278
• Isolation: No transaction has access to any other transaction that is unfinished.
Each transaction is independent.
• Durability: Once a transaction has been committed, it will remain committed
through the use of transaction logs and backups.
What is a relational database?

A database that follows the relational model and stores data in a tabular format is
known as a relational database. The database has rows and columns and a unique
key for each data point.

Relational databases are very common and have high usage. Pretty much everything
you have entered online in a form or something like that usually gets stored in a
relational database.

Examples of relational databases: Microsoft SQL Server, Oracle, MYSQL.

A relational database is one that stores data in tables. The relationship between each
data point is clear and searching through those relationships is relatively easy. The
relationship between tables and field types is called a schema. For relational
databases, the schema must be clearly defined. Let’s look at an example:

Image: Relational Database


Reference: https://insightsoftware.com/blog/whats-the-difference-relational-vs-non-relational-databases/

Advantages of a Relational Database

The main advantage of a relational database is its formally described, tabular


structure, from which data can be easily stored, categorized, queried, and filtered

© Edunet Foundation. All rights reserved .279


without needing to reorganize database tables. Further benefits of relational
databases include:

• Scalability: New data may be added independent of existing records.


• Simplicity: Complex queries are easy for users to perform with SQL.
• Data Accuracy: Normalization procedures eliminate design anomalies.
• Data Integrity: Strong data typing and validity checks ensure accuracy and
consistency.
• Security: Data in tables within a RDBMS can limit access to specific users.
• Collaboration: Multiple users can access the same database concurrently.

Why uses a database?

• Databases can store very large numbers of records efficiently (they take up little
space).
• It is very quick and easy to find information.
• It is easy to add new data and to edit or delete old data.
• Data can be searched easily, eg 'find all Ford cars'.
• Data can be sorted easily, for example into 'date first registered' order.
• Data can be imported into other applications, for example a mail-merge letter
to a customer saying that an MOT test is due.
• More than one person can access the same database at the same time - multi-
access.
• Security may be better than in paper files

Why do we need a Database?

A database is a collection of data, usually stored in electronic form. A database is


typically designed so that it is easy to store and access information.

A good database is crucial to any company or organisation. This is because the


database stores all the pertinent details about the company such as employee records,
transactional records, salary details etc.

© Edunet Foundation. All rights reserved .280


Image: Why do we need a Database
Reference: https://www.tutorialspoint.com/Why-do-we-need-a-Database

The various reasons a database is important are −

Manages large amounts of data


A database stores and manages a large amount of data on a daily basis. This would
not be possible using any other tool such as a spreadsheet as they would simply not
work.

Accurate
A database is pretty accurate as it has all sorts of build in constraints, checks etc.
This means that the information available in a database is guaranteed to be correct
in most cases.

Easy to update data


In a database, it is easy to update data using various Data Manipulation languages
(DML) available. One of these languages is SQL.

Security of data
Databases have various methods to ensure security of data. There are user logins
required before accessing a database and various access specifiers. These allow
only authorised users to access the database.

Data integrity
This is ensured in databases by using various constraints for data. Data integrity in
databases makes sure that the data is accurate and consistent in a database.

Easy to research data


It is very easy to access and research data in a database. This is done using Data
Query Languages (DQL) which allow searching of any data in the database and
performing computations on it.

Persistent storage benefits


What is Persistent Storage?
© Edunet Foundation. All rights reserved .281
Persistent Storage known as non -volatile storage; persistence storage refers to any
of the data storage devices that can retain data even after there is no power supply
to that device.

Among some of the common types of persistent storage are magnetic media, such
as hard disk drives, tapes and several forms of optical media such as DVD.
Persistent storage structures typically can be in the form of storage for files, blocks
or objects.

Benefits of Persistent Storage

Simplicity:

Persistent storage helps developers provision their storage, without necessarily


needing any expertise as storage experts. It simply allows them to provision volumes
for both on-premise/ public cloud services.

Security:

When it comes to the security and encryption aspects of storage solutions, persistent
storage scores high. It fulfils the security requirements of most enterprises in terms
of volume-level encryption, self-encrypting disks, and key management, among
others to protect them against any kind of data loss and security breaches.

Flexibility:

Persistent storage offers you great flexibility over traditional storage and lets you use
the same software across different virtual machines, clouds and containers. Further,
developers also enjoy the flexibility to choose the storage interfaces for their
workload, including file, block or object storage. It also gives developers the ability to
deliver data services with one system, irrespective of protocol, thus boosting
productivity, offering more freedom, and leading to more effective application
development.

Portability:

Today’s cloud-native world requires organizations to adopt a hybrid cloud approach


to be able to combine the benefits of public and on -premises clouds. Persistent
storage makes it easy to migrate your stateless applications across multiple clouds
and migrate your data from one cloud to other clouds.

Efficiency:

© Edunet Foundation. All rights reserved .282


Persistent storage makes application development much more efficient. It eliminates
the need to rewrite applications when you want to port them from one cloud provider
to another and you can simply move applications without expensive or time-
consuming rewrites whenever you want.

Cost-effectiveness:

With persistent storage, you only have to pay for the storage and compute you use.
It scales on-demand with no disruptions, growing and shrinking automatically as you
add and remove files.

MySQL
What is MySQL?
MySQL is world’s most popular database that is open source and free. MySQL was
acquired by Oracle as a part of Sun Microsystems acquisition in 2009.

MySQL is one of the most popular database management systems. It is an important


pillar of LAMP application software. Further, it is cross-platform so works well with all
operating systems including Windows, Linux, macOS, IRIX, and others. In addition,
MySQL is a database management system used to manage relational databases.
MySQL DBMS is owned by Oracle but still, it is open -source software and you can use
it without paying anything. Moreover, you can change its source code according to
your requirements and needs. There is comprehensive documentation available
regarding development and deployment.

Why MySQL is so popular?

MySQL is one of the most popular open -source DBMS and the following are the
reasons behind it:

• It is completely free and open-source database management system.


• MySQL database is very user friendly mostly used with PHP, the most popular
language for web development.
• It is a very powerful DBMS that offers a large set of functionalities which is only
offered by most expensive DBMS.
• MySQL is cross platform and works with almost all operating systems.
• It is customizable because it is an open -source database. Developers can edit
code according to their needs.
• It is quicker than most of other open-source databases and works well and fast
even with the large data set.
• It is compatible with many languages like PHP, PERL, C, C++, JAVA, etc.
© Edunet Foundation. All rights reserved .283
• There are very good stats on its Github repo.

Features of MySQL

• Speed: Of course, the speed at which a server-side program runs depends


primarily on the server hardware. Given that the server hardware is optimal,
MySQL runs very fast. It supports clustered servers for demanding applications.
• Ease of use: MySQL is a high-performance, relatively simple database system.
From the beginning, MySQL has typically been configured, monitored, and
managed from the command line. However, several MySQL graphical
interfaces are available as described below:
o MySQL Administrator: This tool makes it possible for administrators to
set up, evaluate, and tune their MySQL database server. This is intended
as a replacement for mysqladmin.
o MySQL Query Browser: Provides database developers and operators
with a graphical database operation interface. It is especially useful for
seeing multiple query plans and result sets in a single user interface.
o Configuration Wizard: Administrators can choose from a predefined list
of optimal settings, or create their own.
o MySQL System Tray: Provides Windows-based administrators a single
view of their MySQL instance, including the ability to start and stop their
database servers.
• Cost: MySQL is available free of cost. MySQL is an "Open Source" database.
MySQL is part of LAMP (Linux, Apache, MySQL, PHP / Perl / Python)
environment, a fast-growing open-source enterprise software stack. More and
more companies are using LAMP as an alternative to expensive proprietary
software stacks because of its lower cost, reliability, and documentation.
• Query Language Support: MySQL understands standards-based SQL
(Structured Query Language).
• Capability: Many clients can connect to the server at the same time. Clients
can use multiple databases simultaneously. You can access MySQL using
several interfaces such as command-line clients, Web browsers.
• Connectivity and security: MySQL are fully networked, and database can be
accessed from anywhere on the Internet, so you can share your data with
anyone, anywhere. The connectivity could be achieved with Windows programs
by using ODBC drivers. By using the ODBC connector to MySQL, any ODBC-
aware client application (for example, Microsoft Office, report writers, Visual
Basic) can connect to MySQL.
• Portability: MySQL runs on many varieties of UNIX, as well as on other non-
UNIX systems, such as Windows and OS/2. MySQL runs on hardware from
home PCs to high-end server. MySQL can be installed on Windows XP,
Windows Server 2003, Red Hat Fedora Linux, Debian Linux, and others.

© Edunet Foundation. All rights reserved .284


Benefits of MySQL

• Flexible and easy to use: Modify source code according to your own needs
and expectations. The installation process is relatively simple, and doesn’t take
much time.
• High performance: Even if you are storing massive amounts of big e-
Commerce data or doing heavy business intelligence activities, MySQL can
assist you smoothly with optimum speed.
• A mature DBMS: Developers have been using MySQL for years, which means
that there are abundant resources for them. It has evolved over the years and
has very little margin for any kind of bugs.
• Secure database: Data security is the basic need of every web app. With its
Access Privilege System and User Account Management, MySQL sets the
security bar high. It offers both Host-based verification and password encryption
as well.
• Free installation: The community edition of MySQL is free to download. There
are some prepaid options but if your company is too small to pay for them, the
free-to-download model is the most suitable for a fresh start.
• Simple syntax: MySQL’s structure very simple and plain. That’s why
developers even consider MySQL a database with a human -like language.
MySQL is easy to use, most of the tasks can be executed right in the command
line, reducing development steps.

Cons of MySQL

• Owned by Oracle: MySQL used to be open source but now its not completely
open source. It’s mostly now under Oracle’s license which limits the MySQL
community in terms of improving the DBMS.
• Scalability issues: MySQL is not as efficiently scalable as the NoSQL
database. It will need more engineering effort to make it scalable. So, if you
have apps for which your database will increase substantially, you should
choose another DBMS option.
• Limited support for SQL standards: MySQL doesn’t completely compliance
with SQL standards. It does not provide support for some standard SQL
features as well as it has some extensions and features that don’t match the
Structured Query Language standards.

MySQL Commands
Categories of SQL statements
SQL language is divided into four types of primary language statements: DML, DDL,
DCL and TCL. Using these statements, we can define the structure of a database by

© Edunet Foundation. All rights reserved .285


creating and altering database objects and we can manipulate data in a table
through updates or deletions. We also can control which user can read/write data or
manage transactions to create a single unit of work.

The four main categories of SQL statements are as follows −

DML (Data Manipulation Language)

DML statements affect records in a table. These are basic operations we perform on
data such as selecting a few records from a table, inserting new records, deleting
unnecessary records, and updating/modifying existing records.

DML statements include the following −

• SELECT – select records from a table


• INSERT – insert new records
• UPDATE – update/Modify existing records
• DELETE – delete existing records
DDL (Data Definition Language)

DDL statements are used to alter/modify a database or table structure and schema.
These statements handle the design and storage of database objects.

• CREATE – create a new Table, database, schema


• ALTER – alter existing table, column description
• DROP – delete existing objects from database

DCL (Data Control Language)

DCL statements control the level of access that users have on database objects.

• GRANT – allows users to read/write on certain database objects


• REVOKE – keeps users from read/write permission on database objects

TCL (Transaction Control Language)

TCL statements allow you to control and manage transactions to maintain the
integrity of data within SQL statements.

• BEGIN Transaction – opens a transaction


• COMMIT Transaction – commits a transaction
• ROLLBACK Transaction – ROLLBACK a transaction in case of any error

© Edunet Foundation. All rights reserved .286


SQL Commands

DDL Commands - Data Definition Language

Data Definition Language or DDL commands in SQL are used for changing the
structure of a table. In other words, DDL commands are capable of creating,
deleting, and modifying data.

All DDL commands are auto-committed which means that changes made by them
are automatically saved in the database. Following are the various DDL commands:

ALTER

Used for altering the structure of a database. Typically, the ALTER command is used
either to add a new attribute or modify the characteristics of some existing attribute.
For adding new columns to the table:
General Syntax

ALTER TABLE table_name ADD (column_name1 data_type (size), column_name2


data_type (size),….., column_nameN data_type (size));

Example

ALTER TABLE Student ADD (Address varchar2(20));

ALTER TABLE Student ADD (Age number(2), Marks number(3));

For modifying an existing column in the table:


General Syntax:

ALTER TABLE table_name MODIFY (column_name new_data_type(new_size));

Example:

ALTER TABLE Student MODIFY (Name varchar2(20));

The ALTER command can also be used for dropping a column from the table:
General Syntax:

© Edunet Foundation. All rights reserved .287


ALTER TABLE table_name DROP COLUMN column_name;

Example:

ALTER TABLE Student DROP COLUMN Age;

</pre.

Note: - It is not possible to do the following using the ALTER command:

• Change the name of a column


• Change the name of a table
• Decrease the size of a column
CREATE

Used for creating a new table in the database. General Syntax:

CREATE TABLE table_name (column_name1 data_type(size), column_name2 data


_type(size),…., column_nameN data_type(size));

Example:

CREATE TABLE Employee(Name varchar2(20), D.O.B. date, Salary number(6);

DROP

Used for deleting an entire table from the database and all the data stored in it.
General Syntax:

DROP TABLE table_name;

Example:

DROP TABLE Student;

RENAME

Used for renaming a table.


General Syntax:

© Edunet Foundation. All rights reserved .288


RENAME old_table_name TO new_table_name

Example:

RENAME Student TO Student_Details

TRUNCATE

Used for deleting all rows from a table and free the space containing the table.
General Syntax:

TRUNCATE TABLE table_name;

Example:

TRUNCATE TABLE Student;

DML Commands - Data Manipulation Language

The DML or Data Manipulation Language commands help in modifying a relational


database. These commands are not auto-committed, which simply means that all
changes made to the database using DML commands aren’t automatically saved.
It is possible to rollback DML commands. Various DML commands are:
DELETE

Used for removing one or more rows from a table.


General Syntax:
DELETE FROM table_name; (deletes all rows from a table)
DELETE FROM table_name WHERE some_condition; (delete only the row(s) where
the condition is true)
Example:

DELETE FROM Student;

DELETE FROM Student WHERE Name = “Akhil”;

INSERT

Used for inserting data into the row of a table.

© Edunet Foundation. All rights reserved .289


General Syntax:

INSERT INTO table_name (column_name1, column_name2,….,column_nameN) VA


LUES (value1, value2,….,valueN);

OR

INSERT INTO table_name VALUES (value1, value2,….,valueN);

Example:

INSERT INTO Student (Name, Age) VALUES (“Vijay”, “25”);

Insert command can also be used for inserting data into a table from another table.
General Syntax:

INSERT INTO table_name1 SELECT column_name1, column_name2,….,column_n


ameN FROM table_name2;

Example:

INSERT INTO Student SELECT Id, Stream FROM Student_Subject_Details

UPDATE

Used to modify or update the value of a column in a table. It can update all rows or
some selective rows in the table.
General Syntax:

UPDATE table_name SET column_name1 = value1, column_name2 = value2,….,co


lumn_nameN = valueN (for updating all rows)

UPDATE table_name SET column_name1 = value1, column_name2 = value2,….,co


lumn_nameN = valueN [WHERE CONDITION] (for updating particular rows)

Example:

UPDATE Student SET Name = “Akhil” WHERE Id = 22;

DCL Commands - Data Control Language

© Edunet Foundation. All rights reserved .290


GRANT

Used for granting user access privileges to a database.


General Syntax:

GRANT object_privileges ON table_name TO user_name1, user_name2,….,user_n


ameN;

GRANT object_privileges ON table_name TO user_name1, user_name2,….,user_n


ameN WITH GRANT OPTION; (allows the grantee to grant user access privileges
to others)

Example:

GRANT SELECT, UPDATE ON Student TO Akhil Bhadwal

This will allow the user to run only SELECT and UPDATE operations on the Student
table.

GRANT ALL ON Student TO Akhil Bhadwal WITH GRANT OPTION

Allows the user to run all commands on the table as well as grant access privileges
to other users.
REVOKE

Used for taking back permission given to a user.


General Syntax:

REVOKE object_privileges ON table_name FROM user1, user2,… userN;

Example:

REVOKE UPDATE ON Student FROM Akhil;

Note: - A user who is not the owner of a table but has been given the privilege to grant
permissions to other users can also revoke permissions.
TCL Commands - Transaction Control Language

Transaction Control Language commands can only be used with DML commands. As
these operations are auto-committed in the database, they can’t be used while
creating or dropping tables. Various TCL commands are:
© Edunet Foundation. All rights reserved .291
COMMIT

Used for saving all transactions made to a database. Ends the current transaction and
makes all changes permanent that were made during the transaction. Releases all
transaction locks acquired on tables.
General Syntax:

COMMIT;

Example:

DELETE FROM Student WHERE Age = 25;

COMMIT;

ROLLBACK

Used to undo transactions that aren’t yet saved in the database. Ends the transaction
and undoes all changes made during the transaction. Releases all transaction locks
acquired on tables.
General Syntax:

ROLLBACK;

Example:

DELETE FROM Student WHERE Age = 25;

ROLLBACK;

CRUD operations using SQL, DDL and DML


CRUD Operations using MySQL
DDL Commands - Data Definition Language

Data Definition Language or DDL commands in SQL are used for changing the
structure of a table. In other words, DDL commands are capable of creating,
deleting, and modifying data.

All DDL commands are auto-committed which means that changes made by them
are automatically saved in the database. Following are the various DDL commands:

© Edunet Foundation. All rights reserved .292


ALTER

Used for altering the structure of a database. Typically, the ALTER command is used
either to add a new attribute or modify the characteristics of some existing attribute.
For adding new columns to the table:
General Syntax

ALTER TABLE table_name ADD (column_name1 data_type (size), column_name2


data_type (size),….., column_nameN data_type (size));

Example

ALTER TABLE Student ADD (Address varchar2(20));

ALTER TABLE Student ADD (Age number(2), Marks number(3));

For modifying an existing column in the table:


General Syntax:

ALTER TABLE table_name MODIFY (column_name new_data_type(new_size));

Example:

ALTER TABLE Student MODIFY (Name varchar2(20));

The ALTER command can also be used for dropping a column from the table:
General Syntax:

ALTER TABLE table_name DROP COLUMN column_name;

Example:

ALTER TABLE Student DROP COLUMN Age;

</pre.

Note: - It is not possible to do the following using the ALTER command:

• Change the name of a column


© Edunet Foundation. All rights reserved .293
• Change the name of a table
• Decrease the size of a column
CREATE

Used for creating a new table in the database. General Syntax:

CREATE TABLE table_name (column_name1 data_type(size), column_name2 data


_type(size),…., column_nameN data_type(size));

Example:

CREATE TABLE Employee(Name varchar2(20), D.O.B. date, Salary number(6);

DROP

Used for deleting an entire table from the database and all the data stored in it.
General Syntax:

DROP TABLE table_name;

Example:

DROP TABLE Student;

RENAME

Used for renaming a table.


General Syntax:

RENAME old_table_name TO new_table_name

Example:

RENAME Student TO Student_Details

TRUNCATE

Used for deleting all rows from a table and free the space containing the table.
General Syntax:

© Edunet Foundation. All rights reserved .294


TRUNCATE TABLE table_name;

Example:

TRUNCATE TABLE Student;

DML Commands - Data Manipulation Language

The DML or Data Manipulation Language commands help in modifying a relational


database. These commands are not auto-committed, which simply means that all
changes made to the database using DML commands aren’t automatically saved.
It is possible to rollback DML commands. Various DML commands are:
DELETE

Used for removing one or more rows from a table.


General Syntax:
DELETE FROM table_name; (deletes all rows from a table)
DELETE FROM table_name WHERE some_condition; (delete only the row(s) where
the condition is true)
Example:

DELETE FROM Student;

DELETE FROM Student WHERE Name = “Akhil”;

INSERT

Used for inserting data into the row of a table.


General Syntax:

INSERT INTO table_name (column_name1, column_name2,….,column_nameN) VA


LUES (value1, value2,….,valueN);

OR

INSERT INTO table_name VALUES (value1, value2,….,valueN);

Example:

INSERT INTO Student (Name, Age) VALUES (“Vijay”, “25”);

© Edunet Foundation. All rights reserved .295


Insert command can also be used for inserting data into a table from another table.
General Syntax:

INSERT INTO table_name1 SELECT column_name1, column_name2,….,column_n


ameN FROM table_name2;

Example:

INSERT INTO Student SELECT Id, Stream FROM Student_Subject_Details

UPDATE

Used to modify or update the value of a column in a table. It can update all rows or
some selective rows in the table.
General Syntax:

UPDATE table_name SET column_name1 = value1, column_name2 = value2,….,co


lumn_nameN = valueN (for updating all rows)

UPDATE table_name SET column_name1 = value1, column_name2 = value2,….,co


lumn_nameN = valueN [WHERE CONDITION] (for updating particular rows)

Example:

UPDATE Student SET Name = “Akhil” WHERE Id = 22;

Handling databases using core JAVA


What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for
database-independent connectivity between the Java programming language and a
wide range of databases.

The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.

• Making a connection to a database.


• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & modifying the resulting records.

© Edunet Foundation. All rights reserved .296


Fundamentally, JDBC is a specification that provides a complete set of interfaces
that allows for portable access to an underlying database. Java can be used to write
different types of executables, such as

• Java Applications
• Java Applets
• Java Servlets
• Java Server Pages (JSPs)
• Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a
database, and take advantage of the stored data. JDBC provides the same
capabilities as ODBC, allowing Java programs to contain database-independent
code.

JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database
access but in general, JDBC Architecture consists of two layers −

• JDBC API − This provides the application -to-JDBC Manager connection.


• JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases.

The JDBC driver manager ensures that the correct driver is used to access each data
source. The driver manager is capable of supporting multiple concurrent drivers
connected to multiple heterogeneous databases.

Following is the architectural diagram, which shows the location of the driver
manager with respect to the JDBC drivers and the Java application

Image: JDBC Architecture


Reference: https://usemynotes.com/wp-content/uploads/2021/07/jdbc-architecture-.png

JDBC in Java uses a driver manager and a database-specific driver to connect to a


database. The JDBC driver manager makes sure that the correct driver is being used
© Edunet Foundation. All rights reserved .297
to access the databases. It is also capable of handling multiple drivers connected to
multiple databases simultaneously.

Common JDBC Components


The JDBC API provides the following interfaces and classes

Driver Manager: This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using
communication sub protocol. The first driver that recognizes a certain subprotocol
under JDBC will be used to establish a database Connection.

Driver: This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely. Instead, you use Driver Manager
objects, which manages objects of this type. It also abstracts the details associated
with working with Driver objects.

Connection: This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication with
database is through connection object only.

Statement: You use objects created from this interface to submit the SQL statements
to the database. Some derived interfaces accept parameters in addition to executing
stored procedures.

Result Set: These objects hold data retrieved from a database after you execute an
SQL query using Statement objects. It acts as an iterator to allow you to move through
its data.

SQLException: This class handles any errors that occur in a database application.

JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:

• JDBC-ODBC bridge driver


• Native-API driver (partially java driver)
• Network Protocol driver (fully java driver)
• Thin driver (fully java driver)

JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
This is now discouraged because of thin driver.

© Edunet Foundation. All rights reserved .298


Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends
that you use JDBC drivers provided by the vendor of your database instead of the
JDBC-ODBC Bridge.

Image: JDBC-ODBC Bridge Driver


Reference: https://www.javatpoint.com/jdbc-driver

Advantages:

• easy to use.
• can be easily connected to any database.

Disadvantages:

• Performance degraded because JDBC method call is converted into the ODBC
function calls.
• The ODBC driver needs to be installed on the client machine.

Native-API driver

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

© Edunet Foundation. All rights reserved .299


Image: Native-API Driver
Reference: https://www.javatpoint.com/jdbc-driver

Advantage:

• performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

• The Native driver needs to be installed on each client machine.


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

Network Protocol driver

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

Image: Network Protocol Driver


Reference: https://www.javatpoint.com/jdbc-driver

Advantage:

© Edunet Foundation. All rights reserved .300


• No client-side library is required because of application server that can perform
many tasks like auditing, load balancing, logging etc.

Disadvantages:

• Network support is required on client machine.


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

Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database protocol.
That is why it is known as thin driver. It is fully written in Java language.

Image: Thin Driver


Reference: https://www.javatpoint.com/jdbc-driver

Advantage:

• Better performance than all other drivers.


• No software is required at client side or server side.

Disadvantage:

• Drivers depend on the Database.

Java Database Connectivity with 5 Steps

There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:

• Register the Driver class


• Create connection
• Create statement
© Edunet Foundation. All rights reserved .301
• Execute queries
• Close connection

Register the driver class

The forName() method of Class class is used to register the driver class. This method
is used to dynamically load the driver class.

Syntax of forName() method

public static void forName(String className)throws ClassNotFoundException

Example to register the OracleDriver class

Here, Java program is loading oracle driver to establish database connection.


Class.forName("oracle.jdbc.driver.OracleDriver");

Create the connection object


The getConnection() method of DriverManager class is used to establish connection
with the database.
Syntax of getConnection() method
public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String password)
throws SQLException

Example to establish connection with the Oracle database

Connection con=DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:xe","system","password");

Create the Statement object


The createStatement() method of Connection interface is used to create statement.
The object of statement is responsible to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException

Example to create the statement object


Statement stmt=con.createStatement();

© Edunet Foundation. All rights reserved .302


Execute the query

The executeQuery() method of Statement interface is used to execute queries to the


database. This method returns the object of ResultSet that can be used to get all the
records of a table.

Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLException

Example to execute query

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){

System.out.println(rs.getInt(1)+" "+rs.getString(2));

Close the connection object

By closing connection object statement and ResultSet will be closed automatically.


The close () method of Connection interface is used to close the connection.

Syntax of close() method

public void close()throws SQLException

Example to close connection

con.close();

Java JDBC CRUD: SQL Insert, Select, Update, and Delete


1. Prerequisites

To begin, make sure you have the following pieces of software installed on your
computer:

• JDK (download JDK 7).


• MySQL (download MySQL Community Server 5.6.12). You may also want
to download MySQL Workbench - a graphical tool for working with MySQL
databases.

© Edunet Foundation. All rights reserved .303


• JDBC Driver for MySQL (download MySQL Connector/J 5.1.25). Extract the zip
archive and put the mysql-connector-java-VERSION-bin.jar file into classpath
(in a same folder as your Java source files).

2. Creating a sample MySQL database

Let’s create a MySQL database called SampleDB with one table Users with the
following structure:

Execute the following SQL script inside MySQL Workbench:

create database SampleDB;

use SampleDB;

CREATE TABLE `users` (


`user_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`fullname` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL,
PRIMARY KEY (`user_id`)
);

Or if you are using MySQL Command Line Client program, save the above script into
a file, let’s say, SQLScript.sqland execute the following command:

source Path\To\The\Script\File\SQLScript.sql
Here’s an example screenshot taken while executing the above script in MySQL
Command Line Client program:

© Edunet Foundation. All rights reserved .304


3. Understand the main JDBC interfaces and classes

Let’s take an overview look at the JDBC’s main interfaces and classes with which we
usually work. They are all available under the java.sql package:

• DriverManager: this class is used to register driver for a specific database


type (e.g. MySQL in this tutorial) and to establish a database connection with
the server via its getConnection() method.

• Connection: this interface represents an established database connection


(session) from which we can create statements to execute queries and
retrieve results, get metadata about the database, close connection, etc.

• Statement and PreparedStatement: these interfaces are used to execute


static SQL query and parameterized SQL query, respectively. Statement is
the super interface of the PreparedStatement interface. Their commonly used
methods are:

o boolean execute(String sql): executes a general SQL statement. It


returns true if the query returns a ResultSet, false if the query returns
an update count or returns nothing. This method can be used with
a Statement only.

o int executeUpdate(String sql): executes an INSERT, UPDATE or


DELETE statement and returns an update account indicating number
of rows affected (e.g. 1 row inserted, or 2 rows updated, or 0 rows
affected).

o ResultSet executeQuery(String sql): executes a SELECT statement


and returns a ResultSet object which contains results returned by the
query.

• A prepared statement is one that contains placeholders (in form question


marks ?) for dynamic values will be set at runtime. For example:

• SELECT * from Users WHERE user_id=?

• Here the value of user_id is parameterized by a question mark and will be set
by one of the setXXX() methods from the PreparedStatement interface,
e.g. setInt(int index, int value).

• ResultSet: contains table data returned by a SELECT query. Use this object
to iterate over rows in the result set using next() method, and get value of a
column in the current row using getXXX() methods
© Edunet Foundation. All rights reserved .305
(e.g. getString(), getInt(), getFloat() and so on). The column value can be
retrieved either by index number (1-based) or by column name.

• SQLException: this checked exception is declared to be thrown by all the


above methods, so we have to catch this exception explicitly when calling the
above classes’ methods.

4. Connecting to the database

Supposing the MySQL database server is listening on the default


port 3306 at localhost. The following code snippet connects to the database
name SampleDB by the user root and password secret:

String dbURL = "jdbc:mysql://localhost:3306/sampledb";


String username = "root";
String password = "secret";

try {

Connection conn = DriverManager.getConnection(dbURL, username, password);

if (conn != null) {
System.out.println("Connected");
}
} catch (SQLException ex) {
ex.printStackTrace();
}

Once the connection was established, we have a Connection object which can be
used to create statements in order to execute SQL queries. In the above code, we
have to close the connection explicitly after finish working with the database:

conn.close();

INSERT Statement

String sql = "INSERT INTO Users (username, password, fullname, email) VALUES
(?, ?, ?, ?)";

PreparedStatement statement = conn.prepareStatement(sql);


statement.setString(1, "bill");
statement.setString(2, "secretpass");
statement.setString(3, "Bill Gates");
statement.setString(4, "bill.gates@microsoft.com");

int rowsInserted = statement.executeUpdate();


if (rowsInserted > 0) {

© Edunet Foundation. All rights reserved .306


System.out.println("A new user was inserted successfully!");
}

SELECT Statement

String sql = "SELECT * FROM Users";


Statement statement = conn.createStatement();
ResultSet result = statement.executeQuery(sql);

int count = 0;
while (result.next()){
String name = result.getString(2);
String pass = result.getString(3);
String fullname = result.getString("fullname");
String email = result.getString("email");

String output = "User #%d: %s - %s - %s - %s";


System.out.println(String.format(output, ++count, name, pass, fullname, email));
}

UPDATE Statement

String sql = "UPDATE Users SET password=?, fullname=?, email=? WHERE


username=?";

PreparedStatement statement = conn.prepareStatement(sql);


statement.setString(1, "123456789");
statement.setString(2, "William Henry Bill Gates");
statement.setString(3, "bill.gates@microsoft.com");
statement.setString(4, "bill");

int rowsUpdated = statement.executeUpdate();


if (rowsUpdated > 0) {
System.out.println("An existing user was updated successfully!");
}

DELETE Statement

String sql = "DELETE FROM Users WHERE username=?";

PreparedStatement statement = conn.prepareStatement(sql);


statement.setString(1, "bill");

int rowsDeleted = statement.executeUpdate();


if (rowsDeleted > 0) {
System.out.println("A user was deleted successfully!");
}

© Edunet Foundation. All rights reserved .307


Creating DAO (database access objects)
Data Access Object Pattern or DAO pattern is used to separate low level data
accessing API or operations from high level business services. Following are the
participants in Data Access Object Pattern.

• Data Access Object Interface - This interface defines the standard operations
to be performed on a model object(s).
• Data Access Object concrete class - This class implements above interface.
This class is responsible to get data from a data source which can be database
/ xml or any other storage mechanism.
• Model Object or Value Object - This object is simple POJO containing get/set
methods to store data retrieved using DAO class.

Implementation

We are going to create a Student object acting as a Model or Value Object.StudentDao


is Data Access Object Interface.StudentDaoImpl is concrete class implementing Data
Access Object Interface. DaoPatternDemo, our demo class, will use StudentDao to
demonstrate the use of Data Access Object pattern.

Image: DAO Implementation


Reference: https://www.tutorialspoint.com/design_pattern/data_access_object_pattern.htm

Step 1

Create Value Object.


Student.java

public class Student {


private String name;
private int rollNo;
Student(String name, int rollNo){

© Edunet Foundation. All rights reserved .308


this.name = name;
this.rollNo = rollNo;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getRollNo() {


return rollNo;
}

public void setRollNo(int rollNo) {


this.rollNo = rollNo;
}
}

Step 2

Create Data Access Object Interface.


StudentDao.java

import java.util.List;

public interface StudentDao {


public List<Student> getAllStudents();
public Student getStudent(int rollNo);
public void updateStudent(Student student);
public void deleteStudent(Student student);
}

Step 3

Create concrete class implementing above interface.


StudentDaoImpl.java

import java.util.ArrayList;
import java.util.List;

public class StudentDaoImpl implements StudentDao {

//list is working as a database


List<Student> students;

public StudentDaoImpl(){

© Edunet Foundation. All rights reserved .309


students = new ArrayList<Student>();
Student student1 = new Student("Robert",0);
Student student2 = new Student("John",1);
students.add(student1);
students.add(student2);
}
@Override
public void deleteStudent(Student student) {
students.remove(student.getRollNo());
System.out.println("Student: Roll No " + student.getRollNo() + ", deleted from
database");
}

//retrive list of students from the database


@Override
public List<Student> getAllStudents() {
return students;
}

@Override
public Student getStudent(int rollNo) {
return students.get(rollNo);
}

@Override
public void updateStudent(Student student) {
students.get(student.getRollNo()).setName(student.getName());
System.out.println("Student: Roll No " + student.getRollNo() + ", updated in the
database");
}
}

Step 4

Use the StudentDao to demonstrate Data Access Object pattern usage.


DaoPatternDemo.java

public class DaoPatternDemo {


public static void main(String[] args) {
StudentDao studentDao = new StudentDaoImpl();

//print all students


for (Student student : studentDao.getAllStudents()) {
System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " +
student.getName() + " ]");
}

//update student

© Edunet Foundation. All rights reserved .310


Student student =studentDao.getAllStudents().get(0);
student.setName("Michael");
studentDao.updateStudent(student);

//get the student


studentDao.getStudent(0);
System.out.println("Student: [RollNo : " + student.getRollNo() + ", Name : " +
student.getName() + " ]");
}
}

Step 5

Verify the output.

Student: [RollNo : 0, Name : Robert ]


Student: [RollNo : 1, Name : John ]
Student: Roll No 0, updated in the database
Student: [RollNo : 0, Name : Michael ]

Advantages

• The advantage of using data access objects is the relatively simple and rigorous
separation between two important parts of an application that can but should
not know anything of each other, and which can be expected to evolve
frequently and independently.
• If we need to change the underlying persistence mechanism, we only have to
change the DAO layer and not all the places in the domain logic where the DAO
layer is used from.

Disadvantages

• Potential disadvantages of using DAO is a leaky abstraction, code duplication,


and abstraction inversion.

© Edunet Foundation. All rights reserved .311


3.2 Managing data in databases using JSP & Servlet

Connecting to MySQL DB, performing CRUD operations using,


persistent storage of front-end data to MySQL DB
JSP Servlet JDBC MySQL CRUD
We will develop below simple basic features in our User Management web
application:

1. Create a User
2. Update a User
3. Delete a User
4. Retrieve a User
5. List of all Users

The application looks something like this:

Tools and technologies used

• JSP - 2.2 +
• IDE - STS/Eclipse Neon.3
• JDK - 1.8 or later
• Apache Tomcat - 8.5
• JSTL - 1.2.1
• Servlet API - 2.5
• MySQL - mysql-connector-java-8.0.13.jar
© Edunet Foundation. All rights reserved .312
Development Steps

1. Create an Eclipse Dynamic Web Project


2. Add Dependencies
3. Project Structure
4. MySQL Database Setup
5. Create a JavaBean - User.java
6. Create a UserDAO.java
7. Create a UserServlet.java
8. Creating User Listing JSP Page - user-list.jsp
9. Create a User Form JSP Page - user-form.jsp
10. Creating Error JSP page
11. Deploying and Testing the Application Demo

Class Diagram

1. Create an Eclipse Dynamic Web Project

To create a new dynamic Web project in Eclipse:

1. On the main menu select File > New > Project....


© Edunet Foundation. All rights reserved .313
2. In the upcoming wizard choose Web > Dynamic Web Project.

3. Click Next.

4. Enter project name as "jsp-servlet-jdbc-mysql-example";


5. Make sure that the target runtime is set to Apache Tomcat with the currently
supported version.

2. Add Dependencies

Add the latest release of below jar files to the lib folder.

• jsp-api.2.3.1.jar
• servlet-api.2.3.jar
• mysql-connector-java-8.0.13.jar
• jstl-1.2.jar

3. Project Structure

Standard project structure for your reference -

© Edunet Foundation. All rights reserved .314


4. MySQL Database Setup

Let's create a database named "demo" in MySQL. Now, create a user’s table using
below DDL script:

CREATE DATABASE 'demo';


USE demo;

create table users (


id int(3) NOT NULL AUTO_INCREMENT,
name varchar(120) NOT NULL,
email varchar(220) NOT NULL,
country varchar(120),
PRIMARY KEY (id)
);

You can use either MySQL Command Line Client or MySQL Workbench tool to
create the database. The above a user’s table looks like:

© Edunet Foundation. All rights reserved .315


5. Create a JavaBean - User.java

Let's create a User java class to model a user entity in the database with the following
code:

package net.javaguides.usermanagement.model;

public class User {


protected int id;
protected String name;
protected String email;
protected String country;

public User() {}

public User(String name, String email, String country) {


super();
this.name = name;
this.email = email;
this.country = country;
}

public User(int id, String name, String email, String country) {


super();
this.id = id;
this.name = name;
this.email = email;
this.country = country;
}

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCountry() {
return country;
}

© Edunet Foundation. All rights reserved .316


public void setCountry(String country) {
this.country = country;
}
}

6. Create a UserDAO.java

Let's create a UserDAO class which is a Data Access Layer (DAO) class that provides
CRUD (Create, Read, Update, Delete) operations for the table users in a database.
Here’s the full source code of the UserDAO:

package net.javaguides.usermanagement.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import net.javaguides.usermanagement.model.User;

public class UserDAO {


private String jdbcURL = "jdbc:mysql://localhost:3306/demo?useSSL=false";
private String jdbcUsername = "root";
private String jdbcPassword = "root";

private static final String INSERT_USERS_SQL = "INSERT INTO users" + "


(name, email, country) VALUES " +
" (?, ?, ?);";

private static final String SELECT_USER_BY_ID = "select id,name,email,country


from users where id =?";
private static final String SELECT_ALL_USERS = "select * from users"

private static final String DELETE_USERS_SQL = "delete from users where id = ?;";
private static final String UPDATE_USERS_SQL = "update users set name =
?,email= ?, country =? where id = ?;";

public UserDAO() {}

protected Connection getConnection() {


Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");

connection = DriverManager.getConnection(jdbcURL, jdbcUsername,


jdbcPassword);
© Edunet Foundation. All rights reserved .317
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
public void insertUser(User user) throws SQLException {
System.out.println(INSERT_USERS_SQL);
// try-with-resource statement will auto close the connection.
try (Connection connection = getConnection(); PreparedStatement
preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) {
preparedStatement.setString(1, user.getName());
preparedStatement.setString(2, user.getEmail());
preparedStatement.setString(3, user.getCountry());
System.out.println(preparedStatement);
preparedStatement.executeUpdate();
} catch (SQLException e) {
printSQLException(e);
}
}
public User selectUser(int id) {
User user = null;
// Step 1: Establishing a Connection
try (Connection connection = getConnection();
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement =
connection.prepareStatement(SELECT_USER_BY_ID);) {
preparedStatement.setInt(1, id);
System.out.println(preparedStatement);
// Step 3: Execute the query or update query
ResultSet rs = preparedStatement.executeQuery();

// Step 4: Process the ResultSet object.


while (rs.next()) {
String name = rs.getString("name");
String email = rs.getString("email");
String country = rs.getString("country");
user = new User(id, name, email, country);
}
} catch (SQLException e) {
printSQLException(e);
}
return user; }

public List < User > selectAllUsers() {

// using try-with-resources to avoid closing resources (boiler plate code)


List < User > users = new ArrayList < > ();

© Edunet Foundation. All rights reserved .318


// Step 1: Establishing a Connection
try (Connection connection = getConnection();

// Step 2:Create a statement using connection object


PreparedStatement preparedStatement =
connection.prepareStatement(SELECT_ALL_USERS);) {
System.out.println(preparedStatement);
// Step 3: Execute the query or update query
ResultSet rs = preparedStatement.executeQuery();

// Step 4: Process the ResultSet object.


while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
String country = rs.getString("country");
users.add(new User(id, name, email, country));
}
} catch (SQLException e) {
printSQLException(e);
}
return users;
}

public boolean deleteUser(int id) throws SQLException {


boolean rowDeleted;
try (Connection connection = getConnection(); PreparedStatement statement =
connection.prepareStatement(DELETE_USERS_SQL);) {
statement.setInt(1, id);
rowDeleted = statement.executeUpdate() > 0;
}
return rowDeleted;
}

public boolean updateUser(User user) throws SQLException {


boolean rowUpdated;
try (Connection connection = getConnection(); PreparedStatement statement =
connection.prepareStatement(UPDATE_USERS_SQL);) {
statement.setString(1, user.getName());
statement.setString(2, user.getEmail());
statement.setString(3, user.getCountry());
statement.setInt(4, user.getId());

rowUpdated = statement.executeUpdate() > 0;


}
return rowUpdated;
}

private void printSQLException(SQLException ex) {


for (Throwable e: ex) {
if (e instanceof SQLException) {

© Edunet Foundation. All rights reserved .319


e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}

7. Create a UserServlet.java

Now, let's create UserServlet that acts as a page controller to handle all requests
from the client. Let’s look at the code first:

package net.javaguides.usermanagement.web;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.javaguides.usermanagement.dao.UserDAO;
import net.javaguides.usermanagement.model.User;

@WebServlet("/")
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1 L;
private UserDAO userDAO;

public void init() {


userDAO = new UserDAO();
}

protected void doPost(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
doGet(request, response);
}

© Edunet Foundation. All rights reserved .320


protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String action = request.getServletPath();

try {
switch (action) {
case "/new":
showNewForm(request, response);
break;
case "/insert":
insertUser(request, response);
break;
case "/delete":
deleteUser(request, response);
break;
case "/edit":
showEditForm(request, response);
break;
case "/update":
updateUser(request, response);
break;
default:
listUser(request, response);
break;
}
} catch (SQLException ex) {
throw new ServletException(ex);
}
}

private void listUser(HttpServletRequest request, HttpServletResponse response)


throws SQLException, IOException, ServletException {
List < User > listUser = userDAO.selectAllUsers();
request.setAttribute("listUser", listUser);
RequestDispatcher dispatcher = request.getRequestDispatcher("user-list.jsp");
dispatcher.forward(request, response);
}

private void showNewForm(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("user-
form.jsp");
dispatcher.forward(request, response);
}

© Edunet Foundation. All rights reserved .321


private void showEditForm(HttpServletRequest request, HttpServletResponse
response)
throws SQLException, ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
User existingUser = userDAO.selectUser(id);
RequestDispatcher dispatcher = request.getRequestDispatcher("user-
form.jsp");
request.setAttribute("user", existingUser);
dispatcher.forward(request, response);

private void insertUser(HttpServletRequest request, HttpServletResponse


response)
throws SQLException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
String country = request.getParameter("country");
User newUser = new User(name, email, country);
userDAO.insertUser(newUser);
response.sendRedirect("list");
}

private void updateUser(HttpServletRequest request, HttpServletResponse


response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String email = request.getParameter("email");
String country = request.getParameter("country");

User book = new User(id, name, email, country);


userDAO.updateUser(book);
response.sendRedirect("list");
}

private void deleteUser(HttpServletRequest request, HttpServletResponse


response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
userDAO.deleteUser(id);
response.sendRedirect("list");

}
}

8. Creating User Listing JSP Page - user-list.jsp

Next, create a JSP page for displaying all users from the database. Let's create a list-
user.jsp page under the WebContent directory in the project with the following code:

© Edunet Foundation. All rights reserved .322


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>

<head>
<title>User Management Application</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
</head>

<body>

<header>
<nav class="navbar navbar-expand-md navbar-dark" style="background-
color: tomato">
<div>
<a href="https://www.javaguides.net" class="navbar-brand"> User
Management App </a>
</div>

<ul class="navbar-nav">
<li><a href="<%=request.getContextPath()%>/list" class="nav-
link">Users</a></li>
</ul>
</nav>
</header>
<br>

<div class="row">
<!-- <div class="alert alert-success" *ngIf='message'>{{message}}</div> --
>

<div class="container">
<h3 class="text-center">List of Users</h3>
<hr>
<div class="container text-left">

<a href="<%=request.getContextPath()%>/new" class="btn btn-


success">Add
New User</a>
</div>
<br>
<table class="table table-bordered">
© Edunet Foundation. All rights reserved .323
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<th>Country</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<!-- for (Todo todo: todos) { -->
<c:forEach var="user" items="${listUser}">

<tr>
<td>
<c:out value="${user.id}" />
</td>
<td>
<c:out value="${user.name}" />
</td>
<td>
<c:out value="${user.email}" />
</td>
<td>
<c:out value="${user.country}" />
</td>
<td><a href="edit?id=<c:out value='${user.id}' />">Edit</a>
&nbsp;&nbsp;&nbsp;&nbsp; <a href="delete?id=<c:out value='${user.id}'
/>">Delete</a></td>
</tr>
</c:forEach>
<!-- } -->
</tbody>

</table>
</div>
</div>
</body>

</html>

Once you will deploy above JSP page in tomcat and open in the browser looks
something like this:

© Edunet Foundation. All rights reserved .324


9. Create a User Form JSP Page - user-form.jsp

Next, we create a JSP page for creating a new User called user-form.jsp. Here’s its
full source code:

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>

<head>
<title>User Management Application</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-
ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
</head>

<body>

<header>
<nav class="navbar navbar-expand-md navbar-dark" style="background-
color: tomato">
<div>
<a href="https://www.javaguides.net" class="navbar-brand"> User
Management App </a>
</div>

<ul class="navbar-nav">
© Edunet Foundation. All rights reserved .325
<li><a href="<%=request.getContextPath()%>/list" class="nav-
link">Users</a></li>
</ul>
</nav>
</header>
<br>
<div class="container col-md-5">
<div class="card">
<div class="card-body">
<c:if test="${user != null}">
<form action="update" method="post">
</c:if>
<c:if test="${user == null}">
<form action="insert" method="post">
</c:if>

<caption>
<h2>
<c:if test="${user != null}">
Edit User
</c:if>
<c:if test="${user == null}">
Add New User
</c:if>
</h2>
</caption>

<c:if test="${user != null}">


<input type="hidden" name="id" value="<c:out value='${user.id}' />"
/>
</c:if>

<fieldset class="form-group">
<label>User Name</label> <input type="text" value="<c:out
value='${user.name}' />" class="form-control" name="name" required="required">
</fieldset>

<fieldset class="form-group">
<label>User Email</label> <input type="text" value="<c:out
value='${user.email}' />" class="form-control" name="email">
</fieldset>

<fieldset class="form-group">
<label>User Country</label> <input type="text" value="<c:out
value='${user.country}' />" class="form-control" name="country">
</fieldset>

<button type="submit" class="btn btn-success">Save</button>


</form>
</div>
</div>

© Edunet Foundation. All rights reserved .326


</div>
</body>

</html>

Once you will deploy above JSP page in tomcat and open in the browser looks
something like this:

The above page acts for both functionalities to create a new User and Edit the same
user. The edit page looks like:

© Edunet Foundation. All rights reserved .327


10. Creating Error JSP page

Here’s the code of the Error.jsp page which simply shows the exception message:

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8" isErrorPage="true" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Error</title>
</head>
<body>
<center>
<h1>Error</h1>
<h2><%=exception.getMessage() %><br/> </h2>
</center>
</body>
</html>

11. Deploying and Testing the Application

It's time to see a demo of the above User Management web application. Deploy this
web application in tomcat server.

Type the following URL in your web browser to access the User
Management application: http://localhost:8080/jsp-servlet-jdbc-mysql-crud-example/

Create a new User


© Edunet Foundation. All rights reserved .328
Edit a User

List of all Users

© Edunet Foundation. All rights reserved .329


Handling NoSQL database- MongoDB
NOSQL

The term ‘NoSQL’ refers to nonrelational types of databases, and these databases
store data in a format that’s different from relational tables. However, NoSQL
databases can be queried using idiomatic language APIs, declarative structured query
languages, and query-by example languages, which is why they are also referred to
as “not only SQL” databases.
NoSQL databases are widely used in real-time web applications and big data, because
their main advantages are high scalability and high availability.
NoSQL databases are also the preferred choice of developers, as they naturally lend
themselves to an agile development paradigm by rapidly adapting to changing
requirements. NoSQL databases allow the data to be stored in ways that are more
intuitive and easier to understand, or closer to the way the data is used by
applications—with fewer transformations required when storing or retrieving using
NoSQL-style APIs. Moreover, NoSQL databases can take full advantage of the cloud
to deliver zero downtime

SQL versus NoSQL


SQL databases are relational, while NoSQL databases are non -relational. The
relational database management system (RDBMS) is the basis for structured query
language (SQL), which lets users access and manipulate data in highly structured
tables. This is foundational model for database systems such as MS SQL Server, IBM
© Edunet Foundation. All rights reserved .330
DB2, Oracle, and MySQL. But with NoSQL databases, the data access syntax can be
different from database to database.

Image: SQL Vs NoSQL


Reference: https://www.guru99.com/nosql-tutorial.html

Why NoSQL?

The concept of NoSQL databases became popular with Internet giants like Google,
Facebook, Amazon, etc. who deal with huge volumes of data. The system response
time becomes slow when you use RDBMS for massive volumes of data.

To resolve this problem, we could “scale up” our systems by upgrading our existing
hardware. This process is expensive.

The alternative for this issue is to distribute database load on multiple hosts
whenever the load increases. This method is known as “scaling out.”

Image: Why NoSQL?


Reference: https://www.guru99.com/nosql-tutorial.html

NoSQL database is non-relational, so it scales out better than relational databases


as they are designed with web applications in mind.

Brief History of NoSQL Databases

© Edunet Foundation. All rights reserved .331


• 1998- Carlo Strozzi use the term NoSQL for his lightweight, open -source
relational database
• 2000- Graph database Neo4j is launched
• 2004- Google BigTable is launched
• 2005- CouchDB is launched
• 2007- The research paper on Amazon Dynamo is released
• 2008- Facebooks open sources the Cassandra project
• 2009- The term NoSQL was reintroduced

Features of NoSQL

Non-relational

• NoSQL databases never follow the relational model


• Never provide tables with flat fixed-column records
• Work with self-contained aggregates or BLOBs
• Doesn’t require object-relational mapping and data normalization
• No complex features like query languages, query planners,referential integrity
joins, ACID

Schema-free

• NoSQL databases are either schema-free or have relaxed schemas


• Do not require any sort of definition of the schema of the data
• Offers heterogeneous structures of data in the same domain

Image: Schema-Free
Reference: https://www.guru99.com/nosql-tutorial.html
Simple API

• Offers easy to use interfaces for storage and querying data provided
• APIs allow low-level data manipulation & selection methods
• Text-based protocols mostly used with HTTP REST with JSON
• Mostly used no standard based NoSQL query language
• Web-enabled databases running as internet-facing services

Distributed
© Edunet Foundation. All rights reserved .332
• Multiple NoSQL databases can be executed in a distributed fashion
• Offers auto-scaling and fail-over capabilities
• Often ACID concept can be sacrificed for scalability and throughput
• Mostly no synchronous replication between distributed nodes Asynchronous
Multi-Master Replication, peer-to-peer, HDFS Replication
• Only providing eventual consistency
• Shared Nothing Architecture. This enables less coordination and higher
distribution.

Image: Distributed
Reference: https://www.guru99.com/nosql-tutorial.html

Types of NoSQL Databases

NoSQL Databases are mainly categorized into four types: Key-value pair, Column-
oriented, Graph-based and Document-oriented. Every category has its unique
attributes and limitations. None of the above-specified database is better to solve all
the problems. Users should select the database based on their product needs.
Types of NoSQL Databases:

• Key-value Pair Based


• Column-oriented Graph
• Graphs based
• Document-oriented

Image: Types of NoSQL Database


Reference: https://www.guru99.com/nosql-tutorial.html

© Edunet Foundation. All rights reserved .333


Key Value Pair Based

Data is stored in key/value pairs. It is designed in such a way to handle lots of data
and heavy load.

Key-value pair storage databases store data as a hash table where each key is unique,
and the value can be a JSON, BLOB(Binary Large Objects), string, etc.

Image: Key Value pair Based


Reference: https://www.guru99.com/nosql-tutorial.html

It is one of the most basic NoSQL database example. This kind of NoSQL database
is used as a collection, dictionaries, associative arrays, etc. Key value stores help the
developer to store schema-less data. They work best for shopping cart contents.

Redis, Dynamo, Riak are some NoSQL examples of key-value store DataBases.
They are all based on Amazon’s Dynamo paper.

Column-based

Column-oriented databases work on columns and are based on BigTable paper by


Google. Every column is treated separately. Values of single column databases are
stored contiguously.

© Edunet Foundation. All rights reserved .334


Image: Column-based
Reference: https://www.guru99.com/nosql-tutorial.html

Column based NoSQL database

They deliver high performance on aggregation queries like SUM, COUNT, AVG, MIN
etc. as the data is readily available in a column.

Column-based NoSQL databases are widely used to manage data


warehouses, business intelligence, CRM, Library card catalogs,

HBase, Cassandra, HBase, Hypertable are NoSQL query examples of column


based database.

Document-Oriented:

Document-Oriented NoSQL DB stores and retrieves data as a key value pair but the
value part is stored as a document. The document is stored in JSON or XML formats.
The value is understood by the DB and can be queried.

Image: Document-Oriented
Reference: https://www.guru99.com/nosql-tutorial.html

Relational Vs. Document

In this diagram on your left you can see we have rows and columns, and in the right,
we have a document database which has a similar structure to JSON. Now for the
relational database, you have to know what columns you have and so on. However,

© Edunet Foundation. All rights reserved .335


for a document database, you have data store like JSON object. You do not require to
define which make it flexible.

The document type is mostly used for CMS systems, blogging platforms, real-time
analytics & e-commerce applications. It should not use for complex transactions which
require multiple operations or queries against varying aggregate structures.

Amazon SimpleDB, CouchDB, MongoDB, Riak, Lotus Notes, MongoDB , are


popular Document originated DBMS systems.

Graph-Based

A graph type database stores entities as well the relations amongst those entities. The
entity is stored as a node with the relationship as edges. An edge gives a relationship
between nodes. Every node and edge has a unique identifier.

Image: Graph-Based
Reference: https://www.guru99.com/nosql-tutorial.html

Compared to a relational database where tables are loosely connected, a Graph


database is a multi-relational in nature. Traversing relationship is fast as they are
already captured into the DB, and there is no need to calculate them.

Graph base database mostly used for social networks, logistics, spatial data.

Neo4J, Infinite Graph, OrientDB, FlockDB are some popular graph-based


databases.

When should NoSQL be used?

• When huge amount of data needs to be stored and retrieved.


• The relationship between the data you store is not that important
• The data changing over time and is not structured.
• Support of Constraints and Joins is not required at database level
• The data is growing continuously and you need to scale the database regular
to handle the data.

Advantages of NoSQL

© Edunet Foundation. All rights reserved .336


• Can be used as Primary or Analytic Data Source
• Big Data Capability
• No Single Point of Failure
• Easy Replication
• No Need for Separate Caching Layer
• It provides fast performance and horizontal scalability.
• Can handle structured, semi-structured, and unstructured data with equal
effect
• Object-oriented programming which is easy to use and flexible
• NoSQL databases don’t need a dedicated high -performance server
• Support Key Developer Languages and Platforms
• Simple to implement than using RDBMS
• It can serve as the primary data source for online applications.
• Handles big data which manages data velocity, variety, volume, and
complexity
• Excels at distributed database and multi-data center operations
• Eliminates the need for a specific caching layer to store data
• Offers a flexible schema design which can easily be altered without downtime
or service disruption

Disadvantages of NoSQL

• No standardization rules
• Limited query capabilities
• RDBMS databases and tools are comparatively mature
• It does not offer any traditional database capabilities, like consistency when
multiple transactions are performed simultaneously.
• When the volume of data increases it is difficult to maintain unique values as
keys become difficult
• Doesn’t work as well with relational data
• The learning curve is stiff for new developers
• Open-source options so not so popular for enterprises.

MongoDB

MongoDB is a NoSQL database which stores the data in form of key-value pairs. It is
an Open Source, Document Database which provides high performance and
scalability along with data modelling and data management of huge sets of data in an
enterprise application.

MongoDB also provides the feature of Auto-Scaling. Since, MongoDB is a cross


platform database and can be installed across different platforms like Windows, Linux
etc.

What is Document based storage?

© Edunet Foundation. All rights reserved .337


A Document is nothing but a data structure with name-value pairs like in JSON. It is
very easy to map any custom Object of any programming language with a MongoDB
Document. For example : Student object has attributes name, rollno and subjects,
where subjects is a List.

Document for Student in MongoDB will be like:

name : "Program",

rollno : 1,

subjects : ["C Language", "C++", "Core Java"]

Copy

We can see, Documents are actually JSON representation of custom Objects. Also,
excessive JOINS can be avoided by saving data in form of Arrays and
Documents(Embedded) inside a Document.

Features of MongoDB

• Each database contains collections which in turn contains documents. Each


document can be different with a varying number of fields. The size and content
of each document can be different from each other.
• The document structure is more in line with how developers construct their
classes and objects in their respective programming languages. Developers will
often say that their classes are not rows and columns but have a clear structure
with key-value pairs.
• The rows (or documents as called in MongoDB) doesn’t need to have a schema
defined beforehand. Instead, the fields can be created on the fly.
• The data model available within MongoDB allows you to represent hierarchical
relationships, to store arrays, and other more complex structures more easily.
• Scalability – The MongoDB environments are very scalable. Companies across
the world have defined clusters with some of them running 100+ nodes with
around millions of documents within the database

Why Use MongoDB?

• Document-oriented – Since MongoDB is a NoSQL type database, instead of


having data in a relational type format, it stores the data in documents. This
makes MongoDB very flexible and adaptable to real business world situation
and requirements.
• Ad hoc queries – MongoDB supports searching by field, range queries, and
regular expression searches. Queries can be made to return specific fields
within documents.
• Indexing – Indexes can be created to improve the performance of searches
within MongoDB. Any field in a MongoDB document can be indexed.
© Edunet Foundation. All rights reserved .338
• Replication – MongoDB can provide high availability with replica sets. A replica
set consists of two or more mongo DB instances. Each replica set member may
act in the role of the primary or secondary replica at any time. The primary
replica is the main server which interacts with the client an d performs all the
read/write operations. The Secondary replicas maintain a copy of the data of
the primary using built-in replication. When a primary replica fails, the replica
set automatically switches over to the secondary and then it becomes the
primary server.
• Load balancing – MongoDB uses the concept of sharding to scale horizontally
by splitting data across multiple MongoDB instances. MongoDB can run over
multiple servers, balancing the load and/or duplicating data to keep the system
up and running in case of hardware failure.

MongoDB with JAVA

MongoDB Java Driver Download

If you have maven project, just add below dependency to include MongoDB java
driver into your application.

<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>2.12.3</version>
</dependency>

If you have a standalone project, you can download MongoDB Java Driver from
this link and include it in your project build path.

Installation

Before you start using MongoDB in your Java programs, you need to make sure that
you have MongoDB CLIENT and Java set up on the machine. You can check Java
tutorial for Java installation on your machine. Now, let us check how to set up
MongoDB CLIENT.
• You need to download the jar mongodb-driver-3.11.2.jar and its
dependency mongodb-driver-core-3.11.2.jar.. Make sure to download
the latest release of these jar files.
• You need to include the downloaded jar files into your classpath.

Connect to Database

To connect database, you need to specify the database name, if the database doesn't
exist then MongoDB creates it automatically.

import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
© Edunet Foundation. All rights reserved .339
public class ConnectToDB {

public static void main( String args[] ) {

// Creating a Mongo client


MongoClient mongo = new MongoClient( "localhost" , 27017 );

// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");

// Accessing the database


MongoDatabase database = mongo.getDatabase("myDb");
System.out.println("Credentials ::"+ credential);
}
}

Create a Collection

To create a collection, createCollection() method


of com.mongodb.client.MongoDatabase class is used.

import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class CreatingCollection {

public static void main( String args[] ) {

// Creating a Mongo client


MongoClient mongo = new MongoClient( "localhost" , 27017 );

// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");

//Accessing the database


MongoDatabase database = mongo.getDatabase("myDb");

//Creating a collection
database.createCollection("sampleCollection");
System.out.println("Collection created successfully");
}
}

© Edunet Foundation. All rights reserved .340


Getting/Selecting a Collection

To get/select a collection from the database, getCollection() method


of com.mongodb.client.MongoDatabase class is used.

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class selectingCollection {

public static void main( String args[] ) {

// Creating a Mongo client


MongoClient mongo = new MongoClient( "localhost" , 27017 );

// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");

// Accessing the database


MongoDatabase database = mongo.getDatabase("myDb");

// Creating a collection
System.out.println("Collection created successfully");
// Retrieving a collection
MongoCollection<Document> collection =
database.getCollection("myCollection");
System.out.println("Collection myCollection selected successfully");
}
}

Insert a Document

To insert a document into MongoDB, insert() method


of com.mongodb.client.MongoCollection class is used.

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
public class InsertingDocument {
public static void main( String args[] ) {
© Edunet Foundation. All rights reserved .341
// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );

// Accessing the database


MongoDatabase database = mongo.getDatabase("myDb");

// Creating a collection
database.createCollection("sampleCollection");
System.out.println("Collection created successfully");

// Retrieving a collection
MongoCollection<Document> collection =
database.getCollection("sampleCollection");
System.out.println("Collection sampleCollection selected successfully");
Document document = new Document("title", "MongoDB")
.append("description", "database")
.append("likes", 100)
.append("url", "http://www.tutorialspoint.com/mongodb/")
.append("by", "tutorials point");

//Inserting document into the collection


collection.insertOne(document);
System.out.println("Document inserted successfully");
}

Retrieve All Documents

To select all documents from the collection, find() method


of com.mongodb.client.MongoCollection class is used. This method returns a
cursor, so you need to iterate this cursor.

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class RetrievingAllDocuments {
public static void main( String args[] ) {

// Creating a Mongo client


MongoClient mongo = new MongoClient( "localhost" , 27017 );

// Creating Credentials
MongoCredential credential;

© Edunet Foundation. All rights reserved .342


credential = MongoCredential.createCredential("sampleUser",
"myDb", "password".toCharArray());
System.out.println("Connected to the database successfully");

// Accessing the database


MongoDatabase database = mongo.getDatabase("myDb");

// Retrieving a collection
MongoCollection<Document> collection =
database.getCollection("sampleCollection");
System.out.println("Collection sampleCollection selected
successfully");
Document document1 = new Document("title", "MongoDB")
.append("description", "database")
.append("likes", 100)
.append("url", "http://www.tutorial.com/mongodb/")
.append("by", "tutorials point");
Document document2 = new Document("title", "RethinkDB")
.append("description", "database")
.append("likes", 200)
.append("url", "http://www.tutorial.com/rethinkdb/")
.append("by", "tutorials point");
List<Document> list = new ArrayList<Document>();
list.add(document1);
list.add(document2);
collection.insertMany(list);
// Getting the iterable object
FindIterable<Document> iterDoc = collection.find();
int i = 1;
// Getting the iterator
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
i++;
}
}
}

Update Document

To update a document from the collection, updateOne() method


of com.mongodb.client.MongoCollection class is used.

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.model.Updates;
import java.util.Iterator;
© Edunet Foundation. All rights reserved .343
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class UpdatingDocuments {

public static void main( String args[] ) {

// Creating a Mongo client


MongoClient mongo = new MongoClient( "localhost" , 27017 );

// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");

// Accessing the database


MongoDatabase database = mongo.getDatabase("myDb");
// Retrieving a collection
MongoCollection<Document> collection =
database.getCollection("sampleCollection");
System.out.println("Collection myCollection selected successfully");
collection.updateOne(Filters.eq("title", 1), Updates.set("likes", 150));
System.out.println("Document update successfully...");

// Retrieving the documents after updation


// Getting the iterable object
FindIterable<Document> iterDoc = collection.find();
int i = 1;
// Getting the iterator
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
i++;
}
}
}

Delete a Document

To delete a document from the collection, you need to use the deleteOne() method of
the com.mongodb.client.MongoCollection class.

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import java.util.Iterator;
import org.bson.Document;
import com.mongodb.MongoClient;

© Edunet Foundation. All rights reserved .344


import com.mongodb.MongoCredential;
public class DeletingDocuments {

public static void main( String args[] ) {

// Creating a Mongo client


MongoClient mongo = new MongoClient( "localhost" , 27017 );

// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");

// Accessing the database


MongoDatabase database = mongo.getDatabase("myDb");
// Retrieving a collection
MongoCollection<Document> collection =
database.getCollection("sampleCollection");
System.out.println("Collection sampleCollection selected successfully");
// Deleting the documents
collection.deleteOne(Filters.eq("title", "MongoDB"));
System.out.println("Document deleted successfully...");

// Retrieving the documents after updation


// Getting the iterable object
FindIterable<Document> iterDoc = collection.find();
int i = 1;
// Getting the iterator
Iterator it = iterDoc.iterator();
while (it.hasNext()) {
System.out.println(it.next());
i++;
}
}
}
Dropping a Collection

To drop a collection from a database, you need to use the drop() method of
the com.mongodb.client.MongoCollection class.

import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class DropingCollection {

public static void main( String args[] ) {


// Creating a Mongo client
MongoClient mongo = new MongoClient( "localhost" , 27017 );

© Edunet Foundation. All rights reserved .345


// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");

// Accessing the database


MongoDatabase database = mongo.getDatabase("myDb");

// Creating a collection
System.out.println("Collections created successfully");
// Retrieving a collection
MongoCollection<Document> collection =
database.getCollection("sampleCollection");
// Dropping a Collection
collection.drop();
System.out.println("Collection dropped successfully");
}
}

Listing All the Collections

To list all the collections in a database, you need to use


the listCollectionNames() method of
the com.mongodb.client.MongoDatabase class.

import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class ListOfCollection {

public static void main( String args[] ) {

// Creating a Mongo client


MongoClient mongo = new MongoClient( "localhost" , 27017 );
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");

// Accessing the database


MongoDatabase database = mongo.getDatabase("myDb");
System.out.println("Collection created successfully");
for (String name : database.listCollectionNames()) {
System.out.println(name);
}
}
}

© Edunet Foundation. All rights reserved .346


Chapter 4 – Modern Web
Development using ReactJS
© Edunet Foundation. All rights reserved .347
Learning Outcomes:
• Introduction to ReactJS
• Building React Native Application from Scratch

4.1 - Introduction to React JS

ReactJS is a declarative, efficient, and flexible JavaScript library for building reusable
UI components. It is an open-source, component-based front end library responsible
only for the view layer of the application. It was created by Jordan Walke, who was a
software engineer at Facebook. It was initially developed and maintained by
Facebook and was later used in its products like WhatsApp & Instagram. Facebook
developed ReactJS in 2011 in its newsfeed section, but it was released to the public
in the month of May 2013.

Today, most of the websites are built using MVC (model view controller) architecture.
In MVC architecture, React is the 'V' which stands for view, whereas the architecture
is provided by the Redux or Flux.

A ReactJS application is made up of multiple components, each component


responsible for outputting a small, reusable piece of HTML code. The components are
the heart of all React applications. These Components can be nested with other
components to allow complex applications to be built of simple building blocks.
ReactJS uses virtual DOM based mechanism to fill data in HTML DOM. The virtual
DOM works fast as it only changes individual DOM elements instead of reloading
complete DOM every time.

To create React app, we write React components that correspond to various elements.
We organize these components inside higher level components which define the
application structure. For example, we take a form that consists of many elements like
input fields, labels, or buttons. We can write each element of the form as React
components, and then we combine it into a higher-level component, i.e., the form
component itself. The form components would specify the structure of the form along
with elements inside of it.

Why learn ReactJS?

Today, many JavaScript frameworks are available in the market(like angular, node),
but still, React came into the market and gained popularity amongst them. The
previous frameworks follow the traditional data flow structure, which uses the DOM
© Edunet Foundation. All rights reserved .348
(Document Object Model). DOM is an object which is created by the browser each
time a web page is loaded. It dynamically adds or removes the data at the back end
and when any modifications were done, then each time a new DOM is created for the
same page. This repeated creation of DOM makes unnecessary memory wastage and
reduces the performance of the application.

Therefore, a new technology ReactJS framework invented which remove this


drawback. ReactJS allows you to divide your entire application into various
components. ReactJS still used the same traditional data flow, but it is not directly
operating on the browser's Document Object Model (DOM) immediately; instead, it
operates on a virtual DOM. It means rather than manipulating the document in a
browser after changes to our data, it resolves changes on a DOM built and run entirely
in memory. After the virtual DOM has been updated, React determines what changes
made to the actual browser's DOM. The React Virtual DOM exists entirely in memory
and is a representation of the web browser's DOM. Due to this, when we write a React
component, we did not write directly to the DOM; instead, we are writing virtual
components that react will turn into the DOM.

React is a front-end JavaScript library developed by Facebook. It is an open-source


JavaScript framework. It is used to build web and mobile applications. It powers the
most popular social media sites such as Facebook and Instagram. Currently, it is the
most popular developer’s choice for creating JavaScript libraries.

React encourages on creating reusable components. It offers a simple model and


provides better performance. It has a strong client base and a large community. It has
very proper documentation. It can also render the server side code using Node. It
implements the one-way reactive data flow. Hence, it is way beyond the traditional
way of data binding.

Features: Here is a list of impressive features ReactJS possess.

o React Native:

React includes the react libraries. They provide the react architecture to the native
applications such as Android and iOS.

© Edunet Foundation. All rights reserved .349


o Components:

React revolves around the elements. Everything here is a component. This practice
helps in maintaining the code while working on complex projects.

o JSX:

JSX is a JavaScript which uses the HTML tags and syntax to render the components.

It is then processed into the JavaScript function calls of this framework.

o One-Way Reactive Data Flow and Flux:

Flux is a pattern that keeps your data flow unidirectional. React follows the one-way
data flow to process your code.

o Virtual DOM (Document Object Model):

This is a unique feature of React. React creates a data structure which is stored in
internal memory. It is stored as cache. This feature enables the natural rendering of
the page and components.

o License:

React is a licensed product of Facebook Inc. Everything is licensed under its parent
company.

Why choose ReactJS?

As new technologies arise, there is always fierce competition in terms of choices.


Today, you can find an ample number of open-source platforms that help you creating
the front-end web and mobile applications. However, Angular is also a popular choice
for creating a single page and dynamic web applications. However, the question
remains the same – Why React over other JavaScript frameworks?

Let us take a look at the benefits of React over other competitive technologies or
frameworks. Today, developers find it challenging to focus on various trending

Disclaimer: The content is curated for educational purposes only.


© Edunet Foundation. All rights reserved.
technologies. There is always a risk of choosing the proper longtime technology as
that always helps. So, if you are planning to add a new feather to your technology hat,
React should be on the list.

Here’s why it is the best choice.

o Easy to Learn:

In technology, anything easy to learn and understand is always easy to implement.


Any developer can easily understand the syntax and components of React. You
should have a basic knowledge of HTML, CSS, and JavaScript.

o Simple:

ReactJS is easy to learn and implement (only if you have a basic understanding of
JavaScript). It has a well-defined lifecycle. Everything is component based here. It is
simple in comparison to other frameworks.

o Native Approach:

React is known for its reusability. You can extensively use the code and that’s the plus
feature of React. You can create mobile applications on iOS, Android and also the
web applications.

o Data Binding:

React uses one-way data binding. Also, it is easier to debug ReactJS components. It
has one directional flow of data and it uses flux architecture.

o Performance:

ReactJS is fast and secured. Also, it has not much of the performance issues. It does
not offer any built-in container for dependency injection.

© Edunet Foundation. All rights reserved .351


o Testability:

ReactJS applications are easily testable. You can easily set triggers, events, functions
and debug the code. You can easily debug the code.

Which Popular Sites Use ReactJS?


o Facebook:

The Facebook webpage is designed with React. React Native is a version of React. It
is responsible for displaying the Android and iOS native components. The Facebook
mobile app uses React native. Thus, partially, Facebook uses ReactJS.

o Instagram:

ReactJS is extensively used within Instagram. There are numerous features such as
the Google Maps APIs, geo locations, hashtags. The Instagram API is really
impressive.

o WhatsApp:

WhatsApp uses ReactJS for building web user interfaces from Facebook. The newly
launched WhatsApp web uses ReactJS and other frameworks.

o Yahoo! Mail:

Undoubtedly, Yahoo! Mail also uses to React. The products owned by Facebook
wholly or partially use ReactJS.

o Dropbox:

Dropbox has started using ReactJS for a year now. It effectively uses the components
and resources. The effective cloud storage services and backup solutions have been
designed with the help of ReactJS.

© Edunet Foundation. All rights reserved .352


Mostly every application you use in your daily life uses ReactJS. Also, other popular
sites such as the New York Times, Codecademy also use ReactJS.

Thus, this favorite JavaScript library has taken over the market due to its impressive
and easy to use features. So, when it comes to developing an app with a perfect user
interface and experience, ReactJS stands out to be the best choice.

© Edunet Foundation. All rights reserved .353


Getting started with ReactJS

React Environment Setup


In this section, we will learn how to set up an environment for the successful
development of ReactJS application.

o Pre-requisite for ReactJS


1. NodeJS and NPM
2. React and React DOM
3. Webpack
4. Babel

o Ways to install ReactJS

There are two ways to set up an environment for successful ReactJS application. They are given
below.

1. Using the npm command


2. Using the create-react-app command – CRA TOOL

2. Using the create-react-app command

The Create React App is maintained by Facebook and can works on any platform, for example,
macOS, Windows, Linux, etc. To create a React Project using create-react-app, you need to have
installed the following things in your system.

1. Node version >= 8.10

2. NPM version >= 5.6

Let us check the current version of Node and NPM in the system.
Run the following command to check the Node version in the command prompt.
$ node -v
Run the following command to check the NPM version in the command prompt.
$ npm -v

Installation

Here, we are going to learn how we can install React using CRA tool. For this, we need to follow
the steps as given below.

Install React

We can install React using npm package manager by using the following command.

© Edunet Foundation. All rights reserved .354


There is no need to worry about the complexity of React installation. The create-react-app npm
package manager will manage everything, which needed for React project.

C:\Users\vani> npm install -g create-react-app

Create a new React project

Once the React installation is successful, we can create a new React project using create-react-
app command. Here, I choose "Firstreactjs" name for my project.

C:\Users\vani> create-react-app firstreactjs

We can combine the above two steps in a single command using npx. The npx
is a package runner tool which comes with npm 5.2 and above version.

C:\Users\vani> npx create-react-app firstreactjs

The above command will take some time to install the React and create a new project with the
name " firstreactjs."

After successful creation of React project, Now, we need to start the server so that we can access
the application on the browser. Type the following command in the terminal window.

$ cd firstreactjs

$ npm start

NPM is a package manager which starts the server and access the application at default
server http://localhost:3000.

Next, open the project on Code editor. Here, I am using Visual Studio Code.

In React application, there are several files and folders in the root directory. Some of them are as
follows:

1. node_modules: It contains the React library and any other third party libraries needed.

2. public: It holds the public assets of the application. It contains the index.html where React
will mount the application by default on the <div id="root"></div> element.

3. src: It contains the App.css, App.js, App.test.js, index.css, index.js, and serviceWorker.js
files. Here, the App.js file always responsible for displaying the output screen in React.

4. package-lock.json: It is generated automatically for any operations where npm package


modifies either the node_modules tree or package.json. It cannot be published. It will be
ignored if it finds any other place rather than the top-level package.

© Edunet Foundation. All rights reserved .355


5. package.json: It holds various metadata required for the project. It gives information to
npm, which allows to identify the project as well as handle the projects dependencies.

6. README.md: It provides the documentation to read about React topics.

React Environment Setup

Now, open the src >> App.js file and make changes which you want to display on the screen.
After making desired changes, save the file. As soon as we save the file, Webpack recompiles the
code, and the page will refresh automatically, and changes are reflected on the browser screen.
Now, we can create as many components as we want, import the newly created component inside
the App.js file and that file will be included in our main index.html file after compiling by Webpack.

Next, if we want to make the project for the production mode, type the following command. This
command will generate the production build, which is best optimized.

$ npm build

React Components

Earlier, the developers write more than thousands of lines of code for developing a single
page application. These applications follow the traditional DOM structure, and making
changes in them was a very challenging task. If any mistake found, it manually searches
the entire application and update accordingly. The component-based approach was
introduced to overcome an issue. In this approach, the entire application is divided into a
small logical group of code, which is known as components.

A Component is considered as the core building blocks of a React application. It


makes the task of building UIs much easier. Each component exists in the same
space, but they work independently from one another and merge all in a parent
component, which will be the final UI of your application.

Every React component have their own structure, methods as well as APIs. They can
be reusable as per your need. For better understanding, consider the entire UI as a
tree. Here, the root is the starting component, and each of the other pieces becomes
branches, which are further divided into sub-branches

In ReactJS, we have mainly two types of components.

1. Functional Components

© Edunet Foundation. All rights reserved .356


2. Class Components

Functional Components

• In React, function components are a way to write components that only contain a render()
method and don't have their own state.
• They are simply JavaScript functions that may or may not receive data as parameters.
• We can create a function that takes props(properties) as input and returns what should
be rendered.

function WelcomeMessage(props) {

return <h1>Welcome , {props.name}</h1>;

The functional component is also known as a stateless component because they do not hold
or manage state. It can be explained in the below example.

import logo from './logo.svg';


import './App.css';
import ReactDOM from 'react-dom'
import React, {component} from 'react'

function Welcome(props) {
return <h2> Welcome to the Edunet Foundation : {props.name}</h2>;
}

function App() {
return (
<div>
<Welcome name="Kiara" />
<Welcome name="Yuuvraj" />
<Welcome name="Zara" />
</div>
);
}

ReactDOM.render(
<App />,
© Edunet Foundation. All rights reserved .357
document.getElementById('root')
);
export default App;

Class Components

• Class components are more complex than functional components.


• It requires you to extend from React. Component and create a render function which
returns a React element.
• You can pass data from one class to other class components.
• You can create a class by defining a class that extends Component and has a render
function. Valid class component is shown in the below example.

class MyComponent extends React.Component {


render() {
return (
<div>This is main component.</div>
);
}
}

The class component is also known as a statefull component because they can hold or manage
local state. It can be explained in the below example.

import React, { Component } from 'react';


class App extends React.Component {
constructor() {
super();
this.state = {
data:
[
© Edunet Foundation. All rights reserved .358
{
"name":"Abhishek"
},
{
"name":"Saharsh"
},
{
"name":"Ajay"
}
]
}
}
render() {
return (
<div>
<StudentName/>
<ul>
{this.state.data.map((item) => <List data = {item} />)}
</ul>
</div>
);
}
}
class StudentName extends React.Component {
render() {
return (
<div>
<h1>Student Name Detail</h1>
</div>
);
}
}
class List extends React.Component {
render() {
return (
<ul>

© Edunet Foundation. All rights reserved .359


<li>{this.props.data.name}</li>
</ul>
);
}
}
export default App;

4.2 Building React Native Application from Scratch

© Edunet Foundation. All rights reserved .360


There are so many ways we can build React apps. One way is to build React with
NodeJS or Java and another way is to build the React and serve that static content
with NGINX web server. With Java we have to deal with the server code as well, for
example, you need to load index.html page with java.

In this section, we will see the details and implementation with Java. We will go
through step by step with an example.

➢ Introduction
➢ Prerequisites
➢ Example Project
➢ How To Build and Develop The Project
➢ How To Build For Production
➢ Summary
➢ Conclusion

4.2.1 Introduction

React is a javascript library for building web apps and it doesn’t load itself in the
browser. We need some kind of mechanism that loads the index.html (single page) of
React with all the dependencies(CSS and js files) in the browser. In this case, we are
using java as the webserver which loads React assets and accepts any API calls from
the React app.

If you look at the above diagram all the web requests without the /api will go to React
router. All the paths that contain /api will be handled by the Apache Tomcat container.

© Edunet Foundation. All rights reserved .361


4.2.2 Prerequisites

There are some prerequisites for this article. You need to have java installed on your laptop

and how http works. If you want to practice and run this on your laptop you need to have these

on your laptop.

➢ Java

➢ Create React App

➢ VSCode

➢ Eclipse IDE

➢ react-bootstrap

➢ Maven

4.2.3 Example Project

This is a simple project which demonstrates developing and running React application with

Java. We have a simple app in which we can add users, count, and display them at the side,

and retrieve them whenever you want.

© Edunet Foundation. All rights reserved .362


As you add users we are making an API call to the Java server to store them and get
the same data from the server when we retrieve them. You can see network calls in
the following video.

4.2.4 How To Build and Develop The Project

Usually, the way you develop and the way you build and run in production are completely

different. Thatswhy, I would like to define two phases: Development phase and Production

phase.

In the development phase, we run the java server and the React app on completely different

ports. It’s easier and faster to develop that way. If you look at the following diagram the React

app is running on port 3000 with the help of a webpack dev server and the java server is running

on port 8080.

© Edunet Foundation. All rights reserved .363


Development Environment
Project Structure
Let’s understand the project structure for this project. We need to have two completely
different folders for java and react. It’s always best practice to have completely dif ferent
folders for each one. In this way, you will have a clean architecture or any other
problems regarding merging any files.

Project Structure

© Edunet Foundation. All rights reserved .364


If you look at the above project structure, all the React app resides under the src/main/ui folder

and Java code resides under the src/main/java folder. All the resources are under the

folder /src/main/resources such as properties, static assets, etc

Java API

We use spring boot and a lot of other tools such as Spring Devtools, Spring Actuator, etc under

the spring umbrella. Nowadays almost every application has spring boot and it is an open-

source Java-based framework used to create a micro Service. It is developed by the Pivotal

Team and is used to build stand-alone and production-ready spring applications. We start with

Spring initializr and select all the dependencies and generate the zip file.

© Edunet Foundation. All rights reserved .365


Spring Initializer

Once you import the zip file in the eclipse or any other IDE as a Maven project you can see all

the dependencies in the pom.xml. Below is the dependencies section of pom.xml.

pom.xml

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

<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

© Edunet Foundation. All rights reserved .366


<version>2.2.6.RELEASE</version>

<relativePath/> <!-- lookup parent from repository -->

</parent>

<groupId>com.bbtutorials</groupId>

<artifactId>users</artifactId>

<version>0.0.2-SNAPSHOT</version>

<name>users</name>

<description>Demo project for Spring Boot</description>

<properties>

<java.version>1.11</java.version>

</properties>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-actuator</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

<dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId>

<scope>runtime</scope>

<version>1.4.199</version>
© Edunet Foundation. All rights reserved .367
</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-data-rest</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-hateoas</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.data</groupId>

<artifactId>spring-data-rest-hal-browser</artifactId>

</dependency>

<!-- QueryDSL -->

<dependency>

<groupId>com.querydsl</groupId>

<artifactId>querydsl-apt</artifactId>

</dependency>

<dependency>

<groupId>com.querydsl</groupId>

<artifactId>querydsl-jpa</artifactId>

</dependency>

© Edunet Foundation. All rights reserved .368


<dependency>

<groupId>com.h2database</groupId>

<artifactId>h2</artifactId>

<scope>runtime</scope>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-devtools</artifactId>

<scope>runtime</scope>

<optional>true</optional>

</dependency>

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<optional>true</optional>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

<exclusions>

<exclusion>

<groupId>org.junit.vintage</groupId>

<artifactId>junit-vintage-engine</artifactId>

</exclusion>

</exclusions>
© Edunet Foundation. All rights reserved .369
</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

<plugin>

<groupId>com.mysema.maven</groupId>

<artifactId>apt-maven-plugin</artifactId>

<version>1.1.3</version>

<executions>

<execution>

<goals>

<goal>process</goal>

</goals>

<configuration>

<outputDirectory>target/generated-
sources/java</outputDirectory>

<processor>com.querydsl.apt.jpa.JPAAnnotationProcessor</processor>

</configuration>

</execution>

</executions>

</plugin>

</plugins>
© Edunet Foundation. All rights reserved .370
</build>

</project>

Here are the spring boot file and the controller with two routes one with a GET request
and another is POST request.

package com.bbtutorials.users;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class UsersApplication {

public static void main(String[] args) {

SpringApplication.run(UsersApplication.class, args);

controller and the main file

UsersController.java

package com.bbtutorials.users.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.http.ResponseEntity;

© Edunet Foundation. All rights reserved .371


import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import com.bbtutorials.users.entity.Users;

import com.bbtutorials.users.links.UserLinks;

import com.bbtutorials.users.service.UsersService;

import lombok.extern.slf4j.Slf4j;

@Slf4j

@RestController

@RequestMapping("/api/")

public class UsersController {

@Autowired

UsersService usersService;

@GetMapping(path = UserLinks.LIST_USERS)

public ResponseEntity<?> listUsers() {

log.info("UsersController: list users");

List<Users> resource = usersService.getUsers();

return ResponseEntity.ok(resource);

© Edunet Foundation. All rights reserved .372


@PostMapping(path = UserLinks.ADD_USER)

public ResponseEntity<?> saveUser(@RequestBody Users user) {

log.info("UsersController: list users");

Users resource = usersService.saveUser(user);

return ResponseEntity.ok(resource);

Configure H2 Database

This H2 Database is for development only. When you build this project for production you can

replace it with any database of your choice. You can run this database standalone without your

application. We will see how we can configure with spring boot.

First, we need to add some properties to application.properties file under /src/main/resources


application.properties

spring.datasource.url=jdbc:h2:mem:testdb

spring.datasource.driverClassName=org.h2.Driver

spring.datasource.username=sa

spring.datasource.password=password

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
© Edunet Foundation. All rights reserved .373
spring.h2.console.enabled=true

Second, add the below SQL file under the same location.

data.sql

DROP TABLE IF EXISTS users;

CREATE TABLE users (

id INT PRIMARY KEY,

FIRST_NAME VARCHAR(250) NOT NULL,

LAST_NAME VARCHAR(250) NOT NULL,

EMAIL VARCHAR(250) NOT NULL

);

INSERT INTO users (ID, FIRST_NAME, LAST_NAME, EMAIL) VALUES

(1, 'first', 'last 1', 'abc1@gmail.com'),

(2, 'first', 'last 2', 'abc2@gmail.com'),

(3, 'first', 'last 3', 'abc3@gmail.com');

Third, start the application, and spring boot creates this table on startup. Once the
application is started you can go to this URL http://localhost:8080/h2-console and
access the database on the web browser. Make sure you have the same JDBC URL,
username, and password as in the properties file.

© Edunet Foundation. All rights reserved .374


h2 in-memory database

Let’s add the repository files, service files, and entity classes as below and start the spring boot

app.

Users.java

package com.bbtutorials.users.entity;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.validation.constraints.NotNull;

import lombok.Data;

@Entity

@Data

© Edunet Foundation. All rights reserved .375


public class Users {

@Id

@Column

private long id;

@Column

@NotNull(message="{NotNull.User.firstName}")

private String firstName;

@Column

@NotNull(message="{NotNull.User.lastName}")

private String lastName;

@Column

@NotNull(message="{NotNull.User.email}")

private String email;

UsersRepository.java

package com.bbtutorials.users.repository;

import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

import org.springframework.data.querydsl.QuerydslPredicateExecutor;

import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import com.bbtutorials.users.entity.Users;

@RepositoryRestResource()

public interface UsersRepository extends JpaRepository<Users, Integer>,


JpaSpecificationExecutor<Users>, QuerydslPredicateExecutor<Users> {}

© Edunet Foundation. All rights reserved .376


UsersService.java

package com.bbtutorials.users.service;

import java.util.List;

import java.util.Random;

import org.springframework.stereotype.Component;

import com.bbtutorials.users.entity.Users;

import com.bbtutorials.users.repository.UsersRepository;

@Component

public class UsersService {

private UsersRepository usersRepository;

public UsersService(UsersRepository usersRepository) {

this.usersRepository = usersRepository;

public List<Users> getUsers() {

return usersRepository.findAll();

public Users saveUser(Users users) {

users.setId(new Random().nextInt());

return usersRepository.save(users);

© Edunet Foundation. All rights reserved .377


repository, service, and entity files

You can start the application in two ways: you can right-click on the UsersApplication
and run it as a java application or do the following steps.

// mvn install
mvn clean install

// run the app


java -jar target/<repo>.war

Starting the Spring Boot App

Finally, you can list all the users with this endpoint http://localhost:8080/api/users.

© Edunet Foundation. All rights reserved .378


Java code running on port 8080

React App

Now the java code is running on port 8080. Now it’s time to look at the React app. The entire

React app is under the folder src/main/ui. You can create with this command npx create-

react-app ui.

Let’s see some important files here. Here is the service file which calls Java API.

UserService.js

export async function getAllUsers() {

const response = await fetch('/api/users');

return await response.json();

export async function createUser(data) {

const response = await fetch(`/api/user`, {

method: 'POST',
© Edunet Foundation. All rights reserved .379
headers: {'Content-Type': 'application/json'},

body: JSON.stringify(data)

})

return await response.json();

Here is the app component which subscribes to these calls and gets the data from the
API.

App.js

import React, { Component } from 'react';


import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css';
import { Header } from './components/Header'
import { Users } from './components/Users'
import { DisplayBoard } from './components/DisplayBoard'
import CreateUser from './components/CreateUser'
import { getAllUsers, createUser } from './services/UserService'

class App extends Component {

state = {
user: {},
users: [],
numberOfUsers: 0
}

createUser = (e) => {


createUser(this.state.user)
.then(response => {
console.log(response);
this.setState({numberOfUsers: this.state.numberOfUsers + 1})
});
this.setState({user: {}})
}

getAllUsers = () => {
getAllUsers()
.then(users => {
console.log(users)
this.setState({users: users, numberOfUsers: users.length})
});
}

onChangeForm = (e) => {


let user = this.state.user

© Edunet Foundation. All rights reserved .380


if (e.target.name === 'firstname') {
user.firstName = e.target.value;
} else if (e.target.name === 'lastname') {
user.lastName = e.target.value;
} else if (e.target.name === 'email') {
user.email = e.target.value;
}
this.setState({user})
}

render() {

return (
<div className="App">
<Header></Header>
<div className="container mrgnbtm">
<div className="row">
<div className="col-md-8">
<CreateUser
user={this.state.user}
onChangeForm={this.onChangeForm}
createUser={this.createUser}
>
</CreateUser>
</div>
<div className="col-md-4">
<DisplayBoard
numberOfUsers={this.state.numberOfUsers}
getAllUsers={this.getAllUsers}
>
</DisplayBoard>
</div>
</div>
</div>
<div className="row mrgnbtm">
<Users users={this.state.users}></Users>
</div>
</div>
);
}
}

export default App;

Interaction between Angular and Java API

In the development phase, the React app is running on port 3000 with the help of a create-

react-app and Java API running on port 8080.

© Edunet Foundation. All rights reserved .381


There should be some interaction between these two. We can proxy all the API calls to Java

API. Create-react-app provides some inbuilt functionality and to tell the development server to

proxy any unknown requests to your API server in development, add a proxy field to

your package.json of the React. Have a look at the below package.json below. Remember

you need to put this in the React UI package.json file.

package.json

{
"name": "my-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"bootstrap": "^4.5.0",
"react": "^16.13.1",
"react-bootstrap": "^1.0.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.1"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:8080",
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

With this in place, all the calls start with /api will be redirected to http://localhost:8080 where
the Java API running.

© Edunet Foundation. All rights reserved .382


Once this is configured, you can run the React app on port 3000 and java API on 8080 still
make them work together.

// java API (Terminal 1)


mvn clean install
java -jar target/<war file name>// React app (Terminal 2)

cd src/mamin/ui
npm start

Chapter 5 – Web Development using


Spring Framework 2022
© Edunet Foundation. All rights reserved .383
Learning Outcomes:
• Web Development using Spring Framework
o Understanding MVC
o Maven Projects & Dependencies (pom.xml)
o Working with annotations
o Database CRUD operations using DB classes
• Integrating web template UI with Spring
o Creating responsive UI using Bootstrap
o Integrating Spring with all CRUD operations

5.1 – Understanding Spring MVC

5.1.1 What is MVC

The Model-View-Controller (MVC) is an architectural pattern that separates an


application into three main logical components: the model, the view, and the controller.
Each of these components are built to handle specific development aspects of an
application. MVC is one of the most frequently used industry-standard web
development frameworks to create scalable and extensible projects.

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.

View: The View component is used for all the UI logic of the application. For example,
the Customer view will include all the UI components such as text boxes, dropdowns,
etc. that the final user interacts with.

Controller: Controllers act as an interface between Model and View components to


process all the business logic and incoming requests, manipulate data using the Model
component and interact with the Views to render the final output.
© Edunet Foundation. All rights reserved .384
Image: Model-View-Controller
Reference: https://www.tutorialspoint.com/mvc_framework/mvc_framework_introduction.htm

5.1.1 Spring MVC

A Spring MVC is a Java framework which is used to build web applications. It


follows the Model-View-Controller design pattern. It implements all the basic features
of a core spring framework like Inversion of Control, Dependency Injection.

A Spring MVC provides an elegant solution to use MVC in spring framework by the
help of Dispatcher Servlet. Here, Dispatcher Servlet is a class that receives the
incoming request and maps it to the right resource such as controllers, models, and
views.

o Model - A model contains the data of the application. A data can be a single
object or a collection of objects.

o Controller - A controller contains the business logic of an application. Here, the


@Controller annotation is used to mark the class as the controller.

o View - A view represents the provided information in a particular format.


Generally, JSP+JSTL is used to create a view page. Although spring also
supports other view technologies such as Apache Velocity, Thymeleaf and
FreeMarker.

© Edunet Foundation. All rights reserved .385


Image: Spring Web Model-View-Controller
Reference: https://www.javatpoint.com/spring-mvc-tutorial

o Front Controller - In Spring Web MVC, the DispatcherServlet class works as


the front controller. It is responsible to manage the flow of the Spring MVC
application.

Understanding the flow of Spring Web MVC

Image: Architecture of Spring Web MVC


Reference: https://www.javatpoint.com/spring-mvc-tutorial

© Edunet Foundation. All rights reserved .386


o As displayed in the figure, all the incoming request is intercepted by the
DispatcherServlet that works as the front controller.
o The DispatcherServlet gets an entry of handler mapping from the XML file and
forwards the request to the controller.
o The controller returns an object of Model And View.

o The DispatcherServlet checks the entry of view resolver in the XML fil e and
invokes the specified view component.

Dispatcher Servlet

DispatcherServlet acts as the front controller in the Spring’s MVC module. All the user
requests are handled by this servlet. Since this is like any other servlet, it must be
configured in the application’s web deployment descriptor file i.e. web.xml.

<web-app xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID"
version="2.5"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Library</display-name>
<servlet>
<servlet-name>myLibraryAppFrontController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myLibraryAppFrontController</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>

© Edunet Foundation. All rights reserved .387


<welcome-file>welcome.htm</welcome-file>
</welcome-file-list>
</web-app>
We have named the servlet as “myLibraryAppFrontController”. The URI pattern in the
servlet mapping section is “*.htm”. Thus, all the requests matching the URI pattern will
be handled by myLibraryAppFrontController.

Spring Application Context

Default Application context file

By default the dispatcher servlet loads the Spring application context from XML file
with name [servlet name]-servlet.xml. Thus, when our
servlet myLibraryAppFrontController is loaded by the container, it will load the Spring
application context from XML file “/WEB-INF/myLibraryAppFrontController-
servlet.xml”.

User defined application context file

We can override the name and location of the default XML file by providing the
initialization parameters to the dispatcher servlet. The name of the initialization
parameter is contextConfigLocation. The parameter value specifies the name and
location of the application context which needs to be loaded by the container.
<servlet>
<servlet-name>myLibraryAppFrontController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:libraryAppContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

© Edunet Foundation. All rights reserved .388


In the above configuration of myLibraryAppFrontController, when the container
initializes the dispatcher servlet, it will load the Spring application context from XML
file “classpath:libraryAppContext.xml” instead of “/WEB-
INF/myLibraryAppFrontController-servlet.xml”.

Multiple application context files

It is a good practice to split the application into multiple logical units and have multiple
application context file. Thus, on servlet initialization we need to load all these
application context files. It is possible to load the Spring application context from
multiple XML file as shown below:
<servlet>
<servlet-name>myLibraryAppFrontController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:libraryAppContext.xml
classpath:books.xml
classpath:chapters.xml
classpath:titles.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
In the above servlet configuration, we have provided multiple XML files as initialization
parameter value. All these XML files will be loaded by the container on initialization of
the servlet myLibraryAppFrontController.

Spring Handler mappings

As the name specifies, the handler mapping maps the request with the corresponding
request handler (in fact handler execution chain). When a request comes to Spring’s

© Edunet Foundation. All rights reserved .389


dispatcher servlet, it hands over the request to the handler mapping. Handler mapping
then inspects the request and identifies the appropriate handler execution chain and
delivers it to dispatcher servlet. The handler execution chain contains handler that
matches the incoming request and optionally contains the list of interceptors that are
applied for the request. Dispatcher servlet then executes the handlers and any
associated handler interceptor.
There are number of implementation of hander mapping provided by Spring’s MVC
module. Some of these are described below. All the handler mappings classes
implement the interface org.springframework.web.servlet.HandlerMapping.

BeanNameUrlHandlerMapping

This implementation of handler mapping matches the URL of the incoming request
with the name of the controller beans. The matching bean is then used as the controller
for the request. This is the default handler mapping used by the Spring’s MVC module
i.e. in case the dispatcher servlet does not find any handler mapping bean defined in
Spring’s application context then the dispatcher servlet uses
BeanNameUrlHandlerMapping.

Let us assume that we have three web pages in our application. The URL of the pages
are:
1. http://servername:portnumber/ApplicationContext/welcome.htm
2. http://servername:portnumber/ApplicationContext/listBooks.htm
3. http://servername:portnumber/ApplicationContext/displayBookContent.htm
The controllers which will perform the business logic to fulfil the request made to the
above pages are:
1. net.codejava.frameorks.spring.mvc.controller.WelcomeController
2. net.codejava.frameorks.spring.mvc.controller.ListBooksController
3. net.codejava.frameorks.spring.mvc.controller.DisplayBookTOCController
Thus, we need to define the controllers in Spring’s application context file such that
the name of the controller matches the URL of the request. The controller beans in
XML configuration file will look as below.

© Edunet Foundation. All rights reserved .390


<bean
name="/welcome.htm"
class="net.codejava.frameorks.spring.mvc.controller.WelcomeController" />
<bean
name="/listBooks.htm"
class="net.codejava.frameorks.spring.mvc.controller.ListBooksController"/>
<bean
name="/displayBookTOC.htm"
class="net.codejava.frameorks.spring.mvc.controller.DisplayBookTOCController"/
>
Note that we need not define the BeanNameUrlHandlerMapping in Spring’s
application context file because this is the default one being used.

SimpleUrlHandlerMapping

The BeanNameUrlHandlerMapping puts a restriction on the name of the controller


beans that they should match the URL of the incoming
request. SimpleUrlHandlerMapping removes this restriction and maps the controller
beans to request URL using a property “mappings”.

<bean
id="myHandlerMapping"
class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/welcome.htm">welcomeController</prop>
<prop key="/listBooks.htm">listBooksController</prop>
<prop key="/displayBookTOC.htm">displayBookTOCController</prop>
</props>
</property>

© Edunet Foundation. All rights reserved .391


</bean>
<bean name="welcomeController"
class="net.codejava.frameorks.spring.mvc.controller.WelcomeController"/>
<bean name="listBooksController"
class="net.codejava.frameorks.spring.mvc.controller.ListBooksController"/>
<bean name="displayBookTOCController"
class="net.codejava.frameorks.spring.mvc.controller.DisplayBookTOCController"/>

The key of the <prop> element is the URL pattern of the incoming request. The value
of the <prop> element is the name of the controller bean which will perform the
business logic to fulfil the request. SimpleUrlHandlerMapping is one of the most
commonly used handler mapping.

Spring Controllers

Controller is the actual piece of code which performs the business logic to fulfil the
incoming request. Controllers may delegate this responsibility to further service
objects as well. All the user defined controllers must either implement the interface
Controller or extend the abstract class AbstractController. The user defined
controllers need to override the method handleRequestInternal.
The
method handleRequestInternal takes HttpServletRequest and HTTPServletRespons
e aiis the input and returns an object of ModelAndView.

In the Spring’s application context file, we have defined a user defined custom
controller named welcomeController. As per the SimpleUrlHandlerMApping, all the
requests matching URL pattern /welcome.htm will be handled by this controller.
The WelcomeController must extend AbstractController and provide the definition of
method handleRequestInternal. Thus WelcomeController looks as below:

public class WelcomeController extends AbstractController {


@Override
protected ModelAndView handleRequestInternal(HttpServletRequest arg0,

© Edunet Foundation. All rights reserved .392


HttpServletResponse arg1) throws Exception {

return new ModelAndView("welcome");


}
}

MultiActionController

In any medium to large size enterprise web application, there are quite a number of
web pages. To fulfil the request for those web pages we need to define multiple
controllers, one each for a web page. And sometimes the business logic is executed
to fulfil those requests is similar. This creates redundancy of business logic in multiple
controllers and makes the maintenance difficult.

Spring’s MVC module provides a way to deal with this scenario by providing a single
controller fulfilling the request for multiple web pages. Such a controller is known
as Multi Action Controller. A user defined multi action controller should extend the
class org.springframework.web.servlet.mvc.multiaction.MultiActionController. Each
method in user defined multi action controller contains the logic to fulfil the request for
a particular web page.

By default, the URL of the incoming request (excluding the extension part) will be
matched against the name of the method in multi action controller and the matching
method will perform the business logic for the incoming request. So for the incoming
request with URL /welcome.htm, the method name containing the business logic will
be welcome.

Let us assume that the multi action controller in our application


is MyMultiActionController which fulfils the request for the three web pages with
URL /welcome.htm, /listBooks.htm and /displayBookTOC.htm. Thus, the class should
extend the MultiActionController and have three methods with
name welcome, listBooks and displayBookTOC. The controller will look as below:

© Edunet Foundation. All rights reserved .393


public class MyMultiActionController extends MultiActionController {
// This method will server all the request matching URL pattern /welcome.htm
public ModelAndView welcome(HttpServletRequest request,
HttpServletResponse response) {
// Business logic goes here
// Return an object of ModelAndView to DispatcherServlet
return new ModelAndView("Welcome");
}
// This method will server all the request matching URL pattern
// /listBooks.htm
public ModelAndView listBooks(HttpServletRequest request,
HttpServletResponse response) {
// Business logic goes here
// Return an object of ModelAndView to DispatcherServlet
return new ModelAndView("listBooks");
}
// This method will server all the request matching URL pattern
// /displayBookTOC.htm
public ModelAndView displayBookTOC(HttpServletRequest request,
HttpServletResponse response) {
// Business logic goes here
// Return an object of ModelAndView to DispatcherServlet
return new ModelAndView("displayBookTOC");
}
}

MethodNameResolver

Spring MVC provides a number of other method name resolvers that helps to resolve
the multi action controller method name based on the request. Some of these are:

© Edunet Foundation. All rights reserved .394


ParameterMethodNameResolver

A particular parameter in the request contains the method name. The name of the
parameter is defined in the Spring’s application context file while
defining ParameterMethodNameResolver. In the example below, the
parameter controllerMethod in the request will determine the multi action controller
method which will be executed to fulfil the request.

<bean name="parameterMethodNameResolver"
class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodName
Resolver">
<property name="paramName">
<value>controllerMethod</value>
</property>
</bean>

Notes: The request for a particular web page should now contain an additional
parameter with name “controllerMethod” and value as the multi action controller
method name to be executed. The request URL will be as follow:
1. http://servername:portnumber/ProjectWebContext/welcome.htm?controllerMet
hod= handleWelcomePage
2. http://servername:portnumber/ProjectWebContext/listBooks.htm?controllerMe
thod= handleListBooksPage
3. http://servername:portnumber/ProjectWebContext/displayBookTOC.htm?contr
ollerMethod= handleDisplayBookTOCPage
In the above configuration, the request for URL /welcome.htm will be fulfilled by
method handleWelcomePage of multi action controller. Request for
URL /listBooks.htm will be fulfilled by method handleListBooksPage and request for
URL /displayBookTOC.htm will be fulfilled by method handleDisplayBookTOCPage.

PropertiesMethodNameResolver

© Edunet Foundation. All rights reserved .395


The name of method is determined from the list of pre-defined properties supplied to
the method name resolver in Spring’s application context file.
The PropertiesMethodNameResolver in Spring’s application context file will look as
below.

<bean name="propertiesMethodNameResolver"
class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodName
Resolver">
<property name="mappings">
<props>
<prop key="/welcome.htm">handleWelcomePage</prop>
<prop key="/listBooks.htm">handleListBooksPage</prop>
<prop key="/displayBookTOC.htm">handleDisplayBookTOCPage</prop>
</props>
</property>
</bean>

Again, in the above configuration, the request for URL /welcome.htm will be fulfilled by
method handleWelcomePage of multi action controller. Request for
URL /listBooks.htm will be fulfilled by method handleListBooksPage and request for
URL /displayBookTOC.htm will be fulfilled by method handleDisplayBookTOC.
We need to tell the multi action controller to use a particular method name resolver by
setting its property methodNameResolver. Thus the configuration of multi action
controller will look as below:
<bean name="myMultiActionController"
class="net.codejava.frameworks.spring.mvc.controller.MyMultiActionController">
<property name="methodNameResolver">
<ref bean="propertiesMethodNameResolver"/>
</property>
</bean>

ModelAndView

© Edunet Foundation. All rights reserved .396


Spring’s MVC module encapsulates the model object and the view object in a single
entity which is represented by the object of class ModelAndView. This object contains
the model object and view object or the logical name of the view. The model object is
the application data and the view is the object that renders the output to the user. The
controller returns an object of ModelAndView to the dispatcher servlet for further
processing.

ViewResolver

In case ModelAndView object contains the logical name of the view then
the DispatcherServlet needs resolving the view object based on its logical name. To
resolve the view object, DispatcherServlet take the help of ViewResolver. There are
number of implementation of view resolver provided by Spring. All the view resolvers
implement the interface org.springframework.web.servlet.ViewResolver.

InternalResourceViewResolver

It resolves the logical name of the view to an internal resource by prefixing the logical
view name with the resource path and suffixing it with the extension.
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix"value="/WEB-INF/jsp/" />
<property name="suffix"value=".jsp" />
</bean>

If the logical name of the view returned by the controller in ModelAndView object
is Welcome then the view which is shown to the user is /WEB-INF/jsp/Welcome.jsp

BeanNameViewResolver

It resolves the logical name of the view to the bean name which will render the output
to the user. The bean should be defined in the Spring app context file. So if the logical
name returned by the controller in ModelAndView object is Welcome then the bean

© Edunet Foundation. All rights reserved .397


with name Welcome defined in the application context will be responsible to render
the model to the user.

XMLFileViewResolver

This view resolver is the same as BeanNameViewResolver with only difference is that
instead of looking for the beans in Spring’s application context file it looks for beans
defined in a separate XML file (/WEB-INF/views.xml by default). The location and file
name can be overridden by providing a location property while defining
the XMLFileViewResolver.

<bean name="propertiesMethodNameResolver"
class="org.springframework.web.servlet.view.XMLFileViewResolver">
<propertyname="location">
<value>classpath:myViews.xml</value>
</property>
</bean>

ResourceBundleViewResolver

It resolves the logical name of the view to the actual view defined in the resource
bundle. This view resolver takes basename as the input which is the name of the
property file where views can be located.

<bean name="propertiesMethodNameResolver"
class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
<property name="basename">
<value>myViews</value>
</property>
</bean>

© Edunet Foundation. All rights reserved .398


So if the logical name returned by the controller in ModelAndView object
is Welcome then the view resolver will look for the property Welcome.class in
properties file myViews.properties (or myViews_en_US.properties depending upon
the user language and locale).

Advantages of Spring MVC Framework

Let's see some of the advantages of Spring MVC Framework: -

o Separate roles - The Spring MVC separates each role, where the model
object, controller, command object, view resolver, DispatcherServlet, validator,
etc. can be fulfilled by a specialized object.

o Light-weight - It uses light-weight servlet container to develop and deploy your


application.
o Powerful Configuration - It provides a robust configuration for both framework
and application classes that includes easy referencing across contexts, such
as from web controllers to business objects and validators.

o Rapid development - The Spring MVC facilitates fast and parallel


development.
o Reusable business code - Instead of creating new objects, it allows us to use
the existing business objects.
o Easy to test - In Spring, generally we create JavaBeans classes that enable
you to inject test data using the setter methods.

o Flexible Mapping - It provides the specific annotations that easily redirect the
page.

5.1.1 - Maven

Maven is a powerful project management tool that is based on POM (project object
model). It is used for projects build, dependency and documentation.

© Edunet Foundation. All rights reserved .399


It simplifies the build process like ANT. But it is too much advanced than ANT.

Current version of Maven is 3.

Understanding the problem without Maven

There are many problems that we face during the project development. They are
discussed below:

1) Adding set of Jars in each project: In case of struts, spring, hibernate


frameworks, we need to add set of jar files in each project. It must include all the
dependencies of jars also.

2) Creating the right project structure: We must create the right project structure in
servlet, struts etc, otherwise it will not be executed.

3) Building and Deploying the project: We must have to build and deploy the project
so that it may work.

What it does?

Maven simplifies the above-mentioned problems. It does mainly following tasks.

1. It makes a project easy to build

2. It provides uniform build process (maven project can be shared by all the maven
projects)

3. It provides project information (log document, cross referenced sources,


mailing list, dependency list, unit test reports etc.)

4. It is easy to migrate for new features of Maven

Apache Maven helps to manage

o Builds

o Documentation

o Reporing

© Edunet Foundation. All rights reserved .400


o SCMs

o Releases

o Distribution

What is Build Tool

A build tool takes care of everything for building a process. It does following:

o Generates source code (if auto-generated code is used)

o Generates documentation from source code

o Compiles source code

o Packages compiled code into JAR of ZIP file

o Installs the packaged code in local repository, server repository, or central


repository

How to install Maven on windows

You can download and install maven on windows, linux and MAC OS platforms. Here,
we are going to learn how to install maven on windows OS.

To install maven on windows, you need to perform following steps:

1. Download maven and extract it

2. Add JAVA_HOME and MAVEN_HOME in environment variable

3. Add maven path in environment variable

4. Verify Maven

1) Download Maven

To install maven on windows, you need to download apache maven first.

© Edunet Foundation. All rights reserved .401


Download Maven latest Maven software from Download latest version of Maven

For example: apache-maven-3.1.1-bin.zip

Extract it. Now it will look like this:

2) Add MAVEN_HOME in environment variable

Right click on MyComputer -> properties -> Advanced System Settings -


> Environment variables -> click new button

Now add MAVEN_HOME in variable name and path of maven in variable value. It
must be the home directory of maven i.e. outer directory of bin. For
example: E:\apache-maven-3.1.1 .It is displayed below:

© Edunet Foundation. All rights reserved .402


Now click on OK button.

3) Add Maven Path in environment variable

Click on new tab if path is not set, then set the path of maven. If it is set, edit the path
and append the path of maven.

Here, we have installed JDK and its path is set by default, so we are going to append
the path of maven.

The path of maven should be %maven home%/bin. For example, E:\apache-maven-


3.1.1\bin .

© Edunet Foundation. All rights reserved .403


4) Verify maven

To verify whether maven is installed or not, open the command prompt and write:

1. mvn −version

Now it will display the version of maven and jdk including the maven home and java
home.

Let's see the output:

© Edunet Foundation. All rights reserved .404


Maven Repository

A maven repository is a directory of packaged JAR file with pom.xml file. Maven
searches for dependencies in the repositories. There are 3 types of maven repository:

1. Local Repository

2. Central Repository

3. Remote Repository

Maven searches for the dependencies in the following order:

Local repository then Central repository then Remote repository.

If dependency is not found in these repositories, maven stops processing and throws
an error.

1) Maven Local Repository

Maven local repository is located in your local system. It is created by the maven
when you run any maven command.

By default, maven local repository is %USER_HOME%/.m2 directory. For


example: C:\Users\SSS IT\.m2.

© Edunet Foundation. All rights reserved .405


Update location of Local Repository

We can change the location of maven local repository by changing


the settings.xml file. It is located in MAVEN_HOME/conf/settings.xml, for
example: E:\apache-maven-3.1.1\conf\settings.xml.

Let's see the default code of settings.xml file.

settings.xml

...

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.a
pache.org/xsd/settings-1.0.0.xsd">

<!-- localRepository

| The path to the local repository maven will use to store artifacts.

© Edunet Foundation. All rights reserved .406


| Default: ${user.home}/.m2/repository

<localRepository>/path/to/local/repo</localRepository>

-->

...

</settings>

Now change the path to local repository. After changing the path of local repository,
it will look like this:

settings.xml

...

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.a
pache.org/xsd/settings-1.0.0.xsd">

<localRepository>e:/mavenlocalrepository</localRepository>

...

</settings>

As you can see, now the path of local repository is e:/mavenlocalrepository.

2) Maven Central Repository

Maven central repository is located on the web. It has been created by the apache
maven community itself.

© Edunet Foundation. All rights reserved .407


The path of central repository is: http://repo1.maven.org/maven2/.

The central repository contains a lot of common libraries that can be viewed by this
url http://search.maven.org/#browse.

3) Maven Remote Repository

Maven remote repository is located on the web. Most of libraries can be missing from
the central repository such as JBoss library etc, so we need to define remote repository
in pom.xml file.

Let's see the code to add the jUnit library in pom.xml file.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0

http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.javatpoint.application1</groupId>

<artifactId>my-application1</artifactId>

<version>1.0</version>

<packaging>jar</packaging>

<name>Maven Quick Start Archetype</name>

<url>http://maven.apache.org</url>
© Edunet Foundation. All rights reserved .408
<dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.8.2</version>

<scope>test</scope>

</dependency>

</dependencies>

</project>

You can search any repository from Maven official website mvnrepository.com.

Maven pom.xml file

POM is an acronym for Project Object Model. The pom.xml file contains information
of project and configuration information for the maven to build the project such as
dependencies, build directory, source directory, test source directory, plugin, goals
etc.

Maven reads the pom.xml file, then executes the goal.

Before maven 2, it was named as project.xml file. But, since maven 2 (also in maven
3), it is renamed as pom.xml.

Elements of maven pom.xml file


© Edunet Foundation. All rights reserved .409
For creating the simple pom.xml file, you need to have following elements:

Element Description

project It is the root element of pom.xml file.

modelVersion It is the sub element of project. It specifies the model Version. It


should be set to 4.0.0.

groupId It is the sub element of project. It specifies the id for the project
group.

artifactId It is the sub element of project. It specifies the id for the artifact
(project). An artifact is something that is either produced or used
by a project. Examples of artifacts produced by Maven for a
project include: JARs, source and binary distributions, and
WARs.

version It is the sub element of project. It specifies the version of the


artifact under given group.

File: pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0

http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

© Edunet Foundation. All rights reserved .410


<groupId>com.javatpoint.application1</groupId>

<artifactId>my-app</artifactId>

<version>1</version>

</project>

Maven pom.xml file with additional elements

Here, we are going to add other elements in pom.xml file such as:

Element Description

packaging defines packaging type such as jar, war etc.

name defines name of the maven project.

url defines url of the project.

dependencies defines dependencies for this project.

dependency defines a dependency. It is used inside dependencies.

scope defines scope for this maven project. It can be compile, provided,
runtime, test and system.

File: pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
© Edunet Foundation. All rights reserved .411
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0

http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.javatpoint.application1</groupId>

<artifactId>my-application1</artifactId>

<version>1.0</version>

<packaging>jar</packaging>

<name>Maven Quick Start Archetype</name>

<url>http://maven.apache.org</url>

<dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.8.2</version>

<scope>test</scope>

</dependency>

</dependencies>

</project>

5.1.2 - Spring MVC Annotations

© Edunet Foundation. All rights reserved .412


Annotations brought major changes in programming style and slowly eliminating the
XML-based configurations. Spring Framework has used the annotations from the
release of Spring 2.5.

1. @Controller Annotation

This annotation serves as a specialization of @Component, allowing for


implementation classes autodetected through classpath scanning.@Controller
annotation tells the Spring IOC container to treat this class as Spring MVC controller.

To configure/ customize MVC components, Spring MVC provides an option to handle


it either through Java Config or XML. Add @EnableWebMvc will import the Spring
MVC configuration from.WebMvcConfigurationSupport For XML based configuration
use the

<context:component-scan base-package="com.javadevjournal">

@Controller

public class SpringMVCController {

//HTTP Mappings

2. @RestController Annotation

A convenience annotation that is itself annotated


with @Controller and @ResponseBody.

@RestController

public class FilterExampleController {

@GetMapping

© Edunet Foundation. All rights reserved .413


public String greeting() {

return "Hello World";

@GetMapping(value = "/greeting")

public String customGreetings() {

return "Hello From Custom Greetings";

3. @RequestMapping

Annotation for mapping web requests methods in the Spring MVC Controller.
Both Spring MVC and Spring WebFlux support this
annotation.@RequestMapping annotation provides several options to customize its
behavior.

• Consumes – The consumable media types of the mapped request, narrowing


the primary mapping. (e.g. @RequestMapping(consumes = {"application/json",
"application/xml"})).

• method – The HTTP request methods to map (e.g. method =


{RequestMethod.GET,RequestMethod.POST}).

• header – The headers of the mapped request.

• name – the name of the mapping.

• value – The primary mapping expressed by this ann otation

• produces – The producible media types of the mapped request.

Here is an example for the @RequestMapping

© Edunet Foundation. All rights reserved .414


@Controller

public class SpringMVCController {

@RequestMapping(value = {

"/greetings",

"/hello-world"}, method = {RequestMethod.GET,RequestMethod.POST},

consumes = {"application/json","application/xml"},

produces = { "application/json"},headers = {"application/json"

})

public String hellpWorld() {

return "Hello";

[pullquote align=”normal”]This annotation can be used both at the class and at the
method level [/pullquote]

@Controller

@RequestMapping(value = {

"/greetings"

}, method = {

RequestMethod.GET

})

public class SpringMVCController {}

© Edunet Foundation. All rights reserved .415


If you are using Spring 4.3+, check out new and improved @RequestMapping
annotations.

4. @RequestParam

Annotation which shows that it binds a method parameter to a web request parameter.
Request parameters passed by the browser/client as part of the HTTP request,
the @RequestParam annotation help to map these parameters easily at the controller
level.

@GetMapping("/request-mapping-example")

public String requestMappingExample(@RequestParam("code") String code) {

//

With @RequestParam we can specify default value when Spring finds no or empty
value in the request.

public String requestMappingExample(@RequestParam(defaultValue = "1") long


productQty){}

5. @PathVariable

This annotation shows that a method parameter bound to a URI template variable. We
specify the variable as part of the @RequestMapping and bind a method
argument with @PathVariable. Let’s take an example where we want to pass
productCode as part of the URI and not request parameter.

@GetMapping("/products/{id}")

public String getProduct(@PathVariable("id") String id) {

//

© Edunet Foundation. All rights reserved .416


}

Please note following extra points while using @PathVariable.

• The variable name in the @PathVariable annotation is optional if the name of


the part in the template matches the name of the method argument. For the
above example, we can omit “id” from the @PathVariable annotation.

@GetMapping("/products/{id}")

public String getProduct(@PathVariable String id) {

//

• Use “require” parameter to mark the path variable as an optional.

@GetMapping("/products/{id}")

public String getProduct(@PathVariable(required = false) String id) {

//

Here, id is an optional field

6. @SessionAttribute

Annotation to bind a method parameter to a session attribute.@SessionAttribute used


to pass value across different requests through the session. Rather than
using HttpSession object directly, using this annotation can benefit auto type
conversion and optional/required check.

@GetMapping("/user")

© Edunet Foundation. All rights reserved .417


public String sessionexample(@SessionAttribute(name = "userLoginTime")
LocalDateTime startDateTime) {

//

7. @RequestBody

The @RequestBody annotation showing a method parameter bound to the body of


the web request. It passes the body of the request through
an HttpMessageConverter to resolve the method argument depending on the content
the request.

@PostMapping("/product/save") public String saveProduct(@RequestBody Product


product){}

8. @ResponseBody

The @ResponseBody Annotation that shows a method return value bound to the web
response body. Supported for annotated handler methods. Spring treats the result
of the method as the response itself.

@GetMapping("/products/{id}")

public @ResponseBody Product saveProduct(@PathVariable("id") String id) {

//

9. @ExceptionHandler
© Edunet Foundation. All rights reserved .418
ExceptionHandler is a Spring annotation handle exceptions thrown by request
handling. This annotation works at the @Controller level.

@GetMapping("/greeting")

String greeting() throws Exception {

//

@ExceptionHandler({

Exception.class

})

public handleException() {

//

10. @InitBinder

Annotation that identifies methods which initialize the WebDataBinder and used for
populating command and form object arguments of annotated handler methods.

@InitBinder

protected void initBinder(WebDataBinder binder) {

binder.setValidator(customValidator);

11. @ModelAttribute

© Edunet Foundation. All rights reserved .419


@ModelAttribute refers to a property of the Model object in Spring MVC.
This ModelAttribute annotation binds a method parameter or method return value to a
named model attribute, exposed to a web view.

@PostMapping("/customer-registration")

public String processForm(@ModelAttribute("customer") Customer customer) {}

The annotation is used to define objects which should be part of a Model. So if you
want to have a Customer object referenced in the Model you can use the following
method:

@ModelAttribute("customer")

public Person getCustomer() {

//

we don’t have to specify the model key, Spring uses the method’s name by default

@ModelAttribute

public Person getCustomer() {

//

12. @Qualifier Annotation

The @Qualifier annotation helps disambiguate bean references when Spring


otherwise could not do so. In our case, to we can use the @Qualifier annotation help
in the issue to choose the correct bean for the dependency injection. Let’s change our
previous example:

public class OrderFacade {


© Edunet Foundation. All rights reserved .420
@Qualifier("userServiceImpl")

@Autowired

private UserService userService;

13. @CrossOrigin

This annotation allows the cross-domain communication for the annotated handler
methods. This @CrossOrigin annotation enables cross-origin resource sharing only
for this specific method. Let’s take an example where we want to allow only <a
class="bare" href="http://localhost:9000">http://localhost:9002</a> to send cross-
origin requests.

@CrossOrigin(origins = "http://localhost:9002")

@GetMapping("/hello")

public String greeting(@RequestParam(required = false, defaultValue = "Stranger")


String name) {

return "Hello" + name;

© Edunet Foundation. All rights reserved .421


CRUD Operations are the most important operation we have to
perform while building any web-based application. CRUD acronyms
to Create, Read, Update, Delete.

Create a table

Here, we are using emp99 table present in the MySQL database. It has 4 fields: id,
name, salary, and designation. Here, id is auto incremented which is generated by the
sequence.

Spring MVC CRUD Example

1. Add dependencies to pom.xml file.

pom.xml

<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>

<version>5.1.1.RELEASE</version>

</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper -->

© Edunet Foundation. All rights reserved .422


<dependency>

<groupId>org.apache.tomcat</groupId>

<artifactId>tomcat-jasper</artifactId>

<version>9.0.12</version>

</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>servlet-api</artifactId>

<version>3.0-alpha-1</version>

</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>jstl</artifactId>

<version>1.2</version>

</dependency>

<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>8.0.11</version>

</dependency>
© Edunet Foundation. All rights reserved .423
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-jdbc</artifactId>

<version>5.1.1.RELEASE</version>

</dependency>

2. Create the bean class

Here, the bean class contains the variables (along setter and getter methods)
corresponding to the fields exist in the database.

Emp.java

package com.javatpoint.beans;

public class Emp {

private int id;

private String name;

private float salary;

private String designation;

public int getId() {

return id;

public void setId(int id) {

this.id = id;

© Edunet Foundation. All rights reserved .424


}

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public float getSalary() {

return salary;

public void setSalary(float salary) {

this.salary = salary;

public String getDesignation() {

return designation;

public void setDesignation(String designation) {

this.designation = designation;

© Edunet Foundation. All rights reserved .425


3. Create the controller class

EmpController.java

package com.javatpoint.controllers;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import com.javatpoint.beans.Emp;

import com.javatpoint.dao.EmpDao;

@Controller

public class EmpController {

@Autowired

EmpDao dao;//will inject dao from XML file

/*It displays a form to input data, here "command" is a reserved request attribut
e

*which is used to display object data into form

*/

© Edunet Foundation. All rights reserved .426


@RequestMapping("/empform")

public String showform(Model m){

m.addAttribute("command", new Emp());

return "empform";

/*It saves object into database. The @ModelAttribute puts request data

* into model object. You need to mention RequestMethod.POST method

* because default request is GET*/

@RequestMapping(value="/save",method = RequestMethod.POST)

public String save(@ModelAttribute("emp") Emp emp){

dao.save(emp);

return "redirect:/viewemp";//will redirect to viewemp request mapping

/* It provides list of employees in model object */

@RequestMapping("/viewemp")

public String viewemp(Model m){

List<Emp> list=dao.getEmployees();

m.addAttribute("list",list);

return "viewemp";

/* It displays object data into form for the given id.

* The @PathVariable puts URL data into variable.*/

@RequestMapping(value="/editemp/{id}")
© Edunet Foundation. All rights reserved .427
public String edit(@PathVariable int id, Model m){

Emp emp=dao.getEmpById(id);

m.addAttribute("command",emp);

return "empeditform";

/* It updates model object. */

@RequestMapping(value="/editsave",method = RequestMethod.POST)

public String editsave(@ModelAttribute("emp") Emp emp){

dao.update(emp);

return "redirect:/viewemp";

/* It deletes record for the given id in URL and redirects to /viewemp */

@RequestMapping(value="/deleteemp/{id}",method = RequestMethod.GET)

public String delete(@PathVariable int id){

dao.delete(id);

return "redirect:/viewemp";

4. Create the DAO class

Let's create a DAO class to access the required data from the database.

EmpDao.java

package com.javatpoint.dao;
© Edunet Foundation. All rights reserved .428
import java.sql.ResultSet;

import java.sql.SQLException;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.RowMapper;

import com.javatpoint.beans.Emp;

public class EmpDao {

JdbcTemplate template;

public void setTemplate(JdbcTemplate template) {

this.template = template;

public int save(Emp p){

String sql="insert into Emp99(name,salary,designation) values('"+p.getName()


+"',"+p.getSalary()+",'"+p.getDesignation()+"')";

return template.update(sql);

public int update(Emp p){

String sql="update Emp99 set name='"+p.getName()+"', salary="+p.getSalary()


+",designation='"+p.getDesignation()+"' where id="+p.getId()+"";

return template.update(sql);

© Edunet Foundation. All rights reserved .429


}

public int delete(int id){

String sql="delete from Emp99 where id="+id+"";

return template.update(sql);

public Emp getEmpById(int id){

String sql="select * from Emp99 where id=?";

return template.queryForObject(sql, new Object[]{id},new BeanPropertyRowM


apper<Emp>(Emp.class));

public List<Emp> getEmployees(){

return template.query("select * from Emp99",new RowMapper<Emp>(){

public Emp mapRow(ResultSet rs, int row) throws SQLException {

Emp e=new Emp();

e.setId(rs.getInt(1));

e.setName(rs.getString(2));

e.setSalary(rs.getFloat(3));

e.setDesignation(rs.getString(4));

return e;

});

© Edunet Foundation. All rights reserved .430


5. Provide the entry of controller in the web.xml file

web.xml

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

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://j
ava.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd" id="WebApp_ID" version="3.0">

<display-name>SpringMVC</display-name>

<servlet>

<servlet-name>spring</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>spring</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

</web-app>

6. Define the bean in the xml file

spring-servlet.xml

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


© Edunet Foundation. All rights reserved .431
<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<context:component-scan base-
package="com.javatpoint.controllers"></context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResol
ver">

<property name="prefix" value="/WEB-INF/jsp/"></property>

<property name="suffix" value=".jsp"></property>

</bean>

<bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataS


ource">

<property name="driverClassName" value="com.mysql.jdbc.Driver"></property


>

© Edunet Foundation. All rights reserved .432


<property name="url" value="jdbc:mysql://localhost:3306/test"></property>

<property name="username" value=""></property>

<property name="password" value=""></property>

</bean>

<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">

<property name="dataSource" ref="ds"></property>

</bean>

<bean id="dao" class="com.javatpoint.dao.EmpDao">

<property name="template" ref="jt"></property>

</bean>

</beans>

7. Create the requested page

index.jsp

<a href="empform">Add Employee</a>

<a href="viewemp">View Employees</a>

8. Create the other view components

empform.jsp

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

© Edunet Foundation. All rights reserved .433


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<h1>Add New Employee</h1>

<form:form method="post" action="save">

<table >

<tr>

<td>Name : </td>

<td><form:input path="name" /></td>

</tr>

<tr>

<td>Salary :</td>

<td><form:input path="salary" /></td>

</tr>

<tr>

<td>Designation :</td>

<td><form:input path="designation" /></td>

</tr>

<tr>

<td> </td>

<td><input type="submit" value="Save" /></td>

</tr>

</table>

</form:form>
© Edunet Foundation. All rights reserved .434
empeditform.jsp

Here "/SpringMVCCRUDSimple" is the project name, change this if you have different
project name. For live application, you can provide full URL.

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<h1>Edit Employee</h1>

<form:form method="POST" action="/SpringMVCCRUDSimple/editsave">

<table >

<tr>

<td></td>

<td><form:hidden path="id" /></td>

</tr>

<tr>

<td>Name : </td>

<td><form:input path="name" /></td>

</tr>

<tr>

<td>Salary :</td>

<td><form:input path="salary" /></td>

</tr>

© Edunet Foundation. All rights reserved .435


<tr>

<td>Designation :</td>

<td><form:input path="designation" /></td>

</tr>

<tr>

<td> </td>

<td><input type="submit" value="Edit Save" /></td>

</tr>

</table>

</form:form>

viewemp.jsp

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<h1>Employees List</h1>

<table border="2" width="70%" cellpadding="2">

<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</th><th>Edit<
/th><th>Delete</th></tr>

<c:forEach var="emp" items="${list}">

<tr>

<td>${emp.id}</td>

© Edunet Foundation. All rights reserved .436


<td>${emp.name}</td>

<td>${emp.salary}</td>

<td>${emp.designation}</td>

<td><a href="editemp/${emp.id}">Edit</a></td>

<td><a href="deleteemp/${emp.id}">Delete</a></td>

</tr>

</c:forEach>

</table>

<br/>

<a href="empform">Add New Employee</a>

Output:

On clicking Add Employee, you will see the following form.

© Edunet Foundation. All rights reserved .437


Fill the form and click Save to add the entry into the database.

Now, click Edit to make some changes in the provided data.

© Edunet Foundation. All rights reserved .438


Now, click Edit Save to add the entry with changes into the database.

Now, click Delete to delete the entry from the database.

© Edunet Foundation. All rights reserved .439


What is Spring Boot

Spring Boot is a project that is built on the top of the Spring Framework. It provides an
easier and faster way to set up, configure, and run both simple and web-based
applications.

It is a Spring module that provides the RAD (Rapid Application


Development) feature to the Spring Framework. It is used to create a stand-alone
Spring-based application that you can just run because it needs minimal Spring
configuration.

In short, Spring Boot is the combination of Spring Framework and Embedded


Servers.

© Edunet Foundation. All rights reserved .440


In Spring Boot, there is no requirement for XML configuration (deployment descriptor).
It uses convention over configuration software design paradigm that means it
decreases the effort of the developer.

We can use Spring STS IDE or Spring Initializr to develop Spring Boot Java
applications.

Why should we use Spring Boot Framework?

We should use Spring Boot Framework because:

o The dependency injection approach is used in Spring Boot.

o It contains powerful database tran saction management capabilities.

o It simplifies integration with other Java frameworks like JPA/Hibernate ORM,


Struts, etc.

o It reduces the cost and development time of the application.

Along with the Spring Boot Framework, many other Spring sister projects help to build
applications addressing modern business needs. There are the following Spring sister
projects are as follows:

o Spring Data: It simplifies data access from the relational


and NoSQL databases.

o Spring Batch: It provides powerful batch processing.

o Spring Security: It is a security framework that provides robust security to


applications.

o Spring Social: It supports integration with social networking like LinkedIn.

o Spring Integration: It is an implementation of Enterprise Integration Patterns.


It facilitates integration with other enterprise applications using lightweight
messaging and declarative adapters.

© Edunet Foundation. All rights reserved .441


Advantages of Spring Boot

o It creates stand-alone Spring applications that can be started using Java -jar.

o It tests web applications easily with the help of different Embedded HTTP
servers such as Tomcat, Jetty, etc. We don't need to deploy WAR files.

o It provides opinionated 'starter' POMs to simplify our Maven configuration.

o It provides production-ready features such as metrics, health


checks, and externalized configuration.

o There is no requirement for XML configuration.

o It offers a CLI tool for developing and testing the Spring Boot application.

o It offers the number of plug-ins.

o It also minimizes writing multiple boilerplate codes (the code that has to be
included in many places with little or no alteration), XML configuration, and
annotations.

o It increases productivity and reduces development time.

Limitations of Spring Boot

Spring Boot can use dependencies that are not going to be used in the application.
These dependencies increase the size of the application.

Goals of Spring Boot

The main goal of Spring Boot is to reduce development, unit test, and integration
test time.

o Provides Opinionated Development approach

o Avoids defining more Annotation Configuration

o Avoids writing lots of import statements

© Edunet Foundation. All rights reserved .442


o Avoids XML Configuration.

By providing or avoiding the above points, Spring Boot Framework


reduces Development time, Developer Effort, and increases productivity.

Prerequisite of Spring Boot

To create a Spring Boot application, following are the prerequisites. In this tutorial, we
will use Spring Tool Suite (STS) IDE.

o Java 1.8

o Maven 3.0+

o Spring Framework 5.0.0.BUILD-SNAPSHOT

o An IDE (Spring Tool Suite) is recommen ded.

Spring Boot Features

o Web Development

o SpringApplication

o Application events and listeners

o Admin features

o Externalized Configuration

o Properties Files

o YAML Support

o Type-safe Configuration

o Logging

o Security

Web Development

It is a well-suited Spring module for web application development. We can easily


create a self-contained HTTP application that uses embedded servers like Tomcat,
© Edunet Foundation. All rights reserved .443
Jetty, or Undertow. We can use the spring-boot-starter-web module to start and run
the application quickly.

SpringApplication

The SpringApplication is a class that provides a convenient way to bootstrap a Spring


application. It can be started from the main method. We can call the application just
by calling a static run() method.

public static void main(String[] args)

SpringApplication.run(ClassName.class, args);

Application Events and Listeners

Spring Boot uses events to handle the variety of tasks. It allows us to create factories
file that is used to add listeners. We can refer it to using the ApplicationListener key.

Always create factories file in META-INF folder like META-INF/spring.factories.

Admin Support

Spring Boot provides the facility to enable admin -related features for the application.
It is used to access and manage applications remotely. We can enable it in the Spring
Boot application by using spring.application.admin.enabled property.

Externalized Configuration

© Edunet Foundation. All rights reserved .444


Spring Boot allows us to externalize our configuration so that we can work with the
same application in different environments. The application uses YAML files to
externalize configuration.

Properties Files

Spring Boot provides a rich set of Application Properties. So, we can use that in the
properties file of our project. The properties file is used to set properties like server-
port =8082 and many others. It helps to organize application properties.

YAML Support

It provides a convenient way of specifying the hierarchical configuration. It is a


superset of JSON. The SpringApplication class automatically supports YAML. It is an
alternative of properties file.

Type-safe Configuration

The strong type-safe configuration is provided to govern and validate the configuration
of the application. Application configuration is always a crucial task which should be
type-safe. We can also use annotation provided by this library.

Logging

Spring Boot uses Common logging for all internal logging. Logging dependencies are
managed by default. We should not change logging dependencies if no customization
is needed.

Security

© Edunet Foundation. All rights reserved .445


Spring Boot applications are spring bases web applications. So, it is secure by default
with basic authentication on all HTTP endpoints. A rich set of Endpoints is available to
develop a secure Spring Boot application.

Spring Boot Version

The latest version of Spring Boot is 2.0. It introduces a lot of new features along with
some modifications and replacement.

Spring Boot 2.0

Let's have a sneak peek at Spring Boot 2.0.

o What's New
Infrastructure Upgrade
Spring Framework 5

o What's Changed
Configuration Properties
Gradle Plugin
Actuators endpoints

o What's Evolving
Security
Metrics

Spring Boot Architecture

Spring Boot is a module of the Spring Framework. It is used to create stand-alone,


production-grade Spring Based Applications with minimum efforts. It is developed on
top of the core Spring Framework.

Spring Boot follows a layered architecture in which each layer communicates with the
layer directly below or above (hierarchical structure) it.
© Edunet Foundation. All rights reserved .446
Before understanding the Spring Boot Architecture, we must know the different
layers and classes present in it. There are four layers in Spring Boot are as follows:

o Presentation Layer

o Business Layer

o Persistence Layer

o Database Layer

Presentation Layer: The presentation layer handles the HTTP requests, translates
the JSON parameter to object, and authenticates the request and transfer it to the
business layer. In short, it consists of views i.e., frontend part.

Business Layer: The business layer handles all the business logic. It consists of
service classes and uses services provided by data access layers. It also
performs authorization and validation.

© Edunet Foundation. All rights reserved .447


Persistence Layer: The persistence layer contains all the storage logic and
translates business objects from and to database rows.

Database Layer: In the database layer, CRUD (create, retrieve, update, delete)
operations are performed.

Image: Spring Boot Flow Architecture


Reference-

o Now we have validator classes, view classes, an d utility classes.

o Spring Boot uses all the modules of Spring-like Spring MVC, Spring Data, etc.
The architecture of Spring Boot is the same as the architecture of Spring
MVC, except one thing: there is no need for DAO and DAOImpl classes in
Spring boot.

o Creates a data access layer and performs CRUD operation.

o The client makes the HTTP requests (PUT or GET).

© Edunet Foundation. All rights reserved .448


o The request goes to the controller, and the controller maps that request and
handles it. After that, it calls the service logic if required.

o In the service layer, all the business logic performs. It performs the logic on
the data that is mapped to JPA with model classes.

o A JSP page is returned to the user if no error occurred.

Spring Initializr

Spring Initializr is a web-based tool provided by the Pivotal Web Service. With the
help of Spring Initializr, we can easily generate the structure of the Spring Boot
Project. It offers extensible API for creating JVM-based projects.

It also provides various options for the project that are expressed in a metadata model.
The metadata model allows us to configure the list of dependencies supported by JVM
and platform versions, etc. It serves its metadata in a well-known that provides
necessary assistance to third-party clients.

Spring Initializr Modules

Spring Initializr has the following module:

o initializr-actuator: It provides additional information and statistics on project


generation. It is an optional module.

o initializr-bom: In this module, BOM stands for Bill Of Materials. In Spring


Boot, BOM is a special kind of POM that is used to control the versions of a
project's dependencies. It provides a central place to define and update
those versions. It provides flexibility to add a dependency in our module
without worrying about the versions.
Outside the software world, the BOM is a list of parts, items, assemblies, and
other materials required to create products. It explains what,
how, and where to collect required materials.

o initializr-docs: It provides documentation.


© Edunet Foundation. All rights reserved .449
o initializr-generator: It is a core project generation library.

o initializr-generator-spring:

o initializr-generator-test: It provides a test infrastructure for project


generation.

o initializr-metadata: It provides metadata infrastructure for various aspects of


the projects.

o initializr-service-example: It provides custom instances.

o initializr-version-resolver: It is an optional module to extract version


numbers from an arbitrary POM.

o initializr-web: It provides web endpoints for third party clients.

Supported Interface

o It supports IDE STS, IntelliJ IDEA Ultimate, NetBeans, Eclipse. You can
download the plugin from https://github.com/AlexFalappa/nb-springboot

. If you are using VSCode, download the plugin


from https://github.com/microsoft/vscode-spring-initializr

Use Custom Web UI http://start.spring.io

or https://start-scs.cfapps.io

o It also supports the command-line with the Spring Boot


CLI or cURL or HTTPie.

The following image shows the Spring Initializr UI:

© Edunet Foundation. All rights reserved .450


Generating a Project

Before creating a project, we must be friendly with UI. Spring Initializr UI has the
following labels:

© Edunet Foundation. All rights reserved .451


o Project: It defines the kind of project. We can create either Maven
Project or Gradle Project. We will create a Maven Project throughout the
tutorial.

o Language: Spring Initializr provides the choice among three languages Java,
Kotlin, and Groovy. Java is by default selected.

o Spring Boot: We can select the Spring Boot version. The latest version
is 2.2.2.

o Project Metadata: It contains information related to the project, such


as Group, Artifact, etc. Group denotes the package name; Artifact denotes
the Application name. The default Group name is com.example, and the
default Artifact name is demo.

o Dependencies: Dependencies are the collection of artifacts that we can add


to our project.

There is another Options section that contains the following fields:

o Name: It is the same as Artifact.

o Description: In the description field, we can write a description of the


project.

o Package Name: It is also similar to the Group name.

o Packaging: We can select the packing of the project. We can choose


either Jar or War.

o Java: We can select the JVM version which we want to use. We will use Java
8 version throughout the tutorial.

There is a Generate button. When we click on the button, it starts packing the project
and downloads the Jar or War file, which you have selected.

Download and Install STS IDE

Spring Tool Suite (STS) IDE

© Edunet Foundation. All rights reserved .452


Spring Tool Suite is an IDE to develop Spring applications. It is an Eclipse-based
development environment. It provides a ready-to-use environment to implement, run,
deploy, and debug the application. It validates our application and provides quick fixes
for the applications.

Installing STS

Step 1: Download Spring Tool Suite from https://spring.io/tools3/sts/all. Click on the


platform which you are using. In this tutorial, we are using the Windows platform.

Step 2: Extract the zip file and install the STS.

sts-bundle -> sts-3.9.9.RELEASE -> Double-click on the STS.exe.

Step 3: Spring Tool Suite 3 Launcher dialog box appears on the screen. Click on
the Launch button. You can change the Workspace if you want.

© Edunet Foundation. All rights reserved .453


Step 4: It starts launching the STS.

The STS user interface looks like the following:

© Edunet Foundation. All rights reserved .454


© Edunet Foundation. All rights reserved .455
5.2 - Integrating web template UI with Spring

5.2.1 - Creating responsive UI using Bootstrap

Creating a Spring Boot Project

Following are the steps to create a simple Spring Boot Project.

Step 1: Open the Spring initializr https://start.spring.io.

Step 2: Provide the Group and Artifact name. We have provided Group
name com.javatpoint and Artifact spring-boot-example.

Step 3: Now click on the Generate button.

When we click on the Generate button, it starts packing the project in a .rar file and
downloads the project.

© Edunet Foundation. All rights reserved .456


Step 4: Extract the RAR file.

Step 5: Import the folder.

File -> Import -> Existing Maven Project -> Next -> Browse -> Select the project ->
Finish

It takes some time to import the project. When the project imports successfully, we
can see the project directory in the Package Explorer. The following image shows the
project directory:

SpringBootExampleApplication.java

package com.javatpoint.springbootexample;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication

public class SpringBootExampleApplication

public static void main(String[] args)

© Edunet Foundation. All rights reserved .457


{

SpringApplication.run(SpringBootExampleApplication.class, args);

pom.xml

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

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=http://www.w3.o


rg/2001/XMLSchema-
instance xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven
.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<parent>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-parent</artifactId>

<version>2.2.2.BUILD-SNAPSHOT</version>

<relativePath/> <!-- lookup parent from repository -->

</parent>

<groupId>com.javatpoint</groupId>

<artifactId>spring-boot-example</artifactId>

<version>0.0.1-SNAPSHOT</version>

<name>spring-boot-example</name>

<description>Demo project for Spring Boot</description>

<properties>

© Edunet Foundation. All rights reserved .458


<java.version>1.8</java.version>

</properties>

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter</artifactId>

</dependency>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-test</artifactId>

<scope>test</scope>

<exclusions>

<exclusion>

<groupId>org.junit.vintage</groupId>

<artifactId>junit-vintage-engine</artifactId>

</exclusion>

</exclusions>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupId>org.springframework.boot</groupId>
© Edunet Foundation. All rights reserved .459
<artifactId>spring-boot-maven-plugin</artifactId>

</plugin>

</plugins>

</build>

<repositories>

<repository>

<id>spring-milestones</id>

<name>Spring Milestones</name>

<url>https://repo.spring.io/milestone</url>

</repository>

<repository>

<id>spring-snapshots</id>

<name>Spring Snapshots</name>

<url>https://repo.spring.io/snapshot</url>

<snapshots>

<enabled>true</enabled>

</snapshots>

</repository>

</repositories>

<pluginRepositories>

<pluginRepository>

<id>spring-milestones</id>

<name>Spring Milestones</name>
© Edunet Foundation. All rights reserved .460
<url>https://repo.spring.io/milestone</url>

</pluginRepository>

<pluginRepository>

<id>spring-snapshots</id>

<name>Spring Snapshots</name>

<url>https://repo.spring.io/snapshot</url>

<snapshots>

<enabled>true</enabled>

</snapshots>

</pluginRepository>

</pluginRepositories>

</project>

Step 6: Run the SpringBootExampleApplication.java file.

Right-click on the file -> Run As -> Java Applications

The following image shows the application runs successfully.

© Edunet Foundation. All rights reserved .461


5.1.3 - Database CRUD operations using DB classes

What is the CRUD operation?

The CRUD stands for Create, Read/Retrieve, Update, and Delete. These are the
four basic functions of the persistence storage.

The CRUD operation can be defined as user interface conventions that allow view,
search, and modify information through computer-based forms and reports. CRUD is
data-oriented and the standardized use of HTTP action verbs. HTTP has a few
important verbs.

o POST: Creates a new resource

o GET: Reads a resource

o PUT: Updates an existing resource

o DELETE: Deletes a resource

Within a database, each of these operations maps directly to a series of commands.


However, their relationship with a RESTful API is slightly more complex.

Standard CRUD Operation

o CREATE Operation: It performs the INSERT statement to create a new


record.

o READ Operation: It reads table records based on the input parameter.

o UPDATE Operation: It executes an update statement on the table. It is based


on the input parameter.

o DELETE Operation: It deletes a specified row in the table. It is also based on


the input parameter.

How CRUD Operations Works


© Edunet Foundation. All rights reserved .462
CRUD operations are at the foundation of the most dynamic websites. Therefore, we
should differentiate CRUD from the HTTP action verbs.

Suppose, if we want to create a new record, we should use HTTP action verb POST.
To update a record, we should use the PUT verb. Similarly, if we want to delete a
record, we should use the DELETE verb. Through CRUD operations, users and
administrators have the right to retrieve, create, edit, and delete records online.

We have many options for executing CRUD operations. One of the most efficient
choices is to create a set of stored procedures in SQL to execute operations.

The CRUD operations refer to all major functions that are implemented in relational
database applications. Each letter of the CRUD can map to a SQL statement and
HTTP methods.

Operation SQL HTTP verbs RESTful Web Service

Create INSERT PUT/POST POST

Read SELECT GET GET

Update UPDATE PUT/POST/PATCH PUT

Delete DELETE DELETE DELETE

Spring Boot CrudRepository

Spring Boot provides an interface called CrudRepository that contains methods for
CRUD operations. It is defined in the
package org.springframework.data.repository. It extends the Spring
Data Repository interface. It provides generic Crud operation on a repository. If we
want to use CrudRepository in an application, we have to create an interface and
extend the CrudRepository.

© Edunet Foundation. All rights reserved .463


Syntax

1. public interface CrudRepository<T,ID> extends Repository<T,ID>

where,

o T is the domain type that repository manages.

o ID is the type of the id of the entity that repository manages.

For example:

public interface StudentRepository extends CrudRepository<Student, Integer>

In the above example, we have created an interface named StudentRepository that


extends CrudRepository. Where Student is the repository to manage, and Integer is
the type of Id that is defined in the Student repository.

Spring Boot JpaRepository

JpaRepository provides JPA related methods such as flushing, persistence context,


and deletes a record in a batch. It is defined in the
package org.springframework.data.jpa.repository. JpaRepository extends
both CrudRepository and PagingAndSortingRepository.

For example:

public interface BookDAO extends JpaRepository

© Edunet Foundation. All rights reserved .464


Image- Spring Boot JpaRepository
Reference- https://www.javatpoint.com/spring-boot-crud-operations

Why should we use these interfaces?

o The interfaces allow Spring to find the repository interface and create proxy
objects for that.

o It provides methods that allow us to perform some common operations. We can


also define custom methods as well.

CrudRepository vs. JpaRepository


© Edunet Foundation. All rights reserved .465
CrudRepository JpaRepository

CrudRepository does not JpaRepository extends PagingAndSortingRepository.


provide any method for It provides all the methods for implementing the
pagination and sorting. pagination.

It works as JpaRepository extends


a marker interface. both CrudRepository and PagingAndSortingRepo
sitory.

It provides CRUD function It provides some extra methods along with the
only. For method of PagingAndSortingRepository and
example findById(), CrudRepository. For example, flush(),
findAll(), etc. deleteInBatch().

It is used when we do not It is used when we want to implement pagination and


need the functions sorting functionality in an application.
provided by JpaRepository
and
PagingAndSortingReposit
ory.

© Edunet Foundation. All rights reserved .466


5.2.1 - Integrating Spring with all CRUD operations

Spring Boot CRUD Operation Example

Let's set up a Spring Boot application and perform CRUD operation.

Step 1: Open Spring Initializr http://start.spring.io.

Step 2: Select the Spring Boot version 2.3.0.M1.

Step 2: Provide the Group name. We have provided com.javatpoint.

Step 3: Provide the Artifact Id. We have provided spring-boot-crud-operation.

Step 5: Add the dependencies Spring Web, Spring Data JPA, and H2 Database.

Step 6: Click on the Generate button. When we click on the Generate button, it
wraps the specifications in a Jar file and downloads it to the local system.

Step 7: Extract the Jar file and paste it into the STS workspace.

Step 8: Import the project folder into STS.


© Edunet Foundation. All rights reserved .467
File -> Import -> Existing Maven Projects -> Browse -> Select the folder spring-boot-
crud-operation -> Finish

It takes some time to import.

Step 9: Create a package with the name com.javatpoint.model in the


folder src/main/java.

Step 10: Create a model class in the package com.javatpoint.model. We have


created a model class with the name Books. In the Books class, we have done the
following:

o Define four variable bookid, bookname, author, and

o Generate Getters and Setters.


Right-click on the file -> Source -> Generate Getters and Setters.

o Mark the class as an Entity by using the annotation @Entity.

o Mark the class as Table name by using the annotation @Table.

o Define each variable as Column by using the annotation @Column.

Books.java

package com.javatpoint.model;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;

//mark class as an Entity

@Entity

//defining class name as Table name

@Table

public class Books


© Edunet Foundation. All rights reserved .468
{

//Defining book id as primary key

@Id

@Column

private int bookid;

@Column

private String bookname;

@Column

private String author;

@Column

private int price;

public int getBookid()

return bookid;

public void setBookid(int bookid)

this.bookid = bookid;

public String getBookname()

return bookname;

}
© Edunet Foundation. All rights reserved .469
public void setBookname(String bookname)

this.bookname = bookname;

public String getAuthor()

return author;

public void setAuthor(String author)

this.author = author;

public int getPrice()

return price;

public void setPrice(int price)

this.price = price;

Step 11: Create a package with the name com.javatpoint.controller in the


folder src/main/java.

© Edunet Foundation. All rights reserved .470


Step 12: Create a Controller class in the package com.javatpoint.controller. We
have created a controller class with the name BooksController. In the
BooksController class, we have done the following:

o Mark the class as RestController by using the annotation @RestController.

o Autowire the BooksService class by using the annotation @Autowired.

o Define the following methods:

o getAllBooks(): It returns a List of all Books.

o getBooks(): It returns a book detail that we have specified in the path


variable. We have passed bookid as an argument by using the
annotation @PathVariable. The annotation indicates that a method
parameter should be bound to a URI template variable.

o deleteBook(): It deletes a specific book that we have specified in the


path variable.

o saveBook(): It saves the book detail. The annotation @RequestBody


indicates that a method parameter should be bound to the body of the
web request.

o update(): The method updates a record. We must specify the record in


the body, which we want to update. To achieve the same, we have used
the annotation @RequestBody.

BooksController.java

package com.javatpoint.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.DeleteMapping;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;

© Edunet Foundation. All rights reserved .471


import org.springframework.web.bind.annotation.PostMapping;

import org.springframework.web.bind.annotation.PutMapping;

import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RestController;

import com.javatpoint.model.Books;

import com.javatpoint.service.BooksService;

//mark class as Controller

@RestController

public class BooksController

//autowire the BooksService class

@Autowired

BooksService booksService;

//creating a get mapping that retrieves all the books detail from the database

@GetMapping("/book")

private List<Books> getAllBooks()

return booksService.getAllBooks();

//creating a get mapping that retrieves the detail of a specific book

@GetMapping("/book/{bookid}")

private Books getBooks(@PathVariable("bookid") int bookid)

{
© Edunet Foundation. All rights reserved .472
return booksService.getBooksById(bookid);

//creating a delete mapping that deletes a specified book

@DeleteMapping("/book/{bookid}")

private void deleteBook(@PathVariable("bookid") int bookid)

booksService.delete(bookid);

//creating post mapping that post the book detail in the database

@PostMapping("/books")

private int saveBook(@RequestBody Books books)

booksService.saveOrUpdate(books);

return books.getBookid();

//creating put mapping that updates the book detail

@PutMapping("/books")

private Books update(@RequestBody Books books)

booksService.saveOrUpdate(books);

return books;

}
© Edunet Foundation. All rights reserved .473
Step 13: Create a package with the name com.javatpoint.service in the
folder src/main/java.

Step 14: Create a Service class. We have created a service class with the
name BooksService in the package com.javatpoint.service.

BooksService.java

package com.javatpoint.service;

import java.util.ArrayList;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

import com.javatpoint.model.Books;

import com.javatpoint.repository.BooksRepository;

//defining the business logic

@Service

public class BooksService

@Autowired

BooksRepository booksRepository;

//getting all books record by using the method findaAll() of CrudRepository

public List<Books> getAllBooks()

List<Books> books = new ArrayList<Books>();

booksRepository.findAll().forEach(books1 -> books.add(books1));

© Edunet Foundation. All rights reserved .474


return books;

//getting a specific record by using the method findById() of CrudRepository

public Books getBooksById(int id)

return booksRepository.findById(id).get();

//saving a specific record by using the method save() of CrudRepository

public void saveOrUpdate(Books books)

booksRepository.save(books);

//deleting a specific record by using the method deleteById() of CrudRepository

public void delete(int id)

booksRepository.deleteById(id);

//updating a record

public void update(Books books, int bookid)

booksRepository.save(books);

}
© Edunet Foundation. All rights reserved .475
Step 15: Create a package with the name com.javatpoint.repository in the
folder src/main/java.

Step 16: Create a Repository interface. We have created a repository interface with
the name BooksRepository in the package com.javatpoint.repository. It extends
the Crud Repository interface.

BooksRepository.java

package com.javatpoint.repository;

import org.springframework.data.repository.CrudRepository;

import com.javatpoint.model.Books;

//repository that extends CrudRepository

public interface BooksRepository extends CrudRepository<Books, Integer>

Now we will configure the datasource URL, driver class name,


username, and password, in the application.properties file.

Step 17: Open the application.properties file and configure the following
properties.

application.properties

spring.datasource.url=jdbc:h2:mem:books_data

spring.datasource.driverClassName=org.h2.Driver

spring.datasource.username=sa

spring.datasource.password=

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

#enabling the H2 console

© Edunet Foundation. All rights reserved .476


spring.h2.console.enabled=true

Note: Do not forget to enable the H2 console.

After creating all the classes and packages, the project directory looks like the
following.

Now we will run the application.

Step 18: Open SpringBootCrudOperationApplication.java file and run it as Java


Application.

SpringBootCrudOperationApplication.java

package com.javatpoint;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

© Edunet Foundation. All rights reserved .477


@SpringBootApplication

public class SpringBootCrudOperationApplication

public static void main(String[] args)

SpringApplication.run(SpringBootCrudOperationApplication.class, args);

Note: In the next steps we will use rest client Postman. So, ensure that the Postman
application is already installed in your system.

Step 19: Open the Postman and do the following:

o Select the POST

o Invoke the URL http://localhost:8080/books.

o Select the Body

o Select he Content-Type JSON (application/json).

o Insert the data. We have inserted the following data in the Body:

"bookid": "5433",

"bookname": "Core and Advance Java",

"author": "R. Nageswara Rao",

"price": "800"

o Click on the Send

© Edunet Foundation. All rights reserved .478


When the request is successfully executed, it shows the Status:200 OK. It means the
record has been successfully inserted in the database.

Similarly, we have inserted the following data.

"bookid": "0982",

"bookname": "Programming with Java",

"author": "E. Balagurusamy",

"price": "350"

"bookid": "6321",

"bookname": "Data Structures and Algorithms in Java",

"author": "Robert Lafore",

"price": "590"

"bookid": "5433",

"bookname": "Effective Java",

"author": "Joshua Bloch",

"price": "670"

Let's access the H2 console to see the data.

© Edunet Foundation. All rights reserved .479


Step 20: Open the browser and invoke the URL http://localhost:8080/h2-console.
Click on the Connect button, as shown below.

After clicking on the Connect button, we see the Books table in the database, as
shown below.

Step 21: Click on the Books table and then click on the Run button. The table
shows the data that we have inserted in the body.

© Edunet Foundation. All rights reserved .480


Step 22: Open the Postman and send a GET request with the URL
http://localhost:8080/books. It returns the data that we have inserted in the database.

Let's send a GET request with the URL http://localhost:8080/book/{bookid}. We have


specified the bookid 6830. It returns the detail of the book whose id is 6830.
© Edunet Foundation. All rights reserved .481
Similarly, we can also send a DELETE request to delete a record. Suppose we want
to delete a book record whose id is 5433.

Select the DELETE method and invoke the URL http://localhost:8080/book/5433.


Again, execute the Select query in the H2 console. We see that the book whose id
is 5433 has been deleted from the database.

Similarly, we can also update a record by sending a PUT request. Let's update the
price of the book whose id is 6321.

o Select the PUT

o In the request body, paste the record which you want to update and make the
changes. In our case, we want to update the record of the book whose id is
6321. In the following record, we have changed the price of the book.

{
© Edunet Foundation. All rights reserved .482
"bookid": "6321",

"bookname": "Data Structures and Algorithms in Java",

"author": "Robert Lafore",

"price": "500"

o Click on the Send

Now, move to the H2 console and see the changes have reflected or not. We see that
the price of the book has been changed, as shown below.

© Edunet Foundation. All rights reserved .483

You might also like