0% found this document useful (0 votes)
30 views

Internet Programming-1

The document discusses internet programming modules, including introduction to web technology, front end development, and basics of Bootstrap. It covers topics like 3-tier web architecture, HTML5 audio and video elements, the canvas element, CSS transitions, and events in JavaScript.

Uploaded by

IOTE42Pratik Pol
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Internet Programming-1

The document discusses internet programming modules, including introduction to web technology, front end development, and basics of Bootstrap. It covers topics like 3-tier web architecture, HTML5 audio and video elements, the canvas element, CSS transitions, and events in JavaScript.

Uploaded by

IOTE42Pratik Pol
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Internet Programming

Module-wise PYQs

Module 1: Introduction to Web Technology

Draw and Illustrate 3 tier web architecture (2019)


● In 3 tier architecture, there are 3 components: Client PC, An Application server and A Database
Server.
● The work of the server is distributed among application server and database server.
● Application server has the required communication functions.
● The data required by the business logic exists in the database server.
● The required data is returned to public servers and then to client PC.

Presentation Tier
The presentation tier is the user interface and communication layer of the application, where the end
user interacts with the application. Its main purpose is to display information to and collect
information from the user. This top-level tier can run on a web browser, as a desktop application, or a
graphical user interface (GUI), for example. Web presentation tiers are usually developed using HTML,
CSS and JavaScript. Desktop applications can be written in a variety of languages depending on the
platform.

Business Logic Tier


The application tier, also known as the logic tier or middle tier, is the heart of the application. In this
tier, information collected in the presentation tier is processed - sometimes against other information
in the data tier - using business logic, a specific set of business rules. The application tier can also add,
delete or modify data in the data tier.

Database Tier
The application tier, also known as the logic tier or middle tier, is the heart of the application. In this
tier, information collected in the presentation tier is processed - sometimes against other information
in the data tier - using business logic, a specific set of business rules. The application tier can also add,
delete or modify data in the data tier.
Advantages:
● Improved Data Integrity
● High Degree of Flexibility in deployment platform and configurations
● Improved security
● High Performance and persistent objects
● Architecture is scalable, adding users and resources in future would be easy
● Maintenance and modifications can be done effectively
● Code and data reusability can be achieved

Disadvantages:
● 3 tier architecture is complex compared to 1 tier and 2 tier
● Cost of network maintenance and deployment is greater than 1 tier and 2 tier

Write HTML5 code for embedding the audio and video elements in the
web page.(2019, 2018)
The <video> element
The <video> element allows you to embed a video very easily. A really simple example looks
like this:
<video src="rabbit320.webm" controls>
</video>

Additional features when displaying an HTML video.


<video width="400"
height="400"
autoplay
loop
muted
preload="auto"
poster="poster.png" ><!-- some source ---></video>

The <audio> element


The <audio> element works just like the <video> element, with a few small differences as
outlined below. A typical example might look like so:
<audio controls>
<source src="viper.mp3" type="audio/mp3" />
<source src="viper.ogg" type="audio/ogg" />
</audio>
This takes up less space than a video player, as there is no visual component — you just need to
display controls to play the audio. Other differences from HTML video are as follows:

● The <audio> element doesn't support the width/height attributes — again, there is no
visual component, so there is nothing to assign a width or height to.
● It also doesn't support the poster attribute — again, no visual component.

Explain <Canvas> element in HTML5 (2019,2018)


The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.

The <canvas> element is only a container for graphics. You must use JavaScript to
actually draw the graphics.

Canvas has several methods for drawing paths, boxes, circles, text, and adding
images. A canvas is a rectangular area on an HTML page. By default, a canvas has
no border and no content. The markup looks like this:
<canvas id="myCanvas" width="200" height="100"></canvas>

The <canvas> is initially blank, and to display something, a script first needs to
access the rendering context and draw on it.

The canvas element has a DOM method called getContext, used to obtain the
rendering context and its drawing functions. This function takes one parameter,
the type of context2d.

Following is the code to get required context along with a check if your browser
supports <canvas> element −
var canvas = document.getElementById("mycanvas");

if (canvas.getContext) {
var ctx = canvas.getContext('2d');
// drawing code here
} else {

// canvas-unsupported code here


}

CSS Transitions
CSS transitions provide a way to control animation speed when changing CSS properties.
Instead of having property changes take effect immediately, you can cause the changes in a
property to take place over a period of time. For example, if you change the color of an element
from white to black, usually the change is instantaneous. With CSS transitions enabled,
changes occur at time intervals that follow an acceleration curve, all of which can be
customized.
CSS Transitions are controlled using the shorthand transition property. This is the
best way to configure transitions, as it makes it easier to avoid out of sync
parameters, which can be very frustrating to have to spend lots of time debugging
in CSS. You can control the individual components of the transition with the
following sub-properties:

transition-property
Specifies the name or names of the CSS properties to which transitions should be
applied. Only properties listed here are animated during transitions; changes to all
other properties occur instantaneously as usual.

transition-duration
Specifies the duration over which transitions should occur. You can specify a single
duration that applies to all properties during the transition, or multiple values to
allow each property to transition over a different period of time.

transition-timing-function
Specifies a function to define how intermediate values for properties are
computed. Timing functions determine how intermediate values of the transition
are calculated. Most timing functions can be specified by providing the graph of
the corresponding function, as defined by four points defining a cubic bezier.

transition-delay
Defines how long to wait between the time a property is changed and the
transition actually begins.
Transition shorthand CSS syntax
div {
transition: <property> <duration> <timing-function> <delay>;
}

This simple example performs a four-second font size transition with a two-second
delay between the time the user mouses over the element and the beginning of the
animation effect:

#delay {
font-size: 14px;
transition-property: font-size;
transition-duration: 4s;
transition-delay: 2s;
}

#delay:hover {
font-size: 36px;
}

Basics of Bootstrap
Bootstrap is a free and open-source tool collection for creating responsive websites
and web applications. It is the most popular HTML, CSS, and JavaScript
framework for developing responsive, mobile-first websites. Nowadays, the
websites are perfect for all browsers (IE, Firefox, and Chrome) and for all sizes of
screens (Desktop, Tablets, Phablets, and Phones).
Why use Bootstrap ?
By using this framework we can easily manipulate the styling of any web page, like
font style, text color, background color, flex, grid system, etc. Bootstrap V4 & V5
are the most popular versions. There are lots of other CSS frameworks like
Tailwind CSS, Bulma, and Foundation but among them, this framework is the
most popular because:
● It is Faster and Easier way for Web-Development.
● It creates Platform-independent web-pages.
● It creates Responsive Web-pages.
● It designs responsive web pages for mobile devices too.
● It is a free and open-source framework available on www.getbootstrap.com

Module 2: Front End Development

What are events in JS ? Explain different types of events. (2019)


Events are actions or occurrences that happen in the system you are programming,
which the system tells you about so your code can react to them.

For example, if the user clicks a button on a webpage, you might want to react to
that action by displaying an information box. In this article, we discuss some
important concepts surrounding events, and look at how they work in browsers.
This won't be an exhaustive study; just what you need to know at this stage.

Events are fired inside the browser window, and tend to be attached to a specific
item that resides in it. This might be a single element, a set of elements, the HTML
document loaded in the current tab, or the entire browser window. There are many
different types of events that can occur.
For example:
● The user selects, clicks, or hovers the cursor over a certain element.
● The user chooses a key on the keyboard.
● The user resizes or closes the browser window.
● A web page finishes loading.
● A form is submitted.
● A video is played, paused, or ends.
● An error occurs.

To react to an event, you attach an event handler to it. This is a block of code
(usually a JavaScript function that you as a programmer create) that runs when
the event fires. When such a block of code is defined to run in response to an
event, we say we are registering an event handler.

Following code changes background color on button click


HTML
<button>Change color</button>

JS
const btn = document.querySelector('button');

function random(number) {
return Math.floor(Math.random() * (number+1));
}

btn.addEventListener('click', () => {
const rndCol = `rgb(${random(255)}, ${random(255)},
${random(255)})`;
document.body.style.backgroundColor = rndCol;
});

Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an HTML element

The user moves the mouse away from an HTML


onmouseout
element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

Explain Geo Location and media query with an example in HTML5 and
CSS3.
Geo-location in HTML5 is used to share the location with some websites and
be aware of the exact location. It is mainly used for local businesses, restaurants,
or showing locations on the map. It uses JavaScript to give latitude and longitude
to the backend server. Most of the browsers support Geolocation API. Geo-location
API uses a global navigator object which can be created as follows:
var loc = navigator.geolocation;
function getLoc() {
loc.getCurrentPosition(showLoc, errHand);
}
or
function getlocation(){
navigator.geolocation.getCurrentPosition(showLoc, errHand);
}

Output

Location Properties: The following table determines properties used in


getCurrentPosition() and their returning values.

● coords.latitude: Always returns latitude as a decimal number.


● coords.accuracy: Always returns the accuracy of position.
● coords.longitude: Always returns longitude as a decimal number.
● coords.altitude: Returns the altitude in meters above sea level if available.
● coords.altitudeAccuracy: Returns altitude accuracy of position if available.
● coords.heading: Returns heading in degree clockwise from North if available
● coords.speed: Returns speed in mps, if available.
● timestamp: Returns date or time of response if available
Geolocation Methods: The Geolocation has following methods which make it
interesting and easier to work.

● getCurrentPosition(): It fetches the current location of the user.


● watchPosition(): It fetches periodic updates of the user’s current location.
● clearWatch(): It cancels a watchPosition call currently in execution.

Media queries allow you to apply CSS styles depending on a device's general
type (such as print vs. screen) or other characteristics such as screen resolution or
browser viewport width. Media queries are used for the following:

1. To conditionally apply styles with the CSS @media and @import at-rules.
2. To target specific media for the <style>, <link>, <source>, and other HTML
elements with the media= attribute.
3. To test and monitor media states using the Window.matchMedia() and
MediaQueryList.addListener() JavaScript methods.

SYNTAX
A media query is composed of an optional media type and any number of media
feature expressions, which may optionally be combined in various ways using
logical operators. Media queries are case-insensitive.

Following @media rule uses two media queries to target both screen and print
devices:
@media screen, print {
/* ... */
}
Say if we want to make a website responsive for widescreens or mobile phone
screens, then we will add media query which automatically change size of elements
on the page to look as intended.

For widescreen devices


@media (max-width: 1250px) {
/* ... */
}

To limit the styles to devices with a screen, you can chain the media features to the
screen media type:
@media screen and (min-width: 30em) and (orientation:
landscape) {
/* ... */
}
Following rule will apply its styles if the user's device has either a minimum height
of 680px or is a screen device in portrait mode:
@media (min-height: 680px), screen and (orientation: portrait)
{
/* ... */
}

Explain the “Window” object of Javascript DOM.


The Window interface represents a window containing a DOM document; the
document property points to the DOM document loaded in that window. A
window for a given document can be obtained using the document.defaultView
property.

A global variable, window, representing the window in which the script is running,
is exposed to JavaScript code.

The Window interface is home to a variety of functions, namespaces, objects, and


constructors which are not necessarily directly associated with the concept of a
user interface window. However, the Window interface is a suitable place to
include these items that need to be globally available. In a tabbed browser, each
tab is represented by its own Window object; the global window seen by JavaScript
code running within a given tab always represents the tab in which the code is
running.

We can associate methods with the window object to perform certain actions,
some are given as follows

Method Description

alert() Displays an alert box with a message and an OK button

blur() Removes focus from the current window

clearInterval() Clears a timer set with setInterval()


clearTimeout() Clears a timer set with setTimeout()

close() Closes the current window

confirm() Displays a dialog box with a message and an OK and a


Cancel button

focus() Sets focus to the current window

getComputedStyle() Gets the current computed CSS styles applied to an


element

getSelection() Returns a Selection object representing the range of


text selected by the user

matchMedia() Returns a MediaQueryList object representing the


specified CSS media query string

moveBy() Moves a window relative to its current position

moveTo() Moves a window to the specified position


open() Opens a new browser window

print() Prints the content of the current window

prompt() Displays a dialog box that prompts the visitor for input

resizeBy() Resizes the window by the specified pixels

resizeTo() Resizes the window to the specified width and height

scrollBy() Scrolls the document by the specified number of pixels

scrollTo() Scrolls the document to the specified coordinates

setInterval() Calls a function or evaluates an expression at specified


intervals (in milliseconds)

setTimeout() Calls a function or evaluates an expression after a


specified number of milliseconds

stop() Stops the window from loading


What are the benefits of using JSON over XML data?
JavaScript Object Notation (JSON) is a lightweight text-based open standard
designed for human-readable data interchange. It is derived from the JavaScript
programming language for representing simple data structures and associative
arrays, called objects. Despite its relationship to JavaScript, it is
language-independent, with parsers available for most programming
languages.Extensible Markup Language (XML) is a set of rules for encoding
documents in machine-readable form. XML’s design goals emphasize simplicity,
generality, and usability over the Internet.

Earlier days XML used to be the only option available for data exchange. Various
developments in the field of data processing and interchanging have made JSON as
an emergent alternative to XML due to number of reasons, such as

1. JSON is lightweight in comparison with XML.

2. JSON parses data faster than XML by using standard JavaScript functions.
JSON is parsed into a ready-to-use JavaScript object.

3. XML is much more difficult to parse than JSON by using an XML parser.

4. JSON has a better ratio of data to markup.

5. Since the JSON format is text only, it can easily be sent to and from a server,
and used as a data format by any programming language.

6. JavaScript has a built-in function to convert a string, written in JSON format,


into native JavaScript objects: JSON.parse() So, if you receive data from a
server, in JSON format, you can use it like any other JavaScript object.
7. For AJAX applications, JSON is faster and easier than XML which includes
only fetching a JSON string and parsing that string.

8. JSON requires less tags than XML – XML items must be wrapped in open
and close tags whereas in JSON just name the tag once.

9. Because JSON is transportation-independent, you can just bypass the


XMLHttpRequest object for getting your data.

10. Data in XML is arranged in a tree format, which is not always the same
structure as the original data. JSON scores over XML with its map data
structure that matches with the actual data which makes the interpretation
easy and data arrangement more predictable.

11.JSON data structure helps in building RESTful APIs providing simpler data
exchange methods.

12. JSON applies the same data representation method as done in the code.
Hence, many languages can just slurp in JSON to find their own domain
object with ease. JSON allows easy transition of its objects from JSON object
to the objects in code. In XML, this transition is difficult because there is no
alignment between the objects in XML and those in the code.

13. JSON has a limited set of objects that can be modeled. So, in JSON
developers can create simple, more predictive and easy-to-read code.
Whereas in XML, we have more objects that can be modeled and developers
are unrestricted in using any of the user-defined objects. This makes XML
more complex and difficult to read.
Explain with proper syntax and examples how to use different types of
CSS Selectors.
A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other
terms that tell the browser which HTML elements should be selected to have the
CSS property values inside the rule applied to them. The element or elements
which are selected by the selector are referred to as the subject of the selector. CSS
selectors define the pattern to select elements to which a set of CSS rules are then
applied. CSS selectors can be grouped into the following categories based on the
type of elements they can select.

Basic selectors
Universal selector
Selects all elements. Optionally, it may be restricted to a specific namespace or to
all namespaces.

Syntax: * ns|* *|*

Example: * will match all the elements of the document.


Type selector
Selects all elements that have the given node name.

Syntax: elementname

Example: input will match any <input> element.

Class selector
Selects all elements that have the given class attribute.

Syntax: .classname

Example: .index will match any element that has class="index".

ID selector
Selects an element based on the value of its id attribute. There should be only one
element with a given ID in a document.

Syntax: #idname

Example: #toc will match the element that has id="toc".

Attribute selector
Selects all elements that have the given attribute.

Syntax: [attr] [attr=value] [attr~=value] [attr|=value] [attr^=value] [attr$=value]


[attr*=value]

Example: [autoplay] will match all elements that have the autoplay attribute set
(to any value).
Grouping selectors
Selector list
The , selector is a grouping method that selects all the matching nodes.

Syntax: A, B where A and B are HTML tags.

Example: div, span will match both <span> and <div> elements.

Combinators
Descendant combinator
The " " (space) combinator selects nodes that are descendants of the first element.

Syntax: A B

Example: div span will match all <span> elements that are inside a <div>
element.

Child combinator
The > combinator selects nodes that are direct children of the first element.

Syntax: A > B

Example: ul > li will match all <li> elements that are nested directly inside a
<ul> element.

General sibling combinator


The ~ combinator selects siblings. This means that the second element follows the
first (though not necessarily immediately), and both share the same parent.
Syntax: A ~ B

Example: p ~ span will match all <span> elements that follow a <p>,
immediately or not.

Adjacent sibling combinator


The + combinator matches the second element only if it immediately follows the
first element.

Syntax: A + B

Example: h2 + p will match the first <p> element that immediately follows an
<h2> element.

Pseudo-classes and pseudo-elements


Pseudo classes
The : pseudo allows the selection of elements based on state information that is
not contained in the document tree.

Example: a:visited will match all <a> elements that have been visited by the
user.

Pseudo elements
The :: pseudo represents entities that are not included in HTML.

Example: p::first-line will match the first line of all <p> elements.
Explain JSON mashups in detail with a neat diagram.

A Mashup (also known as web application hybrid), is a technique that websites use
to provide resources, functionalities, and services from multiple sources. To put it
in layman’s terms, a mashup works as an aggregator of different services. They
mostly use public APIs that are generally free to use and thus, create a new service
from existing ones.
The readability and simplicity features of JSON have made it one of the most
popular notations in the mashup community. JSON, being a notation, provides a
way in which objects are written so that human beings can read it easily. It has a
built-in JavaScript feature that makes JSON a viable mashup technology. The
architecture of mashups in JSON implementation is shown in the above figure.
The flow of JSON mashups that use dynamic Script method goes in the following
steps:

1. The flow of the process starts with the browser sending request to the server
by using HTTP GET.
2. The Web Server responds with a page that includes the following couple of
important JavaScript functions:
a. A parsing function that expects JavaScript objects to be parameters.
b. The Dynamic Script method is the core of the initiation script through
which a new script tag is added to the page, specifying the source for
that script tag to be the Uniform Resource Locator (URL) at some
partner site.

3. The source code for the new script tag gets loaded by the browser.
4. Amazon receives an HTTP Get request sent from the browser using the
loaded script.
5. A JavaScript object, after being serialized into a JSON Object, is served by the
partner site.
6. A function call to the render function wraps the JSON script, and the
JavaScript entirely becomes the content for the script tag.
7. The new piece of JavaScript is tried for execution by the browser, which calls
the render method from step 2(a).
8. The server invokes the render method and evaluates the JSON script, which is
converted into a JavaScript object. The data contained in the render method
is pushed into the page after the render method, which uses the new
JavaScript object in its execution

DHTML with JS
DHTML stands for Dynamic HTML. Dynamic means that the content of the web
page can be customized or changed according to user inputs i.e. a page that is
interactive with the user. In earlier times, HTML was used to create a static page.
It only defined the structure of the content that was displayed on the page. With
the help of CSS, we can beautify the HTML page by changing various properties
like text size, background color etc. The HTML and CSS could manage to navigate
between static pages but couldn’t do anything else. If 1000 users view a page that
had their information for example Admit card, then there was a problem because
1000 static pages for this application have to be built to work. As the number of
users increases, the problem also increases and at some point it becomes
impossible to handle this problem.

To overcome this problem, DHTML came into existence. DHTML included


JavaScript along with HTML and CSS to make the page dynamic. This
combination made the web pages dynamic and eliminated this problem of creating
static pages for each user. To integrate JavaScript into HTML, a Document Object
Model(DOM) is made for the HTML document. In DOM, the document is
represented as nodes and objects which can be accessed by JavaScript to
manipulate the document.
Uses of DHTML

● It is used for designing the animated and interactive web pages that are
developed in real-time.
● DHTML helps users by animating the text and images in their documents.
● It allows the authors for adding the effects on their pages.
● It also allows the page authors for including the drop-down menus or rollover
buttons.
● This term is also used to create various browser-based action games.
● It is also used to add the ticker on various websites, which needs to refresh
their content automatically.

Features of DHTML
● Its simplest and main feature is that we can create the web page dynamically.
● Dynamic Style is a feature, that allows the users to alter the font, size, color,
and content of a web page.
● It provides the facility for using the events, methods, and properties. And,
also provides the feature of code reusability.
● It also provides the feature in browsers for data binding.
● Using DHTML, users can easily create dynamic fonts for their web sites or
web pages.
● With the help of DHTML, users can easily change the tags and their
properties.
● The web page functionality is enhanced because the DHTML uses a
low-bandwidth effect.

HTML (Hypertext Markup language) DHTML (Dynamic Hypertext Markup


language)

HTML is simply a markup language. DHTML is not a language, but it is a

set of technologies of web development.

It is used for developing and creating web pages. It is used for creating and designing

animated and interactive web sites or pages.

This markup language creates static web pages. This concept creates dynamic web pages.
It does not contain any server-side scripting code It may contain the code of server-side scripting.

The files of HTML are stored with the .html or The files of DHTML are stored with the

.htm extension in a system. .dhtm extension in a system.

A simple page which is created by a user A page which is created by a user using the

without using the scripts or styles called as HTML, CSS, DOM, and JavaScript

an HTML page. technologies called a DHTML page.

This markup language does not need This concept needs database

database connectivity. connectivity because it interacts with users.

Exception Handling in JS
An exception signifies the presence of an abnormal condition which requires special operable
techniques. In programming terms, an exception is the anomalous code that breaks the normal
flow of the code. Such exceptions require specialized programming constructs for its execution.
Exception handling is a process or method used for handling the abnormal statements in the
code and executing them. It is used to keep the flow control of the code/program intact. For
handling the code, various handlers are used that process the exception and execute the code.
For example, the Division of a non-zero value with zero will always result infinity, and it is an
exception. Thus, with the help of exception handling, it can be executed and handled.

Types of Errors
1. Syntax Error: When a user makes a mistake in the predefined syntax of a programming
language, a syntax error may appear.
2. Runtime Error: When an error occurs during the execution of the program, such an error is
known as Runtime error. The codes which create runtime errors are known as Exceptions. Thus,
exception handlers are used for handling runtime errors.
3. Logical Error: An error which occurs when there is any logical mistake in the program that may
not produce the desired output, and may terminate abnormally. Such an error is known as
Logical error.

Handling Runtime errors using try-catch statements


<script type="text/javascript">
<!--
try
{
// Here the main Code run
[break;]
}

catch ( exception e )
{
// The code will run when there is an exception
[break;]
}
//-->
</script>

<html>
<head>
<title>Error and Exception handling</title>
<script type="text/javascript">
function First() {
var a = 123;
var b = 145;
var c = a + b;
try {
alert("Value of a: " + a );
alert("Value of b: " + b );
alert("Sum of a and b: " + c);
}
catch ( e ) {
alert("Error: " + e.description );
}
finally {
alert("Finally block will always execute!" );
}
}
</script>
</head>

<body>
<p>Click the GfG button to see the result:</p>

<form>
<input type="button" value="Click GfG" onclick="First();" />
</form>

</body>
</html>
Module 3: Back End Development

What are servlets? Demonstrate servlet architecture and explain its working principle.
Servlet is one of the server-side programming language which runs on Java enabled server. It is used to
develop web based applications. As it is built on Java platform, servlet is fully compatible with Java
classes and interfaces. Let’s see what are servlets, Java servlets architecture and advantages of servlets
in detail.

What Are Servlets?


● Servlets are used to develop dynamic web applications.
● Servlets are nothing but the Java programs which reside on the server side and their main
purpose is to serve the client request.
● Servlets are fully compatible with Java. You can use any of the available Java APIs like JDBC
inside the servlets.
● As servlets are written in Java, they are platform independent, robust, and secured.
● In Servlets, a thread is created for each request unlike in CGI where a process is created for each
request. Hence, servlets give better performance than CGI.
● Servlets are protocol independent. i.e. they support FTP, SMTP, HTTP etc. protocols.

1. The client sends over a request.


2. The request is accepted by the web server and forwarded to the web container.
3. In order to obtain the servlet’s address, the web container traces a web.xml file corresponding to
the request URL pattern.
4. By the time the above process takes place, the servlet should have been instantiated and
initialized. If the servlet has not been instantiated and initialized, init() method is invoked to
serve the purpose.
5. By passing a ServletRequest and Response object, public service() method is called by the
container.
6. In the next step, the ServletRequest and ServletResponse objects are type-casted to
HttpServletRequest and HttpServletResponse objects by the public service() method.
7. Now the protected service() method is called by the public service() method.
8. The protected service() method dispatches the request to the correct handler method based on
the type of request.
9. When the servlet container shuts down, it unloads all the servlets and calls destroy() method for
each initialized servlet.

Advantages Of Servlets :
1. As servlets support all protocols like FTP, SMTP, HTTP etc. they can be used to develop any kind
of web applications like E-commerce, Content management systems, chat based or file based web
applications etc.
2. As servlets are fully compatible with Java, you can make use of a wide range of available Java
APIs inside the servlets.
3. As they run on Java enabled servers, You need not to worry about garbage collection and memory
leaks. JVM handles them for you.
4. Since servlets are written in Java, they are portable and platform independent. You can run them
on any operating system and on any web servers available today.
5. Servlets inherit security features from JVM and web servers.
6. As servlets are written in Java, you can extend them according to your requirements.
7. As servlets are compiled into bytecodes, they are faster than any other server-side scripting
languages.
Disadvantages
01. Designing a servlet can be pretty laborious.
02.Exceptions need to be handled while designing a servlet since they are not thread-safe.
03.Developers may need additional skills to program a servlet.

JSP Lifecycle
A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a servlet
life cycle with an additional step which is required to compile a JSP into servlet.

Java Servlet Life-Cycle


The Java Servlet Life cycle includes three stages right from its start to the end until the Garbage
Collector clears it. These three stages are described below.
1. init()
2. service()
3. destroy()

1. init()
The init() is the germinating stage of any Java Servlet. When a URL specific to a particular
servlet is triggered, the init() method is invoked. Another scenario when the init() method gets
invoked is when the servers are fired up. With every server starting up, the corresponding
servlets also get started, and so does the init() method. One important specialty of the init()
method is the init() method only gets invoked once in the entire life cycle of the Servlet, and
the init() method will not respond to any of the user's commands.The init() method Syntax:

public void init() throws ServletException {


//init() method initializing
}

2. service()
The service() method is the heart of the life cycle of a Java Servlet. Right after the Servlet's
initialization, it encounters the service requests from the client end. The client may request
various services like:
● GET
● PUT
● UPDATE
● DELETE

The service() method takes responsibility to check the type of request received from the client
and respond accordingly by generating a new thread or a set of threads per the requirement and
implementing the operation through the following methods.
● doGet() for GET
● doPut() for PUT
● doUpdate() for UPDATE
● doDelete() for DELETE

The service() method Syntax:

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException { }

3. destroy()
Like the init() method, the destroy() method is also called only once in the Java Servlet's entire
life cycle.When the destroy() method is called, the Servlet performs the cleanup activities like,
● Halting the current or background threads
● Making a recovery list of any related data like cookies to Disk.
After that, the Servlet is badged, ready for the Garbage collector to have it cleared.
The destroy() method Syntax:
public void destroy() {
//destroy() method finalizing
}

What is session tracking?Show how session tracking is achieved using cookies.


Session simply means a particular interval of time. Session Tracking is a way to maintain the state
(data) of an user. It is also known as session management in servlet. Http protocol is stateless so we
need to maintain state using session tracking techniques. Each time a user requests to the server, the
server treats the request as the new request. So we need to maintain the state of a user to recognize a
particular user.

HTTP is stateless, which means each request is considered as the new request. It is shown in the figure
given below:

There are four techniques used in Session tracking:

1. Cookies: 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. By default, each request is
considered as a new request. In cookies technique, we add cookies with response from the
servlet. So the cookie is stored in the cache of the browser. After that if a request is sent by the
user, a cookie is added with the request by default. Thus, we recognize the user as the old user.

In java, following is the source code snippet to create a cookie:


Cookie cookie = new Cookie("userID", "7456");
res.addCookie(cookie);

2. Hidden Form Field


3. URL Rewriting
4. HttpSession

JDBC
JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent
connectivity between the Java programming language and a wide range of databases. The JDBC library
includes APIs for each of the tasks mentioned below that are commonly associated with database
usage.
● Making a connection to a database.
● Creating SQL or MySQL statements.
● Executing SQL or MySQL queries in the database.
● Viewing & Modifying the resulting records.

Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for
portable access to an underlying database. Java can be used to write different types of executables, such
as −
● Java Applications
● Java Applets
● Java Servlets
● Java ServerPages (JSPs)
● Enterprise JavaBeans (EJBs).

All of these different executables are able to use a JDBC driver to access a database, and take advantage
of the stored data. JDBC provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in
general, JDBC Architecture consists of two layers −
● JDBC API − This provides the application-to-JDBC Manager connection.
● JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity
to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access
each data source. The driver manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases. Following is the architectural diagram, which shows the location of
the driver manager with respect to the JDBC drivers and
the Java application −

The JDBC API provides the following interfaces and classes − JDBC Architecture
● DriverManager − This class manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication sub protocol. The first
driver that recognizes a certain subprotocol under JDBC will be used to establish a database
connection.
● Driver − This interface handles the communications with the database server. You will interact
directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages
objects of this type. It also abstracts the details associated with working with Driver objects.
● Connection − This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with the database is through
connection objects only.
● Statement − You use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored procedures.
● ResultSet − These objects hold data retrieved from a database after you execute an SQL query
using Statement objects. It acts as an iterator to allow you to move through its data.
● SQLException − This class handles any errors that occur in a database application.

HTML form by embedding JSP code


Getting information from the user
<html>
<head>
<title>JSP Form Demo</title>
<style type="text/css">
label{ margin-right:20px;}
input{ margin-top:5px;}
</style>
</head>
<body>
<form action="handleUserInfo.jsp" method="post">
<fieldset>
<legend>User Information</legend>
<label for="fistName">First Name</label>
<input type="text" name="firstName" /> <br/>
<label for="lastName">Last Name</label>
<input type="text" name="lastName" /> <br/>
<label for="email">Email</label>
<input type="text" name="email" /> <br/>
<input type="submit" value="submit">
</fieldset>
</form>
</body>
</html>

The form is very simple which contains three fields: first name, last name, and email. In addition, It
contains the submit button which users can submit when he/she finish entering the data. In the form
tag, you can see it uses the post method to post the form data to the server. We need to create a JSP file
that is responsible for getting and processing the form’s data. The following is the handleUserInfo.jsp
form:

<html>
<head>
<title>JSP Form Demo</title>
</head>
<body>
<%
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String email = request.getParameter("email");
%>
<p>Hi <%=firstName%> <%=lastName%>!,
your submitted email is <%=email%>.</p>
</body>
</html>

Module 4: Rich Internet Applications

What are the characteristics of Rich Internet Applications ?(2019)


Rich Internet Applications (RIA)
● RIAs are web applications that have most of the characteristics of desktop applications, typically
delivered through web-browser plug-ins or independently via sandboxes or virtual machines.
● RIAs have always been about the user experience, enhancing the end-user experience in different
ways.
● RIAs can run faster and be more engaging. They can offer users a better visual experience, better
accessibility, usability and more interactivity than traditional browser applications that use only
HTML and HTTP.
● A RIA can perform computation on both the client side and server side. User Interface, its related
activity and capability on the client side and the data manipulation and operation on the
application server side.
● RIA is developed using various technologies such as Java, Silverlight, JavaFX, JavaScript,
REST/WS etc.

Characteristics of RIA
● Performance - RIAs can often perform better than traditional applications on the basis of the
characteristics of network and applications, performance of server also improved by offloading
possible processing work to the client system and also perceived performance in terms of UI
responsiveness and smoother visual transitions and animations are key aspects of any RIA.

● Offline use - When connectivity is unavailable, it might still be possible to use an RIA. An RIA
platform let the user work with the application without connecting to the Internet and
synchronizing it automatically when the user goes live.

● Consistency of look and feel - With RIA tools, the user interface and experience with
different browsers, devices and operating systems can be more carefully controlled and made
consistent.
● Security - RIAs should be as secure as any other web application, and the framework should be
well equipped to enforce limitations appropriately when the user lacks the required privileges,
especially when running within a constrained environment such as a sandbox.

● Advanced Communications - Sophisticated communications with supporting servers through


optimized network protocols can considerably enhance the user experience.

● Rapid Development - An RIA Framework should facilitate rapid development of a rich user
experience through its easy-to-use interfaces in ways that help developers.

● Direct Interaction - An RIA can use a wider range of controls that allow greater efficiency and
enhance the user experience. In RIAs, for example, users can interact directly with page elements
through editing or drag-and-drop tools. They can also do things like pan across a map or other
image.

● Better Feedback - Because of their ability to change parts of pages without reloading, RIAs can
provide the user with fast and accurate feedback, real-time confirmation of actions and choices,
and informative and detailed error messages.

● Improved Features - RIA allow programmers to embed various functionalities in


graphics-based web pages that look fascinating and engaging like desktop applications. RIA
provide complex application screens on which various mixed media, including different fonts,
vector graphic and bitmap files online conferencing etc. are paused by using different modern
development tools.

● Partial-page updating - RIAs incorporate additional technologies, such as real-time


streaming, high-performance client-side virtual machines, and local caching mechanisms that
reduce latency (wait times) and increase responsiveness.

What is AJAX ? Explain steps required to process AJAX with examples.


AJAX = Asynchronous JavaScript And XML.

AJAX is not a programming language. AJAX just uses a combination of:

● A browser built-in XMLHttpRequest object (to request data from a web server)
● JavaScript and HTML DOM (to display or use the data)
AJAX is a misleading name. AJAX applications might use XML to transport data, but it is equally
common to transport data as plain text or JSON text. AJAX allows web pages to be updated
asynchronously by exchanging data with a web server behind the scenes. This means that it is possible
to update parts of a web page, without reloading the whole page.

1. User sends a request from the UI and a javascript call goes to XMLHttpRequest object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser without reloading the page.

Advantages of AJAX
1. Reduce server traffic and increase speed
2. Enable asynchronous calls: Ajax benefits web developers in how its framework can be used
for lazy loading. Those who don’t know what Lazy Loading is are an optimization technique that’s
widely used for online content. In essence, Ajax allows its users to make asynchronous calls to the
web server without reloading the whole web page. As a web visitor, you don’t have to wait for the
entire page to load entirely in order to access the entire page content. The concept of lazy loading
assists in loading only the required section and delays the remaining, until it is needed by users.
Thus, Ajax Lazy Loading not only improves a web page load it also has a positive impact on user
experience and conversion rates.
3. XMLHttpRequest is a request type widely used for sending a request to Ajax pages. You can
also call it with a different name: Asynchronous HTTP request.
4. Reduce bandwidth usage
5. Form Validation In contrast to traditional form submission, where client-side validations
occur after submission, the AJAX method enables precise and immediate form validation. AJAX
provides speed, which is also one of its significant benefits.

Disadvantages of AJAX
● Open-source. View source is allowed, and anyone can view the code source written for Ajax,
which makes it less secure compared to other technologies
● Search Engines cannot index Ajax pages can not be indexed by Google as well as other search
engines
● The usage of Ajax can cause difficulties for your web pages to debug as well as make them prone
to possible security issues in the future
● Most importantly, Ajax has a considerable dependency on JavaScript, so only browsers that
support Javascripts or XMLHttpRequest can use pages with Ajax techniques
● Users will find it challenging to bookmark a specific state of the application due to the dynamic
web page.
● From the users’ perspective, when you click the back button on the browser, you may not return
to the previous state of the page but the entire page. This happens because the pages with
successive Ajax requests are unable to register with the browser’s history

Draw the diagram for AJAX Web application model and Tradition Web Application
model and compare them.

The classic web application model works like this:

● Most user actions in the interface trigger an HTTP request back to a web server. The server does
some processing, retrieving data, crunching numbers, talking to various legacy systems and then
returns an HTML page to the client.
● It’s a model adapted from the Web’s original use as a hypertext medium, but as fans of The
Elements of User Experience know, what makes the Web good for hypertext doesn’t necessarily
make it good for software applications.
● This approach doesn't make for a great user experience. While the server is doing its thing, the
user waits. And at every step in a task, the user waits some more.
● Obviously, if we were designing the Web from scratch for applications, we wouldn’t make users
wait around. Once an interface is loaded, why should the user interaction come to a halt every
time the application needs something from the server? In fact, why should the user see the
application go to the server at all?
Ajax Working
● An Ajax application eliminates the start-stop-start-stop nature of interaction on the Web by
introducing an intermediary Ajax engine between the user and the server. It seems like adding a
layer to the application would make it less responsive, but the opposite is true.
● Instead of loading a webpage, at the start of the session, the browser loads an Ajax engine written
in JavaScript and usually tucked away in a hidden frame.
● This engine is responsible for both rendering the interface the user sees and communicating with
the server on the user’s behalf.
● The Ajax engine allows the user’s interaction with the application to happen asynchronously —
independent of communication with the server. So the user is never staring at a blank browser
window and an hourglass icon, waiting around for the server to do something.

Module 5: Web Extension: PHP and XML

Differentiate between HTML and XML (2019)


XML XML

HTML is used to display data and focuses on XML is a software and hardware

how data looks. independent tool used to transport and

store data. It focuses on what data is.

HTML is a markup language itself. XML provides a framework to define

markup languages.

HTML is not case sensitive. XML is case sensitive.

HTML is a presentation language. XML is neither a presentation language nor

programming language.

HTML has its own predefined tags. You can define tags according to your need.

In HTML, it is not necessary to use a closing tag. XML makes it mandatory to use a closing tag.

HTML is static because it is used to display data. XML is dynamic because it is used to

transport data.

HTML does not preserve whitespaces. XML preserves whitespaces.

Explain XML Schema in detail (2019)


An XML Schema describes the structure of an XML document. The XML Schema language is also
referred to as XML Schema Definition (XSD). An XML document is called "well-formed" if it contains
the correct syntax. A well-formed and valid XML document is one which have been validated against
Schema.The purpose of an XML Schema is to define the legal building blocks of an XML document:

● the elements and attributes that can appear in a document


● the number of (and order of) child elements
● data types for elements and attributes
● default and fixed values for elements and attributes

employee.xsd
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.javatpoint.com"
xmlns="http://www.javatpoint.com"
elementFormDefault="qualified">

<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="email" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:schema>

Employee.xml
<?xml version="1.0"?>
<employee
xmlns="http://www.javatpoint.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="./employee.xsd">

<firstname>vimal</firstname>
<lastname>jaiswal</lastname>
<email>[email protected]</email>
</employee>

<xs:element name="employee"> : It defines the element name employee.


<xs:complexType> : It defines that the element 'employee' is complex type.

<xs:sequence> : It defines that the complex type is a sequence of elements.

<xs:element name="firstname" type="xs:string"/> : It defines that the element 'firstname' is


of string/text type.

<xs:element name="lastname" type="xs:string"/> : It defines that the element 'lastname' is


of string/text type.

<xs:element name="email" type="xs:string"/> : It defines that the element 'email' is of


string/text type.

Explain the string functions in PHP(2019)


● A string is a collection of characters. String is one of the data types supported by PHP.
● The PHP string functions are part of the PHP core. No installation is required to use these functions.
● PHP has a vast selection of built-in string handling functions that allow you to easily manipulate
strings in almost any possible way.
● The most common string functions are as follows:

Function strlen() - To count the number of characters in a string strlen() function is used.
<?php
$str = "Ques10";
echo "The length of string is:".strlen($str);
?>
// Displays: The length of string is:6

Function str_replace() - Replaces some characters in a string. str_replace() is case-sensitive, but we can
also use its case-insensitive sibling str_ireplace() to avoid case-sensitiveness.
<?php
$oldstr = "The cat was black";
$newstr = str_replace("black", "white", $oldstr);
echo $newstr;
?>
// Displays: The cat was white

Functions strtoupper() & strtolower() - Converts a string into uppercase and lowercase respectively.
<?php
$str1 = "Example of uppercase Function.";
$str2 = "Example of LOWERCASE Function.";
$case1 = strtoupper($str1);
$case2 = strtolower($str2);
echo $case1;
echo "<br>";
echo $case2;
?>
/* Displays: EXAMPLE OF UPPERCASE FUNCTION.
example of lowercase function.*/

Function ucwords() - This function capitalized the first letter of each word.
<?php
$str = "example of PHP string function.";
$cased = ucwords($str);
echo $cased;
?>
// Displays: Example Of PHP String Function.

Function str_repeat() - It is used to repeat same string for a specific number of times.
<?php
$str = “Ques10 ”
Echo “The Repeated string is:”.str_repeat($str , 4);
?>
// Displays: The Repeated string is: Ques10 Ques10 Ques10 Ques10

Function strrev() - This reverses a string.


<?php
echo strrev("Hello world!");
?>
// Displays: !dlrow olleH

Function str_word_count() - Counts the number of words in a string.


<?php
echo str_word_count("Hello world Example");
?>
// Displays: 3
Explain the role of a cookie and differentiate it from sessions.

● A cookie is a small text file that is stored on the user's computer. The maximum file size of a
cookie is 4KB. It is also known as an HTTP cookie, web cookie, or internet Cookie. Whenever a
user visits a website for the first time, the site sends packets of data in the form of a cookie to
the user's computer.
● The cookies help the websites to keep track of the user's browsing history or cart information
when they visit their sites.
● It stores only the "String" data type.
● The information stored within cookies is not secure because this information is stored in
text-format on the client-side, which can be read by anyone.
● We can enable or disable the cookies as per the requirement.
● The cookies generated by a user are only be shown to them, and no other user can see those
cookies.
● Cookies are created and shared between the server and browser with the help of an HTTP
header.
● The path where the cookies are saved is decided by the browser, as Internet explorer usually
stored them in Temporal Internet File Folder.
● When we visit YouTube channel and search for some songs, next time whenever we visit
YouTube, cookies read our browsing history and shows similar songs or last played songs.

Session Cookies

A session stores the variables and their Cookies are stored on the
values within a file in a temporary user's computer as a text file.
directory on the server.
The session ends when the user logout Cookies end on the lifetime set by
from the application or closes his the user.
web browser.

It can store an unlimited amount of data. It can store only limited data.

We can store as much data as we want The maximum size of the


within a session, but there is a browser's cookies is 4 KB.
maximum memory limit, which a script
can use at one time, and it is 128 MB.

We need to call the session_start() function We don't need to call a function to


to start the session. start a cookie as it is stored within
the local computer.

In PHP, to set a session data, the In PHP, to get the data from cookies,
$_SESSION global variable is used. the $_COOKIE global variable is used.

In PHP, to destroy or remove the data We can set an expiration date to


stored within a session, we can use delete the cookie's data. It
the session_destroy() function, and to will automatically delete the data at
unset a specific variable, we can use that specific time. There is no
the unset() function. particular function to remove the data.
Sessions are more secured compared Cookies are not secure, as data is
to cookies, as they save data in stored in a text file, and if
encrypted form. any unauthorized user gets access to
our system, he can temper the data.

Explain XML and DTD with example


XML : DTD stands for Document Type Definition.
A DTD defines the structure and the legal elements and attributes of an XML document

Valid XML Documents


A "Valid" XML document is "Well Formed", as well as it conforms to the rules of a DTD:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note SYSTEM "Note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

The DOCTYPE declaration above contains a reference to a DTD file. The purpose of a DTD is to define
the structure and the legal elements and attributes of an XML document:
The DTD above is interpreted like this:
● !DOCTYPE note - Defines that the root element of the document is note
● !ELEMENT note - Defines that the note element must contain the elements: "to, from,
heading, body"
● !ELEMENT to - Defines the to element to be of type "#PCDATA"
● !ELEMENT from - Defines the from element to be of type "#PCDATA"
● !ELEMENT heading - Defines the heading element to be of type "#PCDATA"
● !ELEMENT body - Defines the body element to be of type "#PCDATA"

Using DTD for Entity Declaration


A DOCTYPE declaration can also be used to define special characters or strings, used in the document:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note [
<!ENTITY nbsp "&#xA0;">
<!ENTITY writer "Writer: Donald Duck.">
<!ENTITY copyright "Copyright: W3Schools.">
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>&writer;&nbsp;&copyright;</footer>
</note>

When to Use a DTD?


● With a DTD, independent groups of people can agree to use a standard DTD for interchanging
data.
● With a DTD, you can verify that the data you receive from the outside world is valid.
● You can also use a DTD to verify your own data.

When NOT to Use a DTD?


● XML does not require a DTD.
● When you are experimenting with XML, or when you are working with small XML files, creating
DTDs may be a waste of time.
● If you develop applications, wait until the specification is stable before you add a DTD.
Otherwise, your software might stop
● working because of validation errors.

Module 6: React JS

What is React JSX (2019)


JSX is a JavaScript Extension Syntax used in React to easily write HTML and JavaScript together. This
is simple JSX code in React. But the browser does not understand this JSX because it's not valid
JavaScript code. This is because we're assigning an HTML tag to a variable that is not a string but just
HTML code.

So to convert it to browser understandable JavaScript code, we use a tool like Babel which is a
JavaScript compiler/transpiler.

Why REACT JSX ?

● It is faster than regular JavaScript because it performs optimization while translating the code to
JavaScript.
● Instead of separating technologies by putting markup and logic in separate files, React uses
components that contain both.
● It is type-safe, and most of the errors can be found at compilation time.
● It makes it easier to create templates.

Basic JSX
● Every JSX tag is converted to React.createElement call and its object representation.

● JSX Expressions, which are written inside curly brackets, allow only things that evaluate to some value like
string, number, array map method and so on.

● In React, we have to use className instead of class for adding classes to the HTML element

● All attribute names in React are written in camelCase.

● undefined, null, and boolean are not displayed on the UI when used inside JSX.

Features of ReactJS
React is a JavaScript Library created by Facebook for creating dynamic and interactive applications and
building better UI/UX design for web and mobile applications. React is an open-source and
component-based front-end library. React is responsible for the UI design. React makes code easier to
debug by dividing them into components.
Features of React:
● JSX (JavaScript Syntax Extension) JSX is a combination of HTML and JavaScript. You can
embed JavaScript objects inside the HTML elements. JSX is not supported by the browsers, as a
result Babel compiler transpiles the code into JavaScript code. JSX makes codes easy and
understandable. It is easy to learn if you know HTML and JavaScript.

● Virtual DOM: DOM stands for Document Object Model. It is the most important part of the
web as it divides into modules and executes the code. Usually, JavaScript Frameworks updates
the whole DOM at once, which makes the web application slow. But react uses virtual DOM
which is an exact copy of real DOM. Whenever there is a modification in the web application, the
whole virtual DOM is updated first and finds the difference between real DOM and Virtual DOM.
Once it finds the difference, then DOM updates only the part that has changed recently and
everything remains the same.

● One-way data binding: ReactJS is designed in such a manner that follows unidirectional data
flow or one-way data binding. The benefits of one-way data binding give you better control
throughout the application. If the data flow is in another direction, then it requires additional
features. It is because components are supposed to be immutable and the data within them
cannot be changed. Flux is a pattern that helps to keep your data unidirectional. This makes the
application more flexible that leads to increased efficiency.

● Performance: ReactJS is known to be a great performer. This feature makes it much better
than other frameworks out there today. The reason behind this is that it manages a virtual DOM.
The DOM is a cross-platform and programming API which deals with HTML, XML or XHTML.
The DOM exists entirely in memory. Due to this, when we create a component, we did not write
directly to the DOM. Instead, we are writing virtual components that will turn into the DOM
leading to smoother and faster performance.

● Components: ReactJS is all about components. ReactJS application is made up of multiple


components, and each component has its own logic and controls. These components can be
reusable which help you to maintain the code when working on larger scale projects.

● Simplicity: ReactJS uses JSX file which makes the application simple to code as well as
understand. We know that ReactJS is a component-based approach which makes the code
reusable as you need. This makes it simple to use and learn.

Problems
Create a XML page storing name, country, runs scored, balls faced for three batsmen.
Represent the same data as a JSON object.
<team>
<player>
<type>batsman</type>
<name>Warszawski</name>
<country>Russia</country>
<runs>100</runs>
<balls>69</balls>
</player>
<player>
<type>batsman</type>
<name>Pandurang Butowski</name>
<country>Russia</country>
<runs>69</runs>
<balls>100</balls>
</player>
<player>
<type>batsman</type>
<name>Podborski </name>
<country>Japan</country>
<runs>234</runs>
<balls>20</balls>
</player>
</team>

{
"teamName": "Mumbai",
"members": [
{
"name": "Pobdorski",
"runs": 234,
"balls": 20,
"type": "batsman",
"country":”Japan”,
},
{
"name": "Pandurang Butowski",
"runs": 420,
"balls": 100,
"type": "batsman",
"country":”Russia”,
},
{
"name": "Warszawski",
"runs":100,
"balls": 69,
"type": "batsman",
"country":”Japan”,
}
]
}

Create a HTML, page showing a message “I use media query”. Write media query such
that the text color changes to light gray when browser window is 600px wide or less
and otherwise it is black.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>I use media query</h1>
</body>
</html>

CSS
@media (max-width: 600px) {
h1{
color: #808080;
}
}

Create a HTML form that accepts first name, last name, department and designation
from the user. Create a PHP code that stores this information in a mysql database
named employee with an existing table emp_details having appropriate schema and
acknowledges the user through appropriate message about success or failure during
data insertion. Assume suitable username and password to access database.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form>
<label>First name </label>
<input></input>
<br>
<label>Last name</label>
<input></input>
<br>
<label>Department</label>
<input></input>
<br>
<label>Designation</label>
<input></input>
<form>
</body>
</html>
Write JavaScript code to change background colour of the web page automatically after
every five seconds.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="script.js"></script>
</head>
<body id=”changeBg”>
<h1>Hello world</h1>
</body>
</html>

Script
let i = 0;
function changeBackground() {
let bg = document.getElementById("changeBg");
var colors = ["black", "blue", "red", "green", "brown"];
bg.style.backgroundColor = colors[i];
i = (i + 1) % colors.length;
}

setInterval(changeBackground, 5000);

Write an external stylesheet and link it with HTML code. The stylesheet should include
the following.
i. The web page will have the background image “img1.jpg”.
ii. The table headings will have red background color.
iii. Background color of alternate paragraphs are different.
iv. The hyperlinks on the web page will not have underline.

style.css
body {
background: url(“gf.png”);
}

th {
background: red;
}

p:nth-child(odd)
{
background:#333;
color: #fff;
padding: 5px;
}
p:nth-child(even)
{
background:#fff;
padding: 5px;
}

a {
Text-decoration: none;
}

Design a web page to maintain a Library Catalogue using XML. It should maintain the
name of the book, author, publisher, and year of publishing. Format it in the tabular
manner using XSLT.
Write code to process online Alumni information for your college. Create forms to get
name, address, date of birth, and email id. Use check boxes for taking hobbies and
radio buttons for selecting branches. Write JavaScript code to validate the following:
i. User has filled all the fields prior to form submission
ii. Valid email-id (with „@‟ and „.‟)
iii. Age validation using DOB (>=22 years)

<html>
<head>
<title> FormData</title>
<script src="script.js"></script>
</head>

<body>

<h1> Enter Alumni information</h1>


<h1> Enter Alumni information</h1>
<form name="form" onsubmit="return validate()" method="POST">
<label for="studentName">Name</label>
<input id="name" type="text" name="studentName" >
<br>
<label for="address">Address</label>
<input id="address" type="text" name="address" pattern="[0-9]{2}" title="Please
enter
valid age" >
<br>
<label for="dob">Date of birth</label>
<input name="dob" type="date" id="dob" >
<br>
<label for="mail">Email ID</label>
<input name="mail" type="email" id="mail" title="Please enter valid phone
number" >
<br>

<fieldset id="hobbies">
<legend>Choose your hobbies</legend>
<input name="reading" type="checkbox" id="reading" value="R"/>
<label for="reading">Reading</label><br>

<input name="music" type="checkbox" id="music" value="M"/>


<label for="music">Listening to music</label><br>

<input name="fanta" type="checkbox" id="fanta" value="F"/>


<label for="fanta">Fantasizing</label>
</fieldset>

<fieldset id="branch">
<legend>You belong to which branch ?</legend>

<input type="radio" name="comps" id="comps" value="C">


<label for="comps">CSE</label><br>

<input type="radio" id="iot" name="iot" value="I">


<label for="iot">CSE (IoT & CSBT)</label><br>

<input type="radio" id="ds" name="ds" value="D"/>


<label for="ds">CSE (Data Science)</label>
</fieldset>
<br>
<input type="submit" value="Submit"></input>
</form>
</body>
</html>

Script

const form = document.querySelector("form")


const name = document.getElementById("name");
const address = document.getElementById("address");
const dob = document.getElementById("dob").value;
const hobbies = document.getElementById("hobbies");
const branch = document.getElementById("branch");
const email = document.getElementById("mail");
//Email validation
email.addEventListener("input", (event) => {
if (email.validity.typeMismatch) {
email.setCustomValidity("Expected an e-mail address!");
email.reportValidity();
} else {
email.setCustomValidity("");
}
});

function validate(DOB){
var twentytwo = momemt().subtract(22,"years");
var birthday = moment(DOB)

if(!birthday.isValid()){
return "invaliddate"
}
elseif(twentytwo.isAfter(DOB)){
return "greater than 22, you are good";
else{
return "Ops wait till 22";
}
}

Write a PHP script to check whether the cookie is set or not.

<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>

<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>

</body>
</html>

Output: Cookie are enabled

Create an HTML page which will divide a page in two horizontal fragments using
frameset tag, each frame should have different background color & different headings.

<!DOCTYPE html>
<html>

<head>
<title>HTML Target Frames</title>
</head>

<frameset cols = "200, *">


<frame src = "upper.htm" name = "upper_page" />
<frame src = "lower.htm" name = "lower_page" />

<noframes>
<body>Your browser does not support frames.</body>
</noframes>
</frameset>

</html>

In the same directory there are upper.htm and lower.htm which are taken as source by frame tag.

<!-- upper.html —->


<!DOCTYPE html>
<html>

<body style=”background: blue;”>

<h1>Look below for greetings</h1>

</body>

</html>

<!-- lower.html —->


<!DOCTYPE html>
<html>

<body style=”background: yellow;”>

<h1>This tag is deprecated so please don’t ask such questions and remove such outdated
things from the syllabus. थंक
ु ले तम
ु च्या अभ्यासक्रमावर.</h1>

</body>

</html>

You might also like