0% found this document useful (0 votes)
10 views14 pages

Ilovepdf Merged

The document outlines various JavaScript validation tasks, including password and form validation, event handling, and exception handling with example codes. It also explains the AJAX web application model compared to traditional models, highlighting the benefits of asynchronous interactions. Additionally, it covers CSS inheritance, animation properties, and the structure of XML documents, including DTD types.

Uploaded by

nisqfile
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views14 pages

Ilovepdf Merged

The document outlines various JavaScript validation tasks, including password and form validation, event handling, and exception handling with example codes. It also explains the AJAX web application model compared to traditional models, highlighting the benefits of asynchronous interactions. Additionally, it covers CSS inheritance, animation properties, and the structure of XML documents, including DTD types.

Uploaded by

nisqfile
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

6.

JavaScript Validation Tasks // Example usage

- 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;

} If (typeof a !== “number” || typeof b !== “number”) {

Const passwordMessage = validatePassword(password); Throw new Error(“Inputs must be numbers.”);

If (passwordMessage !== “Password is valid.”) { }

Alert(passwordMessage); If (b === 0) {

Return false; Throw new Error(“Division by zero is not allowed.”);

} }

Alert(“Form submitted successfully!”); Return a / b;

Return true; } catch (error) {

} Return `Error: ${error.message}`;

</script> }

3. Event Handling }

Task: Implement event handling for various user interactions. // Example usage

Example Code: Console.log(divideNumbers(10, 2)); // Output: 5

<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.

}); AJAX Web Application Model

</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

Traditional Application Model Ajax Web Application Model


▪ Entire page reloads for every request. ▪ No page reload; only parts of the page are
updated.
▪ Slower and less interactive due to visible ▪ Faster and more dynamic, with seamless
refreshes. interactions.
▪ Sends a complete HTML page for each ▪ Sends only the required data (e.g., JSON, XML).
request.
▪ High latency due to full-page reloads. ▪ Low latency as only specific data is exchanged.
▪ Higher, as the server processes and sends ▪ Lower, as the server processes and sends minimal
entire pages. data.
▪ Higher due to complete page reloads. ▪ Lower due to partial updates.
▪ Standard HTTP requests and responses. ▪ AJAX (XMLHttpRequest or Fetch API for
asynchronous calls).
▪ Minimal; most processing is server-side. ▪ Extensive client-side processing using JavaScript.
▪ Limited flexibility for dynamic content. ▪ High flexibility for interactive and dynamic
content.
▪ Simple and easy to implement. ▪ More complex, requires JavaScript for client- side 8.What is inheritance in CSS? Explain CSS Animation properties. Also Explain how shadow effect can be
handling. applied on text using CSS with Example.
▪ Not supported; requires manual refresh or ▪ Supported; real-time updates are possible using
Ans- CSS inheritance describes how certain styles are initialized or computed depending on the CSS
polling. AJAX.
property and whether a value was set. Some properties are inherited with an initial, default value. Other
properties are non-inherited and set to the computed value of its containing element by default.

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.

Understanding CSS Animations

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.

CSS Animation Properties

CSS animations involve several key properties:

@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)>

Example of an XML Document <!ATTLIST book category CDATA #REQUIRED>

<?xml version=”1.0” encoding=”UTF-8”?> <!ELEMENT title (#PCDATA)>

<bookstore> <!ATTLIST title lang CDATA #IMPLIED>

<book category=”fiction”> <!ELEMENT author (#PCDATA)>

<title lang=”en”>The Great Gatsby</title> <!ELEMENT year (#PCDATA)>

<author>F. Scott Fitzgerald</author> <!ELEMENT price (#PCDATA)>

<year>1925</year> ]>

<price>10.99</price> <bookstore>

</book> <book category=”fiction”>

<book category=”non-fiction”> <title lang=”en”>The Great Gatsby</title>

<title lang=”en”>Sapiens</title> <author>F. Scott Fitzgerald</author>

<author>Yuval Noah Harari</author> <year>1925</year>

<year>2011</year> <price>10.99</price>

<price>15.99</price> </book>

</book> </bookstore>

</bookstore> External DTD

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:

<?xml version=”1.0” encoding=”UTF-8”?> Connection conn = DriverManager.getConnection(

<!DOCTYPE bookstore SYSTEM “bookstore.dtd”> “jdbc:mysql://localhost:3306/db_name”, “username”, “password”);

<bookstore> 4. Create a Statement

<book category=”fiction”> Use the Connection object to create a Statement or PreparedStatement for executing SQL queries.

<title lang=”en”>The Great Gatsby</title> Example for a Statement:

<author>F. Scott Fitzgerald</author> Statement stmt = conn.createStatement();

<year>1925</year> 5. Execute the Query

<price>10.99</price> Use the Statement or PreparedStatement object to execute SQL queries.

</book> For example, executing a query to retrieve data:

</bookstore> ResultSet rs = stmt.executeQuery(“SELECT * FROM table_name”);

6. Process the Results

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:

Class.forName(“com.mysql.cj.jdbc.Driver”); 11. Give Characteristics of RIA (Rich Internet Applications)


This step ensures the JDBC driver is registered with the DriverManager. Ans- Rich Internet Applications (RIAs) are web applications that provide a user experience similar to
traditional desktop applications. They combine the benefits of web technologies with the interactivity and
3. Establish a Connection
responsiveness of desktop applications.
Use the DriverManager.getConnection() method to establish a connection with the database.
Here are some key characteristics of RIAs:
Provide the database URL, username, and password as parameters:
Rich User Interface: RIAs offer a visually appealing and interactive user interface. They use advanced XML Benefits
graphics, animations, and multimedia elements to enhance the user experience.
XML (Extensible Markup Language) is a versatile and robust format designed to store and transport
Interactivity: RIAs enable users to interact with the application in real-time without page reloads. They structured data. Its ability to define custom tags and support hierarchical data structures makes it ideal for
support drag-and-drop, context menus, and other interactive features that make the application more representing complex data relationships. XML is platform and language-independent, allowing seamless
engaging. data sharing across diverse systems. With its built-in validation features through DTD (Document Type
Definition) and XSD (XML Schema), XML ensures the integrity and consistency of the data being
Responsiveness: RIAs are highly responsive and provide instant feedback to user actions. They use
exchanged. Moreover, it is widely used in legacy systems and enterprise applications, especially in
asynchronous communication techniques, such as AJAX, to update the interface dynamically without
protocols like SOAP. XML’s extensibility and support for rich metadata make it suitable for applications
refreshing the entire page.
requiring detailed data descriptions or transformations using XSLT, enabling high flexibility in data
Cross-Platform Compatibility: RIAs are designed to work seamlessly across different platforms and processing and representation.
devices. They are built using web technologies like HTML, CSS, and JavaScript, which are supported by
most modern web browsers.
JSON XML
Offline Capabilities: Some RIAs have the ability to work offline by caching data and resources locally. This
allows users to continue using the application even when they are not connected to the internet. ▪ JSON stands for JavaScript Object Notation ▪ eXtensible Markup Language
▪ It Uses Key Value Structure to make platform ▪ uses Tag based Structure to make platform
Enhanced Functionality: RIAs can leverage the capabilities of the user’s device, such as accessing the independent formats independent formats
camera, GPS, or local storage. This enables the development of feature-rich applications with advanced ▪ It is JavaScript Object Notation ▪ It is Extensible markup language
functionality. ▪ It is based on JavaScript language. ▪ It is derived from SGML.
▪ It is a way of representing objects. ▪ It is a markup language and uses tag structure
Security: RIAs implement security measures to protect user data and prevent unauthorized access. They
to represent data items.
use encryption, authentication, and other security mechanisms to ensure the confidentiality and integrity
▪ It does not provides any support for ▪ It supports namespaces.
of user information. namespaces.
Scalability: RIAs can handle a large number of concurrent users and scale to accommodate increasing ▪ It supports array. ▪ It doesn't supports array.
▪ Its files are very easy to read as compared to ▪ Its documents are comparatively difficult to
demand. They are often built using scalable architectures and technologies to ensure optimal
XML. read and interpret.
performance.
▪ It doesn't use end tag. ▪ It has start and end tags.
Overall, RIAs provide a more immersive and interactive user experience compared to traditional web ▪ It is less secured. ▪ It is more secured than JSON.
applications. They offer enhanced functionality, responsiveness, and cross-platform compatibility, making ▪ It doesn't supports comments. ▪ It supports comments.
them a popular choice for building modern web applications. ▪ It supports only UTF-8 encoding. ▪ It supports various encoding.

12. JSON vs XML (Benefits and Differences)


13. What is JSP? Explain life cycle of JSP
Ans- JSON Benefits
Ans- In Java, JSP stands for Jakarta Server Pages( (JSP; formerly JavaServer Pages)). It is a server-side
JSON (JavaScript Object Notation) is a lightweight and efficient format widely used for data exchange in technology that is used for creating web applications. It is used to create dynamic web content. JSP consists
web applications. Its compact structure, based on key-value pairs, makes it faster to parse and easier to of both HTML tags and JSP tags. In this, JSP tags are used to insert JAVA code into HTML pages. It is an
transmit compared to XML. JSON is human-readable and simple to write, ensuring developers can quickly advanced version of Servlet Technology i.e. a web-based technology that helps us to create dynamic and
understand its structure. Its native compatibility with JavaScript makes it ideal for web development, platform-independent web pages. In this, Java code can be inserted in HTML/ XML pages or both. JSP is
particularly in RESTful APIs, where it serves as the standard format for client-server communication. first converted into a servlet by the JSP container before processing the client’s request. JSP has various
Additionally, JSON’s smaller size and reduced redundancy due to the absence of closing tags lead to faster features like JSP Expressions, JSP tags, JSP Expression Language, etc.
network transmission and lower storage requirements. JSON’s wide adoption across programming
languages, coupled with its ability to integrate seamlessly with APIs, makes it a preferred choice for JSP allows embedding Java code in HTML pages, making it easier to build interactive web applications. To
modern web development. further enhance your knowledge of Java web technologies, consider enrolling in the Java Backend course,
which covers essential concepts for backend development.

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"]);

14. Features of PHP }

- Form validation in PHP if (empty($_POST["email"])) {


- Various control structures used in PHP
$errors[] = "Email is required.";
- Program to print factorial of a number
} elseif (!filter_var($_POST["email"], FILTER_VALIDATE_EMAIL)) {
Ans- Features of PHP:-
$errors[] = "Invalid email format.";
PHP (Hypertext Preprocessor) is a widely-used open-source scripting language designed for web
development. Here are its key features: } else {
Easy to Learn and Use- PHP has a simple syntax, making it beginner-friendly and easy to integrate with $email = htmlspecialchars($_POST["email"]);
HTML.
}
Platform Independence- PHP scripts can run on multiple platforms, including Windows, Linux, and macOS.
if (empty($_POST["age"])) {
Server-Side Scripting- PHP runs on the server, generating dynamic web pages.
$errors[] = "Age is required.";
Open Source- PHP is free to use and has a large community for support and updates.
} elseif (!is_numeric($_POST["age"])) {
$errors[] = "Age must be a number."; Switch ($color) {

} else { Case “red”:

$age = (int)$_POST["age"]; Echo “Stop”;

} Break;

if (empty($errors)) { Case “yellow”:

echo "Validation successful! Name: $name, Email: $email, Age: $age"; Echo “Ready”;

} else { Break;

foreach ($errors as $error) { Default:

echo $error . "<br>"; Echo “Go”;

} }

} Looping Structures

} For, while, do-while

?> Foreach (used with arrays)

Example:

Various Control Structures in PHP For ($i = 1; $i <= 5; $i++) {

PHP provides the following control structures for decision-making and loops: Echo $i . “ “;

Conditional Statements }

If, if-else, if-elseif-else $array = [1, 2, 3];

Switch-case Foreach ($array as $value) {

Example: Echo $value . “ “;

$number = 10; }

If ($number > 0) {

Echo “Positive”; PHP Program for Factorial of a number

} elseif ($number < 0) { <?php

Echo “Negative”; // PHP code to get the factorial of a number

} else { // function to get factorial in iterative way

Echo “Zero”; Function Factorial($number){

} $factorial = 1;

$color = “red”; For ($i = 1; $i <= $number; $i++){

$factorial = $factorial * $i; Public void service(HttpServletRequest request, HttpServletResponse response)

} Throws ServletException, IOException

Return $factorial; Destruction (destroy() method)

} 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.

$number = 10; Syntax:

$fact = Factorial($number); Public void destroy()

Echo “Factorial = $fact”; Servlet Life Cycle Diagram

?> Here’s a simple diagram explaining the Servlet life cycle

15. Explain Servet life cycle with neat diagram

Ans- Servlet Life Cycle

The Servlet life cycle defines the steps a servlet goes through from its creation to its destruction. It consists
of the following phases:

Loading and Instantiation

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).

The servlet class is instantiated using the no-argument constructor.

Initialization (init() method)

The init() method is called once after the servlet is instantiated.

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.

Cascading Style Sheets (CSS) is used to format the layout of a webpage.

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.

Inline CSS External CSS


• An inline CSS is used to apply a unique style to a single HTML element. • An external style sheet is used to define the style for many HTML pages.
• An inline CSS uses the style attribute of an HTML element. • To use an external style sheet, add a link to it in the <head> section of each HTML page:
The following example sets the text color of the <h1> element to blue, and the text color of the
<p> element to red:
Example
Example-
<!DOCTYPE html>
<h1 style=”color:blue;”>A Blue Heading</h1>
<html>
<p style=”color:red;”>A red paragraph.</p>
<head>
Internal CSS
<link rel=”stylesheet” href=”styles.css”>
• An internal CSS is used to define a style for a single HTML page.
</head>
• An internal CSS is defined in the <head> section of an HTML page, within a <style> element.
<body>
The following example sets the text color of ALL the <h1> elements (on that page) to blue, and the
text color of ALL the <p> elements to red. In addition, the page will be displayed with a “powderblue” <h1>This is a heading</h1>
background color:
<p>This is a paragraph.</p>
Example
</body>
<!DOCTYPE html>
</html>
<html>

<head>

<style>

Body {background-color: powderblue;}

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)”

Ans- So that this image can be draggable along with

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) {

Padding: 10px; Ev.preventDefault();

Border: 1px solid #aaaaaa; Var data = ev.dataTransfer.getData(“text”);

} Ev.target.appendChild(document.getElementById(data));

</style> }

</head> </script>

<body> </body>

<p> </html>

Drag the GeeksforGeeks image

Into the rectangle: 4.What are cookies? And how do cookies work in servlets.

</p>

<div id=”div1” ondrop=”drop(event)”

Ondragover=”allowDrop(event)”>

</div>

<br>

<img id=”drag1” src=

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>

<html lang=”en”> <td>This is the description for product 2.</td>

<head> </tr>

<meta charset=”UTF-8”> <tr>

<meta name=”viewport” content=”width=device-width, initial-scale=1.0”> <td>3</td>

<title>Product Table</title> <td><a href=https://example.com><img src=”product3.jpg” alt=”Product 3”>Product


3</a></td>
<link rel=”stylesheet” href=”styles.css”>
<td>This is the description for product 3.</td>
</head>
</tr>
<body>
<tr>
<header>
<td>4</td>
Product List
<td><a href=https://example.com><img src=”product4.jpg” alt=”Product 4”>Product
</header>
4</a></td>
<table>
<td>This is the description for product 4.</td>
<tr>
</tr>
<th>Sr. No.</th>
<tr>
<th>Product</th>
<td>5</td>
<th>Description</th>
<td><a href=https://example.com><img src=”product5.jpg” alt=”Product 5”>Product Const age = document.getElementById(“age”).value;
5</a></td>
Const email = document.getElementById(“email”).value;
<td>This is the description for product 5.</td>
Const password = document.getElementById(“password”).value;
</tr>

</table>
Let errorMessages = [];
</body>

</html>
// Validate Name (should contain only A-Z letters)

If (!/^[A-Za-z]+$/.test(name)) {

errorMessages.push(“Name should only contain letters A-Z.”);


6.Create a form which has the following fields ‘Name”, “Age Email ID, Paurword, Using
}
Javascript validate each field as follows

• Name should be between A-Z


• Age should be between 0-100 // Validate Age (should be between 0 and 100)
• Email ID should contain @ If (age < 0 || age > 100 || isNaN(age)) {
• Password should contain 1 Upper case, 1 digit, 1 Special character and length
should be minimum 8 errorMessages.push(“Age should be between 0 and 100.”);

Ans- }

<!DOCTYPE html>

<html lang=”en”> // Validate Email (should contain ‘@’)

<head> If (!email.includes(“@”)) {

<meta charset=”UTF-8”> errorMessages.push(“Email should contain ‘@’.”);

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

<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.

How Form Validation Works in PHP


<form onsubmit=”return validateForm()”> 1. **Client-side validation (Optional but recommended):** This is done using
JavaScript or HTML5 form attributes to provide immediate feedback to the user.
<label for=”name”>Name (A-Z):</label><br>
However, it’s not reliable for security, as users can bypass it.
<input type=”text” id=”name” name=”name”><br><br> 2. **Server-side validation (Required):** After the form is submitted, PHP checks the
data on the server for correctness and security. If the data is valid, it can be
processed (e.g., saved to a database); if not, an error message is shown to the user.
<label for=”age”>Age (0-100):</label><br>

<input type=”number” id=”age” name=”age”><br><br>


Example of PHP Form Validation

1. HTML Form (`index.html`)


<!DOCTYPE html>

<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

- **Purpose**: Translates human-readable domain names into IP addresses. Xhr.onload = function () {

- **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>

Useful for applying unique styles to a single element. H1 {

Takes precedence over internal and external CSS. Color: blue;

Font-size: 24px;

Code:- }

<!DOCTYPE html> P{

<html> Color: green;

<head> Font-style: italic;

<title>Inline CSS Example</title> }

</head> </style>

<body> </head>

<h1 style=”color: blue; font-size: 24px;”>This is an inline styled heading</h1> <body>

<p style=”color: green; font-style: italic;”>This is an inline styled paragraph.</p> <h1>This is an internally styled heading</h1>

</body> <p>This is an internally styled paragraph.</p>

</html> </body>

2.Internal CSS </html>

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> 11.Draw and explain Servlet Architecture and its Lifecycle

<title>External CSS Example</title>

<link rel=”stylesheet” type=”text/css” href=”styles.css”>

</head>

<body>

<h1>This is an externally styled heading</h1>

<p>This is an externally styled paragraph.</p>

</body>

</html>

CSS File (styles.css):

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>

• Product ID <option value=”add”>Addition</option>


• Product Name
<option value=”subtract”>Subtraction</option>
• Product Cost
• Purchase Date <option value=”multiply”>Multiplication</option>
• Purchased by <option value=”divide”>Division</option>
• Seller Name
</select><br><br>
Write the HTML, XML code and DTD for the given data.

13.Write a JSP program to perform four basic arithmetic operation, addition,


<button type=”submit”>Calculate</button>
Subtraction, Division and Multiplication.
</form>
Ans:-

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>

<h1>Basic Arithmetic Operations</h1>


If (num1Str != null && num2Str != null && operation != null) {
<form method=”post” action=”ArithmeticOperations.jsp”>
Try {
<label for=”num1”>Enter First Number:</label>
Double num1 = Double.parseDouble(num1Str);
<input type=”number” name=”num1” id=”num1” required><br><br>
Double num2 = Double.parseDouble(num2Str);

Double result = 0;
<label for=”num2”>Enter Second Number:</label>

<input type=”number” name=”num2” id=”num2” required><br><br>


Switch (operation) {

Case “add”:

Result = num1 + num2; %>

Out.println(“<h2>Result: “ + num1 + “ + “ + num2 + “ = “ + result + “</h2>”); </body>

Break; </html>

Case “subtract”:

Result = num1 – num2;

Out.println(“<h2>Result: “ + num1 + “ – “ + num2 + “ = “ + result + “</h2>”); 14.Explain Exception handling in Javascript with suitable example.

Break; Ans:-

Case “multiply”: Exception Handling in JavaScript

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 {

Break; // Optional: Code to execute regardless of an error


Default: }

Out.println(“<h2>Error: Invalid operation selected.</h2>”); Example: Division by Zero

} Here’s an example where we handle division by zero using exception handling:


} catch (NumberFormatException e) { Code:-
Out.println(“<h2>Error: Invalid number format.</h2>”); Function divideNumbers(a, b) {

} Try {

} If (b === 0) {
// Throw a custom error for division by zero Margin: 20px;

Throw new Error(“Division by zero is not allowed.”); }

} .error {

Let result = a / b; Color: red;

Console.log(`Result: ${result}`); }

} catch (error) { .success {

// Handle the error Color: green;

Console.error(`Error: ${error.message}`); }

} finally { </style>

// Cleanup or final actions </head>

Console.log(“Division operation attempted.”); <body>

} <h1>Check Password Match</h1>

} <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:-

Code: Password Matching Example <label for=”confirmPassword”>Confirm Password:</label>

<!DOCTYPE html> <input type=”password” id=”confirmPassword” name=”confirmPassword”


required><br><br>
<html lang=”en”>

<head>
<button type=”button” onclick=”checkPasswordMatch()”>Submit</button>
<meta charset=”UTF-8”>
</form>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>

<title>Password Match Checker</title>


<p id=”message”></p>
<style>

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>

<title>XML for Beginners</title> <input type="number" id="number" name="number" min="0" required>

<author>John Smith</author> <button type="submit">Calculate</button>

<price>29.99</price> </form>

<publisher>Tech Books</publisher>

</book> <?php

<book id=”2”> if ($_SERVER["REQUEST_METHOD"] == "POST") {

<title>Advanced XML</title> // Get the input number

<author>Jane Doe</author> $number = intval($_POST["number"]);

<price>39.99</price>

<publisher>Expert Press</publisher> // Function to calculate factorial

</book> function factorial($n) {

</library> if ($n == 0 || $n == 1) {

17. Write a PHP program to print factorial of number return 1;

Ans:- }

PHP Code: Factorial Calculation return $n * factorial($n - 1);

<!DOCTYPE html> }

<html lang="en">

<head> // Display the result

<meta charset="UTF-8"> echo "<h2>Factorial of $number is: " . factorial($number) . "</h2>";

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

<title>Factorial Calculation</title> ?>

</head> </body>

<body> </html>

<h1>Calculate Factorial</h1> Example Input and Output

<form method="post" action=""> Input:

Number: 5

Output:

Factorial of 5 is: 120

Input:

Number: 0

Output:

Factorial of 0 is: 1

18. Explain <audio> and <video> elements in HTML5 with example

Ans-

You might also like