Ilovepdf Merged
Ilovepdf Merged
- Password validation (Practice codes with different conditions) Console.log(validatePassword(“P@ssword1”)); // Output: Password is valid.
- Form validation (Practice codes with different conditions)
Console.log(validatePassword(“password”)); // Output: Password must contain at least one
- Event handling
uppercase letter.
- Exception handling
2. Form Validation
Ans- JavaScript Validation Tasks with Practice Examples
Task: Validate a form to ensure all required fields are filled and match specific conditions.
1. Password Validation
Example Code:
Task: Validate a password based on different conditions like length, special characters, and mixed case.
<form id=”myForm”>
Example Code:
<label for=”username”>Username:</label>
Function validatePassword(password) {
<input type=”text” id=”username” name=”username” required><br>
Const minLength = 8;
<label for=”email”>Email:</label>
Const hasUpperCase = /[A-Z]/.test(password);
<input type=”email” id=”email” name=”email” required><br>
Const hasLowerCase = /[a-z]/.test(password);
<label for=”password”>Password:</label>
Const hasNumber = /\d/.test(password);
<input type=”password” id=”password” name=”password” required><br>
Const hasSpecialChar = /[!@#$%^&*]/.test(password);
<button type=”button” onclick=”validateForm()”>Submit</button>
If (password.length < minLength) {
</form>
Return “Password must be at least 8 characters long.”;
<script>
} else if (!hasUpperCase) {
Function validateForm() {
Return “Password must contain at least one uppercase letter.”;
Const username = document.getElementById(“username”).value.trim();
} else if (!hasLowerCase) {
Const email = document.getElementById(“email”).value.trim();
Return “Password must contain at least one lowercase letter.”;
Const password = document.getElementById(“password”).value;
} else if (!hasNumber) {
If (!username) {
Return “Password must contain at least one number.”;
Alert(“Username is required.”);
} else if (!hasSpecialChar) {
Return false;
Return “Password must contain at least one special character (!@#$%^&*).”;
}
} else {
Const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
Return “Password is valid.”;
If (!emailPattern.test(email)) {
}
Alert(“Please enter a valid email.”);
}
Return false;
Alert(passwordMessage); If (b === 0) {
} }
</script> }
3. Event Handling }
Task: Implement event handling for various user interactions. // Example usage
<button id=”clickButton”>Click Me</button> Console.log(divideNumbers(10, 0)); // Output: Error: Division by zero is not allowed.
<input type=”text” id=”hoverInput” placeholder=”Hover over me”> Console.log(divideNumbers(10, “a”)); // Output: Error: Inputs must be numbers.
<p id=”output”></p>
<script> 7. What is AJAX? Explain AJAX Web Application model and compare it With Traditional Application web
model with neat diagrams.
Document.getElementById(“clickButton”).addEventListener(“click”, () => {
Ans- Imagine browsing a website and being able to submit a form, load new content, or update
Document.getElementById(“output”).innerText = “Button was clicked!”;
information without having to refresh the entire page. That’s the magic of AJAX. Asynchronous JavaScript
}); and XML (AJAX) is a web development technique that allows web pages to communicate with a web server
asynchronously, meaning it can send and receive data in the background without interfering with the
Document.getElementById(“hoverInput”).addEventListener(“mouseover”, () => { user’s interaction on the page. This dynamic approach to web development has transformed the way we
Document.getElementById(“output”).innerText = “Mouse is hovering over the input!”; interact with websites, making them more responsive, interactive, and user-friendly.
</script> The AJAX web application model consists of four main components: the user interface, the
XMLHttpRequest object, the server, and the data format.
4. Exception Handling
User Interface: The user interacts with the web application through the user interface, which is typically
Task: Handle errors gracefully using try…catch in JavaScript. built using HTML, CSS, and JavaScript.
Example Code: XMLHttpRequest Object: The XMLHttpRequest object is a built-in JavaScript object that enables
Function divideNumbers(a, b) { communication between the web browser and the server. It allows the web page to send requests to the
server and receive responses asynchronously, without interrupting the user’s interaction with the page.
Try {
Server: The server processes the requests sent by the web page and generates responses. It can be any
server-side technology, such as PHP, Java, or Python, that can handle HTTP requests.
Data Format: The data exchanged between the web page and the server is typically in XML or JSON format.
XML (eXtensible Markup Language) is a markup language that structures data, while JSON (JavaScript
Object Notation) is a lightweight data interchange format based on JavaScript syntax.
Comparison Between Ajax Web Application Model and Traditional Application Model
Animation Property:
CSS Animations are essential for controlling the movement and appearance of elements on web pages.
They consist of defining animation sequences using @keyframes and applying these sequences to
elements using various animation properties.
CSS Animations change the appearance and behavior of various elements in web pages. They are defined
using the @keyframes rule, which specifies the animation properties of the element and the specific time
intervals at which those properties should change.
@keyframes- The @keyframes rule in CSS is used to specify the animation rule.
Animation-name- It is used to specify the name of the @keyframes describing the animation.
Animation-duration- It is used to specify the time duration it takes animation to complete one cycle. <style>
Animation-timing-function- It specifies how animations make transitions through keyframes. There are .gfg1 {
several presets available in CSS which are used as the value for the animation-timing-function like linear,
Font-size: 50px;
ease,ease-in,ease-out, and ease-in-out.
Color: rgb(3, 177, 3);
Animation-delay- It specifies the delay of the start of an animation.
Text-shadow: 2px 2px red;
Animation-iteration-count- This specifies the number of times the animation will be repeated.
}
Animation-direction- It defines the direction of the animation. Animation direction can be normal, reverse,
alternate, and alternate-reverse. .gfg2 {
Animation-fill-mode- It defines how styles are applied before and after animation. The animation fill mode Font-size: 50px;
can be none, forwards, backwards, or both.
Color: rgb(3, 177, 3);
Animation-play-state- This property specifies whether the animation is running or paused.
Text-shadow: 30px 30px red;
Applying Shadow Effect on Text Using CSS
}
In this article, we will learn how to Apply the Shadow Effect on Text Using CSS. The text-shadow property
of CSS is used to apply the shadow effect on text. </style>
Approach: The text-shadow property of CSS is used to apply the shadow effect on text. It takes four values </head>
vertical_shadow, horizontal_shadow, blur, and color. All the details of the properties that text-shadow <body>
properties take are below:
<h1 style=”margin: 10% 20%;” class=”gfg1”>GeeksforGeeks</h1>
Vertical_shadow: It is the position of the shadow of the text vertically.
<h1 style=”margin: 10% 20%;” class=”gfg2”>GeeksforGeeks</h1>
Horizontal_shadow: It is the position of the shadow of the text horizontally.
</body>
Blur: It is the value of how much blur shadow we want. It is optional.
</html>
Color: It is the color of the shadow.
Syntax:
9. Explain the structure of XML Documents with example. Also, what is DTD? Explain internal DTD and
Text-shadow: vertical_shadow horizontal_shadow blur color; external DTD
Example 1: In this example, we are using the above-explained approach. Ans- Structure of XML Documents
<!DOCTYPE html> XML (eXtensible Markup Language) documents are structured hierarchically, allowing data to be stored
<html lang=”en”> and transported in a structured, human-readable, and machine-readable format. An XML document
consists of:
<head>
XML Declaration (Optional): Specifies the XML version and character encoding.
<title>
Root Element: Every XML document must have a single root element that encapsulates all other elements.
How to specify the width, style,
Child Elements: These are nested within the root element, representing the hierarchical structure of the
And color of the rule between columns? data.
</title> Attributes: Provide additional information about elements, specified within the opening tag.
Text Content: The actual data or value inside an element. <!ELEMENT bookstore (book+)>
Comments: Optional, used to add notes or explanations. <!ELEMENT book (title, author, year, price)>
<year>1925</year> ]>
<price>10.99</price> <bookstore>
<year>2011</year> <price>10.99</price>
<price>15.99</price> </book>
</book> </bookstore>
DTD (Document Type Definition) The DTD is stored in a separate file and linked to the XML document using the SYSTEM keyword.
DTD is a set of rules that defines the structure, elements, and attributes of an XML document. It ensures DTD File (bookstore.dtd):
that the XML document adheres to a specific format or structure, thus validating the document.
<!ELEMENT bookstore (book+)>
Types of DTD
<!ELEMENT book (title, author, year, price)>
Internal DTD: Defined within the same XML document.
<!ATTLIST book category CDATA #REQUIRED>
External DTD: Defined in a separate file and referenced from the XML document.
<!ELEMENT title (#PCDATA)>
Internal DTD
<!ATTLIST title lang CDATA #IMPLIED>
The DTD is included within the XML document itself using a <!DOCTYPE> declaration.
<!ELEMENT author (#PCDATA)>
Example:
<!ELEMENT year (#PCDATA)>
<?xml version=”1.0” encoding=”UTF-8”?>
<!ELEMENT price (#PCDATA)>
<!DOCTYPE bookstore [
XML Document:
<book category=”fiction”> Use the Connection object to create a Statement or PreparedStatement for executing SQL queries.
10. Write a short note on JDBC. Explain the steps to connect Java Application to Database using JDBC Use the ResultSet object to iterate through the results of a query.
Ans- JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with Example:
the database. It is a specification from Sun Microsystems that provides a standard abstraction(API or While (rs.next()) {
Protocol) for Java applications to communicate with various databases. It provides the language with Java
database connectivity standards. It is used to write programs required to access databases. JDBC, along System.out.println(“Column1: “ + rs.getString(“column1”));
with the database driver, can access databases and spreadsheets. The enterprise data stored in a relational
}
database(RDB) can be accessed with the help of JDBC APIs.
7. Close the Connection
Steps to Connect Java Application with Database
Once the operations are completed, close the ResultSet, Statement, and Connection objects to free
1. Import JDBC Packages resources.
Include the required JDBC classes by importing the necessary package: Example:
Import java.sql.*; Rs.close();
2. Load and Register the Driver Stmt.close();
Load the database driver class using Class.forName() method. Conn.close();
For example, to connect to a MySQL database:
Life cycle of JSP Database Support- Supports a wide range of databases, such as MySQL, PostgreSQL, SQLite, and more.
A Java Server Page life cycle is defined as the process that started with its creation which later translated Rich Library of Functions- Includes built-in functions for tasks like file handling, string manipulation, and
to a servlet and afterward servlet lifecycle comes into play. This is how the process goes on until its encryption.
destruction.
Fast and Efficient- PHP scripts execute quickly, making it ideal for web applications.
Lifecycle of JSP
Supports Object-Oriented Programming- PHP allows the use of OOP concepts for structured and reusable
Following steps are involved in the JSP life cycle: code.
1. Translation of JSP page to Servlet: This is the first step of the JSP life cycle. This translation phase Cross-Browser Compatibility- PHP-generated web pages are compatible with all major web browsers.
deals with the Syntactic correctness of JSP. Here test.jsp file is translated to test.java.
Integration with Other Technologies- PHP can easily integrate with other technologies like JavaScript,
2. Compilation of JSP page: Here the generated java servlet file (test.java) is compiled to a class file
XML, and APIs.
(test.class).
3. Classloading: The classloader loads the Java class file into the memory. The loaded Java class can
then be used to serve incoming requests for the JSP page.
4. Instantiation: Here an instance of the class is generated. The container manages one or more Form Validation in PHP:
instances by providing responses to requests. <?php
5. Initialization: jspInit() method is called only once during the life cycle immediately after the
generation of the Servlet instance from JSP. if ($_SERVER["REQUEST_METHOD"] == "POST") {
6. Request processing: _jspService() method is used to serve the raised requests by JSP. It takes $name = $email = $age = "";
request and response objects as parameters. This method cannot be overridden.
7. JSP Cleanup: In order to remove the JSP from the use by the container or to destroy the method $errors = [];
for servlets jspDestroy()method is used. This method is called once, if you need to perform any
if (empty($_POST["name"])) {
cleanup task like closing open files, or releasing database connections jspDestroy() can be
overridden. $errors[] = "Name is required.";
We can override jspInit(), jspDestroy() but we can’t override _jspService() method. } else {
$name = htmlspecialchars($_POST["name"]);
} Break;
echo "Validation successful! Name: $name, Email: $email, Age: $age"; Echo “Ready”;
} else { Break;
} }
} Looping Structures
Example:
PHP provides the following control structures for decision-making and loops: Echo $i . “ “;
Conditional Statements }
$number = 10; }
If ($number > 0) {
} $factorial = 1;
} When the servlet is no longer needed, the container calls the destroy() method.
// Driver Code This method is used to release resources such as closing database connections.
The Servlet life cycle defines the steps a servlet goes through from its creation to its destruction. It consists
of the following phases:
The servlet container (e.g., Tomcat) loads the servlet class when it receives the first request for the servlet There are three life cycle methods of a Servlet :
or during server startup (if configured to load on startup).
This method is used for one-time initialization tasks, such as setting up database connections or initializing
resources.
Syntax:
Init()
Public void init(ServletConfig config) throws ServletException
Service()
Request Handling (service() method)
Destroy()
For each client request, the container calls the service() method of the servlet.
Let’s look at each of these methods in details:
The service() method determines the type of request (e.g., GET, POST) and calls the appropriate methods
Init() method: The Servlet.init() method is called by the Servlet container to indicate that this Servlet
(doGet(), doPost()).
instance is instantiated successfully and is about to put into service.
Syntax:
//init() method
Public class MyServlet implements Servlet{ Browser sends a request sent to the web server that hosts the website.
Public void init(ServletConfig config) throws ServletException { The web server then returns a response as a HTML page or any other document format to the browser.
//initialization code Browser displays the response from the server to the user.
} The symbolic representation of a HTTP communication process is shown in the below picture:
//rest of code
Service() method: The service() method of the Servlet is invoked to inform the Servlet about the client
requests.
This method uses ServletRequest object to collect the data requested by the client.
The web browser is called as a User Agent and other example of a user agent is the crawlers of search
This method uses ServletResponse object to generate the output content. engines like Googlebot.
// service() method HTTP Request -A simple request message from a client computer consists of the following components:
Public class MyServlet implements Servlet{ A request line to get a required resource, for example a request GET /content/page1.html is requesting a
resource called /content/page1.html from the server.
Public void service(ServletRequest res, ServletResponse res)
Headers (Example – Accept-Language: EN).
Throws ServletException, IOException {
An empty line.
// request handling code
A message body which is optional.
}
All the lines should end with a carriage return and line feed. The empty line should only contains carriage
// rest of code return and line feed without any spaces.
} HTTP Response -A simple response from the server contains the following components:
Destroy() method: The destroy() method runs only once during the lifetime of a Servlet and signals the HTTP Status Code (For example HTTP/1.1 301 Moved Permanently, means the requested resource was
end of the Servlet instance. permanently moved and redirecting to some other resource).
//destroy() method Headers (Example – Content-Type: html)
Public void destroy() An empty line.
As soon as the destroy() method is activated, the Servlet container releases the Servlet instance. A message body which is optional.
All the lines in the server response should end with a carriage return and line feed. Similar to request, the
16. What is HTTP? Describe structure of HTTP request and Response message empty line in a response also should only have carriage return and line feed without any spaces.
Ans- HTTP stands for HyperText Transfer Protocol. This is a basis for data communication in the internet.
The data communication starts with a request sent from a client and ends with the response received from 17. List and Explain 3 ways to add CSS to HTML.
a web server.
Ans- CSS stands for Cascading Style Sheets.
A website URL starting with http:// is entered in a web browser from a computer (client). The browser can
be a Chrome, Firefox, Edge, Safari, Opera or anything else. CSS saves a lot of work. It can control the layout of multiple web pages all at once.
With CSS, you can control the color, font, the size of text, the spacing between elements, how P {color: red;}
elements are positioned and laid out, what background images or background colors are to be used,
</style>
different displays for different devices and screen sizes, and much more!
</head>
Using CSS
<body>
CSS can be added to HTML documents in 3 ways:
<h1>This is a heading</h1>
• Inline – by using the style attribute inside HTML elements
• Internal – by using a <style> element in the <head> section <p>This is a paragraph.</p>
• External – by using a <link> element to link to an external CSS file
</body>
The most common way to add CSS, is to keep the styles in external CSS files. However, in this
</html>
tutorial we will use inline and internal styles, because this is easier to demonstrate, and easier for you to
try it yourself.
<head>
<style>
H1 {color: blue;}
1.Explain how JavaScript can hide HTML Elements with suitable example. Margin-right: 50px;
Ans- }
Hiding elements in HTML is a common technique used to control the visibility of content on .square {
a webpage. This approach allows developers to dynamically show or conceal elements
Width: 130px;
based on user interactions, the display property involves setting display: none in CSS. This
completely removes the element from the document flow, making it invisible and not taking Height: 130px;
up any space on the page, unlike other visibility properties.
Border-radius: 0%;
Syntax:
Float: left;
Document.getElementById (“element”).style.display = “none”;
Margin-right: 50px;
Example: In this example we will see the implementation of style.display property.
}
<!DOCTYPE html>
#circle {
<html>
Background-color: #196F3D;
<head>
}
<title>Hide elements in HTML</title>
#rounded {
<style type=”text/css”>
Background-color: #5DADE2;
.circle {
}
Width: 130px;
#square {
Height: 130px;
Background-color: #58D68D;
Border-radius: 50%;
}
Float: left;
</style>
Margin-right: 50px;
</head>
}
<body>
.rounded {
<div class=”circle” id=”circle”></div>
Width: 130px;
<div class=”rounded” id=”rounded”></div>
Height: 130px;
<div class=”square” id=”square”></div>
Border-radius: 25%;
<script type=”text/javascript”>
Float: left
Document.getElementById(“circle”).onclick = function () {
Document.getElementById(“circle”).style.display = “none”; 3.Write a code to Drag an image from outside the box and Drop it inside the box
} Ans-
Document.getElementById(“rounded”).onclick = function () { We have given a rectangle area and an image, the task is to drag the image and drop it into
the rectangle.
Document.getElementById(“rounded”).style.display = “none”;
We have to enable
}
Ondrop=”drop(event)”
Document.getElementById(“square”).onclick = function () {
And
Document.getElementById(“square”).style.display = “none”;
Ondragover=”allowDrop(event)”
}
To make the rectangle for image insertion.
</script>
The image link is inserted in the HTML page using
</body>
<img> src
</html>
Attribute.
Whenever we are going to insert the image, we have to enable draggable=”true”. Also,
2. If you wanted to send sensitive information like password to the backend which among
enable
the GHF and the POST method in PHP would you use, justify your answer and distinguish
between these methods. Ondragstart=”drag(event)”
Security: The GET method appends the data to the URL, making it visible in the browser’s Setting the image width and height
address bar and potentially logged in server logs. This makes it vulnerable to eavesdropping
Example: In this example, we will see how to drag and drop an image.
and data breaches. On the other hand, the POST method sends the data in the body of the
HTTP request, which is not visible in the URL or server logs, providing a higher level of <!DOCTYPE HTML>
security.
<html>
Data Length: The GET method has limitations on the length of the data that can be sent,
<head>
typically around 2048 characters. This can be a problem when sending large amounts of
sensitive information. The POST method does not have this limitation, allowing for the <title>
transmission of larger data sets. How to Drag and Drop Images using HTML5 ?
Caching: The GET method allows caching of the URL, which means that sensitive </title>
information may be stored in the browser’s cache or in proxy servers. This can pose a
security risk if unauthorized users gain access to the cached data. The POST method, by <style>
default, does not allow caching, reducing the risk of sensitive data being stored in caches. #div1 {
Width: 350px;
Height: 70px; Function drop(ev) {
} Ev.target.appendChild(document.getElementById(data));
</style> }
</head> </script>
<body> </body>
<p> </html>
Into the rectangle: 4.What are cookies? And how do cookies work in servlets.
</p>
Ondragover=”allowDrop(event)”>
</div>
<br>
https://media.geeksforgeeks.org/wp-content/uploads/20211014104411/gfg2.png
draggable=”true” ondragstart=”drag(event)”
width=”336” height=”69”>
<script>
Function allowDrop(ev) {
Ev.preventDefault();
Function drag(ev) {
Ev.dataTransfer.setData(“text”, ev.target.id);
</tr>
5.Create an external Stylesheet and link it to an HTML, form, the stylesheet should contain <tr>
the following
<td>1</td>
•An header in text with Red Text Colour and Yellow background colour
<td><a href=https://example.com><img src=”product1.jpg” alt=”Product 1”>Product
•A Double lined (Border) table 1</a></td>
•The table should have 5 Rows and 3 Columns <td>This is the description for product 1.</td>
•In the First column Sr. No. of the product, Second column Image with hyperlink and </tr>
Name of the Product, and Third column the description of the product.
<tr>
Ans-
<td>2</td>
HTML File (index.html)
<td><a href=https://example.com><img src=”product2.jpg” alt=”Product 2”>Product
<!DOCTYPE html> 2</a></td>
<head> </tr>
</table>
Let errorMessages = [];
</body>
</html>
// Validate Name (should contain only A-Z letters)
If (!/^[A-Za-z]+$/.test(name)) {
Ans- }
<!DOCTYPE html>
<head> If (!email.includes(“@”)) {
<title>Form Validation</title>
<script> // Validate Password (should have 1 uppercase letter, 1 digit, 1 special character, and
length >= 8)
// Function to validate the form
Const passwordRegex = /^(?=.*[A-Z])(?=.*\d)(?=.*[!@#$%^&*])[A-Za-
Function validateForm() { z\d!@#$%^&*]{8,}$/;
// Get the values from the form fields If (!passwordRegex.test(password)) {
Const name = document.getElementById(“name”).value;
errorMessages.push(“Password must contain at least 1 uppercase letter, 1 digit, 1 <label for=”email”>Email ID:</label><br>
special character, and be at least 8 characters long.”);
<input type=”email” id=”email” name=”email”><br><br>
}
<label for=”password”>Password:</label><br>
// Display errors if any, otherwise allow form submission
<input type=”password” id=”password” name=”password”><br><br>
If (errorMessages.length > 0) {
Alert(errorMessages.join(“\n”));
<input type=”submit” value=”Submit”>
Return false; // Prevent form submission if validation fails
</form>
}
</body>
// If no errors, return true (form will be submitted)
</html>
Return true;
}
7.Explain how forms validation works in PHP, with a suitable example
</script>
Ans-
</head>
Form validation in PHP is a process used to ensure that user input submitted via HTML
<body> forms is accurate, secure, and meets certain requirements before being processed or
stored. This process is crucial for preventing errors, malicious inputs, and ensuring data
integrity. PHP can be used to perform both client-side and server-side validation, but
<h2>Form Validation</h2> server-side validation is critical for security.
<html lang=”en”> 8.Explain Basic internet Protocols which are essential for transferring date and sending
emails.
<head>
Ans-
<meta charset=”UTF-8”>
1. **Transmission Control Protocol (TCP)**
<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>
- **Purpose**: Ensures reliable data transfer over the internet.
<title>PHP Form Validation Example</title>
- **How It Works**: TCP breaks data into packets and ensures they arrive at the
</head>
destination in the correct order. It also handles retransmissions if packets are lost or
<body> corrupted during transit.
- **Role**: It’s used for any application that requires guaranteed data delivery, such as
emails and web browsing.
<h2>Contact Form</h2>
2. **Internet Protocol (IP)**
<form action=”process.php” method=”post”>
- **Purpose**: Provides addressing and routing information for packets of data.
<label for=”name”>Name:</label><br>
- **How It Works**: IP assigns unique addresses (IP addresses) to devices on a network. It
<input type=”text” id=”name” name=”name”><br>
routes data packets from the source to the destination device.
<span class=”error” style=”color: red;”><?php if (isset($nameErr)) echo $nameErr;
- **Role**: Works alongside TCP to direct data through networks.
?></span><br><br>
3. **Hypertext Transfer Protocol (HTTP)**
<label for=”email”>Email:</label><br>
- **Purpose**: Facilitates communication between web browsers and servers.
<input type=”text” id=”email” name=”email”><br>
- **How It Works**: HTTP defines how requests and responses are formatted when
<span class=”error” style=”color: red;”><?php if (isset($emailErr)) echo $emailErr;
transferring web pages and resources (like images and text) from a server to a client
?></span><br><br>
(browser).
<label for=”message”>Message:</label><br>
- **Role**: Used primarily in web browsing, but also essential for transferring other types
<textarea id=”message” name=”message”></textarea><br> of data on the internet.
<span class=”error” style=”color: red;”><?php if (isset($messageErr)) echo 4. **Simple Mail Transfer Protocol (SMTP)**
$messageErr; ?></span><br><br>
- **Purpose**: Handles the sending of emails.
<input type=”submit” value=”Submit”>
- **How It Works**: SMTP is used by email clients (like Outlook or Gmail) to send emails
</form> to email servers and between servers. It defines how email is routed from the sender’s
</body> server to the recipient’s server.
- **Role**: Used to transmit outgoing mail from a client or between email servers.
</html>
5. **Domain Name System (DNS)** // Define what happens when the file is successfully loaded
- **How It Works**: When you type a website address (e.g., www.example.com), DNS If (xhr.status === 200) {
translates it into an IP address that computers can understand, so they know where to
// Display the content of the file in the div
send the data.
Document.getElementById(“content”).textContent = xhr.responseText;
9.Write the AJAX code to read from the text file and displaying it after clicking of a button.
} else {
Ans:-
// Handle errors
<!DOCTYPE html>
Document.getElementById(“content”).textContent = “Error: Unable to load file.”;
<html lang=”en”>
}
<head>
};
<meta charset=”UTF-8”>
// Handle network errors
<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>
Xhr.onerror = function () {
<title>AJAX Text File Reader</title>
Document.getElementById(“content”).textContent = “Error: Network issue.”;
</head>
};
<body>
// Send the request
<h1>Read Text File with AJAX</h1>
Xhr.send();
<button id=”loadButton”>Load Text File</button>
});
<div id=”content” style=”margin-top: 20px; border: 1px solid #ccc; padding: 10px;”>
</script>
<!—The content of the text file will be displayed here →
</body>
</div>
</html>
<script>
Document.getElementById(“loadButton”).addEventListener(“click”, function () {
10.List and Explain the 3 ways to add style sheet (CSS) to an HTML web page with suitable
// Create a new XMLHttpRequest object
examples
Const xhr = new XMLHttpRequest();
Ans-
// Specify the file to read and the HTTP method
1.Inline CSS
Xhr.open(“GET”, “example.txt”, true);
CSS is applied directly to HTML elements using the style attribute.
Features: <style>
Font-size: 24px;
Code:- }
<!DOCTYPE html> P{
</head> </style>
<body> </head>
<p style=”color: green; font-style: italic;”>This is an inline styled paragraph.</p> <h1>This is an internally styled heading</h1>
</html> </body>
CSS is written within a <style> tag inside the <head> section of the HTML document. 3.External CSS
CSS is written in a separate file with the .css extension and linked to the HTML file using a
<link> tag.
Features:
Features:
Useful when styling a single document.
Useful for maintaining styles across multiple web pages.
Styles are applied to all elements in the document that match the defined selectors.
Makes the code modular and easier to manage.
Code:
Example:
<!DOCTYPE html>
HTML File (index.html):
<html>
<!DOCTYPE html>
<head>
<html>
<title>Internal CSS Example</title>
</head>
<body>
</body>
</html>
H1 {
Color: blue;
Font-size: 24px;
P{
Color: green;
Font-style: italic;
}
12.An e-commerce website would like to accept the below mentioned data <label for=”operation”>Select Operation:</label>
would like to transfer the data using XML <select name=”operation” id=”operation” required>
Code: ArithmeticOperations.jsp
<hr>
<!DOCTYPE html>
<html>
<%
<head>
String num1Str = request.getParameter(“num1”);
<title>Arithmetic Operations</title>
String num2Str = request.getParameter(“num2”);
</head>
String operation = request.getParameter(“operation”);
<body>
Double result = 0;
<label for=”num2”>Enter Second Number:</label>
Case “add”:
Break; </html>
Case “subtract”:
Out.println(“<h2>Result: “ + num1 + “ – “ + num2 + “ = “ + result + “</h2>”); 14.Explain Exception handling in Javascript with suitable example.
Break; Ans:-
Result = num1 * num2; Exception handling in JavaScript is a mechanism to handle runtime errors gracefully
without stopping the execution of the program. JavaScript uses the try…catch block for this
Out.println(“<h2>Result: “ + num1 + “ × “ + num2 + “ = “ + result + “</h2>”);
purpose, and optionally, a finally block for cleanup actions. The throw statement is used to
Break; create custom exceptions.
Case “divide”:
If (num2 != 0) { Syntax
Result = num1 / num2; Try {
Out.println(“<h2>Result: “ + num1 + “ ÷ “ + num2 + “ = “ + result + “</h2>”); // Code that may throw an exception
} else { } catch (error) {
Out.println(“<h2>Error: Division by zero is not allowed!</h2>”); // Code to handle the exception
} } finally {
} Try {
} If (b === 0) {
// Throw a custom error for division by zero Margin: 20px;
} .error {
Console.log(`Result: ${result}`); }
Console.error(`Error: ${error.message}`); }
} finally { </style>
} <form id=”passwordForm”>
<label for=”password”>Password:</label>
15. write a JavaScript to check password and confirm password is same or not. <input type=”password” id=”password” name=”password” required><br><br>
Ans:-
<head>
<button type=”button” onclick=”checkPasswordMatch()”>Submit</button>
<meta charset=”UTF-8”>
</form>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>
Body {
<script>
Font-family: Arial, sans-serif;
Function checkPasswordMatch() { - The root element is the top-level element in the XML document, which contains all other
elements.
// Get input values
- An XML document must have exactly one root element.
Const password = document.getElementById(‘password’).value;
3. **Elements**:
Const confirmPassword = document.getElementById(‘confirmPassword’).value;
- An element consists of a start tag, content, and an end tag.
Const messageElement = document.getElementById(‘message’);
- Example: `<name>John Doe</name>`
4. **Attributes** (Optional):
// Check if passwords match
- Elements can have attributes, which provide additional information about an element.
If (password === confirmPassword) {
- Example: `<person gender=”male”>John Doe</person>`
messageElement.textContent = “Passwords match!”;
5. **Text Content**:
messageElement.className = “success”;
- The content of an element can be plain text or can include other elements.
} else {
6. **Comments** (Optional):
messageElement.textContent = “Passwords do not match!”;
- XML allows comments within the document to provide explanations or notes, enclosed
messageElement.className = “error”;
in `<!-- →`.
}
- Example: `<!—This is a comment →`
}
7. **CDATA Sections** (Optional):
</script>
- A section of text that should not be treated as XML, useful for including raw data like
</body> HTML or JavaScript.
</html> - Example: `<![CDATA[<div>Raw HTML content</div>]]>`
16. Explain the structure of XML document with example 8. **Namespaces** (Optional):
Ans- - Namespaces are used to avoid naming conflicts when combining XML documents from
different sources.
An XML (Extensible Markup Language) document is a structured text file used to store and
transport data in a hierarchical manner. The structure of an XML document is defined by - Example: `<x:element xmlns:x=http://www.example.com>Content</x:element>`
the following components:
Example XML Document:
1. **Prolog** (Optional):
<?xml version=”1.0” encoding=”UTF-8”?>
- It defines the version of XML and, optionally, the encoding used.
<library>
- Example: `<?xml version=”1.0” encoding=”UTF-8”?>`
<!—A list of books in the library →
2. **Root Element**:
<book id=”1”> <label for="number">Enter a number:</label>
<price>29.99</price> </form>
<publisher>Tech Books</publisher>
</book> <?php
<price>39.99</price>
</library> if ($n == 0 || $n == 1) {
Ans:- }
<!DOCTYPE html> }
<html lang="en">
</head> </body>
<body> </html>
Number: 5
Output:
Input:
Number: 0
Output:
Factorial of 0 is: 1
Ans-