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

IP Notes

Here is a basic JSP program to display "Hello World": <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello World JSP</title> </head> <body> <h1>Hello World from JSP!</h1> <% out.println("The time is: " + java.util.Calendar.getInstance().getTime()); %> </body> </html> This JSP program: - Imports the java package
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
84 views

IP Notes

Here is a basic JSP program to display "Hello World": <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Hello World JSP</title> </head> <body> <h1>Hello World from JSP!</h1> <% out.println("The time is: " + java.util.Calendar.getInstance().getTime()); %> </body> </html> This JSP program: - Imports the java package
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 63

IP Notes Created by Sumit Jaiswar

Q. 1) Explain how JavaScript can hide HTML Elements with suitable example.

Ans) In this tutorial, we will learn how to hide HTML element with JavaScript.

Hiding an HTML element can be performed in different ways in JavaScript. In this tutorial,
we will see the three most popular ways of doing it −

1. Using the hidden property


2. Using the style.display property
3. Using the style.visibility property

Generally, we use the hidden attribute to hide a particular element. We can toggle between
hiding and showing the element by setting the hidden attribute value to true or false,
respectively.

In the other two ways, we use the style object of the element. We have two properties in
the style object to hide the HTML element, one is the display, and another one is the
visibility.

In JavaScript, we can use both of these properties to hide the HTML elements, but the main
difference between these two is when we use style.visibility property, then the specific tag
is not visible, but the space of the tag is still allocated. Whereas in style.display property,
not only is the tag hidden but also there is no space allocated to that element.

Hidden Code:

<!DOCTYPE html>
<html lang="en"></html>
<head>
<meta charset="utf-18">
<meta name="viewport" content="width=device-width,initial-
scale=1.0">
<title>Hiding Html Element using Javascript</title>
</head>
<body>
<!-- Hiding HTML Element using the Hidden Property -->
<div id="myDiv">Click the below button to hide or show
this</div>
<br>
<br>
<button onclick="hide_hidden()">Hide Element using Hidden
Property</button>
IP Notes Created by Sumit Jaiswar

<button onclick="show_hidden()">Show Element using Hidden


Property</button>

<script>
function hide_hidden(){
document.getElementById("myDiv").hidden=true;
}
function show_hidden(){
document.getElementById("myDiv").hidden=false;
}
</script>
</body>
</html>

style.display

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-18">
<meta name="viewport" content="width=device-width,inital-
scale=1.0">
<title>Hiding HTML Element using style.display Property of
Javascript</title>
<style>
#myDiv{
width: 630px;
height: 300px;
background-color: #f3f3f3;}
</style>
</head>
<body>
<p>Click the hide element button to hide the DIV Element</p>
<div id="myDiv">Hello world! this the DIV element</div><br>
<button onclick="hide()">Hide Element</button>
<button onclick="show()">Show Element</button>
<script>
function hide(){
document.getElementById("myDiv").style.display='none';
}
function show(){
IP Notes Created by Sumit Jaiswar

document.getElementById("myDiv").style.display='inline-
block';
}
</script>
</body>
</html>

style.visibilty

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-18">
<meta name="viewport" content="width=device-width,inital-
scale=1.0">
<title>Hiding HTML Element using style.display Property of
Javascript</title>
<style>
#myDiv{
width: 630px;
height: 300px;
background-color: #f3f3f3;
}
</style>
</head>
<body>
<p>Click the hide element button to hide the DIV Element</p>
<div id="myDiv">Hello world! this the DIV element</div><br>
<button onclick="hide()">Hide Element</button>
<button onclick="show()">Show Element</button>
<script>
function hide(){
document.getElementById("myDiv").style.visibility='hidden';
}
function show(){
document.getElementById("myDiv").style.visibility='visible';
}
</script>
</body>
</html>
IP Notes Created by Sumit Jaiswar

Q. 2) If you wanted to send sensitive information like password to the backend which
among the get and the post method in php would you use , justify your answer.
Ans)
Sending sensitive information, such as passwords, should always be done with the POST
method rather than the GET method in PHP, and here's why:
1. Security:
 GET Method: Parameters are appended to the URL, which means they are
visible in the browser's address bar and can be stored in browser history,
server logs, and may be cached. This makes sensitive information, like
passwords, more susceptible to being compromised.
 POST Method: Parameters are sent in the request body, not in the URL. This
provides a more secure way of transmitting sensitive information because the
data is not exposed in the URL.
2. Request Length Limitations:
 GET Method: The amount of data that can be sent using the GET method is
limited by the browser and server. Exceeding these limits might result in
errors, and it's not suitable for sending large amounts of data or sensitive
information.
 POST Method: There are typically higher limits for data sent via POST, making
it more suitable for transmitting larger amounts of data, like form
submissions with sensitive information.
3. Idempotence:
 GET Method: It is considered idempotent, meaning multiple identical
requests should have the same effect as a single request. This makes it more
suitable for operations that don't modify data.
 POST Method: It is not necessarily idempotent, meaning multiple identical
requests might have different effects. It's designed for operations that modify
data, making it appropriate for actions like submitting forms, including those
with sensitive data.
4. Caching:
 GET Method: Since parameters are included in the URL, responses are more
prone to being cached by browsers and intermediaries. This is not desirable
for sensitive information.
 POST Method: Responses are less likely to be cached, especially when
appropriate headers are set, providing better control over caching behavior.
In summary, the POST method is more secure and suitable for sending sensitive information
as it keeps the data out of the URL, has higher limits for data transmission, and is designed
IP Notes Created by Sumit Jaiswar

for operations that modify data. Always use HTTPS in conjunction with the POST method to
encrypt the data in transit for an additional layer of security.
Q. 3) Write a code in React JS to Display “Hello World”.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Home</title>
<script crossorigin
src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin
src="https://unpkg.com/react-dom@18/umd/react-
dom.development.js"></script>
<script
src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
<script type="text/babel">
// ReactDOM.render(
// "Welcome to React !!",
// document.querySelector("p")
// )
const root =
ReactDOM.createRoot(document.querySelector("h3"));
root.render("Hello ! React");
</script>
</head>
<body>
<h2>Home - Using React</h2>
<h3></h3>
<a href="index.html">Back to Index</a>
</body>
</html>

Q. 4) Write the HTML 5 code to drag a specific image and drop it on specific location.
<!DOCTYPE html>
<html>

<head>
<title>Drag and Drop</title>
<style>
#box {
width: 300px;
height: 300px;
border: 4px dashed black;
IP Notes Created by Sumit Jaiswar

}
</style>
</head>
<body>
<p><b>Drag the Image or browse the file</b></p>
<div id="box" ondrop="drop(event)" ondragover="allowDrop(event)">
</div><br>
<img id="logo" src="https://cdn.pixabay.com/photo/2017/08/05/11/16/logo-
2582748_1280.png" draggable="true" ondragstart="drag(event)" height="100"
width="100">
<script>
function drag(event) {
event.dataTransfer.setData("text", event.target.id);
}
function drop(event) {
event.preventDefault();
var data = event.dataTransfer.getData("Text");
event.target.appendChild(document.getElementById(data));
}
function allowDrop(event) {
event.preventDefault();
}
</script>
</body>
</html>

Q. 5) Write a program to check whether entered number is even or odd .


Ans)
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
<style>
#num,button{
font-size: 30px;
}
</style>
</head>
<body>
<input type="text" name="num" id="num" placeholder="Enter your number" />
<br />
<button type="submit" onclick="check()">Check</button>
<h2>Your Answer</h2>
<script type="text/javascript" charset="utf-8">
IP Notes Created by Sumit Jaiswar

function check(){
let num = document.getElementById("num").value;
let h2 = document.querySelector("h2");
if(num%2==0){
h2.innerText="Number is Even";
}else{
h2.innerText="Number is Odd"
}
}
</script>
</body>
</html>

Q. 6) Write a program to check whether entered number is leap year or not.


Ans)
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
<link rel="stylesheet" href="styles.css" />
<style>
#num,button{
font-size: 30px;
}
</style>
</head>
<body>
<input type="text" name="num" id="num" placeholder="Enter your Year" />
<br />
<button type="submit" onclick="check()">Check</button>
<h2>Your Answer</h2>
<script type="text/javascript" charset="utf-8">
function check(){
let inp = document.getElementById("num");
let year = inp.value;
let h2 = document.querySelector("h2");
if(year%4==0){
h2.innerText="Leap Year";
}else{
h2.innerText="Not a Leap Year"
}
}
</script>
</body>
IP Notes Created by Sumit Jaiswar

</html>

Q. 7) Write a JSP Program to perform four basic arithmetic operation , Addition,


Subtraction, Division and Multipliacation.
Ans)_______________________________________________________________________
Index.html__________________________________________________________________

<!DOCTYPE html>
<html>
<title>Mathematics Operations </title>
<body>
<form method="post" action="index.jsp">
<fieldset style="width:30%; background-color:#b3d1ff">
<h2><center> Mathematical Operation</center></h2>
<hr>
<font size=5 face="Times New Roman">
<input type="radio" name="a1" value="add" checked>Addition</input><br>
<input type="radio" name="a1" value="sub">Subtraction</input><br>
<input type="radio" name="a1" value="mul" >Multiplication</input><br>
<input type="radio" name="a1" value="div" >Division</input><br>
</font>
<table>
<tr>
<td>Enter first Value:</td>
<td> <input type="text" name="t1" value=""></td>
</tr>
<tr>
<td>Enter second Value: </td>
<td><input type="text" name="t2" value=""></td>
</tr><br>
<tr>
<td></td>
<td><input type="submit" name="result" value="Check result!"></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
IP Notes Created by Sumit Jaiswar

___________________________________________________________________________
Index.jsp____________________________________________________________________

<%@ page errorPage="error.jsp" %>


<html>
<body>
<H1><center>Result for <%=request.getParameter("a1")%></center></H1>
<%
String num1=request.getParameter("t1");
String num2=request.getParameter("t2");

int i=Integer.parseInt(num1);
int j=Integer.parseInt(num2);

int k=0;
String str=request.getParameter("a1");
if(str.equals("add"))
k=i+j;
if(str.equals("sub"))
k=i-j;
if(str.equals("mul"))
k=i*j;
if(str.equals("div"))
k=i/j;
%>
Result is: <%=k%>
</body>
</html>
___________________________________________________________________________
error.jsp___________________________________________________________________

<%@ page isErrorPage="true" %>

<h3>Sorry an exception occured!</h3>

Exception is: <%= exception %>


___________________________________________________________________________
web.xml____________________________________________________________________

<web-app>
<servlet>
<servlet-name>xyz</servlet-name>
<jsp-file>/input.html</jsp-file>
IP Notes Created by Sumit Jaiswar

</servlet>
<servlet-mapping>
<servlet-name>xyz</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
</web-app>

Q. 8) Explain Exception handling in Javascript with suitable example.


Ans)
Exception handling in JavaScript involves managing errors that may occur during the
execution of a program. This is important for gracefully handling unexpected situations and
preventing them from causing the entire program to crash. JavaScript provides a try-catch
statement for this purpose.
Here's a simple explanation with an example:
Try-Catch Statement:
The try block is used to enclose the code that might generate an exception, and the catch
block is used to handle the exception if it occurs.

try {
// Code that may throw an exception
let result = someFunction();
console.log(result); // This line will not be executed if an exception occurs
} catch (error) {
// Code to handle the exception
console.error("An error occurred:", error.message);
} finally {
// Code that will always be executed, whether there is an exception or not
console.log("This will always be executed");
}

In this example:
 The try block contains the code that might throw an exception, such as calling a
function (someFunction() in this case).
 If an exception occurs, the control is transferred to the catch block where the error
object contains information about the exception.
 The finally block contains code that will always be executed, regardless of whether
an exception occurred or not.

Example:
function divideNumbers(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
IP Notes Created by Sumit Jaiswar

return a / b;
}

try {
let result = divideNumbers(10, 2);
console.log("Result:", result);

result = divideNumbers(8, 0); // This will throw an exception


console.log("This line will not be executed");
} catch (error) {
console.error("An error occurred:", error.message);
} finally {
console.log("This will always be executed");
}

In this example:
 The divideNumbers function is designed to throw an exception if the second
parameter (b) is zero.
 The first call to divideNumbers(10, 2) succeeds without an exception.
 The second call to divideNumbers(8, 0) throws an exception, and the control goes to
the catch block.
The output will be:

Result: 5
An error occurred: Cannot divide by zero
This will always be executed

This demonstrates how the try-catch statement allows you to handle exceptions and
execute fallback logic when errors occur. It's important to note that exceptions should be
used for exceptional cases, and not as a normal flow of control.

Q. 9) Draw and explain Servlet Architecture and its Lifecycle.


Ans)
Servlet Architecture:
Servlets are Java classes that extend the capabilities of servers and respond to incoming
requests. Servlets follow a specific architecture that includes several components. The
architecture is based on the Java Servlet API, which provides a standard interface for
interacting with the web server.
1. Servlet Class:
 Servlets are Java classes that extend either javax.servlet.GenericServlet or
javax.servlet.http.HttpServlet.
 The GenericServlet class is protocol-independent, while HttpServlet is
specific to HTTP protocol-based servlets.
IP Notes Created by Sumit Jaiswar

2. Servlet Container:
 The Servlet Container (or Servlet Engine) is part of the web server responsible
for managing the lifecycle of servlets and handling their requests.
 Common servlet containers include Apache Tomcat, Jetty, and others.
3. Request and Response Objects:
 Servlets receive requests from clients (usually browsers) and generate
responses.
 The HttpServletRequest object encapsulates the client's request, while the
HttpServletResponse object represents the servlet's response.
4. Web Container:
 The Web Container is a part of the Servlet Container that manages the
execution of servlets.
 It handles the lifecycle of servlets, manages multiple threads, and provides
services like security, deployment, and management.
5. Servlet Interface:
 The Servlet interface provides methods that allow the servlet to be
initialized, handle requests, and be destroyed.
 Key methods include init(), service(), and destroy().
Servlet Lifecycle:
The lifecycle of a servlet involves several stages, from instantiation to destruction. The
Servlet Container manages this lifecycle.
1. Instantiation (Object Creation):
 The servlet container creates an instance of the servlet class using its no-
argument constructor.
 The init() method is called to initialize the servlet. This method is called only
once during the lifecycle.
2. Initialization:
 In the init() method, the servlet can perform tasks such as loading
configuration parameters, establishing database connections, etc.
 This method is called when the servlet is first created and not for each user
request.
3. Handling Requests:
 The service() method is called by the servlet container to handle each client
request.
 The service() method receives ServletRequest and ServletResponse objects
and processes the request.
4. Request Handling (doGet(), doPost(), etc.):
 The service() method typically dispatches the request to more specific
methods like doGet() or doPost() based on the type of HTTP request.
5. Destruction:
 The destroy() method is called when the servlet is being taken out of service,
such as during server shutdown or when the application is undeployed.
IP Notes Created by Sumit Jaiswar

 The servlet can perform cleanup tasks, close database connections, etc., in
this method.
6. Servlet Recycling:
 If the servlet container determines that a servlet needs to be removed from
service (due to inactivity or other factors), it calls the destroy() method, and
the servlet instance is garbage collected.
 If a new request comes in for the same servlet, the container creates a new
instance and calls init() again.
Understanding the servlet architecture and lifecycle is crucial for developing efficient and
reliable web applications in Java.
Q. 10) An e-commerce website would like to accept the below mentioned data and would
like to transfer the data using XML,
i. Product ID
ii. Product Name
iii. Product Cost
iv. Purchase Date
v. Purchased by
vi. Seller Name
Write the HTML, XML Code and DTD for the given data.
Ans)
Index.html__________________________________________________________________

<!DOCTYPE html>
<html>
<head>
<title>E-commerce Data Form</title>
</head>
<body>
<form method="post" action="process_data.php">
<label for="productId">Product ID:</label>
<input type="text" id="productId" name="productId" required><br>

<label for="productName">Product Name:</label>


<input type="text" id="productName" name="productName" required><br>

<label for="productCost">Product Cost:</label>


<input type="text" id="productCost" name="productCost" required><br>

<label for="purchaseDate">Purchase Date:</label>


<input type="date" id="purchaseDate" name="purchaseDate" required><br>

<label for="purchasedBy">Purchased By:</label>


<input type="text" id="purchasedBy" name="purchasedBy" required><br>
IP Notes Created by Sumit Jaiswar

<label for="sellerName">Seller Name:</label>


<input type="text" id="sellerName" name="sellerName" required><br>

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


</form>
</body>
</html>

data.xml____________________________________________________________________

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


<!DOCTYPE e-commerce SYSTEM "e-commerce.dtd">
<e-commerce>
<product>
<productId>123</productId>
<productName>Laptop</productName>
<productCost>1200.00</productCost>
<purchaseDate>2023-01-01</purchaseDate>
<purchasedBy>John Doe</purchasedBy>
<sellerName>TechStore Inc.</sellerName>
</product>
</e-commerce>

e-commerce.dtd_____________________________________________________________

<!ELEMENT e-commerce (product+)>


<!ELEMENT product (productId, productName, productCost, purchaseDate, purchasedBy,
sellerName)>
<!ELEMENT productId (#PCDATA)>
<!ELEMENT productName (#PCDATA)>
<!ELEMENT productCost (#PCDATA)>
<!ELEMENT purchaseDate (#PCDATA)>
<!ELEMENT purchasedBy (#PCDATA)>
<!ELEMENT sellerName (#PCDATA)>

process_data.php____________________________________________________________

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect data from the form
$productId = $_POST["productId"];
$productName = $_POST["productName"];
$productCost = $_POST["productCost"];
$purchaseDate = $_POST["purchaseDate"];
IP Notes Created by Sumit Jaiswar

$purchasedBy = $_POST["purchasedBy"];
$sellerName = $_POST["sellerName"];

// Create an XML document


$xmlDoc = new DOMDocument('1.0', 'UTF-8');
$root = $xmlDoc->createElement('e-commerce');
$product = $xmlDoc->createElement('product');

$product->appendChild($xmlDoc->createElement('productId', $productId));
$product->appendChild($xmlDoc->createElement('productName', $productName));
$product->appendChild($xmlDoc->createElement('productCost', $productCost));
$product->appendChild($xmlDoc->createElement('purchaseDate', $purchaseDate));
$product->appendChild($xmlDoc->createElement('purchasedBy', $purchasedBy));
$product->appendChild($xmlDoc->createElement('sellerName', $sellerName));

$root->appendChild($product);
$xmlDoc->appendChild($root);

// Send the XML content as the response


header('Content-Type: application/xml');
echo $xmlDoc->saveXML();
} else {
// Invalid request method
header('HTTP/1.1 405 Method Not Allowed');
echo 'Method Not Allowed';
}
?>

Q. 11) Explain how form validation works in PHP, with suitable example.
Ans)
Form validation in PHP involves checking user input for correctness and completeness
before processing the data. Proper form validation helps prevent issues like security
vulnerabilities, data integrity problems, and improves the overall user experience. Here's a
simple example of form validation in PHP:
HTML Form (index.html):
<!DOCTYPE html>
<html>
<head>
<title>Form Validation Example</title>
</head>
<body>
<form method="post" action="process_form.php">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required><br>
IP Notes Created by Sumit Jaiswar

<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required><br>

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


</form>
</body>
</html>
PHP Form Processing (process_form.php):
<?php

if ($_SERVER["REQUEST_METHOD"] === "POST") {


// Collect form data
$username = $_POST["username"];
$email = $_POST["email"];
$password = $_POST["password"];

// Validate the form data


$errors = array();

// Validate username
if (empty($username)) {
$errors[] = "Username is required";
} elseif (!preg_match("/^[a-zA-Z0-9_]+$/", $username)) {
$errors[] = "Invalid username format";
}

// Validate email
if (empty($email)) {
$errors[] = "Email is required";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format";
}

// Validate password
if (empty($password)) {
$errors[] = "Password is required";
} elseif (strlen($password) < 8) {
$errors[] = "Password must be at least 8 characters long";
}
IP Notes Created by Sumit Jaiswar

// Process form data if there are no validation errors


if (empty($errors)) {
// Perform further processing, e.g., store data in a database
echo "Form data is valid. Processing...";
} else {
// Display validation errors
echo "Validation errors:<br>";
foreach ($errors as $error) {
echo "- $error<br>";
}
}

} else {
// Invalid request method
header("HTTP/1.1 405 Method Not Allowed");
echo "Method Not Allowed";
}

?>
Explanation:
1. HTML Form:
 The form collects data from the user, including username, email, and
password.
2. PHP Form Processing:
 The PHP script (process_form.php) is responsible for validating and
processing the form data.
 It uses the $_POST superglobal to access the submitted form data.
3. Validation:
 The script performs various validation checks using conditional statements
and regular expressions.
 If any validation errors are encountered, they are stored in the $errors array.
4. Processing Data:
 If there are no validation errors, the script proceeds to process the form data
(e.g., store it in a database). In this example, it simply echoes a message.
5. Displaying Errors:
 If validation errors exist, the script echoes a message indicating the errors.
This is a basic example, and in a real-world scenario, you might want to enhance validation,
implement additional security measures, and customize error messages based on specific
requirements.

Q. 12) Explain Basic Internet Protocols which are essential for transferring data and
sending emails.
IP Notes Created by Sumit Jaiswar

Ans)
Several basic Internet protocols are essential for transferring data and sending emails. Here
are some of the key protocols:

1. Transmission Control Protocol (TCP):


 TCP is one of the core protocols in the Internet protocol suite (TCP/IP).
 It provides reliable, connection-oriented communication between devices on
a network.
 TCP ensures the ordered and error-checked delivery of data between
applications.
2. Internet Protocol (IP):
 IP is another fundamental protocol in the TCP/IP suite.
 It is responsible for addressing and routing packets of data so that they can
travel across networks and arrive at the correct destination.
3. Hypertext Transfer Protocol (HTTP):
 HTTP is the foundation of data communication on the World Wide Web.
 It is used for transmitting hypertext, which includes links to other resources,
such as text, images, and multimedia files.
 HTTP operates on top of TCP and uses port 80 by default.
4. Hypertext Transfer Protocol Secure (HTTPS):
 HTTPS is the secure version of HTTP, adding a layer of encryption using
protocols like SSL (Secure Sockets Layer) or its successor, TLS (Transport Layer
Security).
 It is widely used for secure communication over the Internet, especially in
online transactions, login pages, and other sensitive data transfers.
5. File Transfer Protocol (FTP):
 FTP is a standard network protocol used to transfer files between a client and
a server on a computer network.
 It operates over TCP and allows users to upload or download files from
remote servers.
6. Simple Mail Transfer Protocol (SMTP):
 SMTP is the protocol used for sending emails.
 It defines the rules by which email messages are sent and received over the
Internet.
 SMTP operates over TCP and uses port 25 for communication.
7. Post Office Protocol (POP) and Internet Message Access Protocol (IMAP):
 POP and IMAP are protocols used by email clients to retrieve emails from a
server.
 POP typically downloads emails to the client's device, removing them from
the server.
 IMAP allows users to view emails directly on the server, offering
synchronization across multiple devices.
8. Domain Name System (DNS):
IP Notes Created by Sumit Jaiswar

 DNS translates human-readable domain names into IP addresses, facilitating


the routing of data on the Internet.
 It is crucial for users as it allows them to access websites using familiar
domain names instead of numerical IP addresses.

9. Simple Network Management Protocol (SNMP):


 SNMP is used for managing and monitoring network devices.
 It allows network administrators to monitor the performance and status of
network equipment.
10. Internet Control Message Protocol (ICMP):
 ICMP is primarily used for diagnostic purposes.
 It is commonly associated with the "ping" command, which tests the
reachability of a host on an Internet Protocol (IP) network.
These protocols form the foundation of communication on the Internet, enabling the
transfer of data, browsing the web, sending emails, and managing network resources.
Understanding these protocols is essential for anyone involved in networking, web
development, or system administration.

Q.13) Write the AJAX code to read from the text file and displaying it after clicking of
button.
Ans)
To read data from a text file and display it using AJAX (Asynchronous JavaScript and XML),
you can use the following example. In this example, I'll demonstrate using JavaScript and the
XMLHttpRequest object for simplicity. Note that in modern web development, you might
prefer using the Fetch API or other libraries like jQuery or axios for AJAX requests.
HTML (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AJAX Example</title>
</head>
<body>
<button onclick="loadText()">Load Text</button>
<div id="output"></div>

<script>
function loadText() {
var xhr = new XMLHttpRequest();

// Define the file path (replace 'sample.txt' with your actual file path)
var filePath = 'sample.txt';
IP Notes Created by Sumit Jaiswar

xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// The responseText contains the content of the text file
document.getElementById('output').innerHTML = xhr.responseText;
}
};

// Open the GET request to the file


xhr.open('GET', filePath, true);

// Send the request


xhr.send();
}
</script>
</body>
</html>
In this HTML file:
 The "Load Text" button triggers the loadText JavaScript function.
 The XMLHttpRequest object is used to make an asynchronous GET request to the
server (in this case, the local file system).
Text File (sample.txt):
Create a file named sample.txt in the same directory as your HTML file with some sample
text:
This is a sample text file.
AJAX is awesome!
Explanation:
1. The loadText function is called when the button is clicked.
2. An instance of XMLHttpRequest is created.
3. The onreadystatechange event is used to check when the request is complete.
4. The open method initializes the request (GET request in this case) and specifies the
file path.
5. The send method sends the request to the server.
6. When the server responds with the content of the text file, the onreadystatechange
event is triggered, and if the response is successful (status == 200), the content is
displayed in the output div.
Make sure to run this code on a web server (local or remote) because modern browsers
often have restrictions on making AJAX requests to local files due to security reasons. If
you're using Visual Studio Code, you can install an extension like "Live Server" to easily run a
local server for testing.

Q. 14) List and Explain the 3 ways to add style sheet (CSS) to an HTML web page with
suitable example.
Ans)
IP Notes Created by Sumit Jaiswar

There are several ways to add stylesheets (CSS) to an HTML web page. Here are three
common methods:
1. Inline Styles:
 Inline styles are applied directly within the HTML element using the style
attribute.

Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Inline Styles Example</title>
</head>
<body>
<h1 style="color: blue; text-align: center;">Hello, World!</h1>
<p style="font-size: 16px;">This is a paragraph with inline styles.</p>
</body>
</html>
2. Internal Styles (Embedded Styles):
 Internal styles are defined within the <style> tag in the <head> section of the
HTML document.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Internal Styles Example</title>
<style>
h1 {
color: green;
text-align: center;
}
p{
font-size: 18px;
}
</style>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph with internal styles.</p>
</body>
</html>
IP Notes Created by Sumit Jaiswar

3. External Styles:
 External styles involve placing the styles in a separate CSS file and linking it to
the HTML document using the <link> element.
Example:
style.css:
/* style.css */
h1 {
color: red;
text-align: center;
}
p{
font-size: 20px;
}
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External Styles Example</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph with external styles.</p>
</body>
</html>
In the external styles example, the styles are stored in a separate file named style.css, and
the HTML file links to this file using the <link> element. This method promotes a clean
separation of HTML and CSS, making the code more modular and maintainable.

Q. 15) Create a form which has the following fields ‘Name’, ‘Age’, ‘Email ID’, ‘Password’.
Using Javascript validate each field as follows
i. Name should be between A-Z
ii. Age should be between 0-100
iii. Email should contain ‘@’
iv. Password should contain 1 Upper case, 1 Digit, 1 Special character and length
should be minimum 8
Ans)
HTML form with JavaScript validation for the specified criteria:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
IP Notes Created by Sumit Jaiswar

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


<title>Form Validation Example</title>
<style>
.error {
color: red;
}
</style>
</head>
<body>
<h2>User Registration Form</h2>
<form id="registrationForm" onsubmit="return validateForm()">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<span id="nameError" class="error"></span><br>

<label for="age">Age:</label>
<input type="number" id="age" name="age" required>
<span id="ageError" class="error"></span><br>

<label for="email">Email ID:</label>


<input type="email" id="email" name="email" required>
<span id="emailError" class="error"></span><br>

<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<span id="passwordError" class="error"></span><br>

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


</form>

<script>
function validateForm() {
// Reset error messages
document.getElementById('nameError').innerHTML = "";
document.getElementById('ageError').innerHTML = "";
document.getElementById('emailError').innerHTML = "";
document.getElementById('passwordError').innerHTML = "";

// Get form values


var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
IP Notes Created by Sumit Jaiswar

// Validate Name
if (!/^[a-zA-Z]+$/.test(name)) {
document.getElementById('nameError').innerHTML = "Name should only contain
A-Z characters.";
return false;
}

// Validate Age
if (isNaN(age) || age < 0 || age > 100) {
document.getElementById('ageError').innerHTML = "Age should be between 0 and
100.";
return false;
}

// Validate Email
if (!/\S+@\S+\.\S+/.test(email)) {
document.getElementById('emailError').innerHTML = "Invalid email format.";
return false;
}

// Validate Password
if (!/(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])/.test(password) || password.length <
8) {
document.getElementById('passwordError').innerHTML = "Password should
contain 1 uppercase letter, 1 digit, 1 special character, and be at least 8 characters long.";
return false;
}

// Form is valid
alert("Form submitted successfully!");
return true;
}
</script>
</body>
</html>
In this example:
 The HTML form contains input fields for Name, Age, Email ID, and Password.
 JavaScript function validateForm is called on form submission to perform validation.
 Error messages are displayed if the validation criteria are not met.
 The onsubmit attribute of the form is set to return validateForm() to trigger the
validation function. If the form is valid, it returns true, allowing the form submission.
If not, it returns false, preventing the form submission.
IP Notes Created by Sumit Jaiswar

In JavaScript, a regular expression is defined using forward slashes (/). The syntax for
creating a regular expression literal is /pattern/flags, where:
 pattern: The regular expression pattern that defines the search criteria.
 flags: Optional flags that modify the behavior of the regular expression.
For example:

var pattern = /abc/g;

In this case:
 abc is the regular expression pattern.
 g is the global flag, indicating that the pattern should be applied globally across the
entire string.
Enclosing the regular expression pattern between forward slashes is a common convention
in many programming languages. It helps distinguish regular expressions from other types of
strings.
Alternative to using the regular expression literal syntax, you can also create a regular
expression using the RegExp constructor:

var pattern = new RegExp("abc", "g");

Here, "abc" is the pattern, and "g" is the flag.


Using regular expression literals with forward slashes is often preferred for simplicity and
readability when the pattern is known at the time of writing the code. If the pattern is
dynamic or obtained from user input, using the RegExp constructor with a string is more
suitable.
In the context of your JavaScript validation example:

/^[a-zA-Z]+$/

This regular expression literal checks whether a string consists of one or more (+) uppercase
or lowercase letters (a-z or A-Z) from the start (^) to the end ($). The forward slashes mark
the beginning and end of the regular expression literal.

Let's break down the regular expressions used in the JavaScript validation for each field:
1. Name Validation:
 /^[a-zA-Z]+$/
 ^: Asserts the start of the string.
 [a-zA-Z]+: Matches one or more (+) uppercase or lowercase letters (a-
z or A-Z).
 $: Asserts the end of the string.
 Explanation: The name should only contain alphabetic characters (either
uppercase or lowercase).
2. Age Validation:
 isNaN(age) || age < 0 || age > 100
IP Notes Created by Sumit Jaiswar

 isNaN(age): Checks if the age is not a number.


 age < 0: Checks if the age is less than 0.
 age > 100: Checks if the age is greater than 100.
 Explanation: The age should be a number between 0 and 100.
3. Email Validation:
 /\S+@\S+\.\S+/
 \S+: Matches one or more non-whitespace characters.
 @: Matches the at symbol.
 \S+: Matches one or more non-whitespace characters.
 \.: Matches the dot (.) character.
 \S+: Matches one or more non-whitespace characters.
 Explanation: Validates a basic email format, ensuring it contains the at
symbol (@) and a dot (.) in the domain.
4. Password Validation:
 /(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*()_+])/.test(password) &&
password.length >= 8
 (?=.*[A-Z]): Positive lookahead assertion for at least one uppercase
letter.
 (?=.*\d): Positive lookahead assertion for at least one digit.
 (?=.*[!@#$%^&*()_+]): Positive lookahead assertion for at least one
special character from the given set.
 && password.length >= 8: Checks that the password length is at least
8 characters.
 Explanation: Requires the password to have at least one uppercase letter,
one digit, one special character, and be at least 8 characters long.
Regular expressions are powerful tools for pattern matching and validation. They allow you
to define specific patterns that text should adhere to, making them very useful for form
validation.

Q. 16) Create an external Stylesheet and link it to an HTML form, the stylesheet should
contain the following,
i. An header in text with Red Text Colour and Yellow background colour
ii. A Double lined (Border) table
iii. The table should have 5 Rows and 3 Columns
iv. In the First column Sr. No. of the product, Second Column Image with hyperlink
and Name of the Product, and Third Column the description of the product
Ans)
external stylesheet (styles.css) and an HTML form linked to it. The stylesheet includes styling
for a header, a table with specified characteristics, and the required columns in the table.

External Stylesheet (styles.css):


/* styles.css */

/* Header styling */
IP Notes Created by Sumit Jaiswar

header {
color: red;
background-color: yellow;
padding: 10px;
text-align: center;
}

/* Table styling */
table {
border-collapse: collapse;
width: 100%;
}

table, th, td {
border: 2px double black;
}

HTML Form (index.html):


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Styled Table</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Product Information</h1>
</header>

<table>
<thead>
<tr>
<th>Sr. No.</th>
<th>Product Image & Name</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><a href="#"><img src="product1.jpg" alt="Img 1"></a> Product 1</td>
<td>Description of Product 1</td>
IP Notes Created by Sumit Jaiswar

</tr>
<tr>
<td>2</td>
<td><a href="#"><img src="product2.jpg" alt="Img 2"></a> Product 2</td>
<td>Description of Product 2</td>
</tr>
<tr>
<td>3</td>
<td><a href="#"><img src="product3.jpg" alt="Img 3"></a> Product 3</td>
<td>Description of Product 3</td>
</tr>
<tr>
<td>4</td>
<td><a href="#"><img src="product4.jpg" alt="Img 4"></a> Product 4</td>
<td>Description of Product 4</td>
</tr>
<tr>
<td>5</td>
<td><a href="#"><img src="product5.jpg" alt="Img 5"></a> Product 5</td>
<td>Description of Product 5</td>
</tr>
</tbody>
</table>
</body>
</html>

Output:

Product Information
Sr. No. Product Image & Name Description
In 1 Description of Product 1
Img1 Product 1
2 Img2 Product 2 Description of Product 2

3 Img3 Product 3 Description of Product 3

4 Img4 Product 4 Description of Product 4

5 Img5 Product 5 Description of Product 5


this example:
 The styles.css file contains styling rules for the header and table.
 The HTML file (index.html) links to the external stylesheet using the <link> element.
IP Notes Created by Sumit Jaiswar

 The table is structured with 5 rows and 3 columns, with specific styling for each
column.
 Images in the second column are linked and styled to have a maximum width and
height.

Q. 17) Write a Javascript to check password and confirm password are same or not.
Ans)
JavaScript to check whether the password and confirm password fields in a form are the
same. Here's an example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Password Matching Example</title>
</head>
<body>
<form id="passwordForm" onsubmit="validateForm()">
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>

<label for="confirmPassword">Confirm Password:</label>


<input type="password" id="confirmPassword" name="confirmPassword" required>
<span id="passwordError" class="error"></span>
<br>

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


</form>

<script>
function validateForm() {
// Get password and confirm password values
var password = document.getElementById('password').value;
var confirmPassword = document.getElementById('confirmPassword').value;

// Check if passwords match


if (password !== confirmPassword) {
document.getElementById('passwordError').innerText = "Passwords do not
match.";
} else {
document.getElementById('passwordError').innerText = "Password Match";
}
IP Notes Created by Sumit Jaiswar

}
</script>
</body>
</html>
In this example:
 The HTML form has two password fields: one for the password and another for
confirming the password.
 The JavaScript function validateForm is called when the form is submitted.
 Inside the function, it compares the values of the password and confirm password
fields.
 If the passwords do not match, it displays an error with message ‘Password do not
match’
 If the passwords match, it displays message ‘Password match’

Q. 18) What is Servlet and Explain Servlet Life Cycle with neat diagram.
Ans)
A Servlet in Java is a server-side technology used to extend the capabilities of web servers
by providing dynamic, content-rich web applications. Servlets are Java classes that handle
HTTP requests and generate responses dynamically. They adhere to the Java Servlet API
specification, which defines a set of interfaces and classes that servlets must implement or
extend.
The life cycle of a servlet describes the stages a servlet goes through from its instantiation to
its destruction. The Servlet life cycle is managed by the servlet container (like Apache
Tomcat). The key methods involved in the servlet life cycle are:

The life cycle of a servlet in Java consists of several stages, and understanding this life cycle
is crucial for developing servlet-based applications. Here is an explanation of the servlet life
cycle along with a simple diagram:
Servlet Life Cycle Stages:
1. Loading:
 When a web container like Tomcat starts or when a request for the servlet is
received for the first time, the servlet class is loaded into memory.
 The init() method is called during the loading stage. This method is called
only once in the lifetime of a servlet and is used for one-time initialization
tasks.
2. Initialization:
 The init() method is responsible for initializing the servlet.
 The servlet container calls this method after loading the servlet class.
 It is typically used to perform tasks such as opening a database connection,
loading configuration parameters, etc.
3. Request Handling:
 Once initialized, the servlet can handle multiple requests concurrently.
 For each request, a new thread is spawned by the servlet container to handle
that request.
IP Notes Created by Sumit Jaiswar

 The service() method is called for each request. It is responsible for


processing the request and generating the response.

4. Destroying:
 When the servlet container decides to take the servlet out of service (e.g.,
when shutting down or reloading the web application), it calls the destroy()
method.
 The destroy() method is used to perform cleanup tasks, such as closing
database connections or releasing resources.

Diagram:
+------------------------+
| Servlet Class |
+------------------------+
|
| (1) Load Servlet Class
|
V
+-------------------------------+
| init() |
| One-time initialization |
+-------------------------------+
|
| (2) Handle Requests
|
v
+-------------------------------+
| service() |
| Process each request |
+-------------------------------+
|
| (3) Unload Servlet
v
+----------------------------------+
| destroy() |
| Cleanup and finalization |
+----------------------------------+

Explanation:
1. Load Servlet Class:
 The servlet class is loaded into memory when the web container starts or
when the first request for the servlet is received.
2. One-time Initialization (init()):
IP Notes Created by Sumit Jaiswar

 The init() method is called by the servlet container during the loading stage.
It is responsible for one-time initialization tasks.

3. Handle Requests (service()):


 The service() method is called for each incoming request. It is responsible for
processing the request, generating the response, and handling multiple
requests concurrently.
4. Unload Servlet (destroy()):
 The destroy() method is called when the servlet container decides to take the
servlet out of service (e.g., during application shutdown or reload). It is used
for cleanup tasks.
This life cycle ensures that servlets can handle requests efficiently, initialize resources when
needed, and release resources appropriately when the servlet is taken out of service.

Q. 19) What is AJAX? Explain AJAX Web Application model with neat diagram.
Ans)
 AJAX Web application model uses JavaScript and XMLHttpRequest object for
asynchronous data exchange. The JavaScript uses the XMLHttpRequest object to
exchange data asynchronously over the client and server.
 AJAX Web application model resolve the major problem of synchronous request-
response model of communication associated with classical Web application model,
which keeps the user in
waiting state and does not
provide the best user
experience.
 AJAX, a new approach to
Web applications, which is
based on several
technologies that help in
developing applications with
better user experience. It
uses JavaScript and XML as
the main technology for
developing interactive Web
applications.

 The AJAX application


eliminates the start-stop-
start-stop nature or the
click, wait, and refresh
IP Notes Created by Sumit Jaiswar

criteria of the client-server interaction by introducing intermediary layer between


the user and the Web server.
 Instead of loading the Web page at the beginning of the session, the browser loads
the AJAX engine written in JavaScript.
 Every user action that normally would generate an HTTP request takes the form of a
JavaScript call to the AJAX Engine.
 The server response comprises data and not the presentation, which implies that the
data required by the client is provided by the server as the response, and
presentation is implemented on that data with the help of markup language from
Ajax engine.
 The JavaScript does not redraw all activities instead only updates the Web page
dynamically.
 In JavaScript, it is possible to fill Web forms and click buttons even when the
JavaScript has made a request to the Web server and the server is still working on
the request in the background. When server completes its processing, code updates
just the part of the page that has changed. This way client never has to wait around.
That is the power of asynchronous requests.
 AJAX Engine between the client and the application, irrespective of the server, does
asynchronous communication. This prevents the user from waiting for the server to
complete its processing.
 The AJAX Engine takes care of displaying the UI and the interaction with the server
on the user’s behalf.
 In traditional Web applications, the synchronous mode of communication existed
between the client and the server as shown in following figure:
IP Notes Created by Sumit Jaiswar

 Since AJAX is essentially used for a partial update and asynchronous communication,
the AJAX model used for programming and it is not restricted for use with specific
data exchange format, specific programming language, or the specific
communication mechanism.

 Above diagram clarify that every user action generates an HTTP request that takes
the form of a JavaScript to call the AJAX engine.
 Responses to the user actions do not involve the trip back to the server as in the
classical Web application model. Instead, the AJAX Engine handles on its own, such
as data validation, some navigation and editing data in memory.
 If the AJAX Engine needs something from the server, like retrieving new data or
loading additional interface code, then the engine makes the asynchronous
interaction with the server using JavaScript and XMLHttpRequest object for
asynchronous data exchange.
 The engine’s interaction with the server does not interrupt the user’s interaction
with the application. In this way, the asynchronous communication is done with the
help of the AJAX engine.

Q. 20) What is JSX? Write JSX attributes with example.


Ans)
JSX, or JavaScript XML, is a syntax extension for JavaScript recommended by React for
describing what the UI should look like. It allows developers to write HTML elements and
components in a syntax that looks similar to XML or HTML, but it's actually a syntactic sugar
for function calls and object creation.
In JSX, you can use attributes to specify additional information or settings for HTML
elements or React components. Here's an example of JSX attributes:

const MyComponent = () => {


// JSX with attributes
IP Notes Created by Sumit Jaiswar

return (
<div className="container" id="main-container">
<h1 style={{ color: 'blue', fontSize: '24px' }}>Hello, JSX!</h1>
<input type="text" placeholder="Enter your name" onChange={(e) =>
console.log(e.target.value)} />
<button disabled={false} onClick={() => alert("Button clicked!")}>Click me</button>
</div>
);
};

// Render the component


ReactDOM.render(<MyComponent />, document.getElementById('root'));

In this example:
 The className attribute is used instead of class to set the CSS class of the div
element. This is because class is a reserved keyword in JavaScript.
 The id attribute sets the identifier of the div element.
 The style attribute is used to set inline styles for the h1 element. Note that the style
value is an object where CSS property names are camelCased.
 The onChange attribute is used with the input element to define a function that will
be called when the input value changes.
 The disabled attribute on the button element is used to enable or disable the
button.
 The onClick attribute on the button element defines a function that will be called
when the button is clicked.
Remember that JSX attributes are written in camelCase, similar to how they are in
JavaScript, and some attributes might have different names than their HTML counterparts
(e.g., className instead of class). The expressions inside curly braces {} allow you to embed
JavaScript expressions or variables within JSX.

Q. 21) Explain the structure of XML Documents with example.


Ans)
XML (eXtensible Markup Language):
XML is a markup language that is designed to store and transport data. It is a simple,
flexible, and human-readable format, making it suitable for representing structured data.
XML documents consist of elements, attributes, and text content, organized in a hierarchical
structure.
Structure of XML Documents:
1. XML Declaration:
 An optional declaration at the beginning of the document that specifies the
XML version and character encoding.

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


IP Notes Created by Sumit Jaiswar

2. Root Element:
 The outermost element that contains all other elements in the XML
document.

<root>
<!-- Other elements go here -->
</root>

3. Elements:
 Represent the structure of the data and can contain other elements,
attributes, and text content.
<book>
<title>Harry Potter and the Sorcerer's Stone</title>
<author>J.K. Rowling</author>
</book>

4. Attributes:
 Provide additional information about elements and are written within the
opening tag.
<book genre="fantasy">
<!-- ... -->
</book>

5. Text Content:
 The actual data or information stored within an element.

<title>Harry Potter and the Sorcerer's Stone</title>

6. Comments:
 Allow the inclusion of comments within the XML document.
<!-- This is a comment -->
7. Processing Instructions:
 Special instructions for applications processing the XML document.

<?xml-stylesheet type="text/xsl" href="style.xsl"?>

Example of an XML Document:


<?xml version="1.0" encoding="UTF-8"?>
<library>
<book>
<title>1984</title>
<author>George Orwell</author>
<genre>dystopian fiction</genre>
IP Notes Created by Sumit Jaiswar

<published>1949</published>
</book>
<book>
<title>To Kill a Mockingbird</title>
<author>Harper Lee</author>
<genre>fiction</genre>
<published>1960</published>
</book>
<!-- Additional books go here -->
</library>
In this example:
 The root element is <library>.
 The <book> elements represent individual books, each with <title>, <author>,
<genre>, and <published> child elements.
 The XML declaration specifies the version and encoding of the XML document.
 Comments (<!-- ... -->) provide human-readable explanations.
XML is commonly used for data interchange between systems, configuration files, and
representing hierarchical data structures. Its simplicity and extensibility make it a widely
adopted standard for various applications.

Q. 22) What is inheritance in CSS? Explain CSS Animation properties.


Ans)
Inheritance in CSS:
Inheritance in CSS refers to the mechanism by which certain property values are passed
from a parent element to its child elements within the document tree. When a style
property is applied to a parent element, that property can be inherited by its child elements
unless explicitly overridden.
Here are some key points about inheritance in CSS:
1. Inherited Properties:
 Not all properties are inherited. Only specific properties are designed to be
inherited by default, such as font properties, color, text alignment, etc.
2. Default Values:
 If a property is not inherited, the child elements will use their default values
for that property.
3. Overriding Inheritance:
 Child elements can override inherited properties by applying their own styles.
4. Inheritance Example:
body {
font-family: Arial, sans-serif;
color: #333;
}
IP Notes Created by Sumit Jaiswar

h1 {
/* Inherits font-family and color from body */
}

p{
/* Inherits font-family and color from body */
}

.special {
color: red; /* Overrides color inherited from body */
}

CSS Animation Properties:


CSS animations allow the gradual changing of an element's style from one set of CSS
properties to another. Animations in CSS are achieved using the @keyframes rule and
animation properties.
Here are some key CSS animation properties:
1. @keyframes Rule:
 Defines the animation behavior at different points in time. It allows you to
create custom animations.

@keyframes slideIn {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
2. animation-name:
 Specifies the name of the @keyframes rule that defines the animation.
.element {
animation-name: slideIn;
}
3. animation-duration:
 Specifies the duration of the animation in seconds or milliseconds.
.element {
animation-duration: 2s;
}
4. animation-timing-function:
 Defines how the animation progresses over time. It specifies the speed curve
of the animation.
.element {
animation-timing-function: ease-in-out;
IP Notes Created by Sumit Jaiswar

}
5. animation-delay:
 Specifies a delay before the animation starts.
.element {
animation-delay: 1s;
}
6. animation-iteration-count:
 Defines the number of times an animation should run.
.element {
animation-iteration-count: infinite;
}
7. animation-direction:
 Specifies whether the animation should play forward, backward, or alternate.
.element {
animation-direction: alternate;
}
8. animation-fill-mode:
 Defines what values are applied by the animation outside the time it is
executing.
.element {
animation-fill-mode: forwards;
}
9. animation-play-state:
 Allows the control of whether the animation is running or paused.
.element {
animation-play-state: running;
}
These properties, when used together, allow you to create smooth and visually appealing
animations in CSS. The @keyframes rule defines the animation steps, while the other
properties control the animation's duration, timing, delay, and other aspects.

Q. 23) Explain the steps to connect Java Application to Database using JDBC.
Ans)
Connecting a Java application to a database using JDBC (Java Database Connectivity)
involves several steps. JDBC is a Java-based API that allows Java applications to interact with
relational databases. Here are the general steps to connect a Java application to a database
using JDBC:
1. Download and Include JDBC Driver:
 Download the JDBC driver for the specific database you are using. Each
database vendor provides its own JDBC driver.
 Include the JDBC driver JAR file in your project's classpath. You can do this by
adding it to your project's build path or placing it in the "lib" directory.
2. Load JDBC Driver:
IP Notes Created by Sumit Jaiswar

 Load the JDBC driver using the Class.forName() method. This step is
necessary to register the driver with the DriverManager.
try {
Class.forName("com.databasevendor.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
 Replace "com.databasevendor.jdbc.Driver" with the actual driver class for
your database.
3. Create Database Connection:
 Establish a database connection using the DriverManager.getConnection()
method. You need to provide the database URL, username, and password.

String url =
"jdbc:your_database_type://your_database_host:your_port/your_database_name";
String username = "your_username";
String password = "your_password";

try (Connection connection = DriverManager.getConnection(url, username, password)) {


// Database connection established
} catch (SQLException e) {
e.printStackTrace();
}
 Replace the placeholders in the url variable with your actual database details.
4. Create Statement or PreparedStatement:
 Create a Statement or PreparedStatement object for executing SQL queries.

try (Connection connection = DriverManager.getConnection(url, username, password)) {


Statement statement = connection.createStatement();
// or
// PreparedStatement preparedStatement =
connection.prepareStatement("your_sql_query_here");
} catch (SQLException e) {
e.printStackTrace();
}
5. Execute SQL Queries:
 Use the created Statement or PreparedStatement to execute SQL queries
against the database.

try (Connection connection = DriverManager.getConnection(url, username, password);


Statement statement = connection.createStatement()) {

String sqlQuery = "SELECT * FROM your_table";


ResultSet resultSet = statement.executeQuery(sqlQuery);
IP Notes Created by Sumit Jaiswar

// Process the ResultSet


while (resultSet.next()) {
// Retrieve data from the result set
}

} catch (SQLException e) {
e.printStackTrace();
}
6. Handle Results:
 Process the results obtained from the executed queries.
7. Close Resources:
 Close the ResultSet, Statement, and Connection objects to release resources.
try {
// Close ResultSet, Statement, and Connection
} catch (SQLException e) {
e.printStackTrace();
}
 Use try-with-resources or explicitly close the resources in a finally block.
Remember to handle exceptions appropriately in your code. Additionally, it's recommended
to use connection pooling for better performance in production environments.

Q. 24) Explain the features of PHP and Write a PHP Program to print Factorial of Number.
Ans)
PHP (Hypertext Preprocessor) is a server-side scripting language widely used for web
development. Here are some key features of PHP:
1. Easy to Learn: PHP syntax is similar to C and other programming languages, making
it easy for developers to learn and use.
2. Open Source: PHP is open-source and freely available. It has a large and active
community of developers contributing to its growth and improvement.
3. Platform Independence: PHP is platform-independent, which means it can run on
various operating systems such as Windows, Linux, macOS, etc.
4. Web Integration: PHP is designed for web development and can be easily embedded
into HTML. It is often used to create dynamic web pages.
5. Database Support: PHP supports a wide range of databases, including MySQL,
PostgreSQL, Oracle, and others. It facilitates easy database integration.
6. Extensive Library Support: PHP has a vast collection of libraries and frameworks,
such as Laravel, Symfony, and CodeIgniter, that help developers build robust and
scalable applications.
7. Security: PHP has built-in security features, and with proper coding practices,
developers can create secure web applications. Additionally, it supports encryption
and authentication mechanisms.
IP Notes Created by Sumit Jaiswar

8. Scalability: PHP applications can scale from small websites to large enterprise-level
applications, making it suitable for various project sizes.
Now, let's write a simple PHP program to calculate the factorial of a number:

<?php
function calculateFactorial($number) {
if ($number == 0 || $number == 1) {
return 1;
} else {
return $number * calculateFactorial($number - 1);
}
}

// Input number for which factorial needs to be calculated


$number = 5;

// Call the function to calculate factorial


$factorial = calculateFactorial($number);

// Display the result


echo "Factorial of $number is: $factorial";
?>

In this example:
 The calculateFactorial function is a recursive function to calculate the factorial of a
given number.
 We set the value of $number to 5 for demonstration purposes, but you can change it
to any non-negative integer.
 The result is then displayed using echo.

Q. 25) Explain Document Object Model in detail.


Ans)
The Document Object Model (DOM) is a programming interface and representation of
structured documents. It primarily applies to HTML and XML documents but can be used
with other markup languages as well. The DOM represents a document as a tree-like
structure, where each node in the tree corresponds to a part of the document. This
hierarchical structure allows developers to manipulate and interact with the content,
structure, and style of a document through programming languages like JavaScript.
Here are the key aspects of the Document Object Model:
1. Tree Structure:
 The DOM represents an HTML or XML document as a tree structure.
 Each node in the tree corresponds to a part of the document, such as
elements, attributes, and text.
2. Node Types:
IP Notes Created by Sumit Jaiswar

 There are various types of nodes in the DOM, including elements, attributes,
text, comments, and more.
 Elements represent the HTML or XML tags, attributes represent the
properties of elements, text nodes represent the text content, etc.
3. Hierarchy:
 The DOM hierarchy reflects the hierarchical structure of the document.
 Elements are nested inside each other, creating parent-child relationships.
4. API for Manipulation:
 The DOM provides an API (Application Programming Interface) that allows
developers to manipulate the document dynamically.
 Common operations include adding, modifying, or deleting elements and
attributes.
5. Dynamic Interaction:
 Developers can dynamically update the content and structure of a document
in response to user actions or other events.
 This dynamic interaction is a key feature of client-side web development,
often done using JavaScript.
6. Language Agnostic:
 While DOM is commonly used with JavaScript in web browsers, it is not
limited to a specific programming language.
 Different programming languages can interact with the DOM through
language-specific bindings or APIs.

7. Browser Integration:
 In web development, browsers provide a built-in implementation of the
DOM.
 JavaScript can be used to access and manipulate the DOM in a web page,
making it possible to create dynamic and interactive user interfaces.
8. Traversal and Manipulation:
 Developers can traverse the DOM tree to navigate through nodes and access
their properties.
 Nodes can be added, removed, or modified, enabling dynamic updates to the
document.
9. Event Handling:
 The DOM enables the registration and handling of events, such as mouse
clicks or keyboard input.
 Events trigger specific actions, allowing developers to create responsive and
interactive web applications.
In summary, the Document Object Model provides a structured and standardized way to
represent and interact with documents in web development. It plays a crucial role in
enabling the dynamic and interactive nature of modern web applications.

Q. 26) Explain <audio> and <video> elements in HTML5 with example.


Ans)
IP Notes Created by Sumit Jaiswar

The <audio> and <video> elements are part of the HTML5 specification and are used to
embed audio and video content into web pages. These elements provide a standardized
way to include multimedia content without relying on third-party plugins like Flash. Here's
an explanation of each element along with examples:
<audio> Element:
The <audio> element is used to embed audio content on a web page. It supports various
audio formats, and the browser will automatically choose the appropriate format based on
its capabilities. You can include multiple source elements to provide fallbacks for different
formats.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Audio Example</title>
</head>
<body>

<audio controls>
<source src="audio/sample.mp3" type="audio/mp3">
<source src="audio/sample.ogg" type="audio/ogg">
Your browser does not support the audio tag.
</audio>

</body>
</html>
In this example:
 The controls attribute adds playback controls (play, pause, volume, etc.) to the audio
player.
 Two <source> elements provide different audio formats (mp3 and ogg). The browser
will choose the first format it supports.

<video> Element:
The <video> element is used to embed video content on a web page. Like <audio>, it
supports multiple source elements to provide fallbacks for different video formats.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video Example</title>
</head>
IP Notes Created by Sumit Jaiswar

<body>

<video width="640" height="360" controls>


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

</body>
</html>
In this example:
 The width and height attributes set the dimensions of the video player.
 The controls attribute adds playback controls to the video player.
 Two <source> elements provide different video formats (mp4 and webm). The
browser will choose the first format it supports.
It's important to note that the actual supported formats may vary between browsers, so
providing fallbacks in multiple formats increases the likelihood that the content will be
playable across different platforms.

Q. 27) Write an external style 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 heading will have red background color.
iii. Background color of alternate paragraphs are different.
iv. The hyperline on the webpage will not have underline.
Ans)
External stylesheet (style.css) that includes the specified styling rules. Additionally, a simple
HTML code that links to this stylesheet.
style.css (External Stylesheet):
/* Resetting default margin and padding */
body, h1, h2, p {
margin: 0;
padding: 0;
}

/* Setting the background image for the entire webpage */


body {
background-image: url('img1.jpg');
background-size: cover;
background-repeat: no-repeat;
}

/* Styling the table heading with red background color */


table th {
IP Notes Created by Sumit Jaiswar

background-color: red;
}

/* Setting different background colors for alternate paragraphs */


p:nth-child(even) {
background-color: #e0e0e0; /* Light Gray */
}

p:nth-child(odd) {
background-color: #f0f0f0; /* Lighter Gray */
}

/* Removing underline from hyperlinks */


a{
text-decoration: none;
}

index.html (HTML Code linking to the Stylesheet):


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Styled Webpage</title>

<!-- Linking to the external stylesheet -->


<link rel="stylesheet" href="style.css">
</head>
<body>

<h1>This is a Heading</h1>

<table>
<thead>
<tr>
<th>Table Heading 1</th>
<th>Table Heading 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1, Cell 1</td>
<td>Row 1, Cell 2</td>
</tr>
IP Notes Created by Sumit Jaiswar

<tr>
<td>Row 2, Cell 1</td>
<td>Row 2, Cell 2</td>
</tr>
</tbody>
</table>

<p>This is a paragraph with the default background color.</p>


<p>This is another paragraph with a different background color.</p>
<p>Yet another paragraph with a different background color.</p>

<a href="#">This is a hyperlink without underline.</a>

</body>
</html>

Output.

This is a Heading
Table Heading 1 Table Heading 2

Row 1, Cell 1 Row 1, Cell 2

Row 2, Cell 1 Row 2, Cell 2


This is a paragraph with the default background color.
This is another paragraph with a different background color.
Yet another paragraph with a different background color.
This is a hyperlink without underline.

Q. 28) Write code to process online Alumni information for your college. Create form to
get name, address, date of birth, and email id. 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).
Ans)
HTML form that collects Alumni information and JavaScript code for validation. This example
includes checks for empty fields, a valid email format, and age validation based on the date
of birth.
index.html (Alumni Information Form):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
IP Notes Created by Sumit Jaiswar

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


<title>Alumni Information Form</title>
<link rel="stylesheet" href="style.css">
</head>
<body>

<h2>Alumni Information Form</h2>

<form id="alumniForm" onsubmit="return validateForm()">


<label for="name">Name:</label>
<input type="text" id="name" name="name" required>

<label for="address">Address:</label>
<textarea id="address" name="address" required></textarea>

<label for="dob">Date of Birth:</label>


<input type="date" id="dob" name="dob" required>

<label for="email">Email ID:</label>


<input type="email" id="email" name="email" required>

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


</form>

<script src="script.js"></script>
</body>
</html>

script.js (JavaScript Validation):

function validateForm() {
var name = document.getElementById('name').value;
var address = document.getElementById('address').value;
var dob = document.getElementById('dob').value;
var email = document.getElementById('email').value;

// Check if all fields are filled


if (name === "" || address === "" || dob === "" || email === "") {
alert("Please fill in all the fields.");
return false;
}

// Check for a valid email format


var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
IP Notes Created by Sumit Jaiswar

if (!emailRegex.test(email)) {
alert("Please enter a valid email address.");
return false;
}

// Check age (>=22 years)


var dobDate = new Date(dob);
var today = new Date();
var age = today.getFullYear() - dobDate.getFullYear();

if (today.getMonth() < dobDate.getMonth() || (today.getMonth() ===


dobDate.getMonth() && today.getDate() < dobDate.getDate())) {
age--;
}

if (age < 22) {


alert("Alumni must be at least 22 years old.");
return false;
}

// If all validations pass, the form can be submitted


return true;
}

This JavaScript code is embedded directly in the HTML file for simplicity. However, in a
production environment, you may consider separating the JavaScript code into an external
file.

Q. 29) Create a well formed XML document to maintain Library catalogue. It should
contain the name of the book, author, publisher and year of publishing, format it in
tabular manner using XSLT.
Ans)
Below is an example of a well-formed XML document for a Library catalog and an
accompanying XSLT stylesheet to format it in a tabular manner.

XML Document (library_catalog.xml):


<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="library_catalog.xslt"?>

<libraryCatalog>
<book>
<name>Introduction to Algorithms</name>
<author>Thomas H. Cormen</author>
<publisher>The MIT Press</publisher>
IP Notes Created by Sumit Jaiswar

<year>2009</year>
</book>
<book>
<name>Database Management Systems</name>
<author>Raghu Ramakrishnan</author>
<publisher>McGraw-Hill</publisher>
<year>2002</year>
</book>
<!-- Add more book entries as needed -->
</libraryCatalog>

XSLT Stylesheet (library_catalog.xslt):


<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<head>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h2>Library Catalog</h2>
<table>
<tr>
<th>Name</th>
<th>Author</th>
<th>Publisher</th>
<th>Year of Publishing</th>
</tr>
<xsl:apply-templates select="libraryCatalog/book" />
</table>
IP Notes Created by Sumit Jaiswar

</body>
</html>
</xsl:template>

<xsl:template match="book">
<tr>
<td><xsl:value-of select="name" /></td>
<td><xsl:value-of select="author" /></td>
<td><xsl:value-of select="publisher" /></td>
<td><xsl:value-of select="year" /></td>
</tr>
</xsl:template>

</xsl:stylesheet>

This XSLT stylesheet transforms the XML document into an HTML table, displaying the
library catalog information in a tabular format. You can apply this XSLT to the XML
document using a suitable XSLT processor or a web browser that supports XSLT processing.

5 Marks Each Questions:

Q. 1) What is the difference between Class selector and Id selector?


Ans)
Feature Class Selector ID Selector
Syntax Starts with a period (.) followed by the Starts with a hash (#) followed by
class name. the ID name.
Applicability Can be applied to multiple HTML Should be unique and used for a
elements on a page. specific HTML element.
Example .example-class { styles; } #example-id { styles; }
Specificity Less specific than ID selectors. More specific than class
selectors.
Usage Suitable for styling multiple elements Used when styling a specific,
with a common characteristic. unique element.
It's important to note that while class selectors can be applied to multiple elements, ID
selectors should be unique within a page, and it's generally recommended to use them
sparingly due to their high specificity.

Q. 2) Explain built-in objects in JavaScript.


Ans)
Built-in objects in JavaScript are predefined objects that are part of the JavaScript language
and provide essential functionalities. They are readily available for use in any JavaScript
program and cover a wide range of tasks. Here's an explanation in bullet points:
1. Object Types:
IP Notes Created by Sumit Jaiswar

 JavaScript has several built-in object types that serve various purposes, such
as manipulating strings, numbers, arrays, dates, and more.
2. Global Objects:
 Some built-in objects are available globally, meaning they can be accessed
from anywhere in a JavaScript program without the need for explicit
instantiation.
3. Examples of Built-in Objects:
 String Object: Provides methods for working with strings.

let str = "Hello, World!";


console.log(str.length); // Outputs: 13

 Array Object: Offers methods for manipulating arrays.

let arr = [1, 2, 3, 4, 5];


console.log(arr.length); // Outputs: 5

 Math Object: Provides mathematical operations and constants.

let result = Math.sqrt(25); // Calculates the square root


console.log(result); // Outputs: 5

 Date Object: Handles date and time operations.

let today = new Date();


console.log(today.getFullYear()); // Outputs the current year

4. Utility Objects:
 In addition to data manipulation, JavaScript also has utility objects like Math
for mathematical operations and Date for handling dates.
5. Custom Objects:
 While built-in objects cover many common use cases, developers can also
create custom objects to encapsulate related data and functions according to
their specific needs.
Q. 3) What is session in servlet and list different ways to handle it.
Ans)
In Java Servlets, a session refers to a mechanism for maintaining state information about a
user across multiple requests and responses. It enables the server to recognize a specific
user and associate data with that user throughout their interaction with a web application.
Sessions are essential for storing user-specific information and maintaining continuity during
a user's visit to a website.
Different ways to handle sessions in Servlets:
1. Cookies:
IP Notes Created by Sumit Jaiswar

 Description: Cookies are small pieces of data stored on the client's machine.
Servlets can use cookies to store a unique session identifier, allowing the
server to associate subsequent requests with the correct session.
 Pros: Widely supported, transparent to the user.
 Cons: Limited storage capacity, potential security concerns.
2. URL Rewriting:
 Description: Session information is appended to URLs as parameters. Each
link on the web page includes the session ID, and the server uses it to identify
the associated session.
 Pros: No reliance on client-side storage mechanisms.
 Cons: Alters URL structure, potential security concerns.
3. Hidden Form Fields:
 Description: Session data is stored in hidden form fields within HTML forms.
When the form is submitted, the session information is sent back to the
server.
 Pros: No reliance on cookies, transparent to the user.
 Cons: Limited to form submissions.
4. URL Encoding:
 Description: Similar to URL rewriting, session information is encoded directly
into the URLs. The encoded data is decoded by the server to identify the
session.
 Pros: No reliance on cookies, transparency.
 Cons: Can impact URL readability, potential security concerns.
5. Session Tracking API (HttpSession):
 Description: Java Servlets provide a built-in session tracking API through the
HttpSession interface. It allows developers to store and retrieve session data
on the server side. The servlet container manages session tracking using
cookies or URL rewriting internally.
 Pros: Standardized, easy to use, supports server-side storage.
 Cons: Requires client-side support.
Each method has its strengths and weaknesses, and the choice depends on factors like
security requirements, client capabilities, and developer preferences. The HttpSession
interface is a common and recommended approach for handling sessions in Java Servlets.

Q. 4) Give characteristics of RIA.


Ans)
Rich Internet Applications (RIAs) are web applications that possess characteristics and
features typically associated with desktop applications. Here are five key characteristics of
RIAs:
1. User Interface Interactivity:
 RIAs provide a highly interactive and responsive user interface. Users can
experience smooth and dynamic interactions, including drag-and-drop
functionality, animated transitions, and real-time updates without requiring
page reloads.
IP Notes Created by Sumit Jaiswar

2. Rich Media Content:


 RIAs often incorporate rich media elements such as audio, video, and high-
quality graphics. This enhances the overall user experience and allows for the
presentation of content in a more engaging and visually appealing manner.
3. Client-Side Processing:
 RIAs shift a significant portion of processing tasks to the client side, reducing
the need for frequent server requests. This results in faster response times
and a more seamless user experience, especially when dealing with data
manipulation and form validation.
4. Asynchronous Communication:
 RIAs leverage asynchronous communication with the server, allowing them
to fetch and update data in the background without requiring a full page
reload. This approach, often facilitated by technologies like AJAX
(Asynchronous JavaScript and XML), contributes to a more responsive
application.
5. Cross-Browser Compatibility:
 RIAs are designed to be compatible with multiple web browsers, ensuring a
consistent experience across different platforms. This characteristic is crucial
for reaching a broad user base and providing a uniform user experience
regardless of the browser being used.
These characteristics collectively contribute to the development of web applications that
closely resemble and, in some cases, surpass the user experience offered by traditional
desktop applications. RIAs are often built using technologies such as JavaScript frameworks
(e.g., Angular, React, or Vue.js), Adobe Flash (though its usage has declined), and
HTML5/CSS3 for enhanced multimedia capabilities.

Q. 5) How to define variable in PHP and explain scope of variables.


Ans)
Defining Variables in PHP: In PHP, variables are declared using the dollar sign ($) followed
by the variable name. Variable names are case-sensitive, and they must start with a letter or
an underscore. Subsequent characters can be letters, numbers, or underscores. Here's an
example of defining variables in PHP:
<?php
$name = "John";
$age = 25;
$isStudent = true;
?>

Scope of Variables in PHP:


1. Global Scope:
IP Notes Created by Sumit Jaiswar

 Variables declared outside of any function or class have a global scope. They
can be accessed from any part of the script, including inside functions.

<?php
$globalVar = "I am a global variable";

function myFunction() {
global $globalVar;
echo $globalVar; // Accessing the global variable inside a function
}

myFunction();
?>
2. Local Scope:
 Variables declared inside a function have a local scope. They are only
accessible within that specific function.
<?php
function myFunction() {
$localVar = "I am a local variable";
echo $localVar;
}

myFunction();
// echo $localVar; // This would result in an error as $localVar is not accessible
outside the function.
?>
3. Static Variables:
 When a variable is declared as static inside a function, it retains its value
between function calls. It has local scope but persists across different calls to
the function.
<?php
function counter() {
static $count = 0;
$count++;
echo $count;
}

counter(); // Outputs 1
counter(); // Outputs 2
counter(); // Outputs 3
?>
4. Superglobal Variables:
IP Notes Created by Sumit Jaiswar

 PHP provides predefined global arrays known as superglobals that are


accessible from any part of the script. Examples include $_GET, $_POST,
$_SESSION, etc.

<?php
$userId = $_GET['id']; // Accessing a value from the superglobal $_GET array
echo $userId;
?>
Understanding variable scope is crucial for writing maintainable and error-free PHP code.
Variables should be used in the appropriate scope to ensure proper data encapsulation and
avoid unintended side effects.

Q. 6) What is the use of XMLHttpRequest object? Explain methods that are used to send
request to server using AJAX.
Ans)
The XMLHttpRequest object is a core component of Asynchronous JavaScript and XML
(AJAX), a technique used to perform asynchronous communication between a web browser
and a web server. It allows web pages to dynamically update content without requiring a full
page reload. The XMLHttpRequest object is supported by modern web browsers and is a
key part of enabling asynchronous requests.
Use of XMLHttpRequest object: The primary use of the XMLHttpRequest object is to send
HTTP requests to a server and handle the server's response asynchronously. This enables
the development of dynamic and responsive web applications by fetching data or updating
parts of a web page without reloading the entire document.
Methods used to send requests to the server using AJAX:
1. open(method, url, async, user, password) Method:
 This method initializes a new request. It specifies the type of HTTP method
(GET, POST, etc.), the URL to send the request to, and whether the request
should be asynchronous (true for asynchronous, false for synchronous).

var xhr = new XMLHttpRequest();


xhr.open('GET', 'https://example.com/data', true);

2. setRequestHeader(name, value) Method:


 This method sets the value of an HTTP request header. It is often used to set
headers such as Content-Type or custom headers.

xhr.setRequestHeader('Content-Type', 'application/json');

3. send(data) Method:
 This method sends the actual HTTP request. For POST requests, data can be
included in the request body.
IP Notes Created by Sumit Jaiswar

xhr.send();
// or
xhr.send(JSON.stringify({ key: 'value' }));

4. onreadystatechange Event:
 This event is triggered whenever the readyState property of the
XMLHttpRequest object changes. Developers can define a function to handle
different states of the request, such as when the request is complete
(readyState is 4) and the response is ready.

xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};

5. abort() Method:
 This method aborts the current HTTP request.

xhr.abort();

These methods collectively allow developers to create and configure an XMLHttpRequest


object, send requests to a server, and handle the server's response asynchronously. AJAX,
facilitated by the XMLHttpRequest object, has become a fundamental technology for
building modern, interactive web applications.

Q. 7) What are the benefits of using JSON over XML data?


Ans)
Using JSON (JavaScript Object Notation) over XML (eXtensible Markup Language) for data
interchange in web applications offers several advantages. Here are five key benefits:
1. Readability and Conciseness:
 JSON data is more human-readable and concise than XML. JSON uses a
lightweight syntax with key-value pairs, making it easier for developers to
read and write. It reduces unnecessary verbosity, leading to more compact
data representations.
2. Parsing and Data Processing:
 JSON is easier and faster to parse in JavaScript compared to XML. Since JSON
can be directly mapped to JavaScript objects, parsing is a native operation,
resulting in quicker and more efficient data processing on the client side.
3. Data Structure Representation:
 JSON directly represents data structures as objects and arrays, mirroring the
native data structures in many programming languages. This natural
representation simplifies data manipulation and integration with
IP Notes Created by Sumit Jaiswar

programming languages, reducing the need for complex parsing and


conversion steps.
4. Efficiency in Network Transfer:
 JSON data tends to be smaller in size compared to equivalent XML data. This
smaller payload is beneficial for network efficiency, especially in scenarios
with limited bandwidth or when optimizing for faster data transfer. The
reduced data size can contribute to improved application performance.
5. Native JavaScript Support:
 JSON is native to JavaScript, meaning JavaScript has built-in support for
parsing and generating JSON data. This native support simplifies data
handling in web applications, eliminating the need for additional libraries or
parsers. In contrast, while XML is widely supported, processing XML data in
JavaScript often requires additional steps and libraries.
In summary, JSON is preferred over XML in many web development scenarios due to its
readability, efficiency in data transfer, native support in JavaScript, and a more natural
representation of data structures. However, the choice between JSON and XML may also
depend on specific project requirements, existing infrastructure, and interoperability needs.

Q. 8) Write a program in JSP to display system date and time.


Ans)
In JavaServer Pages (JSP), you can use the built-in java.util.Date class to obtain the system
date and time. Here's a simple example program that displays the system date and time:
<%@ page import="java.util.Date" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>System Date and Time</title>
</head>
<body>

<h2>System Date and Time:</h2>

<%
// Get the current date and time
Date currentDate = new Date();

// Format the date and time


java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("dd-MM-
yyyy HH:mm:ss");
String formattedDate = dateFormat.format(currentDate);
%>
IP Notes Created by Sumit Jaiswar

<p>The current date and time is: <%= formattedDate %></p>

</body>
</html>
In this example:
1. The java.util.Date class is imported to work with date and time.
2. The Date class is used to get the current date and time.
3. The SimpleDateFormat class is used to format the date and time according to a
specified pattern ("dd-MM-yyyy HH:mm:ss" in this case).
4. The formatted date is then displayed on the JSP page using <%= formattedDate %>.
Save this code in a .jsp file and deploy it to a servlet container or application server that
supports JSP, such as Apache Tomcat. When you access the JSP page in a web browser, it
will display the current system date and time.

Q. 9) List and explain different features of React.


Ans)
React is a popular JavaScript library for building user interfaces, particularly for single-page
applications where dynamic and responsive UIs are crucial. Here are different features of
React along with brief explanations:
1. Declarative Syntax:
 React uses a declarative syntax, allowing developers to describe the desired
UI state and React takes care of updating the DOM to match that state. This
makes the code more predictable and easier to understand.
2. Component-Based Architecture:
 React follows a component-based architecture where UIs are broken down
into reusable components. Each component manages its own state and can
be composed to build complex UIs. This promotes code reusability and
maintainability.
3. Virtual DOM:
 React uses a virtual DOM (Document Object Model) to efficiently update the
actual DOM. Instead of directly manipulating the DOM for every state
change, React compares the virtual DOM with the actual DOM and only
updates the necessary parts. This leads to improved performance.
4. Unidirectional Data Flow:
 React enforces a unidirectional data flow. Data flows in a single direction
from parent to child components. This one-way data binding simplifies data
management and makes it easier to understand how changes in state will
affect the UI.
5. JSX (JavaScript XML):
 React uses JSX, a syntax extension that allows mixing HTML-like tags with
JavaScript code. JSX makes the code more readable and concise. It is then
transformed into regular JavaScript using a transpiler like Babel before being
executed in the browser.
IP Notes Created by Sumit Jaiswar

6. React Hooks:
 Introduced in React 16.8, hooks are functions that allow developers to use
state and other React features in functional components. This simplifies the
creation of components by allowing them to have state and lifecycle methods
without using class components.
7. Reusable Components:
 React encourages the creation of reusable components, which can be shared
and composed to build complex UIs. This modularity improves code
organization and maintainability.
8. React Router:
 React Router is a library for handling navigation and routing in React
applications. It enables the creation of single-page applications with multiple
views, allowing for a more seamless user experience.
9. State Management (Context API):
 React provides a Context API that allows for efficient state management and
sharing state between components without the need for props drilling. This is
particularly useful for managing global state in large applications.
10. Ecosystem and Community:
 React has a vibrant ecosystem and a large, active community. There is an
extensive set of libraries, tools, and resources available to complement and
enhance React development.
These features collectively contribute to React's popularity and its effectiveness in building
scalable and maintainable web applications.
Q. 10) List and Explain Session Tracking Techniques.
Ans)
Session tracking is a mechanism used in web development to maintain state information
about a user across multiple requests. It allows web applications to recognize and associate
data with a specific user during their visit. Several techniques for session tracking exist, each
with its own advantages and considerations. Here are five common session tracking
techniques:
1. Cookies:
 Explanation: Cookies are small pieces of data stored on the client's browser.
In session tracking, a unique session identifier is typically stored in a cookie.
The server uses this identifier to associate subsequent requests with the
correct session data.
 Advantages: Widely supported, easy to implement.
 Considerations: Limited storage capacity, reliance on client-side support.
2. URL Rewriting:
 Explanation: Session information is appended to URLs as parameters. Each
link on the web page includes the session ID, and the server uses it to identify
the associated session.
 Advantages: No reliance on client-side storage.
 Considerations: Alters URL structure, potential security concerns.
3. Hidden Form Fields:
IP Notes Created by Sumit Jaiswar

 Explanation: Session data is stored in hidden form fields within HTML forms.
When the form is submitted, the session information is sent back to the
server.
 Advantages: No reliance on cookies, transparent to the user.
 Considerations: Limited to form submissions.
4. URL Encoding:
 Explanation: Similar to URL rewriting, session information is encoded directly
into the URLs. The encoded data is decoded by the server to identify the
session.
 Advantages: No reliance on cookies, transparency.
 Considerations: Can impact URL readability, potential security concerns.
5. Session Management using HttpSession (Server-Side):
 Explanation: In server-side session management, a unique session ID is
generated and stored on the server. This session ID is then associated with
the user's session data on the server.
 Advantages: No reliance on client-side storage, secure.
 Considerations: May require additional server resources, may be less
scalable.
Each session tracking technique has its own strengths and weaknesses, and the choice
depends on factors such as security requirements, client capabilities, and developer
preferences. It's common for web applications to use a combination of these techniques
based on the specific needs and constraints of the project.

Q. 11) Differentiate between HTML and HTML5.


Ans) Differentiation between HTML and HTML5:
Feature HTML HTML5
DOCTYPE Requires detailed DOCTYPE Simplified to <!DOCTYPE html>.
Declaration declaration.
Syntax Relatively strict syntax, More lenient syntax, supports self-
requires explicit closing closing tags.
tags.
New Semantic Lacks specific semantic Introduces new semantic elements for
Elements elements like <header>, better document structure.
<nav>, etc.
Multimedia Limited multimedia support, Native support for <audio> and <video>
Support often relies on third-party elements, eliminating the need for
plugins. plugins.
Form Input Types Limited form input types Introduces new form input types (e.g.,
and attributes. email, url, tel) and attributes (e.g.,
placeholder, required).
APIs and Features Limited support for modern Incorporates new APIs and features like
APIs and features. Geolocation, Web Storage, WebSocket,
and Canvas.
Cross-browser May require additional Offers improved cross-browser
IP Notes Created by Sumit Jaiswar

Compatibility scripting for modern compatibility and native support for


features. modern web features.
HTML5 represents an evolution of the traditional HTML, introducing new elements,
attributes, and features that enhance the development of web applications and provide a
more standardized and efficient approach to structuring content on the web.

Q. 12) What are cookies? And how do cookies work in servlets?


Ans)
Cookies: Cookies are small pieces of data that are stored on the client's machine by a web
browser. They are commonly used to track and store information about the user's
interactions with a website. Cookies are sent between the client and the server with each
HTTP request, allowing the server to recognize the user and maintain state information
across multiple requests.
How Cookies Work in Servlets: In Java Servlets, cookies are used to store and retrieve
information about the client's session. Here's a brief explanation of how cookies work in
servlets:
1. Creating Cookies:
 In a servlet, you can create cookies using the Cookie class. Cookies are added
to the response object, and they are sent to the client along with the
response.

Cookie userCookie = new Cookie("username", "john_doe");


response.addCookie(userCookie);

2. Sending Cookies to the Client:


 The addCookie() method is used to include the cookie in the response.
Cookies are sent to the client as part of the HTTP response headers.
3. Client-Side Storage:
 Once received by the client, cookies are stored locally on the user's machine.
They can be viewed and managed through the browser's settings.
4. Including Cookies in Subsequent Requests:
 With each subsequent HTTP request to the server (when the user visits a new
page or performs an action), the browser automatically includes the relevant
cookies in the request headers.
5. Reading Cookies in Servlet:
 In subsequent requests, servlets can read the cookies sent by the client using
the request.getCookies() method.

Cookie[] cookies = request.getCookies();


if (cookies != null) {
for (Cookie cookie : cookies) {
String name = cookie.getName();
String value = cookie.getValue();
// Process the cookie data
IP Notes Created by Sumit Jaiswar

}
}
6. Session Tracking:
 Cookies are often used for session tracking. A unique session identifier stored
in a cookie allows the server to associate subsequent requests with the
correct session, enabling the maintenance of user-specific information across
multiple pages.
While cookies are a widely used mechanism for maintaining state in web applications, it's
important to note that they have some limitations, such as limited storage capacity and
potential security concerns. Additionally, privacy regulations may impact how cookies are
used and stored.

You might also like