Question Bank With Solution Web Technology (BCS-502)
Question Bank With Solution Web Technology (BCS-502)
Ques. COs
No.
Questions
Define Protocol. Provide the name of protocols governing web.
1 CO1
What is a web project?Explain web development strategies. Also explain Web Team?
2 CO1
What is client server relationship? How it is implemented? How client server paradigm is different from peer to peer
3 CO1 paradigm?
Differentiate between Internet and WWW? What are the different services provided by Internet?
4 CO1
Create an HTML code to create a web page that contains the user registration form with following details user name,
5 CO1 user date of birth, user address, user gender, user email id, user mobile number.
What do you understand by hyperlinks in HTML? Write mark-up for an image hyperlink
8 CO1
Write HTML code to design “a form for online Railway Reservation Website” (Make Assumptions). OR Write the HTML
9 CO1 code to design a Student registration form. (Assume fields).
10 CO1
Explain <iframe> and frameset. Explain the anchor and table tag in HTML?
11 CO1
Design a XML DTD for self describing weather report having following details: Date, location, temperature range
(Location describes city, state and its country. Country code is unique and not left blank. Temperature range describes
13 CO1
high and low temp. in Fahrenheit or Celsius)
Write an example of XML DTD. What are rules for writing DTD? Schema.
14 CO1
Write suitable XML markup to display the data of books with title, author, publisher and price. Explain well formed and
15 CO1 valid xml?
Design HTML document that divides the browser screen into two frames. The frame on the left will be a menu consisting
16 CO1 of hyperlinks. Clicking on any one of these links will lead to a new page open in the target frame on right hand side.
CO2 Create a css rule that makes all the text 2 times larger than the base font of the system. Mention can you integrate css
23 on a web page.
CO2 What is CSS? Discuss the different ways to create CSS. Explain with example.
24
CO2 Explain the difference between id and class selector in css?
25
CO2 Write the syntax of CSS property that can be used to remove the underline from a hyperlink.
28
CO2 Construct a web page using CSS to show the 3 horizontal and 3 vertical navigation bars that links to the different web
29 pages
CO2 Explain box model in CSS. Design a web page with a table of 6 rows. Use nthchild property of CSS to color Odd rows and
30 even rows in different colors. Highlight the even rows on mouse over.
CO2 Explain cascading and the style precedence rules when using multiple approaches.
31
CO2 Explain image spites with example. Explain Float css property.
32
CO2 Write code to create different types of link using pseudo-class selector.
38
CO3 Construct a JavaScript program using text boxes, two for inputs and others for output, implement four operations
41 addition, subtraction, multiplication and division on two input numbers on clicking of buttons ‘add’, ‘subtract’, ‘multiply’
and ‘divide’. Print the result in text box.
CO3 Discuss in brief how to perform Client Side Validation like Mandatory fields and Email field using Java Script? Justify with
42 a suitable example.
CO3 Design a JavaScript program to display the current day and time in the following format. Today is : Monday. Current time
43 is : 11 AM : 50 : 58
CO3 Why do we need client side scripting languages like Java Script? How AJAX like technologies is so useful these days? How
44 AJAX is used for single page processing?
CO3 Illustrate Array in JavaScript. Create a program in JavaScript to implement an array of five elements and perform the
45 operationspush, pop, shift, unshift and join on the array.
CO3 Write a program in JavaScript to print first n terms of Fibonacci series (0, 1, 1, 2, 3, 5, 8, 13, 21, 34…)
46
CO3 Discuss function in Java Script. Outline a JS function that takes 4 variables, a, b, c, d, and prints true in an alert box if
50 input a > input b and input c > input d. Else, print false in an alert box
CO3 What is AJAX? Explain its advantage and its working? Explain with example?
51
CO3 Describe various applications of JavaScript as a client side scripting language.
52
CO3 Illustrate and compare various dialog boxes in JavaScript with suitable JavaScript code.
53
CO3 Describe URL class in Java. Write a Java code display protocol, port number, host of given url with the help of this class.
54
CO3 Explain Factory methods with example.Create a Java program to find out the IP address of your machine
58
CO4 Explain the EJB Architecture . Explain session bean, message bean and entity beans. Also explain the drawbacks of EJBs.
59
CO4 Illustrate Java Bean. Explain Properties of java Bean. Give example.
60
CO4 What are the data types in MongoDB?How do you Delete a Document?
73
CO4 What is a Document in MongoDB?Explain InsertOne and InsertMany command in MongoDB with example.
77
CO5 Explain the architecture and lifecycle of a JavaServer Page (JSP) within a web application.
85
CO5 Discuss the different types of standard action tags used in JSP.
88
CO5 Define the advantages of servlet over CGI? Explain with an example
89
CO5 Illustrate why the session is required in web applications. Mention all the session tracking techniques in servlet with their
90 pros and cons. Also give example of each.
CO5 Describe Servlet. Explain types of Servlet. Give an example of HttpServlet. Write steps to execute the servlet.
91
CO5 What are Java Server Pages? Explain life cycle of a JSP page? How JSP are better than Servlets?
92
CO5 What are JSP directives? Explain various types of directives with example?
94
CO5 Explain the Life cycle of servlet? Also write a servlet for displaying a string “HELLO WORLD!”
96
CO5 What are java Beans? Why they are used? Write a JSP page and use an existing java bean in JSP page by using the
97 standard action. Write the program with describing the output?
CO5 Discuss the role of the HttpServletRequest and HttpServletResponse interfaces in servlet programming.
98
CO5 Discuss the compilation process of JSP files into servlets and how they are executed by the servlet container.
99
CO5 Provide examples of how you can use these interfaces to retrieve request parameters, set response headers, and send
100 data back to the client.
Web Technology((BCS-502)
Unit -1 Question Bank With Solution
Q1. Define Protocol. Provide the name of protocols governing the web.
A protocol is a set of rules that explain how to conduct oneself in formal situations or
how to transmit data between entities. Protocols can be implemented by software or
hardware, but they are not software or hardware themselves.
Types of Internet Protocol
Web Team: the collection of workers who are brought together in order to create digital-
based content. Within that team, there can be a number of roles. The number is varied and
could actually change depending on the task given to the team.
Q.3.What is client server relationship? How it is implemented? How client server paradigm is
different from peer to peer paradigm?
The client-server relationship is a networking model where a client program requests a service
or resource from a server program. The client and server communicate using a request-
response pattern, where the client sends a request and the server responds. The client and
server must follow a common communications protocol to ensure they know what to expect.
Communications protocol
The client and server use a common communications protocol to define the rules,
language, and dialog patterns for communication. TCP/IP is a common protocol used for
client-server communication.
Application programming interface (API)
The server may use an API to formalize data exchange. An API is an abstraction layer that
restricts communication to a specific content format.
Scheduling system
The server uses a scheduling system to prioritize incoming requests from clients.
Server software
The server software may limit availability to clients to prevent abuse and maximize
availability.
The client-server relationship differs from the peer-to-peer relationship in several ways:
The main difference between the client-server and peer-to-peer paradigms is that in a client-
server network, clients request services from a server, while in a peer-to-peer network, each
node can request and provide services:
Network type
A client-server network is centralized, while a peer-to-peer network is decentralized.
Cost
A client-server network is more expensive to set up, while a peer-to-peer network doesn't
require as much equipment.
Reliability and security
A client-server network is more reliable and secure than a peer-to-peer network.
Load balancing
In a client-server network, load balancing distributes network traffic across multiple
servers. In a peer-to-peer network, an algorithm balances load, and peers with modest
resources can help share the load.
Both client-server and peer-to-peer networks use dedicated servers, TCP/PP-based protocols,
and support devices in both client and server roles.
Q.4. Differentiate between the Internet and WWW? What are the different services provided
by the Internet?
The main difference between the internet and the World Wide Web (WWW) is that the
internet is a network of computers that the WWW runs on, while the WWW is a service offered
by the internet:
The internet
A global network of computers that connects devices all over the world using copper
wires, fiber optic connections, or wireless networks. The internet is a public network
that anyone can connect to. It's a superset of the WWW, and is administered by
organizations like the Internet Assigned Numbers Authority (IANA).
The WWW
A service that allows users to access online information structured in HTML over the HTTP
protocol. The WWW is a subset of the internet, and is more software-oriented than the
internet, which is primarily based on hardware. The WWW's existence depends on the
internet.
● Information dissemination: The internet allows people to share and exchange resources
and information.
● Data availability: The internet makes data resources available.
Q.5.Create an HTML code to create a web page that contains the user registration form with
following details user name, user date of birth, user address, user gender, user email id, user
mobile number.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>User Registration Form</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
.container {
width: 50%;
margin: 50px auto;
padding: 20px;
background-color: #fff;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
color: #333;
}
label {
display: block;
margin: 10px 0 5px;
color: #333;
}
input[type="text"], input[type="email"], input[type="date"], input[type="tel"], textarea {
width: 100%;
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
margin-bottom: 20px;
}
input[type="radio"], input[type="checkbox"] {
margin-right: 10px;
}
.form-group {
margin-bottom: 15px;
}
.gender-group {
display: inline-block;
}
.btn {
display: inline-block;
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
.btn:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="container">
<h2>User Registration Form</h2>
<form action="#" method="post">
<!-- User Name -->
<div class="form-group">
<label for="username">User Name:</label>
<input type="text" id="username" name="username" required>
</div>
</body>
</html>
In web development, a form is an HTML element that allows users to input data, which can
then be sent to a server for processing. Forms are used to collect data from users such as text,
selection choices, dates, numbers, and more. Common examples include login forms,
registration forms, search boxes, feedback forms, and contact forms.
A form typically consists of various input elements (like text fields, checkboxes, radio buttons,
dropdowns, etc.) and is usually enclosed within the <form> HTML tag. When the user submits
the form, the data entered in the form is sent to a web server for further processing (such as
storing in a database, sending an email, etc.).
method Defines how the data will be sent to the server. method="POST"
Common values are GET (appends data to the URL)
and POST (sends data in the request body).
action Specifies the URL where the form data will be action="process_form.php"
submitted. This can be a server-side script, the
same page, or an external URL.
● Use POST when dealing with sensitive or large data.
● Use GET for search forms or when you want to pass parameters in the URL.
● Always set the action attribute to the correct endpoint for data processing.
In HTML, lists are used to group related items together. There are two main types of lists:
1. Ordered List (<ol>): This list is used when the order of the list items is important. It
displays items in a numbered or alphabetized sequence.
2. Unordered List (<ul>): This list is used when the order of the list items is not important.
It displays items with bullet points (or other symbols) instead of numbers or letters.
Purpose Used when the order of items matters Used when the order of items
(e.g., steps in a process, rankings). does not matter (e.g., a list of
features).
List Marker Displays a numbered list (default is Displays a bullet point (typically
numeric, but can be customized to a circle).
Roman numerals, letters, etc.).
List Items <li> (List Item) inside <ol> <li> (List Item) inside <ul>
Customization Can be customized to show letters (a, b, Bullet style can be customized
c, ...) or Roman numerals (i, ii, iii, ...). to use square boxes, circles, or
other shapes.
Use Cases When order or ranking matters (e.g., When order is not important
instructions, ranking lists). (e.g., lists of features,
ingredients).
Q.8.What do you understand by hyperlinks in HTML? Write mark-up for an image hyperlink
Hyperlinks in HTML are used to link one page to another or to specific sections within a page.
They are created using the <a> tag. To create an image hyperlink, you wrap the <img> tag inside
an <a> tag. Here’s an example:
<a href="https://www.example.com">
<img src="image.jpg" alt="Description of Image">
</a>
Q.9. Write HTML code to design “a form for online Railway Reservation Website” (Make
Assumptions). OR Write the HTML code to design a Student registration form. (Assume
fields).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Student Registration Form</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f4f4f9;
}
.container {
width: 50%;
margin: 50px auto;
padding: 20px;
background-color: white;
border-radius: 8px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
h2 {
text-align: center;
color: #333;
}
label {
display: block;
margin: 10px 0 5px;
font-weight: bold;
}
input[type="text"],
input[type="email"],
input[type="password"],
input[type="tel"],
select,
textarea {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 4px;
box-sizing: border-box;
}
input[type="radio"],
input[type="checkbox"] {
margin-right: 10px;
}
button {
background-color: #4CAF50;
color: white;
border: none;
padding: 12px 20px;
cursor: pointer;
border-radius: 4px;
width: 100%;
}
button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="container">
<h2>Student Registration Form</h2>
<form action="/submit" method="POST">
<!-- Personal Information Section -->
<label for="first-name">First Name:</label>
<input type="text" id="first-name" name="first_name" required>
<label for="gender">Gender:</label>
<input type="radio" id="male" name="gender" value="male" required>
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
<label for="terms">
<input type="checkbox" id="terms" name="terms" required>
I agree to the <a href="#">terms and conditions</a>.
</label>
<button type="submit">Register</button>
</form>
</div>
</body>
</html>
HTML Frames
In HTML, a frame is used to display multiple, independent sections or documents within a single
web page. Frames are typically used to divide a browser window into different sections, where
each section can independently load different web pages. This technique allows for more
interactive or complex page layouts. Frames were traditionally created using the <frame> and
<frameset> elements in HTML.
However, HTML frames are now considered obsolete in modern web design, and they have
been replaced by more flexible techniques such as CSS and JavaScript. Despite this, it’s still
useful to understand how they worked historically and their advantages.
<frame src="page1.html">
<frame src="page2.html">
</frameset>
Advantages of Frames :
An iframe (inline frame) is an HTML element used to embed another HTML document inside
the current document. Unlike traditional frames (which were used to divide a browser window
into multiple sections), the <iframe> is used to display a separate document within a designated
area of a page.
Syntax:
<frameset>
The <frameset> element was used in earlier versions of HTML (HTML 4) to create a layout with
multiple, independent frames within a page. It replaced the <body> tag and allowed for dividing
the browser window into multiple sections (rows or columns). Each section could load a
different HTML document.
<frameset cols="50%, 50%">
<frame src="page1.html">
<frame src="page2.html">
</frameset>
The <a> tag, also known as the anchor tag, is used to create hyperlinks that allow users to
navigate from one page to another or to a specific part of a page. It is one of the most essential
elements for web navigation.
The <table> tag is used to display tabular data (rows and columns). Tables are useful for
presenting structured information like lists, schedules, statistics, and more.
Attributes:
● border: Specifies whether the table has a border (usually set with CSS).
● cellpadding: Defines the space between the cell content and the cell border.
● cellspacing: Defines the space between individual cells.
● width, height: Specifies the dimensions of the table.
● style: Allows you to add CSS for styling the table.
Use Cases:
<table border="1">
<caption>Student Information</caption>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
<tr>
<td>John Doe</td>
<td>18</td>
<td>A</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>17</td>
<td>B</td>
</tr>
</tbody>
</table>
Q.13.Design a XML DTD for self describing weather report having following details: Date,
location, temperature range (Location describes city, state and its country. Country code is
unique and not left blank. Temperature range describes high and low temp. in Fahrenheit or
Celsius)
● WeatherReport: This is the root element, which contains Date, Location, and
TemperatureRange.
● Date: Contains the date information (a textual value, such as "2024-12-06").
● Location: Contains three sub-elements: City, State, and Country.
○ City: The city name (e.g., "Los Angeles").
○ State: The state name (e.g., "California").
○ Country: The country name (e.g., "USA") with an attribute code, which is a
unique ID for the country (e.g., "US").
● TemperatureRange: Contains two sub-elements: High and Low, which describe the high
and low temperatures.
○ High and Low both have a unit attribute that specifies whether the temperature
is in Fahrenheit or Celsius.
○ High: The high temperature (e.g., "75").
○ Low: The low temperature (e.g., "60").
○ unit attribute for both High and Low: This attribute specifies the temperature
unit, and it can either be "Fahrenheit" or "Celsius".
Q.14. Write an example of XML DTD. What are the rules for writing DTD? .
Rules for Writing DTD (Document Type Definition):
1. Elements Declaration:
○ Use the <!ELEMENT> keyword to define elements and their content models.
○ Content Models:
■ #PCDATA (Parsed Character Data) is used for text content within an
element.
■ Parentheses () are used to group elements and define the sequence.
■ A + sign means that the element appears one or more times (e.g.,
<Library> (Book+) means a Library must contain one or more books).
■ A * sign means that the element can appear zero or more times.
■ A ? sign means that the element is optional (can appear zero or one
time).
2. Attributes Declaration:
○ Use the <!ATTLIST> keyword to define attributes for elements.
4.Comments:
● Comments in DTD can be added using the syntax <!-- comment -->.
5.External/Internal DTD:
● External DTD: Stored in a separate file (e.g., library.dtd), and referenced in the XML file.
● Internal DTD: Defined within the XML file itself, typically between <!DOCTYPE> and the
root element.
Q.15.Write suitable XML markup to display the data of books with title, author, publisher and
price. Explain well formed and valid xml?
Explanation:
This XML file has three books, each with the required information.
Q.16.Design HTML document that divides the browser screen into two frames. The frame on
the left will be a menu consisting of hyperlinks. Clicking on any one of these links will lead to
a new page open in the target frame on right hand side.
To create an HTML document that divides the browser screen into two frames, where the left
side acts as a menu containing hyperlinks, and the right side displays the content corresponding
to the selected link, you can use the <frameset> element. However, please note that the
<frameset> element is deprecated in HTML5 in favor of more modern layout techniques like
CSS Flexbox or CSS Grid.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frame Layout Example</title>
</head>
<body>
</body>
</html>
Explanation:
1. <frameset>: The <frameset> tag defines a set of frames. In this case, it divides the
screen into two columns. The cols="25%, 75%" attribute means the left column will take
up 25% of the screen width, and the right column will take up 75%.
2. Left Frame (<frame src="menu.html" name="menu">): This frame contains the menu,
and it is named "menu". The src attribute specifies the content of the left frame (e.g.,
menu.html).
3. Right Frame (<frame src="home.html" name="content">): This frame is where the
content will appear based on the selected link from the menu. The name="content"
attribute allows links in the left frame (menu) to target this specific frame.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Menu</title>
</head>
<body>
<ul>
</ul>
</body>
</html
Explanation of menu.html:
● The menu consists of an unordered list (<ul>).
● Each list item (<li>) contains a hyperlink (<a>). The target="content" attribute ensures
that when a link is clicked, the corresponding content is loaded in the right frame
(content).
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Page 1</title>
</head>
<body>
<h1>Welcome to Page 1</h1>
<p>This is the content of Page 1.</p>
</body>
</html>
Tags Predefined tags (e.g., <h1>, <p>) Custom tags defined by the user
Tag Closing Not always required (some tags are Strictly requires closing or self-
self-closing) closing tags
Strictness Lenient (browser fixes some errors) Strict (errors prevent processing)
Validation Optional validation (HTML5 Mandatory validation via DTD or
specification) XSD
Error Handling Tolerates errors and tries to render Fails if the syntax is incorrect
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Book Catalog</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h1>Book Catalog</h1>
<table>
<tr>
<th>Title</th>
<th>Author</th>
<th>Year</th>
<th>Price</th>
</tr>
<tr>
<td>Learn HTML</td>
<td>John Doe</td>
<td>2022</td>
<td>$25.99</td>
</tr>
<tr>
● Purpose: The HTML document displays a book catalog on a webpage, which includes a
table with book details such as title, author, year of publication, and price.
● Presentation: HTML focuses on the layout and presentation of the content, including
the use of <table>, <th>, and <td> tags to define the structure of the table.
● Tags: The tags used here are predefined HTML tags that are used for page layout and
display. There is no focus on the underlying data structure; the goal is to present the
information in a user-friendly format.
In contrast, XML is used for storing and transporting the data in a structured format. It allows
data to be easily exchanged between systems, applications, or services. Here is an XML
representation of the same book catalog:
● Purpose: The XML document is structured data that represents a book catalog. It stores
information about the books in a hierarchical format, which can be used by computers
or applications to process or exchange the data.
● Data-Oriented: XML focuses on the data itself (book title, author, year, price) without
concerning itself with how the data will be presented. It provides a way to represent the
structure of the information in a machine-readable format.
● Tags: Unlike HTML, XML allows custom tags such as <catalog>, <book>, <title>,
<author>, etc. These tags are not predefined and are designed to represent the data in a
meaningful way. The data is stored inside these tags, and the structure of the document
is defined by the user or the system.
DTD (Document Type Definition) is a set of rules that defines the structure, the legal elements,
attributes, and their relationships in an XML document. It is a way to specify the allowed
structure and content of an XML document, essentially serving as a "blueprint" or "contract" for
how XML data should be structured.
A DTD defines:
In essence, a DTD specifies the rules for creating valid XML documents, ensuring that the XML
conforms to a specific structure.
Types of DTD
1. Internal DTD: The DTD is included within the same XML file, like in the first example
above.
2. External DTD: The DTD is stored in a separate file, referenced by the XML document
using the DOCTYPE declaration. In the above example, the XML document references an
external DTD file called books.dtd.
While DTD and XML are closely related, they serve different purposes and have some key
differences:
Purpose Defines the structure and rules A markup language used to store and
for an XML document. transport data.
Data vs. Defines the structure of XML Defines the data and its content in a
Structure documents, i.e., which structured way, but does not enforce
elements are allowed and how any structure or rules.
they relate.
Error Handling DTD is used to validate the XML data does not validate its structure
structure of XML, ensuring that automatically; it only stores the data.
XML follows predefined rules. You need to validate XML with DTD,
XSD, or other mechanisms.
Flexibility Less flexible: DTD has strict More flexible: XML can represent any
rules and a limited set of kind of structured data, and you can
features for defining data types define your own tags without
and constraints. limitations.
Tags DTD defines rules for the XML uses custom-defined tags that
allowed tags in XML. It does represent data. It is used for storing and
not contain any actual data. transporting the actual data.
Support for Data DTD has limited support for XML does not define data types but can
Types data types (e.g., text, numbers) be validated using external schemas like
but cannot handle complex XSD (XML Schema Definition), which
data types. supports complex data types.
Definition of DTD can define element XML alone does not define relationships
Relationships relationships, like child or constraints, but these can be
elements, ordering, and enforced through validation tools like
occurrence constraints (e.g., +, DTD or XSD.
*).
Extensibility DTD is not very extensible and XML is extensible and allows you to
does not support complex data create custom tags to define and store
validation. data.
When working with XML documents in programming, two of the most common ways to parse
XML data are through SAX (Simple API for XML) and DOM (Document Object Model). These are
two distinct approaches to parsing XML, each with its own characteristics, advantages, and use
cases.
Feature SAX Parser (Simple API for XML) DOM Parser (Document Object Model)
Parsing Event-based: SAX parses XML Tree-based: DOM loads the entire XML
Approach sequentially and triggers events document into memory as a tree
(like start or end of elements, text structure with nodes representing
content) as it encounters them. elements, attributes, and data.
Memory Usage Low memory usage: SAX High memory usage: DOM loads the
processes the XML document entire XML document into memory,
sequentially and does not need to creating a tree structure, which
load the entire document into requires more memory, especially for
memory. large documents.
Speed Faster for large XML documents Slower for large XML documents
since it doesn’t require loading because it must load the entire
the entire document into document into memory before parsing.
memory. It processes the However, it is faster for certain
document as it reads it. operations once the document is in
memory.
Ease of Use Complex: SAX requires handling Easier: DOM provides a straightforward
events through callback methods interface to navigate and manipulate
(e.g., startElement, endElement). the XML structure. You can directly
Developers must manage the access and modify elements in the
state of parsing manually. document.
Use Cases Best for streaming, large XML Best for small to medium-sized XML
documents, or when only part of documents that require frequent
the document is needed. Suitable access to the entire document. Useful
for applications like XML feeds, for applications where the entire
log files, and when parsing one document must be loaded and
element at a time is enough. manipulated in memory (e.g., editors,
document generators).
Modification of Not suitable for modification: SAX Suitable for modification: DOM allows
Document is primarily a read-only parser, you to modify the XML structure, add
and you cannot modify the or remove nodes, and save the changes
document while parsing it. back to the XML file.
Error Handling Limited: SAX provides error Better control: DOM allows better error
notifications during the parsing handling because it loads the entire
process (e.g., malformed XML), document into memory first. You can
but there is less control over error manipulate the tree, perform
recovery because it's streaming validations, and handle errors more
data. easily.
Ans :With an external style sheet, you can change the look of an entire website by changing just
one file!
Each HTML page must include a reference to the external style sheet file inside the <link>
element, inside the head section.
Example
External styles are defined within the <link> element, inside the <head> section of an HTML
page:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
</head>
<body>
<h1>Welcome to designing.</h1>
<p> An external style sheet can be written in any text editor, and must be saved with a .css
extension.<br>
The external .css file should not contain any HTML tags
.</p>
</body>
</html>
An external style sheet can be written in any text editor, and must be saved with a .css extension.
The external .css file should not contain any HTML tags.
"mystyle.css"
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
Q22 :Describe the advantages of CSS.
CSS saves time − You can write CSS once and then reuse same sheet in
multiple HTML pages. You can define a style for each HTML element and apply it
to as many Web pages as you want.
∙ Pages load faster − If you are using CSS, you do not need to write HTML
tag ,attributes every time. Just write one CSS rule of a tag and apply it to all
the occurrences of that tag. So less code means faster download times.
∙ Easy maintenance − To make a global change, simply change the style, and
all elements in all the web pages will be updated automatically.
∙ Superior styles to HTML − CSS has a much wider array of attributes than
HTML, so you can give a far better look to your HTML page in comparison to
HTML attributes.
∙ Multiple Device Compatibility − Style sheets allow content to be optimized
for more than one type of device. By using the same HTML document,
different versions of a website can be presented for handheld devices such as
PDAs and cell phones or for printing.
∙ Global web standards − Now HTML attributes are being deprecated and it is
being recommended to use CSS. So its a good idea to start using CSS in all the
HTML ages to make them compatible to future browsers.
Q23: Create a css rule that makes all the text 2 times larger than the base font of the system.
Mention can you integrate css on a web page.
Internal CSS
Inline CSS
External CSS
Q24: What is CSS? Discuss the different ways to create CSS. Explain with example.
Ans Cascading Style Sheet, fondly referred to as CSS, is a simple design language intended
to simplify the process of making web pages presentable.
CSS handles the look and feel part of a web page. Using CSS, you can control the color of the
text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out,
what background images or colors are used, layout designs, variations in display for different
devices and screen sizes as well as a variety of other effects.
External CSS
Internal CSS
Inline CSS
External CSS
With an external style sheet, you can change the look of an entire website by changing just one
file!
Each HTML page must include a reference to the external style sheet file inside the <link>
element, inside the head section.
Example
External styles are defined within the <link> element, inside the <head> section of an HTML
page:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="mystyle.css">
</head>
<body>
<h1>Welcome to designing.</h1>
<p> An external style sheet can be written in any text editor, and must be saved with a .css
extension.<br>
The external .css file should not contain any HTML tags
.</p>
</body>
</html>
An external style sheet can be written in any text editor, and must be saved with a .css extension.
The external .css file should not contain any HTML tags.
"mystyle.css"
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
Internal CSS
An internal style sheet may be used if one single HTML page has a unique style.
The internal style is defined inside the <style> element, inside the head section.
Example
Internal styles are defined within the <style> element, inside the <head> section of an HTML
page:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>
<h1>Welcome to designing.</h1>
<p> An style sheet can be written in any text editor, and must be saved with a .css
extension.<br>
.</p>
</body>
</html>
Inline CSS
An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style attribute can contain
any CSS property.
Example
Inline styles are defined within the "style" attribute of the relevant element:
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Explain the difference between id and class selector in css.
Ans
Class Id
We can apply a class to various elements so that it The Id is unique in a page, and we can
could be numerous times on a single page. only apply it to one specific element.
The class is assigned to an element and its name The name of the Id starts with the "#"
starts with "." followed by the name of the class. symbol followed by a unique id name.
We can attach only one ID selector to an
We can attach multiple class selectors to an element.
element.
Syntax: Syntax:
.class{ #id{
// declarations of CSS // declarations of CSS
} }
CSS id Selector
The id selector uses the id attribute of an HTML element to select a specific element.
The id of an element is unique within a page, so the id selector is used to select one unique
element!
To select an element with a specific id, write a hash (#) character, followed by the id of the
element.
#para1 {
text-align: center;
color: red;
}
<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
text-align: center;
color: red;
</style>
</head>
<body>
</body>
</html>
Output: Hello World!
Class Selector
The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the class name.
Example
In this example all HTML elements with class="center" will be red and center-aligned:
.center {
text-align: center;
color: blue;
}
<!DOCTYPE html>
<html> <head>
<style>
.example {
text-align: center;
color: blue;
font-size: 25px;
}
</style>
</head>
<body>
<h1 class="example">This heading is blue and center-aligned.</h1>
<p class="example">This paragraph is blue and center-aligned.</p>
</body>
</html>
A block-level element always starts on a new line, and the browsers automatically add some
space (a margin) before and after the element.
A block-level element always takes up the full width available (stretches out to the left and right
as far as it can).
Two commonly used block elements are: <p> and <div>.
<div>
<h2>London</h2>
<p>London is the capital city of England.</p>
<p>London has over 13 million inhabitants.</p>
</div>
<p>The yellow background is added to demonstrate the footprint of the DIV element.</p>
</body>
</html>
Inline Elements
<!DOCTYPE html>
<html>
<body>
</body>
</html>
<a> <abbr> <acronym> <b> <bdo> <big> <br> <button> <cite> <code> <dfn> <em> <i>
<img> <input> <kbd> <label> <map>
<object> <output> <q> <samp> <script> <select> <small> <span> <strong> <sub>
<sup> <textarea> <time> <tt> <var>
CSS selectors are used to "find" (or select) the HTML elements you want to style.
Simple selectors:
Select element to style on the basis of the name of tag select .In below example ,we
select a <p>(para tag) on which apply the CSS properties.
Example:
p{
text-align: center;
color: red;
}
<!DOCTYPE html>
<html>
<head>
<style>
p{
text-align: center;
color: red;
</style>
</head>
<body>
<p>And me!</p>
</body>
</html>
Output:
Every paragraph will be affected by the style.
Me too!
And me!
CSS id Selector
The id selector uses the id attribute of an HTML element to select a specific element.
The id of an element is unique within a page, so the id selector is used to select one unique
element!
To select an element with a specific id, write a hash (#) character, followed by the id of the
element.
#para1 {
text-align: center;
color: red;
}
Class Selector
The class selector selects HTML elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the class name.
Example
In this example all HTML elements with class="center" will be red and center-aligned:
.center {
text-align: center;
color: blue;
}
The universal selector (*) selects all HTML elements on the page.
Example
The CSS rule below will affect every HTML element on the page:
*{
text-align: center;
color: blue;
}
The grouping selector selects all the HTML elements with the same style definitions.
Example
In this example we have grouped the selectors from the code above:
h1, h2, p {
text-align: center;
color: red;
}
CSS Combinators
• A combinator is something that explains the relationship between the selectors.
• A CSS selector can contain more than one simple selector. Between the
simple selectors, we can include a combinator.
There are four different combinators in CSS:
• descendant selector (space)
• child selector (>)
• adjacent sibling selector (+)
• general sibling selector (~)
1. Descendent Selectors: This Selector targets both direct and indirect children of a parent tag.
The symbol is (space)
Syntax: parent_tag child_tag{property: value;}
2. Child Selectors: This Selector targets the only the direct children of the parent tag. The symbol
is > (greater than)
Syntax: parent_tag > child_tag{property: value;}
3. Adjacent Selectors: This Selector targets the element which is the first sibling of the targeted
HTML tag or element.
This Selector targets the element which is exactly adjacent to the targeted HTML tag or element.
The symbol is + (plus)
Syntax: parent_tag + target_tag{property: value;}
4. General Sibling Selectors: This Selector targets all the siblings of the target HTML tag or
element.
This Selector targets all the adjacent tags of the target HTML tag or element.
The symbol is ~ (tilde)
Syntax: parent_tag ~ target_tag{property: value;}
Q 28 Write the syntax of CSS property that can be used to remove the underline from a hyperlink
Ans: Syntax:
a:link {
text-decoration: none;
}
Q 29 Construct a web page using CSS to show the 3 horizontal and 3 vertical navigation bars
that links to the different web pages
Ans:
<!DOCTYPE html>
<html>
<head>
<style>
.horizontal-nav a {
color: white;
text-decoration: none;
padding: 10px 20px;
margin-right: 10px;
border-radius: 5px;
}
.horizontal-nav {
display: inline;
flex-direction: row;
background-color: #333;
padding: 10px; margin-bottom: 20px; }
.vertical-nav
{
display: block;
flex-direction: column;
background-color: #333;
padding: 10px;
}
.vertical-nav a {
color: white;
text-decoration: none;
padding: 10px;
margin-bottom: 10px;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="horizontal-nav">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#services">Services</a>
</div>
<div class="vertical-nav">
<a href="#section1">Section 1</a>
<a href="#section2">Section 2</a>
<a href="#section3">Section 3</a>
</div>
</body>
</html>
}
Q30.Explain box model in CSS. Design a web page with a table of 6 rows. Use nthchild property
of CSS to color Odd rows and even rows in different colors. Highlight the even rows on mouse
over.
Ans
In CSS, the term "box model" is used when talking about design and layout.
The CSS box model is essentially a box that wraps around every HTML element. It consists of:
content, padding, borders and margins. 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
Border - A border that goes around the padding and content
Margin - Clears an area outside the border. The margin is transparent
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div {
background-color: lightgrey;
width: 300px;
border: 15px solid green;
padding: 100px;
margin: 50px;
}
</style>
</head>
<body>
<p>The CSS box model is essentially a box that wraps around every HTML element. It consists
of: borders, padding, margins, and the actual content.</p>
<div>This text is the content of the b`ox. We have added a 50px padding, 20px margin and a
15px green border
</body>
</html>
Use nthchild property of CSS to color Odd rows and even rows in different colors. Highlight the
even rows on mouse over.
<!DOCTYPE html>
<html lang="en">
<head>
<title>
To set alternate table row color using CSS
</title>
<style>
.highlight { background-color: #8888FF }
.normal { background-color: #c8e6c9}
table {
width: 20%;
border-collapse: collapse;
}
th {
background-color: #04af2f;
color:white;
}
th, td {
padding: 10px;
border: 1px solid #ccc;
text-align: center;
}
tr:nth-of-type(even) {
background-color: #c8e6c9;
onMouseOver: "this.className='highlight'";
onMouseOut:"this.className='normal'";
}
tr:nth-of-type(odd) {
background-color: #e8f5e9;
}
</style>
</head>
<body>
<h3>
To Set Alternate Table Row Color Using CSS
</h3>
<p>
In this example we have used <strong>nth-of-type
</strong> psuedo-class selector to set alternate
table row color using CSS.
</p>
<table>
<tr>
<th>Name</th>
<th>Phone</th>
</tr>
<tr>
<td>Ravi</td>
<td>7045689765</td>
</tr>
<tr>
<td>Amit</td>
<td>9876543210</td>
</tr>
<tr>
<td>Priya</td>
<td>9123456789</td>
</tr>
<tr>
<td>Sunil</td>
<td>8234567890</td>
</tr>
<tr>
<td>Neha</td>
<td>9654321098</td>
</tr>
</table>
</body>
</html>
Q31 Explain cascading and the style precedence rules when using multiple approaches.
Ans
Ans: Image Sprites: image sprite is a collection of images put into a single image.
A web page with many images can take a long time to load and generates multiple server
requests.
Using image sprites will reduce the number of server requests and save bandwidth.
Example;
!DOCTYPE html>
<html>
<head>
<style>
#home {
width: 46px;
height: 44px;
background: url(img_navsprites.gif) 0 0;
}
#next {
width: 43px;
height: 44px;
background: url(img_navsprites.gif) -91px 0;
}
</style>
</head>
<body>
</body>
</html>
Float:
The float property specifies whether an element should float to the left, right, or not at all.
Syntax:
float: none|left|right|initial|inherit;
<!DOCTYPE html>
<html>
<head>
<style>
img {
float: left;
}
</style>
</head>
<body>
<h1>The float Property</h1>
</body>
</html>
Ans The CSS border properties allow you to specify the style, width, and color of an element's
border.
The border-style property can have from one to four values (for the top border, right border,
bottom border, and the left border).
Margin:
Margins are used to create space around elements, outside of any defined borders.
CSS has properties for specifying the margin for each side of an element:
margin-top
margin-right
margin-bottom
margin-left
If the margin property has four values:
An element with greater stack order is always in front of an element with a lower stack order.
Note: z-index only works on positioned elements (position: absolute, position: relative, position:
fixed, or position: sticky) and flex items (elements that are direct children of display:flex
elements).
Ans A navigation bar is basically a list of links, so using the <ul> and <li> elements makes
perfect sense:
<!DOCTYPE html>
<html>
<body>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
<p>Note: We use href="#" for test links. In a real web site this would be URLs.</p>
</body>
</html>
Example for horizontal navigation
<!DOCTYPE html>
<html>
<head>
<style>
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
li {
display: inline;
}
</style>
</head>
<body>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#about">About</a></li>
</ul>
</body>
</html>
Position
The position property specifies the type of positioning method used for an element.
static
relative
fixed
absolute
sticky
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.
Syntax: postion:static;
Ans:
The width and height of the display: inline elements The width and height of the display:
can’t be changed. inline-block elements can be changed.
It can have padding and margin in the horizontal
It can have padding and margin in all four
direction. But, with respect to the vertical direction,
directions.
it does not have a margin and padding.
It cannot have a child block element. It can have a child block element.
Ans A website can be divided into various sections comprising of header, menus, content, and
footer based on which there are many different layout designs available for developers. Different
layouts can be created by using a div tag and using CSS property to style it.
A header is usually located at the top of the website (or right below a top navigation menu). It
often contains a logo or the website name.
2.Navigation Bar
A navigation bar contains a list of links to help visitors navigating through your website.
Content Section
The content section is the main body of the website. The user can divide the content section in an
n-column layout.
The most common layouts are:
Footer
The footer is placed at the bottom of your page. It often contains information like copyright and
contact info.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
*{
box-sizing: border-box;
color:white;
}
body {
margin: 0;
background-image:url("desert.jpg");
color:white;
.header {
background-color: #f1f1f1;
padding: 20px;
text-align: center;
background-image:url("Hydrangeas.jpg");
color:white;
.topnav {
overflow: hidden;
background-color: #333;
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
text-decoration: none;
.topnav a:hover {
background-color: #ddd;
color: red;
.column {
float: left;
width: 33.33%;
padding: 15px;
.row::after {
content: "";
display: table;
clear: both;
/* Responsive layout - when the screen is less than 800px wide, make the two columns stack on
top of each other instead of next to each other */
.leftcolumn, .rightcolumn {
width: 100%;
padding: 0;
/* Responsive layout - when the screen is less than 400px wide, make the navigation links stack
on top of each other instead of next to each other */
.topnav a {
float: none;
width: 100%;
.footer {
padding: 20px;
align: center;
background: #ddd;
margin-top: 20px;
text-align: center;
</style>
</head>
<body>
<div class="header">
<h1>Header</h1>
</div>
<div class="topnav">
<a href="#">Link</a>
<a href="#">Link</a>
<a href="#">Link</a>
</div>
<div class="row">
<div class="column">
<p>Responsive Web design is the approach that suggests that design and development should
respond to the user’s behavior and environment based on screen size, platform and
orientation.</p>
</div>
<div class="column">
<h2>Resposive architecture</h2>
<p>Recently, an emergent discipline called “responsive architecture” has begun asking how
physical spaces can respond to the presence of people passing through them. Through a
combination of embedded robotics and tensile materials, architects are experimenting with art
installations and wall structures that bend, flex, and expand as crowds approach them. Motion
sensors can be paired with climate control systems to adjust a room’s temperature and ambient
lighting as it fills with people. Companies have already produced “smart glass technology” that
can automatically become opaque when a room’s occupants reach a certain density threshold,
giving them an additional layer of privacy.”</p>
</div>
<div class="column">
<h2>Flexible Images</h2>
</div>
</div>
<div class="footer">
<h2>Footer</h2>
</div>
</body>
</html>
Q37 Explain different types of border with example.
Ans The CSS border properties allow you to specify the style, width, and color of an element's
border.
The border-style property can have from one to four values (for the top border, right border,
bottom border, and the left border).
Example:
<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>
</html>
Q38 Write code to create different types of link using pseudo-class selector.
A pseudo-class can be defined as a keyword which is combined to a selector that defines the
special state of the selected elements. It is added to the selector for adding an effect to the
existing elements based on their states. For example, The ":hover" is used for adding special
effects to an element when the user moves the cursor over the element.
Syntax:
selector:pseudo-class {
property: value;
}
Dynamic Pseudo Classes
Pseudo Class Selector specifies the special state of the content.
The Pseudo Class Selector are:
1. Link
2. Visited
3. Hover
4. Active
5. Focus
o Each dynamic pseudo class selector is declared with the single colon :
o Link, Visited only applicable for anchor tag.
o Link is used to style the unvisited link
o Link doesn’t style the already visited link.
o Active applies the style at the time of click event.
o Hover is applicable for all the HTML elements.
o Focus styles when the element is focused.
o Focus selector is applicable for <a> tag and also for the elements which takes user input
that is for <input> and textarea> tag.
o While using all the Link, Visited, Hover and Active selectors. Hover should be declared
after Link and Visited. Along with that the Active should be declared after Hover,
because to make the elements effective.
Example:
a : link {
color: aqua;
background-color : red;
}
a : visited {
color : green;
}
a : hover {
color : yellow;
}
a : active {
color : chocolate;
}
input : focus{
color : red;
background-color : yellow;
}
Example:
<!DOCTYPE html>
<html>
<head>
<style>
/* unvisited link */
a:link {
color: red;
/* visited link */
a:visited {
color: green;
a:hover {
color: hotpink;
/* selected link */
a:active {
color: blue;
}
</style>
</head>
Example:
<html>
<head>
<style>
p{
display: none;
background-color: yellow;
padding: 20px;
div:hover p {
display: block;
</style>
</head>
<body>
</div>
</body>
</html>
Ans The position property specifies the type of positioning method used for an element.
static
relative
fixed
absolute
sticky
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.
Syntax: postion:static;
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.
Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it
to be adjusted away from its normal position.
However if an absolute positioned element has no positioned ancestors, it uses the document
body, and moves along with page scrolling.
Synatx: position:absolute;
Example:
<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
position: relative;
width: 400px;
height: 200px;
border: 3px solid #73AD21;
background-image:url("lighthouse.jpg");
}
div.absolute {
position: absolute;
top: 80px;
right: 0;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
</style>
</head>
<body>
<h2>position: absolute;</h2>
<p>An element with position: absolute; is positioned relative to the nearest positioned ancestor
(instead of positioned relative to the viewport, like fixed):</p>
</body>
</html>
Q 40 Explain different combinators selector in CSS
1. Descendent Selectors: This Selector targets both direct and indirect children of a parent tag.
The symbol is (space)
Syntax: parent_tag child_tag{property: value;}
2. Child Selectors: This Selector targets the only the direct children of the parent tag. The symbol
is > (greater than)
Syntax: parent_tag > child_tag{property: value;}
3. Adjacent Selectors: This Selector targets the element which is the first sibling of the targeted
HTML tag or element.
This Selector targets the element which is exactly adjacent to the targeted HTML tag or element.
The symbol is + (plus)
Syntax: parent_tag + target_tag{property: value;}
4. General Sibling Selectors: This Selector targets all the siblings of the target HTML tag or
element.
This Selector targets all the adjacent tags of the target HTML tag or element.
The symbol is ~ (tilde)
Syntax: parent_tag ~ target_tag{property: value;}
41.Construct a JavaScript program using text boxes, two for inputs and others for output,
implement four operations addition, subtraction, multiplication and division on two input
numbers on clicking of buttons ‘add’, ‘subtract’, ‘multiply’ and ‘divide’. Print the result in text
box.
<!doctype html>
<html>
<head>
<script>
var numOne, numTwo, res, temp;
function fun()
{
numOne = parseInt(document.getElementById("one").value);
numTwo = parseInt(document.getElementById("two").value);
if(numOne && numTwo)
{
temp = document.getElementById("res");
temp.style.display = "block";
res = numOne + numTwo;
document.getElementById("add").value = res;
res = numOne - numTwo;
document.getElementById("subtract").value = res;
res = numOne * numTwo;
document.getElementById("multiply").value = res;
res = numOne / numTwo;
document.getElementById("divide").value = res;
}
}
</script>
</head>
<body>
</body>
</html>
<script>
function validateemail()
{
var x=document.myform.email.value;
var atposition=x.indexOf("@");
var dotposition=x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){
alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);
return false;
}
}
</script>
<body>
<form name="myform" method="post" action="#" onsubmit="return validateemail();">
Email: <input type="text" name="email"><br/>
43.Design a JavaScript program to display the current day and time in the following format.
Today is : Monday. Current time is : 11 AM : 50 : 58
// Get the day of the week (0-6, where 0 is Sunday and 6 is Saturday)
var day = today.getDay();
// Array of day names
var daylist = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
// Determine if it's AM or PM
var prepand = (hour >= 12) ? " PM " : " AM ";
44. Why do we need client side scripting languages like Java Script? How AJAX like technologies
is so useful these days? How AJAX is used for single page processing?
Asynchronous JavaScript and XML (AJAX) is used for single page processing by allowing web pages
to be updated without reloading the entire page. This is done by exchanging small amounts of data with
the server behind the scenes.
Here's how AJAX works for single page processing:
1. Event occurs: A user performs an action on the web page, such as clicking a button
2. JavaScript creates an XMLHttpRequest object: This object sends a request to the web server
3. Server processes the request: The server uses a server-side scripting language like PHP, Java, Ruby, or
Python to process the request
4. Server sends a response: The server sends the requested HTML, XML, or JavaScript data back to the
web page
5. JavaScript reads the response: JavaScript performs the proper action, such as updating the page
AJAX allows for quick website interaction because only parts of the page are reloaded and
refreshed. Some examples of applications that use AJAX include Google Maps, Gmail, YouTube, and
Facebook tabs.
45. Illustrate Array in JavaScript. Create a program in JavaScript to implement an array of five
elements and perform the operations push, pop, shift, unshift and join on the array.
JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
Let's see the example of creating array directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
3) JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that we don't have to
provide value explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
let arr = [ 1, 2, 3 ];
arr.push(4);
console.log(arr);
// [ 1, 2, 3, 4 ]
push() returns length of the new array.
let arr = [ 1, 2, 3, 4 ];
let arrLength = arr.push( 5, 6, 7 );
console.log(arrLength);
// 7
let arr = [ 1, 2, 3, 4 ];
let removedElement = arr.pop();
console.log(removedElement);
// 4
let arr = [ 0, 1, 2, 3 ];
arr.shift();
console.log(arr);
// [ 1, 2, 3 ]
shift() returns the removed element from the array.
let arr = [ 0, 1, 2, 3 ];
let removedElement = arr.shift();
console.log(removedElement);
// 0
let arr = [ 1, 2, 3 ];
arr.unshift(0);
console.log(arr);
// [ 0, 1, 2, 3 ]
unshift() returns length of the new array.
let arr = [ 4, 5, 6 ];
let arrLength = arr.unshift( 0, 1, 2, 3 );
console.log(arrLength);
// 7
46.Write a program in JavaScript to print first n terms of Fibonacci series (0, 1, 1, 2, 3, 5, 8, 13, 21,
34…)
/ program to generate fibonacci series up to n terms
console.log('Fibonacci Series:');
An HTML event can be something the browser does, or something a user does.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
In the following example, an onclick attribute (with code), is added to a <button> element:
Example
<button onclick="document.getElementById('demo').innerHTML = Date()">The time is?</button>
In the example above, the JavaScript code changes the content of the element with id="demo".
In the next example, the code changes the content of its own element (using this.innerHTML):
Example
<button onclick="this.innerHTML = Date()">The time is?</button>
Common HTML Events
Here is a list of some common HTML events:
Event Description
onmouseout The user moves the mouse away from an HTML element
Event handlers can be used to handle and verify user input, user actions, and browser actions:
Many different methods can be used to let JavaScript work with events:
● HTML event attributes can execute JavaScript code directly
● HTML event attributes can call JavaScript functions
● You can assign your own event handler functions to HTML elements
● You can prevent events from being sent or being handled
● And more ...
In our examples we will build the navigation bar from a standard HTML list.
A navigation bar is basically a list of links, so using the <ul> and <li> elements makes perfect sense:
Example
<ul>
<li><a href="default.asp">Home</a></li>
<li><a href="news.asp">News</a></li>
<li><a href="contact.asp">Contact</a></li>
<li><a href="about.asp">About</a></li>
</ul>
HTML has several semantic elements that define the different parts of a web page:
49.Design a HTML form with name, address, pincode and password. Outline a JavaScript code that can
validate on following constraints: a. No fields must be left blank b. Pincode must be numeric and
contain 6 digits c. Password field (i) At least contains 1 Capital letter. (ii) Minimum length 8 characters
<html>
<head>
<script>
function fun()
{
let x = document.forms["f1"]["t1"].value;
let y = document.forms["f1"]["t2"].value;
if (x.length<6)
{
alert("error1");
}
if (!isNaN(x))
{
alert("error2");
}
if (y.length<6)
{
alert("error3");
}
}
</script>
</head>
<body>
<form name="f1">
Name<input type="text" name="t1" ><br>
Password<input type="password" name="t2">
<input type="button" onclick="fun()" value="ok">
</form>
</body>
</html>
Pincode Validation
<!DOCTYPE html>
<html>
<head>
<title>Pincode Validation</title>
</head>
<h1 align="center">
</h1>
<script type="text/javascript">
function validate()
var pincode;
pincode=form1.t1.value;
if(pincode.length==0)
form1.t1.focus();
else if(Number.isInteger(pincode))
{
form1.t1.focus();
else if(pincode.length<6||pincode.length>8)
form1.t1.focus();
else
alert("Pincode accepted");
</script>
</body>
</html>
Password Validation
<!DOCTYPE html>
<html>
<body>
<h3>Password Validation</h3>
<p>Try to submit the form.</p>
<div>
<form action="/action_page.php">
<label >Password</label>
<input type="password" id="psw" name="psw" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Must contain at least one number and one uppercase and lowercase letter, and at least 8 or more
characters" required>
<input type="submit" value="Submit">
</form>
</div>
<div >
<h3>Password must contain the following:</h3>
<p >A <b>lowercase</b> letter</p>
<p >A <b>capital (uppercase)</b> letter</p>
<p >A <b>number</b></p>
<p >Minimum <b>8 characters</b></p>
</div>
<script>
var myInput = document.getElementById("psw");
var letter = document.getElementById("letter");
var capital = document.getElementById("capital");
var number = document.getElementById("number");
var length = document.getElementById("length");
// When the user clicks on the password field, show the message box
myInput.onfocus = function() {
document.getElementById("message").style.display = "block";
}
// When the user clicks outside of the password field, hide the message box
myInput.onblur = function() {
document.getElementById("message").style.display = "none";
}
// When the user starts to type something inside the password field
myInput.onkeyup = function() {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if(myInput.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
// Validate numbers
var numbers = /[0-9]/g;
if(myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}
// Validate length
if(myInput.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
}
</script>
</body>
</html>
50.Discuss function in Java Script. Outline a JS function that takes 4 variables, a, b, c, d, and
prints true in an alert box if input a > input b and input c > input d. Else, print false in an alert
box
A JavaScript function is a block of code designed to perform a particular task.
Example
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}
Example
<script language="JavaScript">
function question9(a,b,c,d)
{
if (a>b&&c>d) {
alert("true")
}
else {
alert("false")
}
}
</script>
51.What is AJAX? Explain its advantage and its working? Explain with example?
AJAX tutorial covers concepts and examples of AJAX technology for beginners and professionals.
AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of inter-related
technologies like JavaScript, DOM, XML, HTML/XHTML, CSS, XMLHttpRequest etc.
What is AJAX?
AJAX allows you to send and receive data asynchronously without reloading the web page. So it is fast.
AJAX allows you to send only important information to the server not the entire page. So only valuable
data from the client side is routed to the server side. It makes your application interactive and faster.
Where it is used?
There are too many web applications running on the web that are using ajax technology
like gmail, facebook,twitter, google map, youtube etc.
Before understanding AJAX, let’s understand classic web application model and ajax web application
model first.
Synchronous (Classic Web-Application Model)
A synchronous request blocks the client until operation completes i.e. browser is unresponsive. In such
case, javascript engine of the browser is blocked.
Figure 3.3 Synchronous Model
As you can see in the above image, full page is refreshed at request time and user is blocked until
request completes.
AJAX Technologies
As describe earlier, ajax is not a technology but group of inter-related technologies. AJAX technologies
includes:
● HTML/XHTML and CSS
● DOM
● XML or JSON
● XMLHttpRequest
● JavaScript
Understanding XMLHttpRequest
An object of XMLHttpRequest is used for asynchronous communication between client and server.
It performs following operations:
1. Sends data from the client in the background
2. Receives the data from the server
3. Updates the webpage without reloading it.
AJAX communicates with the server using XMLHttpRequest object. Let's try to understand the flow of
ajax or how ajax works by the image displayed below.
● Works with Document Object Model (DOM) for response to user interactions
1. Web Development
2. Web Applications
3. Presentations
4. Server Applications
5. Web Servers
6. Games
7. Art
8. Smartwatch Apps
9. Mobile Apps
10. Flying Robots
53.Illustrate and compare various dialog boxes in JavaScript with suitable JavaScript code.
function Warning() {
Confirm box: A confirm box is often used if you want the user to verify or accept something. When a
confirm box pops up, the user will have to click either “OK” or “Cancel” to proceed. If the user clicks
on the OK button, the window method confirm() will return true. If the user clicks on the Cancel button,
then confirm() returns false and will show null.
Example:
● JavaScript
function Confirmation() {
if (Val == true) {
console.log(" CONTINUED!");
return true;
} else {
console.log("NOT CONTINUED!");
return false;
Prompt Box: A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either “OK” or “Cancel” to proceed after
entering an input value. If the user clicks the OK button, the window method prompt() will return the
entered value from the text box. If the user clicks the Cancel button, the window
method prompt() returns null.
Example:
● JavaScript
function Value(){
var Val = prompt("Enter your name : ", "Please enter your name");
54.Describe URL class in Java. Write a Java code display protocol, port number, host of given url
with the help of this class.
Java URL
The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to
a resource on the World Wide Web. For example:
1. https://www.javatpoint.com/java-tutorial
File Name or directory name: In this case, index.jsp is the file name.
//URLDemo.java
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
}catch(Exception e){System.out.println(e);}
}
}
Output:
Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial
55. Create a JavaScript program to make an arithmetic calculator.
<!-
- Create a simple Program to build the Calculator in JavaScript using with HTML and CSS web languages. -
->
<!DOCTYPE html>
<html lang = "en">
<head>
<title> JavaScript Calculator </title>
<style>
h1 {
text-align: center;
padding: 23px;
background-color: skyblue;
color: white;
}
#clear{
width: 270px;
border: 3px solid gray;
border-radius: 3px;
padding: 20px;
background-color: red;
}
.formstyle
{
width: 300px;
height: 530px;
margin: auto;
border: 3px solid skyblue;
border-radius: 5px;
padding: 20px;
}
input
{
width: 20px;
background-color: green;
color: white;
border: 3px solid gray;
border-radius: 5px;
padding: 26px;
margin: 5px;
font-size: 15px;
}
#calc{
width: 250px;
border: 5px solid black;
border-radius: 3px;
padding: 20px;
margin: auto;
}
</style>
</head>
<body>
<h1> Calculator Program in JavaScript </h1>
<div class= "formstyle">
<form name = "form1">
<!-- This input box shows the button pressed by the user in calculator. -->
<input id = "calc" type ="text" name = "answer"> <br> <br>
<!-- Display the calculator button on the screen. -->
<!-- onclick() function display the number prsses by the user. -->
<input type = "button" value = "1" onclick = "form1.answer.value += '1' ">
<input type = "button" value = "2" onclick = "form1.answer.value += '2' ">
<input type = "button" value = "3" onclick = "form1.answer.value += '3' ">
<input type = "button" value = "+" onclick = "form1.answer.value += '+' ">
<br> <br>
</form>
</div>
</body>
</html>
56.What are the different data types present in javascript?
String
Number
Bigint
Boolean
Undefined
Null
Symbol
Object
Examples
// Numbers:
let length = 16;
let weight = 7.5;
// Strings:
let color = "Yellow";
let lastName = "Johnson";
// Booleans
let x = true;
let y = false;
// Object:
const person = {firstName:"John", lastName:"Doe"};
// Array object:
const cars = ["Saab", "Volvo", "BMW"];
// Date object:
const date = new Date("2022-03-25");
Java Socket programming is used for communication between the applications running on different JRE.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
Here, we are going to make one-way client and server communication. In this application, client sends a
message to the server, server reads the message and prints it. Here, two classes are being used: Socket and
ServerSocket. The Socket class is used to communicate client and server. Through this class, we can read
and write message. The ServerSocket class is used at server-side. The accept() method of ServerSocket
class blocks the console until the client is connected. After the successful connection of client, it returns
the instance of Socket at server-side.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be used
to create a socket.
1) public InputStream getInputStream() returns the InputStream attached with this socket.
2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
58.Explain Factory methods with example.Create a Java program to find out the IP address of
your machine.
The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one
of the available factory methods. Factory methods are merely a convention whereby static methods in a
class return an instance of that class. This is done in lieu of overloading a constructor with various
parameter lists when having unique method names makes the results much clearer.
Three commonly used InetAddress factory methods are shown here:
static InetAddress getLocalHost( ) throws UnknownHostException
static InetAddress getByName(String hostName) throws UnknownHostException
static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException
The getLocalHost( ) method simply returns the InetAddress object that represents the local host. The
getByName( ) method returns an InetAddress for a host name passed to it. If these methods are unable to
resolve the host name, they throw an UnknownHostException.
On the Internet, it is common for a single name to be used to represent several machines. In the world of
web servers, this is one way to provide some degree of scaling. The getAllByName( ) factory method
returns an array of InetAddresses that represent all of the addresses that a particular name resolves to. It
will also throw an UnknownHostException if it can’t resolve the name to at least one address.
InetAddress also includes the factory method getByAddress( ), which takes an IP address and returns an
InetAddress object. Either an IPv4 or an IPv6 address can be used.
The following example prints the addresses and names of the local machine and two Internet web sites:
// Demonstrate InetAddress.
import java.net.*;
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("www.HerbSchildt.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}
Java program to find IP address of your computer
Output:
System IP Address : 10.0.8.204
Public IP Address : 35.166.48.97
59.Explain the EJB Architecture . Explain session bean, message bean and entity beans. Also
explain the drawbacks of EJBs.
Java beans incorporate a set of objects into one accessible object that can be accessed easily from any
application. This single accessible object is maintainable, customizable, and reusable. The setter/getter
method and the single public constructor are used to govern that single accessible object. We can update
and read the value of any variable of any object by using the setter and getter, respectively.
The EJB stands for Enterprise Java beans that is a server-based architecture that follows the
specifications and requirements of the enterprise environment. EJB is conceptually based on the Java
RMI(Remote Method Invocation) specification. In EJB, the beans are run in a container having four-tier
architecture. This architecture consists of four layers, i.e., Client layer, Web layer, Application layer, and
Data layer.
Architecture
The EJB architecture has two main layers, i.e., Application Server and EJB Container, based on which
the EJB architecture exist. The graphical representation of the EJB architecture is given below.
In the above diagram, the logical representation of how EJBs are invoked and deployed by using
RMI(Remote Method Invocation) is defined. The containers of the EJB cannot be self-deployed. In
order to deploy the containers, it requires the Application server.
Application Server
In the EJB architecture, the Application server is the outermost layer that holds or contains the Container
to be deployed. The application layer plays an important role in executing the application developed using
the beans. It provides the necessary environment to execute those applications. Some most popular
application servers are Web-logic, Tomcat, JBoss, Web-sphere, Wildfly, and Glass-finish. The main tasks
of the application server are:
1. Manage Interfaces
2. Execution of the processes
3. Connecting to the database
4. Manage other resources.
Container
In EJB architecture, the Container is the second outermost layer. It is a very important layer for enterprise
beans that are contained in it. For the enterprise bean, the Container provides various supporting services,
which are as follows:
o It provides support for transactional services such as registering the objects, assign remote
interfaces, purge the instances.
o It provides support for monitoring the object's activities and coordinating distributed components.
o It provides support for security services.
o It provides support for the pooling of resources.
o It provides support for managing the Life-cycle of beans and their concurrency.
o It provides support to concentrate on business logic.
Beans
Java beans of the enterprise are installed in the Container in the same way as a Plain old java object (POJO)
is installed and registered to the Container. For developing secured, large scale and robust business
applications, beans provide business logic.
Types of EJB
There are three types of Enterprise Java Beans or EJB available, which are as follows:
Stateless EJB
In order to implement the stateless business logic, the stateless EJBs are primarily used. Storing a user's
physical address into an inventory system's database is an example of the stateless EJB. In addition, a
stateless bean would be perfect for this type of business logic because it is not necessary to have more
than two forms on the user interface at all stages of the transaction.
Stateful EJB
The Stateful EJB is just opposite to the Stateless EJB. The Stateful EJBs are used when we have to
maintain the state of the application on the backend during the user session. The shopping cart of an online
shopping application is an example of the Stateful EJB. In order to achieve such application, we will use
the following steps:
Message-driven EJB
Another special type of EJB that is used for sending and receiving messages from message brokers
implements the JMS specification. The systems based on the broker are loosely coupled. The components
that communicate through the broker have the advantage of not waiting for one request to finish before
submitting another request because the broker by nature is asynchronous.
Disadvantages of EJB
JavaBean
In any programming language, reusability is the main concern. To achieve the same concern, Java
introduced the concept of JavaBean. It is a software component that has been designed to be reusable in
a variety of environments. In this section, we will dive into the topic and understand the horizons of
concept in this what is JavaBeans, its advantages, disadvantages, Life cycle.
In other words, JavaBeans are classes that encapsulate multiple objects into a single object. It also helps
in accessing these object from multiple places. It contains several elements like Constructors, getter and
setter methods and much more.
//Employee.java
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//setting value to the object
System.out.println(e.getName());
}}
Note: There are two ways to provide values to the object. One way is by constructor and second is by
setter method.
JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the object. The feature can be
of any Java data type, containing the classes that you define.
A JavaBean property may be read, write, read-only, or write-only. JavaBean features are accessed through
two methods in the JavaBean's implementation class:
Properties of setter Methods
For Boolean properties getter method name can be prefixed with either "get" or "is". But recommended
to use "is".
Advantages of JavaBean
The following are the advantages of JavaBean:
1. Non-blocking I/O:
o Node.js uses an event-driven, non-blocking I/O model, making it efficient and
lightweight for handling multiple simultaneous connections.
2. Single-threaded, Event-driven Architecture:
o Despite being single-threaded, Node.js handles many concurrent connections
using events and callbacks, making it ideal for I/O-heavy tasks like real-time
applications or APIs.
3. Package Management (npm):
o Node.js includes npm (Node Package Manager), a vast ecosystem of libraries
and modules that developers can use to add functionality to their applications.
4. Cross-platform:
o Node.js works on various operating systems like Windows, macOS, and Linux.
5. Fast Execution:
o Being powered by the V8 engine, it compiles JavaScript to machine code,
leading to fast execution of code.
6. Asynchronous Programming:
o Node.js supports asynchronous programming using callbacks, promises, and
async/await, which are ideal for building high-performance applications.
● Web Servers and APIs: Build RESTful APIs and web servers that can handle a high
number of simultaneous requests.
● Real-time Applications: Applications like chat apps, collaboration tools, and gaming
platforms, where real-time data transmission is critical.
● Command-line Tools: Create scripts and command-line applications for automating
tasks.
● Microservices: Develop microservices for scalability and modular development.
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
1. Server-side Development
2. Real-time Applications
3. Building APIs
● With frameworks like Express.js, Node.js simplifies the development of RESTful APIs
and GraphQL APIs. These APIs can serve data to web and mobile applications.
5. Microservices Architecture
● Node.js is commonly used for developing microservices, where applications are broken
into smaller, independently deployable services. This ensures better scalability and fault
isolation.
● Node.js enables developers to create scripts and automation tools (e.g., build tools, task
runners) that simplify workflows.
7. Scalability
● Its asynchronous architecture and ability to handle many connections with low
overhead make it a great choice for applications requiring scalability.
8. Cross-platform Development
● With tools like Electron.js, Node.js can also be used to build cross-platform desktop
applications (e.g., Slack, Visual Studio Code).
● Using Node.js, developers can use JavaScript for both frontend and backend,
simplifying development and enabling code reuse.
2. Scalability
● Node.js uses an event loop for handling I/O operations, which allows it to process
multiple requests without waiting for previous ones to complete. This is ideal for data-
intensive, real-time applications.
● Developers can use JavaScript for both the frontend and backend, creating a unified
development stack. This reduces the learning curve and improves productivity.
● Code can often be shared or reused between client-side and server-side applications.
● Node.js has a vast library of packages and modules available through npm (Node
Package Manager), which simplifies development by offering pre-built tools for
common tasks.
6. Real-time Applications
7. Cross-platform Development
● With frameworks like Electron.js, Node.js can be used to create desktop applications
that work on Windows, macOS, and Linux, using the same codebase.
8. Community Support
● Node.js has a large, active community of developers. This ensures continuous updates,
shared knowledge, and third-party tools to extend its functionality.
● Developers familiar with JavaScript on the client side can quickly learn Node.js and
begin building server-side applications.
● Its simplicity, unified language for frontend and backend, and reusable code result in
faster development cycles.
14. Extensibility
a. Client-Side
● The frontend of the application, usually built using HTML, CSS, and JavaScript
frameworks like React, Angular, or Vue.js.
● The client communicates with the server via HTTP/HTTPS or WebSocket protocols.
b. Server-Side
● The backend, powered by Node.js, handles requests from the client, processes business
logic, and interacts with the database.
● Node.js uses frameworks like Express.js, NestJS, or Koa.js to simplify routing,
middleware, and request handling.
c. Database
● The server communicates with a database to store or retrieve data. Common databases
include:
o SQL Databases: MySQL, PostgreSQL.
o NoSQL Databases: MongoDB, Cassandra.
o Node.js supports both relational and non-relational databases through libraries
like mongoose (for MongoDB) or sequelize (for SQL).
● Purpose: Handles interactions with the user interface (UI) and sends requests to the
server.
● Technologies: Frontend frameworks, RESTful API calls, WebSocket connections.
b. Application Layer
● Purpose: Implements business logic, processes client requests, and sends responses
back to the client.
● Technologies: Node.js frameworks (e.g., Express.js, NestJS).
● Common tasks:
o Routing requests.
o Validating inputs.
o Managing sessions/authentication.
● Purpose: Interfaces with the database for data storage and retrieval.
● Technologies: ORMs (e.g., Mongoose, Sequelize), direct database queries.
d. Database Layer
3. Architecture Styles
Depending on the use case, Node.js applications may adopt different architectural styles:
a. Monolithic Architecture
● All application components (frontend, backend, and database) are tightly integrated.
● Simpler to develop but harder to scale as the application grows.
b. Microservices Architecture
c. Serverless Architecture
d. Real-time Architecture
● Used for applications requiring real-time communication (e.g., chat apps, live games).
● Utilizes WebSockets or libraries like Socket.io for bi-directional communication.
Event Loop
Non-blocking I/O
● Ensures the application remains responsive while waiting for tasks like database queries
or file operations.
Middleware
// Middleware
app.use(express.json());
// Routes
app.get('/api/users', (req, res) => {
res.send({ message: 'List of users' });
});
// Start Server
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Answer:
1. V8 Engine
Node.js is built on Google Chrome's V8 JavaScript engine, which compiles JavaScript directly
to machine code, making it highly efficient and fast.
Node.js operates on a single-threaded event loop model, which is different from traditional
server-side languages (like PHP, Java, or Python), which create a new thread for each incoming
request. In Node.js, the event loop enables the server to handle many requests simultaneously
in a non-blocking, asynchronous manner.
● Event Loop: The event loop continuously checks the event queue to see if there are any
I/O operations (e.g., file reading, database queries) that have been completed and need
to be processed.
● Non-Blocking I/O: Node.js performs I/O operations (such as file system access,
network requests, etc.) asynchronously, meaning the application doesn't need to wait
for one operation to complete before moving on to the next.
● Callback Functions: When an I/O task finishes, the event loop executes a callback
function associated with that task. This allows Node.js to keep processing other requests
in the meantime.
Node.js uses asynchronous programming to handle operations without waiting for one task to
finish before starting another. This is achieved through:
For example, reading a file in Node.js won't block the server from handling other requests;
instead, Node.js will continue processing other requests while it waits for the file to be read.
When the reading is complete, the callback function is executed with the result.
While Node.js itself is single-threaded, it uses the libuv library to handle asynchronous I/O
operations. Libuv provides a thread pool that allows certain types of blocking operations (e.g.,
file system access) to be offloaded to background threads, so the main thread is not blocked.
● The event loop handles non-blocking tasks like HTTP requests, while I/O-bound tasks
(like database queries, file reads, etc.) are passed to the thread pool.
● This architecture enables Node.js to handle many concurrent connections without the
performance issues caused by threading in traditional server models.
5. Module System
Node.js uses a module-based architecture, where code can be organized into reusable modules
(JavaScript files). The require function is used to import modules into an application.
● Core Modules: Node.js comes with a set of built-in modules like fs (file system), http,
path, events, and more.
● Third-party Modules: Node.js also supports a vast ecosystem of external modules
available through npm (Node Package Manager).
Node.js is often used to create HTTP servers that can handle requests. The http module allows
you to create a web server that listens for HTTP requests and sends responses.
7. Event-Driven Architecture
Node.js uses an event-driven architecture where the application can respond to various events
like HTTP requests, user interactions, or sensor data. The application listens for these events
and triggers the appropriate actions when they occur.
● The EventEmitter class allows you to create custom events and handle them
asynchronously.
● For example, you could create an event that fires when a user uploads a file, and the
application can process it without blocking other operations.
Though Node.js is single-threaded, it can handle many concurrent requests effectively due to
its non-blocking nature. While the event loop is processing I/O operations asynchronously, it
can serve multiple requests in parallel. This makes it well-suited for real-time applications like
chat apps, live-streaming, and games.
9. Scalability
Node.js is designed to scale efficiently. Due to its asynchronous, non-blocking nature, it can
handle thousands of concurrent connections. Moreover, you can scale your Node.js application
horizontally by using Cluster Module or tools like PM2 to fork multiple instances of the
application across different CPU cores.
1. Package Management: NPM is used to manage libraries and packages that your project
depends on. It allows developers to install, update, and manage third-party packages
easily.
2. Command-Line Interface (CLI): NPM also provides a command-line interface to
interact with the package registry, run scripts, and perform other tasks like managing
dependencies and versioning.
A RESTful API is an architectural style for designing networked applications, and it is based
on a set of principles that allow clients and servers to communicate over the HTTP protocol.
REST (Representational State Transfer) is a lightweight, stateless, and scalable approach to
building web services that interact with data and resources.
Stateless: Each request from the client to the server must contain all the information necessary
to understand and process the request (e.g., authentication data, parameters). The server does
not store any client context between requests.
● Client-Server Architecture: The client and server are separate entities, allowing each to
evolve independently. The client makes requests to the server, which processes them
and sends back a response.
● Uniform Interface: A RESTful API has a consistent and predefined set of operations
for interacting with resources (such as GET, POST, PUT, DELETE). This uniformity
simplifies interaction between different components and platforms.
● Resource-Based: RESTful APIs treat data as resources that can be accessed,
manipulated, or represented in different formats (such as JSON or XML). Each resource
is identified by a URI (Uniform Resource Identifier), typically in the form of URLs
(e.g., /users, /products/{id}).
POST /users: Creates a new user with the data sent in the request body.
PUT /users/{id}: Updates the user details with the specified ID.
Simplicity: REST is simple to use and understand, as it leverages standard HTTP methods.
Scalability: REST APIs are stateless, allowing easy scalability and distribution of requests.
Interoperability: REST APIs can be used across different platforms (web, mobile, desktop) and
programming languages.
Flexibility: REST allows different data formats, and the client and server can evolve
independently as long as the interface remains consistent.
Answer: REPL terminal is an interactive programming environment that allows users to write
and execute code one command or expression at a time. REPL stands for:
Read: Reads the user input (a single command, expression, or line of code).
● Immediate Feedback: You can test code snippets and see the results instantly without
needing to compile or build an entire program.
● Interactive Learning: REPLs are excellent for learning and experimenting with
programming languages.
● Language-Specific: Most modern programming languages provide their own REPL
environments (e.g., Python has the python command, Node.js has node, etc.).
● Error Debugging: REPLs can help you identify and fix errors by running code
incrementally.
● Document-Oriented Storage:
Data is stored in flexible, JSON-like structures called documents, which are organized into
collections.
Documents can contain nested structures and arrays, making them more expressive and
adaptable to real-world data models than traditional rows and columns.
● Schema Flexibility:
MongoDB is schema-less, meaning you don't need to define a rigid structure beforehand. Each
document in a collection can have its own unique structure.
● Scalability:
Supports horizontal scaling via sharding, distributing data across multiple servers or clusters.
Ideal for handling large-scale applications with high throughput and massive datasets.
● High Performance:
● Built-In Features:
1. Schema Flexibility
Example: Adding a new field doesn’t require modifying the entire database schema.SQL
Databases: Rigid schemas requiring predefined tables and columns.Schema changes can be
costly and time-consuming in large datasets.
MongoDB: Handles JSON-like documents (BSON), allowing storage of nested data and arrays
directly.Ideal for data that doesn’t fit neatly into rows and columns, like social media profiles
or IoT data.SQL Databases: Require normalization or additional tables to represent complex
relationships, which can make queries more complex.
3. Horizontal Scalability
MongoDB: Supports horizontal scaling through sharding, where data is distributed across
multiple servers.Suitable for applications needing to handle massive amounts of data and high
user traffic.
MongoDB: Flexible data model enables rapid prototyping and faster development
cycles.Especially beneficial for startups or agile teams.SQL Databases: Development might be
slower due to the need to design and maintain rigid schemas upfront.
MongoDB: Optimized for high-volume insert and update operations due to its document model
and ability to process data in parallel.Example: IoT data logging or real-time analytics.
SQL Databases: Write performance can be hindered by complex transactions, constraints, and
normalization requirements.
JSON-like documents align well with modern web and mobile development.
SQL Databases:
MongoDB: Data often represents the application's objects directly, reducing the need for
Object-Relational Mapping (ORM).
SQL Databases: Often require multiple table joins to reconstruct an object, which can be
computationally expensive.
MongoDB: Supports automatic failover and data redundancy via replica sets.
SQL Databases: High availability often requires additional setup or third-party solutions.
Despite MongoDB's strengths, SQL databases like MySQL, PostgreSQL, or Oracle still excel
in scenarios requiring:
Complex Transactions: ACID compliance for highly consistent, multi-step operations (e.g.,
banking).
Reporting and Analytics: SQL’s robust querying and aggregation capabilities with JOINs and
complex relationships.
Answer:- MongoDB offers several advantages that make it a popular choice for modern
applications. Below are some key benefits:
1. Flexible Data Model
Dynamic Schemas: Unlike SQL databases, MongoDB doesn’t require a predefined schema.
Documents in the same collection can have different structures, making it highly adaptable to
evolving data requirements.
JSON-Like Documents: Data is stored in a BSON (Binary JSON) format, allowing for nested
structures, arrays, and more complex data representations.
2. Scalability
Horizontal Scaling: MongoDB supports sharding, enabling you to distribute data across
multiple servers to handle large-scale datasets and high traffic efficiently.
Elastic Growth: Easily scale up or down based on application needs without significant
architectural changes.
3. High Performance
Real-Time Applications: Suitable for IoT, social media, and real-time analytics due to its
support for fast data ingestion and processing.
Geospatial Features: Native support for geospatial queries makes it ideal for location-based
applications like ride-sharing or delivery services.
5. Ease of Development
Rapid Prototyping: The flexible schema reduces the need for extensive setup, allowing
developers to iterate quickly.
7. High Availability
Replica Sets: Built-in replication ensures data redundancy and automatic failover in case of
node failure, enhancing reliability.
8. Cost-Effectiveness
Open Source: MongoDB Community Edition is free to use, making it accessible for startups
and small businesses.
Cloud Integration: Managed solutions like MongoDB Atlas reduce operational costs by
handling infrastructure, backups, and scaling.
MongoDB Atlas: A cloud-based managed database service with features like auto-scaling,
backups, and monitoring.
Driver Support: Offers robust drivers for multiple programming languages, making it easy to
integrate with various tech stacks.
MongoDB integrates seamlessly with modern cloud platforms, enabling deployment across
distributed systems with minimal overhead.
Question 73:-What are the data types in MongoDB?How do you Delete a Document?
MongoDB supports a variety of data types, which are stored in BSON (Binary JSON). Below
are the most common MongoDB data types:
String:
Used to store text.
Integer:
Example: "age": 25
Double:
Boolean:
Object:
Example:
json
Copy code
Array:
json
Copy code
Null:
Date:
ObjectId:
Binary Data:
Decimal128:
Regular Expression:
Timestamp:
Used for storing a timestamp, often for replication and internal MongoDB operations.
1. Using deleteOne()
Example:
This deletes the first document where the name field is "John".
2. Using deleteMany()
Example:
Example:
Example:
db.collectionName.deleteMany({});
1. find():
Retrieves documents that match the specified query criteria. Returns all matching documents.
Example:
2. findOne():
Example:
Query Syntax
Queries in MongoDB are JSON-like objects specifying field-value pairs and operators.
Example:
Operators:
Example:-
3. Logical Operators:
Example:-
db.collectionName.find({
});
4. Array Queries:
Retrieves documents where the scores array has an element between 90 and 100.
Projection
Control which fields to include or exclude in the query result using the second parameter of
find() or findOne().
Example:
Sorting
Example:
Pagination
Example:
db.collectionName.find().skip(10).limit(5);
Aggregation Framework
Example:
db.collectionName.aggregate([
{ $sort: { count: -1 } }
]);
Filters documents with status: "active", groups them by age, counts the occurrences, and sorts
by count.
Text Search
Example:
Regex Queries
Example:
Interactive Environment:
Database Management:
Administrative Commands:
Perform tasks like creating indexes, managing users, and monitoring database
performance.
1. $eq (Equal)
Syntax:
Example:
Matches documents where the specified field is not equal to a given value.
Syntax:
Example:
Matches documents where the specified field is greater than a given value.
Syntax:
Example:
Matches documents where the specified field is less than a given value.
Syntax:
Example:
5. $in (In)
Matches documents where the specified field’s value is in a given array of values.
Syntax:
Example:
You can combine these operators in a single query using logical operators like $and, $or, etc.
Example:
db.products.find({
$and: [
{ price: { $gt: 50 } },
});
Retrieves products with a price greater than 50 and less than 200.
Answer:-In MongoDB, a database is a container for collections, which in turn store documents.
Databases in MongoDB are used to logically organize and manage data. Each database is
independent, allowing you to store and operate on different datasets separately.
1. Namespace:
○ Each database has a unique name.
○ Collections within a database are identified by the database name and collection
name, forming a namespace.
2. Multiple Databases:
○ A single MongoDB instance can host multiple databases, enabling you to
segregate data for different applications or purposes.
3. Default Database:
○ MongoDB provides a default database called test. If no database is specified,
test is used.
4. Database Limit:
○ MongoDB doesn't impose a strict limit on the number of databases. Practical
limits depend on system resources.
5. Data Storage:
○ Each database is stored in its own set of files on disk.
1. Field-Value Pairs:
○ Documents consist of key-value pairs (fields and their corresponding data).
Example:
json
"age": 30,
"isActive": true
○
2. Dynamic Schema:
○ Documents within the same collection can have different fields or structures.
Example:
json
○
3. Nested Structures:
○ Documents can contain embedded documents and arrays.
Example:
json
"name": "John",
○
4. Unique Identifier:
○ Each document has a unique _id field automatically generated unless specified
manually.
MongoDB provides commands to insert documents into a collection. These are insertOne and
insertMany.
1. insertOne Command
Syntax:
javascript
db.collectionName.insertOne(document)
Example:
javascript
db.users.insertOne({
age: 30,
isActive: true
});
●
○ Inserts the document into the users collection.
Output:
json
"acknowledged": true,
"insertedId": ObjectId("64c7f9e0f7894c8d7f7f8a7a")
}
●
2. insertMany Command
The insertMany method is used to insert multiple documents into a collection at once.
Syntax:
javascript
db.collectionName.insertMany([document1, document2, ...])
Example:
javascript
db.users.insertMany([
]);
●
○ Inserts three documents into the users collection.
Output:
json
{
"acknowledged": true,
"insertedIds": {
"0": ObjectId("64c7f9e0f7894c8d7f7f8a7a"),
"1": ObjectId("64c7f9e0f7894c8d7f7f8a7b"),
"2": ObjectId("64c7f9e0f7894c8d7f7f8a7c")
●
Key Points for insertOne and insertMany
1. Atomicity:
○ insertOne: Operation is always atomic (affects only one document).
○ insertMany: The operation is atomic only if ordered is set to true (default
behavior). If one document insertion fails, the entire operation is aborted.
2. Ordered vs. Unordered Insertion:
○ By default, insertMany inserts documents in the order provided (ordered: true).
○ To allow the operation to continue even if some insertions fail, set ordered:
false.
Example:
db.users.insertMany([
○
■ In this case, the second document will succeed, but the third document
(duplicate _id) will fail without stopping the operation.
1. No Schema:
○ Collections in MongoDB do not enforce a fixed schema, allowing you to store
documents with varying fields.
2. Named Group of Documents:
○ Each collection has a unique name within the database.
3. Dynamic Structure:
○ Documents within the same collection can have different fields and data types.
4. Automatic Creation:
○ Collections are created automatically when you insert the first document into
them.
5. Indexes:
○ Collections can have indexes to speed up queries, including primary indexes on
the _id field (which is automatically indexed by default).
MongoDB provides two primary methods for updating documents: updateOne() and
updateMany(). These methods allow you to modify existing documents in a collection.
1. updateOne() Command
The updateOne() method is used to update a single document that matches the specified filter
criteria. If multiple documents match, only the first matching document will be updated.
Syntax:
javascript
db.collection.updateOne(
Example: Update a single document where the name is "John" to set the age to 35.
javascript
db.users.updateOne(
);
●
○ The above command will update only the first document where name is "John".
● Options:
○ $set: Modifies the value of a field.
○ $inc: Increments the value of a field.
○ $unset: Removes a field.
Output:
json
{
"acknowledged": true,
"matchedCount": 1,
"modifiedCount": 1
●
○ matchedCount: Number of documents that matched the filter.
○ modifiedCount: Number of documents actually modified.
2. updateMany() Command
The updateMany() method is used to update all documents that match the specified filter
criteria. It is useful when you want to apply the same update to multiple documents at once.
Syntax:
javascript
db.collection.updateMany(
Example: Update all documents where the status is "inactive" to set the isActive field to true.
javascript
db.users.updateMany(
);
●
○ This command will update all documents in the users collection where status is
"inactive", setting the isActive field to true.
● Options:
○ $set: Modifies the value of a field.
○ $inc: Increments the value of a field.
○ $mul: Multiplies the value of a field.
○ $push: Adds elements to an array.
○ $unset: Removes a field.
Output:
json
"acknowledged": true,
"matchedCount": 3,
"modifiedCount": 3
●
○ matchedCount: Number of documents that matched the filter.
○ modifiedCount: Number of documents actually modified.
1. Using updateOne():
○ Scenario: You want to update a single user's age where the name is "Alice".
javascript
db.users.updateOne(
{ name: "Alice" },
{ $set: { age: 28 } }
);
2.
3. Using updateMany():
○ Scenario: You want to update the status of all users who are "inactive" to
"active".
javascript
db.users.updateMany(
{ status: "inactive" },
);
4.
1. updateOne():
○ Updates only the first matching document.
○ Useful when you want to update a specific document or just the first match.
2. updateMany():
○ Updates all matching documents.
○ Useful when you want to apply the same update across multiple documents.
$set: Sets the value of a field. If the field doesn't exist, it will be created.
javascript
db.users.updateOne(
{ name: "John" },
{ $set: { age: 40 } }
);
{ name: "John" },
{ $inc: { age: 1 } }
);
{ name: "Alice" },
);
db.users.updateOne(
{ name: "Alice" },
);
Answer:-In MongoDB, logical operators are used to combine multiple conditions in a query,
allowing you to perform more complex searches. These operators are used with the $and, $or,
$not, and $nor conditions to combine multiple query expressions.
1. $and:
○ The $and operator is used to match documents that satisfy all the conditions
provided in the query.
○ Multiple conditions must all be true for the document to be a match.
Syntax:
javascript
Copy code
{ $and: [{ condition1 }, { condition2 }] }
Example: Retrieve documents from the users collection where age is greater than 25 and status
is "active":
javascript
Copy code
db.users.find({
$and: [
{ age: { $gt: 25 } },
{ status: "active" }
});
○
■ This will match documents where both conditions are true: age > 25 and
status is "active".
2. $or:
○ The $or operator is used to match documents that satisfy at least one of the
conditions provided in the query.
○ Any one of the conditions must be true for the document to be a match.
Syntax:
javascript
Copy code
{ $or: [{ condition1 }, { condition2 }] }
Example: Retrieve documents from the users collection where age is less than 18 or status is
"inactive":
javascript
Copy code
db.users.find({
$or: [
{ age: { $lt: 18 } },
{ status: "inactive" }
});
○
■ This will match documents where either age < 18 or status is "inactive".
3. $not:
○ The $not operator is used to negate a condition. It matches documents that do
not satisfy the given condition.
Syntax:
javascript
Copy code
{ field: { $not: condition } }
Example: Retrieve documents from the users collection where the age is not equal to 30:
javascript
Copy code
db.users.find({
});
○
■ This will match all documents where age is not equal to 30.
4. $nor:
○ The $nor operator is used to match documents where none of the specified
conditions are true.
○ It combines conditions similar to $or, but negates the result.
Syntax:
javascript
Copy code
{ $nor: [{ condition1 }, { condition2 }] }
Example: Retrieve documents from the users collection where age is not greater than 40 and
status is not "inactive":
javascript
Copy code
db.users.find({
$nor: [
{ age: { $gt: 40 } },
{ status: "inactive" }
});
○
■ This will match documents where neither age > 40 nor status is
"inactive".
Question:- 80 What are NoSQL databases? What are the different types of NoSQL
databases?
Answer:-NoSQL (Not Only SQL) databases are a type of database that provide a mechanism
for storing and retrieving data in ways other than the traditional relational database model
(SQL). Unlike relational databases, which use structured query language (SQL) and a fixed
schema, NoSQL databases are designed to be flexible, scalable, and suitable for large,
distributed data storage, especially in environments with big data and high-velocity,
unstructured data.
NoSQL databases are popular for applications that require high availability, horizontal scaling,
and the ability to handle a variety of data types like documents, key-value pairs, graphs, and
wide-column stores.
1. Schema-less Design:
○ NoSQL databases do not require a predefined schema. This allows flexibility in
storing data with different structures.
2. Horizontal Scalability:
○ NoSQL databases are often designed to scale out by adding more servers
(nodes) to the system, enabling them to handle larger loads and data volumes
effectively.
3. High Availability and Fault Tolerance:
○ Many NoSQL databases are built to be distributed and replicated across multiple
servers or data centers, ensuring high availability and fault tolerance.
4. Flexible Data Models:
○ NoSQL databases support a variety of data models, such as key-value pairs,
documents, graphs, and column-family stores.
5. Unstructured or Semi-structured Data:
○ NoSQL databases can handle unstructured or semi-structured data, which is not
easily accommodated by traditional relational databases.
NoSQL databases are broadly categorized based on their data model. Here are the most
common types:
1. Key-Value Stores
○ Description: The simplest form of NoSQL databases. Data is stored as key-
value pairs, where the key is a unique identifier and the value can be a string,
number, or more complex data structure.
○ Use Case: Suitable for scenarios requiring high-speed data retrieval, such as
caching, session management, and user profile storage.
○ Examples:
■ Redis: An in-memory key-value store, often used for caching and real-
time applications.
■ Riak: A distributed key-value store designed for high availability and
fault tolerance.
Example:
json
Copy code
{
○
2. Document Stores
○ Description: Data is stored as documents, typically in JSON or BSON format.
These documents can contain nested structures, arrays, and fields with different
data types. Document stores are highly flexible and allow for semi-structured
data.
○ Use Case: Ideal for content management systems, user data storage, and
applications with dynamic data structures.
○ Examples:
■ MongoDB: A popular document-based NoSQL database that uses
BSON (binary JSON) to store documents.
■ CouchDB: A document-based database that uses JSON for storing data
and supports HTTP-based APIs.
Example:
json
Copy code
{
"user_id": "123",
"name": "Alice",
"age": 30,
○
3. Column-Family Stores
○ Description: Data is stored in columns rather than rows, which is the traditional
way in relational databases. Each column can store a large number of values,
and columns can be grouped into column families for better performance.
○ Use Case: Suitable for analytics applications, real-time data processing, and
applications that require fast read/write operations on large datasets.
○ Examples:
■ Apache Cassandra: A highly scalable, distributed column-family store
designed for handling large amounts of data across many commodity
servers.
■ HBase: A column-family store built on top of Hadoop, designed for
handling large amounts of sparse data.
Example:
vbnet
Copy code
Column Family: user_profile
○
4. Graph Databases
○ Description: Data is represented as nodes (entities) and edges (relationships)
between them. Graph databases excel at handling relationships and are
commonly used in applications like social networks, recommendation engines,
and fraud detection.
○ Use Case: Suitable for applications that require complex queries about
relationships, such as social networking, fraud detection, and route
optimization.
○ Examples:
■ Neo4j: One of the most popular graph databases, known for its powerful
querying capabilities using the Cypher query language.
■ ArangoDB: A multi-model database that supports graph, document, and
key-value data models.
○ Example:
■
5. Search Engines
○ Description: Though not always considered a traditional NoSQL database,
search engines like Elasticsearch store and index large amounts of unstructured
text data and provide fast search capabilities.
○ Use Case: Commonly used for full-text search, log analysis, and analytics
applications.
○ Examples:
■ Elasticsearch: A distributed search and analytics engine based on
Apache Lucene.
■ Solr: Another search platform built on top of Apache Lucene.
○ Example:
■ Indexing documents with full-text search capabilities.
UNIT-5
Q.81 what is difference between Get and Post method?
In Java, when dealing with web applications, the GET and POST methods are used to send data
from the client (browser) to the server. Here's a breakdown of their differences:
GET method:
● Data transmission:
Data is appended to the URL as query parameters
(e.g., https://www.example.com/search?q=java).
● Visibility:
Data is visible in the URL, which can be problematic for sensitive information.
● Data limit:
Limited amount of data can be sent due to URL length restrictions.
● Caching:
GET requests can be cached by the browser, which can improve performance but can lead to
stale data.
● Use cases:
Retrieving data from the server, such as loading a webpage or performing a search.
POST method:
● Data transmission: Data is sent in the body of the request, hidden from the user.
● Security: More secure than GET as data is not visible in the URL.
● Caching: POST requests are not cached by default, ensuring that data is always fresh.
● Use cases: Submitting data to the server for processing, such as creating a new user account or
submitting a form.
● The client sends the request through the browser to the Web server/Application Server.
● The server passes the client request to the respective servlet.
● Servlet processes the request generates the response and sends the response back to the server.
● The server passes the generated response to the browser/client.
● We can achieve this in 2 ways, servlet provides
● forward() method in RequestDispatcher.
RequestDispatcher Interface
● Servlets provide RequestDispatcher in javax.servlet package. It defines an object to
dispatch the client request from one servlet to another servlet on the same server. Basically,
this can be used to receive the client request object and send that object to any other
resource such as Servlet, JSP, HTML file, etc. We can get the RequestDispatcher object
using the below
Syntax:
r.forward(req, resp);
endRedirect() method
It sends a temporary redirect response to the client using the specified redirect location URL given
in the method and clears the buffer. Let’s consider a scenario, where we need to redirect the request
from a servlet to other servlets which is in another server, in this case, we can use the
sendRedirect() method so that the client/browser knows where the request is going and getting
processed.
● Speed: Servlets are faster than CGI scripts because they use a different process model.
● Efficiency: Servlets use lightweight Java threads to handle requests, while CGI uses
heavyweight operating system processes.
● Portability: Servlets are portable because they use the Java language.
● Robustness: Servlets are managed by the JVM, so there's no need to worry about memory leaks
or garbage collection.
● Security: Servlets are secure because they use the Java language.
● Access to Java APIs: Servlets can access the large set of APIs available for the Java platform.
The nine implicit objects available to a JavaServer Pages (JSP) page are:
request, response, pageContext, session, application, out, config, page, and exception.
request
1
This is the HttpServletRequest object associated with the request.
response
2 This is the HttpServletResponse object associated with the response to the
client.
out
3
This is the PrintWriter object used to send output to the client.
session
4
This is the HttpSession object associated with the request.
application
5
This is the ServletContext object associated with the application context.
config
6
This is the ServletConfig object associated with the page.
pageContext
7 This encapsulates use of server-specific features like higher
performance JspWriters.
page
8 This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
Exception
9 The Exception object allows the exception data to be accessed by designated
JSP.
Q.85 Explain the architecture and lifecycle of a JavaServer Page (JSP) within a web
application.
A JavaServer Page (JSP) is a collection of technologies that helps developers create dynamic web
pages using the Java programming language. The architecture and lifecycle of a JSP are as
follows:
A JavaServer Page (JSP) is a collection of technologies that helps developers create dynamic web
pages using the Java programming language. The architecture and lifecycle of a JSP are as
follows:
Lifecycle
The lifecycle of a JSP begins when a client requests the page. The steps in the lifecycle are:
1. The web container receives the request for a JSP
4. The servlet generates HTML output, which is sent back to the client
5. The page is cached for faster access the next time it is requested
JSP has several advantages, including:
● Less coding: Custom tags reduce the amount of code required, making coding more flexible
● Fast development: No need to recompile or redeploy the project when modifying a JSP page
● Easy integration: Supports Java APIs, which can be easily integrated with HTML code
Tomcat offers a lightweight and efficient solution for hosting Java web applications. Tomcat is
popular for several reasons. Its scalability is admired by many. Tomcat's robustness is useful. It
has great community support which brings relief to the users. With its modular architecture and
adherence to industry standards, Tomcat enables developers to build and deploy web applications
with ease.
Q.87 Explain types of Cookies with example.
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.
In this example, we are storing the name of the user in the cookie object and accessing it in another
servlet. As we know well that session corresponds to the particular user. So if you access it from
too many browsers with different values, you will get the different value.
Q.88 Discuss the different types of standard action tags used in JSP.
There are many JSP action tags or elements. Each JSP action tag is used to perform some
specific tasks.
The action tags are used to control the flow between pages and to use Java Bean. The Jsp
action tags are given below.
jsp:getProperty
prints the value of property of the bean.
Q.89 Define the advantages of servlet over CGI? Explain with an example
1. Platform Independence
Servlets are written entirely in java so these are platform independent. Servlets can run on any
Servlet enabled web server. For example if you develop an web application in windows machine
running Java web server, you can easily run the same on apache web server (if Apache Serve is
installed) without modification or compilation of code. Platform independency of servlets provide
a great advantages over alternatives of servlets.
2. Performance
Due to interpreted nature of java, programs written in java are slow. But the java servlets runs very
fast. These are due to the way servlets run on web server. For any program initialization takes
significant amount of time. But in case of servlets initialization takes place first time it receives a
request and remains in memory till times out or server shut downs. After servlet is loaded, to
handle a new request it simply creates a new thread and runs service method of servlet. In
comparison to traditional CGI scripts which creates a new process to serve the request.
3. Extensibility
Java Servlets are developed in java which is robust, well-designed and object oriented language
which can be extended or polymorphed into new objects. So the java servlets take all these
advantages and can be extended from existing class to provide the ideal solutions.
4. Safety
Java provides very good safety features like memory management, exception handling etc.
Servlets inherits all these features and emerged as a very powerful web server extension.
5. Secure
Servlets are server side components, so it inherits the security provided by the web server. Servlets
are also benefited with Java Security Manager.
Q.90 Illustrate why the session is required in web applications. Mention all the session
tracking techniques in servlet with their pros and cons. Also give example of each.
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each
time user requests to the server, server treats the request as the new request. So we need to maintain
the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the figure
given below:
Here are given 6 steps to create a servlet example. These steps are required for all the servers.
The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.
Here, we are going to use apache tomcat server in this example. The steps are as follows:
2. Create a Servlet
The directory structure defines that where to put the different types of files so that web container
may get the information and respond to the client.
The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's see
the directory structure that must be followed to create the servlet.
As you can see that the servlet class file must be in the classes folder. The web.xml file must be
under the WEB-INF folder.
2)Create a Servlet
The HttpServlet class is widely used to create the servlet because it provides methods to
handle http requests such as doGet(), doPost, doHead() etc.
In this example we are going to create a servlet that extends the HttpServlet class. In this
example, we are inheriting the HttpServlet class and providing the implementation of the
doGet() method. Notice that get request is the default request.
2) weblogic.jar
Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss
1. Compilation of JSP page: Here the generated java servlet file (test.java) is compiled to a class
file (test.class).
2. Classloading: The classloader loads the Java class file into the memory. The loaded Java class
can then be used to serve incoming requests for the JSP page.
3. Instantiation: Here an instance of the class is generated. The container manages one or more
instances by providing responses to requests.
4. Initialization: jspInit() method is called only once during the life cycle immediately after the
generation of the Servlet instance from JSP.
5. Request processing: _jspService() method is used to serve the raised requests by JSP. It takes
request and response objects as parameters. This method cannot be overridden.
6. JSP Cleanup: In order to remove the JSP from the use by the container or to destroy the
method for servlets jspDestroy()method is used. This method is called once, if you need to
perform any cleanup task like closing open files, or releasing database connections
jspDestroy() can be overridden.
request
1
This is the HttpServletRequest object associated with the request.
response
2 This is the HttpServletResponse object associated with the response
to the client.
out
3
This is the PrintWriter object used to send output to the client.
session
4
This is the HttpSession object associated with the request.
application
5 This is the ServletContext object associated with the application
context.
config
6
This is the ServletConfig object associated with the page.
pageContext
7 This encapsulates use of server-specific features like higher
performance JspWriters.
page
8 This is simply a synonym for this, and is used to call the methods
defined by the translated servlet class.
Exception
9 The Exception object allows the exception data to be accessed by
designated JSP.
Q.94 What are JSP directives? Explain various types of directives with
example?
The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
There are three types of directives:
● page directive
● include directive
● taglib directive
Syntax of JSP Directive
<%@ directive attribute="value" %>
Attributes of JSP page directive
● import
● contentType
● extends
● info
● buffer
1) Import
The import attribute is used to import class,interface or all the members of a package.It is similar
to import keyword in java class or interface.
Example of import attribute
<html>
<body>
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the
HTTP response.The default value is "text/html;charset=ISO-8859-1".
3)extends
The extends attribute defines the parent class that will be inherited by the generated servlet.It is
rarely used.
4)info
This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.
5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page.The
default size of the buffer is 8Kb.
jsp:include
1
Includes a file at the time the page is requested.
jsp:useBean
2
Finds or instantiates a JavaBean.
jsp:setProperty
3
Sets the property of a JavaBean.
jsp:getProperty
4
Inserts the property of a JavaBean into the output.
jsp:forward
5
Forwards the requester to a new page.
jsp:plugin
6 Generates browser-specific code that makes an OBJECT or EMBED tag for the
Java plugin.
7 jsp:element
Defines XML elements dynamically.
jsp:attribute
8
Defines dynamically-defined XML element's attribute.
jsp:body
9
Defines dynamically-defined XML element's body.
jsp:text
10
Used to write template text in JSP pages and documents.
init()
Whenever a user invokes the URL associated with the particular servlet, the init() method is
called. It is called only once, not each time a request is made. An instance of a servlet is created
through the init() method. Each user request creates a new thread catering to GET and POST
requests.
//initialization code
}
service()
The web container calls the service() method each time there is a new request to the servlet. This
is done by spawning a new thread. This method checks the HTTP request type, i.e, whether it is a
GET, POST, DELETE, etc, and calls the doGet, doPost, doDelete, etc methods as per the
request.
destroy()
This method is called just once at the end of the Life Cycle of Servlet. It helps perform all the
clean-up activities, including closing database connections and halting background threads.
Then, the servlet is removed from the container.
//clean-up code
The following represents the Servlet Life Cycle. When a request is sent for a particular web page,
the corresponding servlet must be initialized. The servlet container/web container will load the
servlet and create an instance of it through init().
Subsequent requests to the same web page will invoke the service() method. This method will
typecast the ServletRequest and ServletResponse objects to HttpServletRequest and
HttpServletResponse objects, respectively. Servlets can handle multiple requests concurrently
since each request results in a new thread.
The destroy() method is only called once all threads within the servlet's service methods have
exited or after a timeout period.
Q.97 what are java Beans? Why they are used? Write a JSP page and use an
existing java bean in JSP page by using the standard action. Write the program
with describing the output?
A JavaBean is a specially constructed Java class written in the Java and coded according to the
JavaBeans API specifications.
Following are the unique characteristics that distinguish a JavaBean from other Java classes −
● It should be serializable and that which can implement the Serializable interface.
A JavaBean property is a named attribute that can be accessed by the user of the object. The
attribute can be of any Java data type, including the classes that you define.
A JavaBean property may be read, write, read only, or write only. JavaBean properties are
accessed through two methods in the JavaBean's implementation class −
getPropertyName()
1 For example, if property name is firstName, your method name would
be getFirstName() to read that property. This method is called accessor.
setPropertyName()
2 For example, if property name is firstName, your method name would
be setFirstName() to write that property. This method is called mutator.
A read-only attribute will have only a getPropertyName() method, and a write-only attribute
will have only a setPropertyName() method.
Example
Consider a student class with few properties –
public StudentsBean() {
}
public String getFirstName(){
return firstName;
}
public String getLastName(){
return lastName;
}
public int getAge(){
return age;
}
public void setFirstName(String firstName){
this.firstName = firstName;
}
public void setLastName(String lastName){
this.lastName = lastName;
}
public void setAge(Integer age){
this.age = age;
}
}
HttpServletRequest
Allows servlets to read data from HTTP requests, including request headers and form data. The
servlet container creates an HttpServletRequest object and passes it to the servlet's service
methods.
HttpServletResponse
Allows servlets to write data to HTTP responses, including response headers and the response
message body.
Here are some methods available in the HttpServletRequest interface:
getDateHeader
Returns the value of a specified request header as a long value that represents a Date object
getCookies
Returns an array containing all of the Cookie objects the client sent with this request
getSession
Returns the current session associated with this request, or creates one if there isn't one
An HTTP servlet is a type of servlet that handles HTTP requests and provides HTTP responses,
usually as HTML page
Q.99 Discuss the compilation process of JSP files into servlets and how they
are executed by the servlet container.
A JSP container is an entity that translates, executes, and processes JSP pages and delivers requests
to them.
The exact make-up of a JSP container varies from implementation to implementation, but it will
consist of a servlet or collection of servlets. The JSP container, therefore, is executed by a servlet
container. (Servlet containers are summarized in "Servlet Containers".)
A JSP container may be incorporated into a Web server if the Web server is written in Java, or the
container may be otherwise associated with and used by the Web server.
Presuming the typical on-demand translation scenario, a JSP page is usually executed through the
following steps:
1. The user requests the JSP page through a URL ending with a .jsp file name.
2. Upon noting the .jsp file name extension in the URL, the servlet container of the Web
server invokes the JSP container.
3. The JSP container locates the JSP page and translates it if this is the first time it has been
requested. Translation includes producing servlet code in a .java file and then compiling
the .java file to produce a servlet .class file.
The servlet class generated by the JSP translator subclasses a class (provided by the JSP
container) that implements the javax.servlet.jsp.HttpJspPage interface (described
in "Standard JSP Interfaces and Methods"). The servlet class is referred to as the page
implementation class. This document will refer to instances of page implementation classes
as JSP page instances.
Translating a JSP page into a servlet automatically incorporates standard servlet
programming overhead into the generated servlet code, such as implementing
the javax.servlet.jsp.HttpJspPage interface and generating code for its service method.
4. The JSP container triggers instantiation and execution of the page implementation class.
The servlet (JSP page instance) will then process the HTTP request, generate an HTTP
response, and pass the response back to the client.
Q.100 Provide examples of how you can use these interfaces to retrieve
request parameters, set response headers, and send data back to the client.
MockServer.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
HttpServletResponse resp)
resp.setContentType("text/html");
PrintWriter ab = resp.getWriter();
ab.close();
}
}