Full Stack Web Development - Handbook
Full Stack Web Development - Handbook
Full Stack
Web Development
Table of Content
Learning Outcomes
• Introduction to ReactJS
• Understanding MVC
After going through this handbook, the reader will be able to:
• Create and host websites and web apps for commercial usage
• Fundamentals of Databases
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 −
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.
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
Internet-Based Services
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.
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.
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:
Cons of Internet
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.
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:
What is Hyperlink?
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.
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.
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”.
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.
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.
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.
Practical Activities
© Edunet Foundation. All rights reserved .15
Open/run the HTML file in a web browser to check the output.(40min)
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">
</head>
<body text="blue">
<hr color="green">
<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.
</body>
Output/Results snippet:
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.
HMTL Example
<!DOCTYPE html>
<html>
<body>
<h1>HTML Tutorial</h1>
<p>HTML Introduction</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.
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
Unordered
used to group a set of items without any order. <ul>,<li>
List
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
<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
disc Starts a list using discs type bullets (default) <ul type="disc">
</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
<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.
There are two attributes can be used to customize ordered list, they are
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
Example and
List Style Type Description
Syntax
<html>
<title> Ordered List Example - Tutorials Class </title>
<body>
</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.
<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.
<!DOCTYPE html>
<html>
<head>
<style>
thead {color:green;}
tbody {color:blue;}
tfoot {color:red;}
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<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
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>
Month Date
January 10.01.2014
February 10.01.2014
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.
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.
• Canvas
• Scalable Vector Graphics (SVG)
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.
A <SVG> element:
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
Video format
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.
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.
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
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".
Method Attribute
The method attribute specifies the HTTP method (GET or POST) to be used when
submitting the form data.
EXAMPLE:
</form>
Name Attribute
If the name attribute is omitted, the data of that input field will not be sent at all.
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>
<label> Element
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.
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 .
<button> Element
Radio Buttons
Radio buttons are used to let the user select exactly one option from a pre-defined set
of options.
<label for="male">Male</label>
<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.
The file fields allow a user to browse for a local file and send it as an attachment with
the form data.
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.
The rows attribute specifies the visible number of lines in 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.
<option value="sydney">Sydney</option>
<option value="melbourne">Melbourne</option>
<option value="cromwell">Cromwell</option>
</select> </form>
multiple attribute to allow the user to select more than one value:
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.
<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.
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>
</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.
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.
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.
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.
<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
</pre>
<mark> Tag
The <mark> tag is used to present a part of text in one document as marked or
highlighted for reference purposes.
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.
<big> Tag
<p><big>Bigger text</big></p>
The <del> tag specifies a part of the text that was deleted from the document.
Browsers display this text as a strikethrough.
The <ins> tag defines the text that has been inserted (added) to the document. The
content of the tag is displayed as underlined.
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.
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.
<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.
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.
<p> We can insert the <br /> 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.
Tags Description
<p> Paragraph
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
<p> Paragraph
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>
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
Practical Activity
Lists (30min)
Program:
<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>
<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>
<p>E = mc<sup>2</sup></br>
<pre>
</pre>
</body>
</html>
Output/Results snippet:
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;
</head>
<body>
<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>
</ul>
</body>
</html>
Output/Results snippet:
Forms (30mins)
Program:
<html>
<head>
<style>
input[type=text] {
width: 100%;
margin: 8px 0;
box-sizing: border-box;
</style>
</head>
<body>
<form>
</form>
</body>
</html>
Output/Results snippet:
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.
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.
Accessibility. Several CSS features will make the Web more accessible to users with
disabilities:
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".
• 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
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
text-decoration Sets the decoration added to the text none, underline, line-through, overline
BORDER
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
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-style Sets the style of a f ont Normal, italic, oblique, initial, inherit
LIST
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 {
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{
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, 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;
}
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.
.section {
background: var(currentColor);
}
CSS variables can be used and updated dynamically, illustrate with below example
:root {
$value: 10px;
}
.radius {
border-radius: $value;
}
.section .item.blue {
color: blue;
}
Transform
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.
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;
}
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
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.
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.
Delay 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;
}
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:
• Content - The content of the box, where text and images appear
• Padding - Clears an area around the content. The padding 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;
}
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;
}
320px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 0px (left + right margin)
= 350px
Total element width = width + left padding + right padding + left border + right border
+ left margin + right margin
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.
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.
Flexbox
The display property is also used for new fangled layout methods like Flexbox.
.header {
display: flex;
}
Grid
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 following example specifies that an image should float to the right in a text:
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.
• 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".
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;
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).
Practical Activities
Program:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<header>
</header>
<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>
</footer>
</body>
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;
animation-name: example;
animation-duration: 4s;
@keyframes example {
to {background-color: yellow;}
</style>
</head>
<body>
<div></div>
</body>
</html>
Output/Results snippet:
Box Model(40mins)
Program:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<style>
div {
width: 300px;
height: 200px;
padding: 15px;
</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:
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>
</body>
</html>
Output/Results snippet:
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.
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.
NOTE − Here script refer to any VBScript or JavaScript function or piece of code.
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.
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.
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.
onmouseout script Script runs when mouse pointer moves out of an element
onmouseover script Script runs when mouse pointer moves over an element
The changes are called by a timer. When the timer interval is small, the
animation looks continuous.
<!DOCTYPE html>
<html>
<body>
<div id ="myContainer">
<div id ="myAnimation">My animation will go here</div>
</div>
</body>
<html>
#myContainer {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#myAnimation {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
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:
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.
<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>
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.
<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:
<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.
• 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
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;
}
}
If a form field (fname) is empty, the required attribute prevents this form from being
submitted:
Data validation is the process of ensuring that user input is clean, correct, and
useful.
• 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.
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.
Expires − The date the cookie will expire. If this is blank, the cookie will expire when
the visitor quits the browser.
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
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.
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.
//create a cookie with a domain to the current page and path to the entire domain.
You can access the cookie like this which will return all the cookies saved for the
current domain.
var x = document.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.
<html>
<head>
© Edunet Foundation. All rights reserved .94
<title>Cookie!!!</title>
<script type="text/javascript">
function createCookie(cookieName,cookieValue,daysToExpire)
date.setTime(date.getTime()+(daysToExpire*24*60*60*1000));
function accessCookie(cookieName)
if (temp.indexOf(name)==0)
return temp.substring(name.length,temp.length);
return "";
function checkCookie()
if (user!="")
else
num = prompt("How many days you want to store your name on your
computer?");
</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.
sessionStorage.removeItem("key");
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.";
Program:
<html>
<head>
<!--
function over() {
function out() {
//-->
</script>
</head>
<body>
</div>
</body>
</html>
Output/Results snippet:
© Edunet Foundation. All rights reserved .99
DOM (40mins)
Program:
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction() {
document.getElementById("demo").innerHTML = "Paragraph changed!";
}
</script>
</body>
</html>
Output/Results snippet:
Animations(50mins)
Program:
<!DOCTYPE HTML>
<html>
<body>
<script>
train.onclick = function() {
let start = Date.now();
}, 20);
}
</script>
</body>
</html>
Output/Results snippet:
Program:
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays) {
d.setTime(d.getTime() + (exdays*24*60*60*1000));
function getCookie(cname) {
var ca = decodedCookie.split(';');
var c = ca[i];
if (c.indexOf(name) == 0) {
return "";
function checkCookie() {
var user=getCookie("username");
if (user != "") {
} else {
</script>
</head>
<body onload="checkCookie()"></body>
</html>
Output/Results snippet:
Program:
<!DOCTYPE html>
<html>
<head>
<script>
function clickCounter() {
if (sessionStorage.clickcount) {
sessionStorage.clickcount = Number(sessionStorage.clickcount)+1;
} else {
sessionStorage.clickcount = 1;
} else {
</script>
</head>
<body>
<div id="result"></div>
<p>Close the browser tab (or window), and try again, and the counter is reset.</p>
</body>
</html>
Output/Results snippet:
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>
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
Slide Show
For the slide show we can use a <section> or <div> element as a picture container:
Sections
Looking at the "Layout Draft" we can see that the next step is to create articles.
<section style="max-width:600px">
<h2>THE BAND</h2>
<p><i>We love music</i></p>
</section>
<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;
}
.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">
Here the image slideshow repeats after every 3 seconds. The images will be
frequently changing with 3 second delay .
Design
Plan
❑ Download compiled and minified CSS bundles and JavaScript Plugin
❑ (Or) Download source SaaS, JavaScript and documentation files
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
❑ Easy to use: Anybody with just basic knowledge of HTML and CSS can start using
Bootstrap
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
BS5 Colors
Example: Example:
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:
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:
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:
Example: Example:
❑ 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:
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<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>
<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">
<br>
<div class="row">
</div>
<br>
<div class="row">
</div>
<br>
<div class="row">
</div>
</div>
</body>
</html>
BS GRID O/P:
© Edunet Foundation. All rights reserved .121
Portfolio Project
Code Implementation
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<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>
Navigation
<nav class="navbar navbar-expand-sm bg-dark navbar-dark">
<div class="container-fluid">
<ul class="navbar-nav">
<li class="nav-item">
</li>
<li class="nav-item">
</li>
<li class="nav-item">
</li>
<li class="nav-item">
</li>
</ul>
© Edunet Foundation. All rights reserved .123
</div>
</nav>
<div class="row">
<div class="col-sm-4">
<h2>About Me</h2>
<h5>Photo of me:</h5>
<li class="nav-item">
</li>
<li class="nav-item">
</li>
<li class="nav-item">
</li>
<li class="nav-item">
</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>
Learning Outcomes:
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.
class ClassName {
// fields
// methods
Here, fields (variables) and methods represent the state and behavior of the object
respectively.
class Bicycle {
// state or field
// behavior or method
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.
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.
class Bicycle {
// field of class
// method of class
void braking() {
...
// create object
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().
class Lamp {
// true if light is on
boolean isOn;
void turnOn() {
isOn = true;
void turnOff() {
isOn = false;
class Main {
led.turnOn();
halogen.turnOff();
class Lamp {
// true if light is on
boolean isOn;
void turnOn() {
isOn = true;
led.turnOn();
Java Methods
A method is a block of code that performs a specific task.
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.
method body - It includes the programming statements that are used to perform some
tasks. The method body is enclosed inside the curly braces { }.
class Main {
// create a method
int sum = a + b;
// return value
return sum;
// calling method
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.
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.
class Main {
// create a method
// return statement
int result;
result = square(10);
class Main {
obj.display1();
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.
For example,
print() is a method of java.io.PrintSteam. The print("...") method prints the string inside
quotation marks.
// method defined
return x * x;
// method call
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.
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.
class MethodOverloading {
}
© Edunet Foundation. All rights reserved .137
private static void display(int a, int b){
display(1);
display(1, 4);
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 {
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.
class Main {
// constructor
Main() {
System.out.println("Constructor Called:");
name = "Jack";
© Edunet Foundation. All rights reserved .140
}
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
private Constructor() {
© Edunet Foundation. All rights reserved .141
// body of the constructor
class Main {
int i;
private Main() {
i = 5;
System.out.println("Constructor is called");
We have created a constructor Main(). Here, the constructor does not accept any
parameters. Hence, it is known as a no-arg constructor.
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 {
class Main {
String languages;
languages = lang;
We have created a constructor named Main(). Here, the constructor takes a single
parameter. Notice the expression,
Here, we are passing the single value to the constructor. Based on the argument
passed, the language variable is initialized inside the constructor.
class Main {
int a;
boolean b;
System.out.println("Default Value:");
}}
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.
String language;
Main() {
this.language = "Java";
Main(String language) {
this.language = language;
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.
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'.
// create a string
Here, we have created a string variable named type. The variable is initialized with the
string Java Programming.
class Main {
// create strings
// print strings
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.
class Main {
// create a string
In the above example, the length() method calculates the total number of characters
in the string and returns it.
class Main {
// create second
We have created two strings named first and second. Notice the statement,
Here, the concat() method joins the second string to the first string and assigns it to
the joinedString variable.
class Main {
// create 3 strings
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.
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,
Now escape characters tell the compiler to escape double quotes and read the whole
text.
// create a string
Here, we have created a string variable named example. The variable holds the string
"Hello! ".
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.
Since strings in Java are objects, we can create strings using the new keyword as
well. For example,
In the above example, we have created a string name using the new keyword.
class Main {
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.
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).
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.
replace() replaces the specified old character with the specified new
character
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 {
In the above example, we have declared 2 methods: method1() and method2(). Here,
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
When variables and methods are declared private, they cannot be accessed outside
of the class. For example,
class Data {
d.name = "Programiz";
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
System.out.println("I am an animal");
dog.display();
// Animal.java file
// public class
// public variable
// public method
System.out.println("I am an animal.");
// Main.java
animal.legCount = 4;
animal.display();
class Main {
int instVar;
Main(int instVar){
this.instVar = instVar;
Output:
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.
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.
Once any entity (variable, method or class) is declared final, it can be assigned only
once. That is,
class Main {
AGE = 45;
When we run the program, we will get a compilation error with the following message.
AGE = 45;
© Edunet Foundation. All rights reserved .159
^
In Java, the final method cannot be overridden by the child class. For example,
class FinalDemo {
obj.display();
When we run the program, we will get a compilation error with the following message.
obj.display();
When we run the program, we will get a compilation error with the following message.
Its syntax is
class Main {
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).
class Animal {
// to perform inheritance
In the above example, the Dog class is created by inheriting the methods and fields
from the Animal class.
class Animal {
String name;
class Main {
labrador.name = "Rohu";
labrador.eat();
Output
My name is Rohu
I can eat
In the above example, we have derived a subclass Dog from superclass Animal.
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.
class Animal {
@Override
class Main {
labrador.eat();
labrador.bark();
Output
I can bark
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.
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.
class Animal {
@Override
class Main {
labrador.eat();
labrador.bark();
Output
I can eat
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,
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.
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,
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,
3. Hierarchical Inheritance
In hierarchical inheritance, multiple subclasses extend from a single superclass. For
example,
4. Multiple Inheritance
In multiple inheritance, a single subclass extends from multiple superclasses. For
example,
5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance. For example,
class Animal {
System.out.println("I am an animal.");
System.out.println("I am a dog.");
class Main {
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.
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.
class Animal {
System.out.println("I am an animal.");
super.displayInfo();
System.out.println("I am a dog.");
class Main {
d1.displayInfo();
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.
Before we learn about the super keyword, make sure to know about Java inheritance.
class Animal {
// overridden method
// overriding method
@Override
display();
class Main {
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.
class Animal {
// overridden method
System.out.println("I am an animal");
@Override
System.out.println("I am a dog");
display();
super.display();
class Main {
dog1.printMessage();
Output
I am a dog
I am an animal
class Animal {
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.
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.
class Animal {
System.out.println("I am an animal");
Dog() {
super();
System.out.println("I am a dog");
class Main {
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.
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,
...
// throws an error
An abstract class can have both the regular methods and abstract methods. For
example,
// abstract method
// regular method
void method2() {
If a class contains an abstract method, then the class should be declared abstract.
Otherwise, it will generate an error. For example,
// error
class Language {
// abstract 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,
obj.display();
Output
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.
System.out.println("Bark bark");
class Main {
d1.makeSound();
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.
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.
System.out.println("SportsBike Brake");
System.out.println("MountainBike Brake");
class Main {
m1.brake();
s1.brake();
Output:
MountainBike Brake
SportsBike 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().
Here, MountainBike makes its own implementation of brake() and SportsBike makes
its own implementation of brake().
Java Interface
An interface is a fully abstract class. It includes a group of abstract methods (methods
without a body).
interface Language {
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.
interface Polygon {
class Main {
r1.getArea(5, 6);
Output
Here, the Rectangle class implements Polygon. And, provides the implementation of
the getArea() method.
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 {
// extending 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.
interface A {
...
interface B {
...
interface C extends A, B {
...
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,
// 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.
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.
interface Polygon {
void getArea();
// default method
int length = 6;
int breadth = 5;
int length = 5;
class Main {
r1.getArea();
r1.getSides();
s1.getArea();
s1.getSides();
© Edunet Foundation. All rights reserved .193
}
Output
I have 4 sides.
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.
import java.lang.Math;
interface Polygon {
void getArea();
int perimeter = 0;
private int a, b, c;
this.a = a;
this.b = b;
this.c = c;
s = 0;
s = (double) (a + b + c)/2;
area = Math.sqrt(s*(s-a)*(s-b)*(s-c));
class Main {
© Edunet Foundation. All rights reserved .195
public static void main(String[] args) {
t1.getArea();
t1.getPerimeter(2, 3, 4);
Output
Area: 2.9047375096555625
Perimeter: 9
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.
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.
System.out.println("Rendering Polygon...");
// renders Square
System.out.println("Rendering Square...");
// renders circle
System.out.println("Rendering Circle...");
class Main {
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.
class Area {
int length;
int breadth;
this.length = length;
this.breadth = breadth;
class Main {
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.
Why Encapsulation?
In Java, encapsulation helps us to keep related fields and methods together, which
makes our code cleaner and easy to read.
class Person {
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.
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.
1. RuntimeException
These exceptions are not checked at compile-time but run-time. Some of the common
runtime exceptions are:
The NullPointerException would not have occurred if you had checked whether the
variable was initialized or not before using it.
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.
1. try...catch block
2. finally block
3. throw and throws keyword
try {
// code
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.
class Main {
try {
int divideByZero = 5 / 0;
catch (ArithmeticException e) {
Output
In the example, we are trying to divide a number by 0. Here, this code generates an
exception.
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.
The finally block is optional. And, for each try block, there can be only one finally block.
try {
//code
// catch block
finally {
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.
class Main {
try {
catch (ArithmeticException e) {
finally {
Output
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.
When we throw an exception, the flow of the program moves from the try block to the
catch block.
class Main {
divideByZero();
Output
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.
import java.io.*;
class Main {
try {
findFile();
catch (IOException e) {
System.out.println(e);
Output
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.
try{
// code
catch(exception) {
// code
The catch block includes the code that is executed when there occurs an exception
inside the try block.
class Main {
try {
int divideByZero = 5 / 0;
catch (ArithmeticException e) {
Output
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.
We use the throws keyword in the method declaration to declare the type of exceptions
that might occur within it.
// code
As you can see from the above syntax, we can use throws to declare multiple
exceptions.
import java.io.*;
class Main {
try{
findFile();
} catch(IOException e){
Output
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.
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.
throw throwableObject;
class Main {
Output
at Main.divideByZero(Main.java:3)
at Main.main(Main.java:7)
exit status 1
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.
@AnnotationName
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.
class Animal {
System.out.println("I am an animal.");
@Override
System.out.println("I am a dog.");
class Main {
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.
@AnnotationName()
© Edunet Foundation. All rights reserved .212
Since these annotations do not contain elements, parentheses can be excluded. For
example,
@Override
@AnnotationName(elementName = "elementValue")
@AnnotationName(value = "elementValue")
In this case, the element name can be excluded as well. The element name will be
value by default.
@AnnotationName("elementValue")
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.
import java.util.*;
class Main {
wordList.add("MS-SAP");
wordsList();
Output
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
Type definitions
Type casts
throws clause
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.
1. Predefined annotations
@Deprecated
@Override
@SuppressWarnings
@SafeVarargs
@FunctionalInterface
2. Custom annotations
3. Meta-annotations
@Retention
@Documented
@Target
@Inherited
@Repeatable
@Deprecated
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
*/
@Deprecated
class Main {
/**
* @deprecated
*/
@Deprecated
System.out.println("Deprecated method");
deprecatedMethod();
Output
Deprecated method
class Animal {
// overridden method
System.out.println("I am an animal");
// overriding method
@Override
System.out.println("I am a dog");
display();
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.
@SuppressWarnings("warningCategory")
For example,
@SuppressWarnings("deprecated")
@SuppressWarnings({"warningCategory1", "warningCategory2"})
For example,
@SuppressWarnings({"deprecated", "unchecked"})
@SuppressWarnings("someundefinedwarning")
class Main {
@Deprecated
System.out.println("Deprecated method");
@SuppressWarnings("deprecated")
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
// Initialization code...
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.
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.
// Servlet code
A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.
// Servlet code
After the destroy() method is called, the servlet object is marked for garbage collection.
The destroy method definition looks like this −
// 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.
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 java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Do required initialization
response.setContentType("text/html");
// 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.
$ 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
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.
<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>
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
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:
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.
It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
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.
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
All the above mentioned steps can be seen in the following diagram −
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.
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 –
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.
JSP Initialization
// 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.
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.
JSP – Syntax
Elements of JSP
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.
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/>
<%
%>
</html>
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.
You can write the XML equivalent of the above syntax as follows −
<jsp:declaration>
code fragment
</jsp:declaration>
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.
You can write the XML equivalent of the above syntax as follows −
<jsp:expression>
expression
</jsp:expression>
<html>
<body>
</body>
</html>
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 −
<html>
<body>
<%-- 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
–
3 <\%
4 %\>
5 \'
© Edunet Foundation. All rights reserved .243
A single quote in an attribute that uses single quotes.
6 \"
JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has the
following form −
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 −
10. jsp:text Used to write template text in JSP pages and documents.
1 request
2 response
© Edunet Foundation. All rights reserved .245
This is the HttpServletResponse object associated with the response to
the client.
3 out
4 session
5 application
6 config
7 pageContext
8 page
This is simply a synonym for this, and is used to call the methods
defined by the translated servlet class.
9 Exception
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.
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.
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.
• getInputStream() − Call this method to read binary data stream coming from
the client.
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>
</head>
<body>
<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>
<html>
<body>
<br />
</form>
</html>
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>
</head>
<body>
<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>
</body>
</html>
<html>
<body>
<br />
</form>
</body>
</html>
Following is an example HTML code, CheckBox.htm, for a form with two checkboxes.
<body>
</form>
</body>
</html>
Following is main.jsp JSP program to handle the input given by the web browser for
the checkbox button.
<html>
<head>
</head>
<body>
<ul>
<li><p><b>Maths Flag:</b>
<%= request.getParameter("maths")%>
</p></li>
<%= request.getParameter("physics")%>
</p></li>
<li><p><b>Chemistry Flag:</b>
<%= request.getParameter("chemistry")%>
</p></li>
</ul>
</body>
</html>
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.
<html>
<head>
</head>
<body>
<th>Param Name</th>
<th>Param Value(s)</th>
</tr>
<%
while(paramNames.hasMoreElements()) {
%>
</table>
</center>
</body>
</html>
<html>
<body>
</form>
</body>
</html>
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.
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.
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.
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 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().
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.
<%
if (session.isNew() ){
session.setAttribute(userIDKey, userID);
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>
<th>Session info</th>
<th>Value</th>
</tr>
<tr>
<td>id</td>
</tr>
<tr>
© Edunet Foundation. All rights reserved .258
<td>Creation Time</td>
</tr>
<tr>
</tr>
<tr>
<td>User ID</td>
</tr>
<tr>
<td>Number of visits</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 –
<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.
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.
HTTP/1.1 200 OK
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
Host: zink.demon.co.uk:1126
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
A JSP script will then have access to the cookies through the request method
request.getCookies() which returns an array of Cookie objects.
You call the Cookie constructor with a cookie name and a cookie value, both of which
are strings.
Neither the name nor the value should contain white space or any of the following
characters −
[]()=,"/?@:;
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);
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.
<%
lastName.setMaxAge(60*60*24);
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>
<br />
</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
Example
Let us now read cookies that were set in the previous example −
<html>
<head>
<title>Reading Cookies</title>
<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
cookies = request.getCookies();
cookie = cookies[i];
} else {
%>
</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 −
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>
<%
cookies = request.getCookies();
cookie = cookies[i];
if((cookie.getName( )).compareTo("first_name") == 0 ) {
cookie.setMaxAge(0);
response.addCookie(cookie);
cookie.getName( ) + "<br/>");
} else {
out.println(
}
© 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.
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 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 −
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.
<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>
</jsp:text>
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 −
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")}
${pageContext.request.queryString}
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.
For example, to access a parameter named order, use the expression ${param.order}
or ${param["order"]}.
<html>
<head>
<body>
<center>
</center>
<p>${param["username"]}</p>
</div>
</body>
</html>
The param object returns single string values, whereas the paramValues object
returns string arrays.
<html>
<head>
</head>
<center>
</center>
<p>${header["user-agent"]}</p>
</div>
</body>
</html>
The header object returns single string values, whereas the headerValues object
returns string arrays.
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.
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.
• Core Tags
• Formatting tags
• SQL tags
• XML tags
• JSTL Functions
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 −
SQL Tags
The JSTL SQL tag library provides tags for interacting with relational databases
(RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server.
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.
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 −
What is a database?
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.
• 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.
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:
• 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
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.
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.
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.
Simplicity:
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:
Efficiency:
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 open -source DBMS and the following are the
reasons behind it:
Features 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
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.
DDL statements are used to alter/modify a database or table structure and schema.
These statements handle the design and storage of database objects.
DCL statements control the level of access that users have on database objects.
TCL statements allow you to control and manage transactions to maintain the
integrity of data within SQL statements.
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
Example
Example:
The ALTER command can also be used for dropping a column from the table:
General Syntax:
Example:
</pre.
Example:
DROP
Used for deleting an entire table from the database and all the data stored in it.
General Syntax:
Example:
RENAME
Example:
TRUNCATE
Used for deleting all rows from a table and free the space containing the table.
General Syntax:
Example:
INSERT
OR
Example:
Insert command can also be used for inserting data into a table from another table.
General Syntax:
Example:
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:
Example:
Example:
This will allow the user to run only SELECT and UPDATE operations on the Student
table.
Allows the user to run all commands on the table as well as grant access privileges
to other users.
REVOKE
Example:
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:
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:
ROLLBACK;
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:
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
Example
Example:
The ALTER command can also be used for dropping a column from the table:
General Syntax:
Example:
</pre.
Example:
DROP
Used for deleting an entire table from the database and all the data stored in it.
General Syntax:
Example:
RENAME
Example:
TRUNCATE
Used for deleting all rows from a table and free the space containing the table.
General Syntax:
Example:
INSERT
OR
Example:
Example:
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:
Example:
The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.
• 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 −
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
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:
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.
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.
Advantage:
Disadvantage:
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.
Advantage:
Disadvantages:
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.
Advantage:
Disadvantage:
There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:
The forName() method of Class class is used to register the driver class. This method
is used to dynamically load the driver class.
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
con.close();
To begin, make sure you have the following pieces of software installed on your
computer:
Let’s create a MySQL database called SampleDB with one table Users with the
following structure:
use SampleDB;
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:
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:
• 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.
try {
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
(?, ?, ?, ?)";
SELECT Statement
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");
UPDATE Statement
DELETE Statement
• 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
Step 1
Step 2
import java.util.List;
Step 3
import java.util.ArrayList;
import java.util.List;
public StudentDaoImpl(){
@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
//update student
Step 5
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
1. Create a User
2. Update a User
3. Delete a User
4. Retrieve a User
5. List of all Users
• 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
Class Diagram
3. Click Next.
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
Let's create a database named "demo" in MySQL. Now, create a user’s table using
below DDL script:
You can use either MySQL Command Line Client or MySQL Workbench tool to
create the database. The above a user’s table looks like:
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 User() {}
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;
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() {}
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;
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);
}
}
}
}
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:
<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">
<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>
<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:
Next, we create a JSP page for creating a new User called user-form.jsp. Here’s its
full source code:
<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>
<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>
</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:
Here’s the code of the Error.jsp page which simply shows the exception message:
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/
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
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.”
Features of NoSQL
Non-relational
Schema-free
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
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:
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.
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
They deliver high performance on aggregation queries like SUM, COUNT, AVG, MIN
etc. as the data is readily available in a column.
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
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,
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.
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
Graph base database mostly used for social networks, logistics, spatial data.
Advantages of NoSQL
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.
name : "Program",
rollno : 1,
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
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 {
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
Create a Collection
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class CreatingCollection {
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
//Creating a collection
database.createCollection("sampleCollection");
System.out.println("Collection created successfully");
}
}
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 {
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
// 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
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 );
// 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");
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 Credentials
MongoCredential credential;
// 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
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 {
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
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;
// Creating Credentials
MongoCredential credential;
credential = MongoCredential.createCredential("sampleUser", "myDb",
"password".toCharArray());
System.out.println("Connected to the database successfully");
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 {
// 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");
}
}
import com.mongodb.client.MongoDatabase;
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
public class ListOfCollection {
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.
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.
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.
o React Native:
React includes the react libraries. They provide the react architecture to the native
applications such as Android and iOS.
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.
Flux is a pattern that keeps your data flow unidirectional. React follows the one-way
data flow to process your code.
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.
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
o Easy to Learn:
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.
ReactJS applications are easily testable. You can easily set triggers, events, functions
and debug the code. You can easily debug the code.
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.
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.
There are two ways to set up an environment for successful ReactJS application. They are given
below.
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.
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.
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.
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.
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.
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.
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
1. Functional 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) {
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.
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
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.
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.
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
➢ VSCode
➢ Eclipse IDE
➢ react-bootstrap
➢ Maven
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,
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.
Project Structure
and Java code resides under the src/main/java folder. All the resources are under the
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.
Once you import the zip file in the eclipse or any other IDE as a Maven project you can see all
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
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>
</parent>
<groupId>com.bbtutorials</groupId>
<artifactId>users</artifactId>
<version>0.0.2-SNAPSHOT</version>
<name>users</name>
<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>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-apt</artifactId>
</dependency>
<dependency>
<groupId>com.querydsl</groupId>
<artifactId>querydsl-jpa</artifactId>
</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
SpringApplication.run(UsersApplication.class, args);
UsersController.java
package com.bbtutorials.users.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
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/")
@Autowired
UsersService usersService;
@GetMapping(path = UserLinks.LIST_USERS)
return ResponseEntity.ok(resource);
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
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
);
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.
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
@Id
@Column
@Column
@NotNull(message="{NotNull.User.firstName}")
@Column
@NotNull(message="{NotNull.User.lastName}")
@Column
@NotNull(message="{NotNull.User.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()
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
this.usersRepository = usersRepository;
return usersRepository.findAll();
users.setId(new Random().nextInt());
return usersRepository.save(users);
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
Finally, you can list all the users with this endpoint http://localhost:8080/api/users.
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
method: 'POST',
© Edunet Foundation. All rights reserved .379
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
})
Here is the app component which subscribes to these calls and gets the data from the
API.
App.js
state = {
user: {},
users: [],
numberOfUsers: 0
}
getAllUsers = () => {
getAllUsers()
.then(users => {
console.log(users)
this.setState({users: users, numberOfUsers: users.length})
});
}
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>
);
}
}
In the development phase, the React app is running on port 3000 with the help of a create-
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
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.
cd src/mamin/ui
npm start
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.
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 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>
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”.
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>
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.
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
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.
SimpleUrlHandlerMapping
<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>
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:
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.
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:
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
<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
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
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>
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 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.
There are many problems that we face during the project development. They are
discussed below:
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?
2. It provides uniform build process (maven project can be shared by all the maven
projects)
o Builds
o Documentation
o Reporing
o Releases
o Distribution
A build tool takes care of everything for building a process. It does following:
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.
4. Verify Maven
1) Download Maven
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:
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.
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.
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
If dependency is not found in these repositories, maven stops processing and throws
an error.
Maven local repository is located in your local system. It is created by the maven
when you run any maven command.
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.
<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>
Maven central repository is located on the web. It has been created by the apache
maven community itself.
The central repository contains a lot of common libraries that can be viewed by this
url http://search.maven.org/#browse.
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>
<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.
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.
Before maven 2, it was named as project.xml file. But, since maven 2 (also in maven
3), it is renamed as pom.xml.
Element Description
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.
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>
<artifactId>my-app</artifactId>
<version>1</version>
</project>
Here, we are going to add other elements in pom.xml file such as:
Element Description
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>
<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>
1. @Controller Annotation
<context:component-scan base-package="com.javadevjournal">
@Controller
//HTTP Mappings
2. @RestController Annotation
@RestController
@GetMapping
@GetMapping(value = "/greeting")
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.
@RequestMapping(value = {
"/greetings",
consumes = {"application/json","application/xml"},
})
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
})
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")
//
With @RequestParam we can specify default value when Spring finds no or empty
value in the request.
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}")
//
@GetMapping("/products/{id}")
//
@GetMapping("/products/{id}")
//
6. @SessionAttribute
@GetMapping("/user")
//
7. @RequestBody
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}")
//
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")
//
@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
binder.setValidator(customValidator);
11. @ModelAttribute
@PostMapping("/customer-registration")
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")
//
we don’t have to specify the model key, Spring uses the method’s name by default
@ModelAttribute
//
@Autowired
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")
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.
pom.xml
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.1.RELEASE</version>
</dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jasper</artifactId>
<version>9.0.12</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>3.0-alpha-1</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<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>
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;
return id;
this.id = id;
return name;
this.name = name;
return salary;
this.salary = salary;
return designation;
this.designation = designation;
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
@Autowired
/*It displays a form to input data, here "command" is a reserved request attribut
e
*/
return "empform";
/*It saves object into database. The @ModelAttribute puts request data
@RequestMapping(value="/save",method = RequestMethod.POST)
dao.save(emp);
@RequestMapping("/viewemp")
List<Emp> list=dao.getEmployees();
m.addAttribute("list",list);
return "viewemp";
@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";
@RequestMapping(value="/editsave",method = RequestMethod.POST)
dao.update(emp);
return "redirect:/viewemp";
@RequestMapping(value="/deleteemp/{id}",method = RequestMethod.GET)
dao.delete(id);
return "redirect:/viewemp";
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;
JdbcTemplate template;
this.template = template;
return template.update(sql);
return template.update(sql);
return template.update(sql);
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setSalary(rs.getFloat(3));
e.setDesignation(rs.getString(4));
return e;
});
web.xml
<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>
spring-servlet.xml
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">
</bean>
</bean>
</bean>
</bean>
</beans>
index.jsp
empform.jsp
<table >
<tr>
<td>Name : </td>
</tr>
<tr>
<td>Salary :</td>
</tr>
<tr>
<td>Designation :</td>
</tr>
<tr>
<td> </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.
<h1>Edit Employee</h1>
<table >
<tr>
<td></td>
</tr>
<tr>
<td>Name : </td>
</tr>
<tr>
<td>Salary :</td>
</tr>
<td>Designation :</td>
</tr>
<tr>
<td> </td>
</tr>
</table>
</form:form>
viewemp.jsp
<h1>Employees List</h1>
<tr><th>Id</th><th>Name</th><th>Salary</th><th>Designation</th><th>Edit<
/th><th>Delete</th></tr>
<tr>
<td>${emp.id}</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/>
Output:
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.
We can use Spring STS IDE or Spring Initializr to develop Spring Boot Java
applications.
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 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 offers a CLI tool for developing and testing the Spring Boot application.
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.
Spring Boot can use dependencies that are not going to be used in the application.
These dependencies increase the size of the application.
The main goal of Spring Boot is to reduce development, unit test, and integration
test time.
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 Web Development
o SpringApplication
o Admin features
o Externalized Configuration
o Properties Files
o YAML Support
o Type-safe Configuration
o Logging
o Security
Web Development
SpringApplication
SpringApplication.run(ClassName.class, args);
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.
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
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
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
The latest version of Spring Boot is 2.0. It introduces a lot of new features along with
some modifications and replacement.
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 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.
Database Layer: In the database layer, CRUD (create, retrieve, update, delete)
operations are performed.
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 In the service layer, all the business logic performs. It performs the logic on
the data that is mapped to JPA with model classes.
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.
o initializr-generator-spring:
Supported Interface
o It supports IDE STS, IntelliJ IDEA Ultimate, NetBeans, Eclipse. You can
download the plugin from https://github.com/AlexFalappa/nb-springboot
or https://start-scs.cfapps.io
Before creating a project, we must be friendly with UI. Spring Initializr UI has the
following labels:
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 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.
Installing STS
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.
Step 2: Provide the Group and Artifact name. We have provided Group
name com.javatpoint and Artifact spring-boot-example.
When we click on the Generate button, it starts packing the project in a .rar file and
downloads the project.
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
SpringApplication.run(SpringBootExampleApplication.class, args);
pom.xml
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.BUILD-SNAPSHOT</version>
</parent>
<groupId>com.javatpoint</groupId>
<artifactId>spring-boot-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-example</name>
<properties>
</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>
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.
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.
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.
where,
For example:
For example:
o The interfaces allow Spring to find the repository interface and create proxy
objects for that.
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().
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.
Books.java
package com.javatpoint.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
@Id
@Column
@Column
@Column
@Column
return bookid;
this.bookid = bookid;
return bookname;
}
© Edunet Foundation. All rights reserved .469
public void setBookname(String bookname)
this.bookname = bookname;
return author;
this.author = author;
return price;
this.price = price;
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;
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;
@RestController
@Autowired
BooksService booksService;
//creating a get mapping that retrieves all the books detail from the database
@GetMapping("/book")
return booksService.getAllBooks();
@GetMapping("/book/{bookid}")
{
© Edunet Foundation. All rights reserved .472
return booksService.getBooksById(bookid);
@DeleteMapping("/book/{bookid}")
booksService.delete(bookid);
//creating post mapping that post the book detail in the database
@PostMapping("/books")
booksService.saveOrUpdate(books);
return books.getBookid();
@PutMapping("/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;
@Service
@Autowired
BooksRepository booksRepository;
return booksRepository.findById(id).get();
booksRepository.save(books);
booksRepository.deleteById(id);
//updating a record
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;
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
After creating all the classes and packages, the project directory looks like the
following.
SpringBootCrudOperationApplication.java
package com.javatpoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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.
o Insert the data. We have inserted the following data in the Body:
"bookid": "5433",
"price": "800"
"bookid": "0982",
"price": "350"
"bookid": "6321",
"price": "590"
"bookid": "5433",
"price": "670"
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.
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 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",
"price": "500"
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.