0% found this document useful (0 votes)
71 views30 pages

WebTechnology Questions

The document summarizes key aspects of HTTP, HTML, CSS, and JavaScript. Regarding HTTP, it states that HTTP is stateless, connectionless, and media independent. It provides the default port numbers for HTTP and HTTPS. For HTML, it defines each term in the acronym. It defines inline, internal, and external CSS with examples. For JavaScript, it lists several features and provides an example of a function. It also provides examples of client-side form validation and common String object methods.
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)
71 views30 pages

WebTechnology Questions

The document summarizes key aspects of HTTP, HTML, CSS, and JavaScript. Regarding HTTP, it states that HTTP is stateless, connectionless, and media independent. It provides the default port numbers for HTTP and HTTPS. For HTML, it defines each term in the acronym. It defines inline, internal, and external CSS with examples. For JavaScript, it lists several features and provides an example of a function. It also provides examples of client-side form validation and common String object methods.
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

MODULE 1 1

1. Why HTTP is called stateless, connectionless, media independent protocol?


Ans: Stateless: In a stateless protocol, each request from a client to a server is processed independently, without any knowledge of the
requests that came before it. This means that the server does not retain information about previous requests, and each request must
contain all the information needed to understand and process the request.
Connectionless: In a connectionless protocol, each request/response pair is processed independently. After the server sends the
response to the client, the connection is closed. The next request from the client will result in a new connection. This makes the
protocol more efficient as it does not need to maintain a connection between requests.
Media Independent: HTTP is media independent because it can send any type of data as long as both the client and the server know
how to handle the data content. This is achieved by specifying the content type using appropriate MIME-types.
2. What is the default port number of http?
Ans: 80 and 443 for https
3. Significance of each word in html.
Ans: The name "HTML" stands for HyperText Markup Language. The term "HyperText" refers to the text that is not just plain text but
is linked to other text. The term "Markup" refers to the use of special characters to indicate how text should be formatted.
4. Define inline and external CSS with example.
Ans: Inline CSS: Inline CSS is used to apply styles to a single element. The CSS is written within the HTML element using the style
attribute. Inline CSS is specific to the element it is applied to and has the highest specificity.
<p style="color: blue; font-size: 20px;">This is a paragraph.</p>

Internal CSS: Internal CSS is used to apply styles to multiple elements within a single HTML document. The CSS is written within the
<style> tags in the <head> section of the HTML document.
<html>
<head>
<style>
p {
color: blue;
font-size: 20px;
}
</style>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>

External CSS: External CSS is used to apply styles to multiple HTML documents. The CSS is written in a separate file with a .css
extension. This file is then linked to the HTML document using the <link> tag in the <head> section of the HTML document.
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>

p {
color: blue;
font-size: 20px;
}
MODULE 2 2
1. Describe the several features of JavaScript in brief.
Ans: JavaScript is a powerful, dynamic, and versatile programming language that adds interactivity to websites. Here are some of the
key features of JavaScript:
a. Interpreted Language: JavaScript is an interpreted language, meaning it's executed line by line by the JavaScript engine in the
browser. This allows for dynamic behavior and immediate feedback.
b. Multi-Paradigm: JavaScript supports multiple programming paradigms, including object-oriented, imperative, and declarative (e.g.,
functional programming) styles. This flexibility allows developers to choose the most suitable approach for their specific needs.
c. Dynamic Typing: JavaScript is a dynamically typed language, which means you don't have to declare the type of a variable when
you create it. The type is associated with the value, not the variable.
d. First-Class Functions: In JavaScript, functions are first-class objects. This means that functions can be assigned to variables, stored
in data structures, passed as arguments to other functions, and returned as values from other functions.
e. Event-Driven: JavaScript is event-driven, which means it can respond to user actions like clicks or key presses. This is a key feature
for creating interactive web applications
f. Asynchronous Programming: JavaScript supports asynchronous programming, which allows it to perform non-blocking operations.
This is particularly useful for tasks like fetching data from a server, which can take some time to complete.
g. Platform Independent: Javascript will run in the same way in all systems with any operating system.
h. Prototype-Based Inheritance: JavaScript uses prototype-based inheritance, which is a bit different from class-based inheritance used
in many other programming languages. In prototype-based inheritance, objects can inherit properties and methods directly from other
objects.
2. Describe the JavaScript function with example.
Ans: In JavaScript, functions are first class values. It is a block of code designed to perform a specific task. Functions are defined
using the function keyword, followed by a name, and then parentheses (). Function parameters are listed inside the parentheses in the
function definition. The code to be executed by the function is placed inside curly brackets {}.
Function syntax for named functions: Anonymous functions: Methods are just function values inside of objects:
function add(x, y) { function(x, y) { var myobj = {};
return x + y; return x + y; myobj.add = function(x, y) {
} } return x + y;
};
myobj.add(2, 3) // 5
3. Write a Java script code which will check whether an email id is valid or not. Consider all possible cases.
function validateEmail(email) {
int flag = 0;
for (var i = 0; i <email.length(); i++){
if(email.charAt(i) == 0){
flag = 1;
break;
}
}
if (flag == 0)
return false;
}
function validateEmail(email) {
const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return regex.test(String(email).toLowerCase());
}

4. How will you do client side validation using JavaScript?


Ans: Client-side validation using JavaScript is a technique to validate user inputs on the client side (in the web browser) before
submitting the form to the server. It helps enhance user experience by providing immediate feedback without requiring a round-trip to
the server. Here's a basic example of client-side validation using JavaScript:
HTML form:
<form id="myForm" onsubmit="return validateForm()">
<label for="username">Username:</label>
3
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>

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


</form>

Javascript Validation
function validateForm() {
// Get form inputs
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
// Validate username
if (username === "") {
alert("Please enter a username.");
return false;
}
// Validate password
if (password === "") {
alert("Please enter a password.");
return false;
}
// Additional validation logic can be added here
// If all validations pass, return true to submit the form
return true;
}

5. Explain the various methods and its usage of String object.


Ans: The JavaScript String object is used to represent and manipulate a sequence of characters. The methods of String object do not
change the original string. They return a new string. Here are some of the most commonly used methods of the String object:
1. charAt(index): This method returns the character at the specified index. JavaScript strings are zero-based, meaning the first
character is at index 0.
let str = "Hello, World!";
console.log(str.charAt(0)); // Outputs: H

2. concat(string2, string3, ..., stringX): This method combines the text of two or more strings and returns a new string.
let str1 = "Hello";
let str2 = "World";
let str3 = str1.concat(" ", str2);
console.log(str3); // Outputs: Hello World

3. indexOf(substring, start): This method returns the position of the first occurrence of a specified value in a string. It returns -1 if the
value to search for never occurs.
let str = "Hello, World!";
console.log(str.indexOf("World")); // Outputs: 7

4. slice(startIndex, endIndex): This method extracts a section of a string and returns it as a new string, without modifying the original
string.
let str = "Hello, World!";
console.log(str.slice(0, 5)); // Outputs: Hello

5. split(separator, limit): This method splits a String object into an array of strings by separating the string into substrings.
let str = "Hello, World!";
console.log(str.split(",")); // Outputs: [ 'Hello', ' World!' ]

6. toLowerCase(): This method returns the calling string value converted to lowercase.
let str = "Hello, World!";
console.log(str.toLowerCase()); // Outputs: hello, world!
6. Using JavaScript display a system clock in the browser. 4
<body>
<span id="clock"></span> <br> <br>
<button onclick="myTimer()" value="Submit">Submit</button>
<script>
setInterval(myTimer, 1000);
function myTimer() {
const date = new Date();
document.getElementById("clock").innerHTML = "Time is " +
date.toLocaleTimeString();
}
</script>
</body>

7. Create a telephone directory using JavaScript such that the telephone number will be displayed in a text box whenever you
will select a name from the list box.
<body>
<form>
<label>Name: </label>
<select id="names" onchange="updatePhoneNumber()">
<option value="">Select a name</option>
<option value="1234567890">John Doe</option>
<option value="0987654321">Jane Doe</option>
</select>
<input type="text" id="phoneNumber" readonly>
</form>
<script>
function updatePhoneNumber() {
// Get the select element
var names = document.getElementById('names');
// Get the phone number from the value of the selected option
var phoneNumber = names.options[names.selectedIndex].value;
// Get the text input element
var phoneNumberInput = document.getElementById('phoneNumber');
// Update the text input value
phoneNumberInput.value = phoneNumber;
}
</script>
</body>

8. Write the purpose of toString() method in the context of JavaScript.


Ans: The toString() method in JavaScript is used to convert a value to a string. This method can be used with any data type, including
numbers, strings, arrays, objects, and more. It's particularly useful when you need to concatenate different types of values together, or
when you need to display a value in a string format. Here are some examples of how to use the toString() method:
1. Numbers: When called on a number, toString() converts the number to a string.
let num = 123;
console.log(num.toString()); // "123"

2. Arrays: When called on an array, toString() converts the array to a string, with each element separated by a comma.
let arr = [1, 2, 3];
console.log(arr.toString()); // "1,2,3"

3. Objects: When called on an object, toString() returns a string representation of the object. By default, this is "[object Object]".
let obj = {name: "John", age: 30};
console.log(obj.toString()); // "[object Object]"
9. State the differences between Java and JavaScript. 5
Java Javascript

Java is a strongly typed language and variables must be declared JavaScript is a loosely typed language and has a more
first to use in the program. relaxed syntax and rules.

Java is an object-oriented programming language primarily used JavaScript is a scripting language used for creating interactive a
for developing complex enterprise applications. web pages.

Java applications can run in any virtual machine(JVM) or JavaScript code used to run only in the browser, but now it
browser. can run on the server via Node.js.

Objects of Java are class-based. We can’t make any program in JavaScript Objects are prototype-based.
java without creating a class.

Java has a thread-based approach to concurrency. Javascript has an event-based approach to concurrency.

Java is statically typed, which means that data types are JavaScript is dynamically typed, which means that data types
determined at compile time. are determined at runtime.

10. State the purpose of ECMAScript standard in the context of JavaScript.


Ans: ECMAScript is a language specification, Javascript is a programming language which implements that specification. This means
that when we see new features in Javascript, those features were actually added to the ECMAScript specification, and Javascript then
implemented them in order to remain adherent to the ECMAScript standards.
Here are some of the key purposes of the ECMAScript standard:
a. Standardization: The ECMAScript standard provides a formal specification for JavaScript. This means that it defines the syntax,
semantics, and behavior of the language, ensuring that all JavaScript implementations (like different browsers or JavaScript engines)
behave consistently.
b. Interoperability: By standardizing JavaScript, the ECMAScript standard helps ensure that JavaScript code can run consistently
across different platforms and environments. This is particularly important for web development, where JavaScript is used to create
interactive web pages that can run in any web browser.
c. Future Development: The ECMAScript standard also guides the future development of JavaScript. New features and improvements
to the language are proposed and discussed in the context of the ECMAScript standard. This ensures that the language evolves in a
consistent and controlled manner.
d. Community Participation: The ECMAScript standard is developed through a process of community participation. Developers,
browser vendors, and other stakeholders contribute to the standard, ensuring that it reflects the needs and priorities of the JavaScript
community.
11. State the property attributes in the context of JavaScript Object.
Ans: Properties are the values associated with a JavaScript object. A JavaScript object is a collection of unordered properties.
Properties can usually be changed, added, and deleted, but some are read only. All properties have a name. In addition they also have a
value. The value is one of the property's attributes. Other attributes are: enumerable, configurable, and writable. These attributes define
how the property can be accessed (is it readable?, is it writable?).
12. Define associative array in the context of JavaScript.
Ans: Associative arrays are basically objects in JavaScript where indexes are replaced by user-defined keys. They do not have a length
property like a normal array and cannot be traversed using a normal for loop.
var arr = {key1:'value1', key2:'value2'}

Here, arr, is an associative array with key1, key2 being its keys or string indexes and value1 & value 2 are its elements.
var arr = { "Company Name": 'Flexiple', "ID": 123};

13. State purpose of spread operator(...) in the context of JavaScript Array.


Ans: The spread operator (...) in JavaScript is used to expand iterable elements such as arrays, strings, or objects into individual
elements. It's a convenient way to combine arrays, merge objects, or pass elements of an array as arguments to a function.
1. Combining Arrays: The spread operator can be used to combine two or more arrays into a new array.
let arr1 = [1, 2, 3]; 6
let arr2 = [4, 5, 6];
let combined = [...arr1, ...arr2]; // [1, 2, 3, 4, 5, 6]

2. Copying Arrays: The spread operator can be used to create a copy of an array.
let arr = [1, 2, 3];
let copy = [...arr]; // [1, 2, 3]

3. Merging Objects: The spread operator can be used to merge two or more objects into a new object.
let obj1 = {a: 1, b: 2};
let obj2 = {c: 3, d: 4};
let merged = {...obj1, ...obj2}; // {a: 1, b: 2, c: 3, d: 4}

4. Passing Array Elements as Arguments: The spread operator can be used to pass elements of an array as arguments to a function.
let arr = [1, 2, 3];
Math.max(...arr); // 3

14. Define arrow function in the context of JavaScript Array.


Ans: In JavaScript, an arrow function is a compact alternative to a traditional function expression. It's a way to write functions in a
more concise manner. Arrow functions are always anonymous, meaning they don't have a name. They are typically used in situations
where you need a function as an argument for another function, such as in array methods like map(), filter(), and reduce().
Here's an example of an arrow function:
let sum = (a, b) => a + b;

In this example, sum is an arrow function that takes two arguments, a and b, and returns their sum.
Arrow functions have some unique characteristics:
1. No this Binding: Unlike traditional functions, arrow functions do not have their own this context. Instead, they inherit the this value
from the enclosing scope. This makes them particularly useful when working with methods that rely on the this keyword.
2. Implicit Return: If the body of an arrow function consists of a single expression, you can omit the return keyword and the curly
braces. The function will return the result of the expression.
let sum = (a, b) => a + b; // Implicit return

3. No Arguments Object: Arrow functions do not have their own arguments object. Instead, they inherit the arguments object from the
enclosing scope.
Arrow functions are used extensively in JavaScript array methods. For example, you can use an arrow function with the map() method
to create a new array with the results of calling a provided function on every element in the array:
let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(num => num * num); // [1, 4, 9, 16, 25]

15. Explain how public field declaration is different from private field declaration in the context of JavaScript Class with
example.
Ans: Public fields are writable, enumerable, and configurable properties. They are part of the class's public API and can be accessed
and modified from outside the class. They are declared directly in the class body. Here's an example:
class ClassWithField {
field; // public field
fieldWithInitializer = "instance field"; // public field with initializer
}

Private fields are also part of the class's internal state, but they are not accessible from outside the class. They are declared with a #
prefix. Here's an example:
class Car {
#milesDriven = 0; // private field
drive(distance) {
this.#milesDriven += distance;
}
getMilesDriven() {
return this.#milesDriven;
}
}

16. Explain the concept of symbol in the context of JavaScript with an example. 7
Ans: In JavaScript, a Symbol is a unique and immutable data type that is often used to identify object properties. It is a built-in object
whose constructor returns a symbol primitive. Symbols are created using the Symbol() function, which returns a new unique symbol
each time it's called. Even if two symbols have the same description, they are not equal.
let sym1 = Symbol();
let sym2 = Symbol("foo");
let sym3 = Symbol("foo");
console.log(sym1 === sym2); // false
console.log(sym2 === sym3); // false

17. Define Typed Array in the context of JavaScript with example.


Ans: In Javascript, a typed array is an array-like buffer of binary data. JavaScript typed arrays are array-like objects that provide a
mechanism for reading and writing raw binary data in memory buffers.
Typed arrays are not intended to replace arrays for any kind of functionality. Instead, they provide developers with a familiar interface
for manipulating binary data.
Typed arrays are not arrays. isArray() on a typed array returns false.
18. State the purpose of global object in the context of JavaScript.
Ans: The global object in JavaScript is an object that always exists in the global scope. It provides variables and functions that are
available anywhere. In a browser environment, it is named window, for Node.js it is global. Global variables and functions declared
with var (not let/const) become the property of the global object.
19. How "strict equality operator(===)" is different from "normal equality operator(==)".
Ans: In JavaScript, the equality operator == and the strict equality operator === are used to compare two values for equality. However,
they behave differently when it comes to type coercion.
The == operator, also known as the loose equality operator, checks for equality after doing any necessary type conversions. This
means that it tries to convert the operands to the same type before comparing them. If the operands are of different types, == will
attempt to convert them to the same type and then compare them. This is known as type coercion.
console.log("5" == 5); // true, because "5" is converted to 5 and then compared
console.log(true == 1); // true, because true is converted to 1 and then compared

On the other hand, the === operator, also known as the strict equality operator, does not do type coercion. It will not convert the
operands to the same type before comparing them. If the operands are of different types, === will simply return false.
console.log("5" === 5); // false, because the types (string and number) are different
console.log(true === 1); // false, because the types (boolean and number) are different

20. What is destructuring assignment in the context of JavaScript?


Ans: Destructuring assignment in JavaScript is a feature that allows you to unpack values from arrays, or properties from objects, into
distinct variables. This can make your code more concise and easier to read.
Array Destructuring:
let arr = ['one', 'two', 'three'];
let [first, second, third] = arr;
console.log(first); // 'one'
console.log(second); // 'two'
console.log(third); // 'three'

Object Destructuring:
let obj = { a: 1, b: 2, c: 3 };
let { a, b, c } = obj;
console.log(a); // 1
console.log(b); // 2
console.log(c); // 3
21. State the purpose of for/of loop with example. 8
Ans: The for...of loop in JavaScript is used to iterate over iterable objects such as arrays, strings, maps, and sets. It simplifies the
process of looping over these objects and is particularly useful when you want to work with each element of the iterable directly,
rather than with their indices. Here's a basic example of a for...of loop with an array:
let arr = ['apple', 'banana', 'cherry'];
for (let value of arr) {
console.log(value);
}

In this example, the for...of loop iterates over the arr array. On each iteration, it assigns the current element's value to the value variable
and executes the console.log(value) statement.
22. Describe several techniques of object creation in the context of JavaScript.
Ans: Objects can be created with object literals, with the new keyword, and with the Object.create() function.
a. Object Literals: An object literal is a comma separated list of colon-separated name:value pairs, enclosed within curly braces. A
property name is a JavaScript identifier or a string literal (the empty string is allowed). A property value is any JavaScript expression;
the value of the expression (it may be a primitive value or an object value) becomes the value of the property.
let empty = {}; // An object with no properties
let point = { x: 0, y: 0 }; // Two numeric properties
let p2 = { x: point.x, y: point.y+1 }; // More complex values

b. Creating Objects with new : The new operator creates and initializes a new object. The new keyword must be followed by a
function invocation. A function used in this way is called a constructor and serves to initialize a newly created object.
let o = new Object(); // Create an empty object: same as {}.
let a = new Array(); // Create an empty array: same as [].
let d = new Date(); // Create a Date object representing the

c. Object.create() : Object.create() creates a new object, using its first argument as the prototype of that object.
let o1 = Object.create({x: 1, y: 2}); // o1 inherits properties x and y.
o1.x + o1.y // => 3
let o2 = Object.create(null); // o2 inherits no props or methods.
let o3 = Object.create(Object.prototype); // o3(empty object) is like {} or new Object().

One use for Object.create() is when you want to guard against unintended (but non malicious) modification of an object by a library
function that you don’t have control over. Instead of passing the object directly to the function, you can pass an object that inherits
from it.
library.function(Object.create(o));

23. Explain map() method in the context of JavaScript Array.


Ans: The map() method in JavaScript is a built-in array method that creates a new array by calling a provided function on every
element in the original array. It's a non-mutating method, meaning it doesn't change the original array, but instead creates a new one.
The map() method takes in a callback function as its argument. This callback function is called for each element in the array.
let numbers = [1, 2, 3, 4, 5];
let squares = numbers.map(function(num) {
return num * num;
});
console.log(squares); // [1, 4, 9, 16, 25]

24. How call() and apply() methods facilitate indirect invocation of a function in the context of JavaScript Function.
Ans: The call() method is used to invoke a function with a given this value and arguments provided individually.
const person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
person.fullName.call(person1, "Oslo", "Norway"); 9

The apply() method is used to invoke a function with a given this value and arguments provided as an array
const person = {
fullName: function(city, country) {
return this.firstName + " " + this.lastName + "," + city + "," + country;
}
}
const person1 = {
firstName:"John",
lastName: "Doe"
}
person.fullName.apply(person1, ["Oslo", "Norway"]);

25. Explain the concept of string interpolation in the context of JavaScript with example.
Ans: String interpolation in JavaScript is a process in which an expression is inserted or placed in the string. To insert or embed this
expression into the string a template literal is used. By using string interpolation in JavaScript, values like variables and mathematical
expressions and calculations can also be added.
The template literal has a dollar sign followed by curly brackets. Inside the curly brackets of this template literal, the expression or the
mathematical calculation which is to be evaluated and embedded should be written.
let firstName = "John";
let lastName = "Doe";
let text = `Welcome ${firstName}, ${lastName}!`;
console.log(text); // "Welcome John, Doe!"

26. Explain the concept of Set and Map class in the context of JavaScript.
Ans: A Set is a collection of unique items. This means that it cannot contain duplicate values. The items in a Set can be of any type,
including primitive values and objects.
let set = new Set();
set.add(1);
set.add(2);
set.add(3);
console.log(set.has(1)); // true
console.log(set.has(4)); // false
set.delete(1);
set.clear();

Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.
let map = new Map();
map.set('1', 'str1'); // a string key
map.set(1, 'num1'); // a numeric key
map.set(true, 'bool1'); // a boolean key
// remember the regular Object? it would convert keys to string
// Map keeps the type, so these two are different:
alert( map.get(1) ); // 'num1'
alert( map.get('1') ); // 'str1'
alert( map.size ); // 3

for (let item of set) {


console.log(item);
}
for (let [key, value] of map) {
console.log(key, value);
}
27. Write a script that uses function ‘c-area’ to prompt the user for the radius of a circle and calculate and print the area of a
circle. 10
function cArea() {
let radius = prompt("Enter the radius of the circle:");
let area = Math.PI * Math.pow(radius, 2);
console.log("The area of the circle is: " + area);
}
cArea();

28. Write a Javascript function that determines for a pair of integers whether the second integer is a multiple of the first.
function isMultiple(num1, num2) {
return num2 % num1 === 0;
}

29. With the help of an example show how a function can be called using EventListner in JavaScript.
Ans: In JavaScript, an Event Listener is a way to handle events such as clicks, mouse movements, key presses, etc. The
addEventListener() method is used to set up an event listener for a specific event on a specific element.
Here is an example of how a function can be called using an Event Listener in JavaScript:
<body>
<button id="myButton">Click me</button>
<script>
document.getElementById("myButton").addEventListener("click", function() {
alert("Button was clicked!");
});
</script>
</body>

30. Describe JavaScript Object and Array with example.


Ans: An object in JavaScript is a standalone entity, with key value pairs. It is similar to real-life objects such as a car, a person, or a
house. Each of these objects has properties and behaviors associated with it. Each property is a key-value pair, where the key is a
string and the value can be any valid JavaScript value. In JavaScript, an object can be created using curly braces {}. Here's an example
of a JavaScript object:
const person = {
firstName: "John",
lastName: "Doe",
age: 46
};

You can access the properties of an object using dot notation or bracket notation. For example, person.firstName or
person["firstName"] will both return "John".
An array in JavaScript is a special variable that can hold more than one value at a time. Arrays are used to store multiple values in a
single variable. They are created using square brackets []. Here's an example of a JavaScript array:
const cars = ["Saab", "Volvo", "BMW"];

31. How arrays are handled in Java Script?


Ans: JavaScript arrays are special variables that can hold more than one value at a time. They are used to store multiple values in a
single variable. Arrays are created using square brackets [] 1. Here's an example of creating an array:
const cars = ["Saab", "Volvo", "BMW"];

You can access the elements of an array using their index. Array indices start at 0, so cars[0] will return "Saab" 1.
Arrays in JavaScript are dynamic and can contain a mix of different data types. They are zero-indexed, meaning the first element of an
array is at index 0, the second is at index 1, and so on..
You can modify the elements of an array by accessing the index value. For example:
let dailyActivities = ['eat', 'sleep'];
dailyActivities[2] = 'exercise';
console.log(dailyActivities); // ['eat', 'sleep', 'exercise']
JavaScript arrays have various built-in methods for manipulating and interacting with the data they contain. Some of these methods 11
include sort(), push(), pop(), forEach(), and map() 1, 3, 5.
For example, you can use the push() method to add a new element to the end of an array:
const cars = ["Saab", "Volvo", "BMW"];
cars.push("Audi");
console.log(cars); // ["Saab", "Volvo", "BMW", "Audi"]

And you can use the forEach() method to execute a function for each element in the array:
const cars = ["Saab", "Volvo", "BMW"];
cars.forEach(car => {
console.log(car);
});

JavaScript arrays are resizable and can contain a mix of different data types. They are not associative arrays, so array elements cannot
be accessed using arbitrary strings as indexes, but must be accessed using nonnegative integers as indexes
32. Give an example to create a copy of an array using spread operator in JavaScript.
const originalArray = [1, 2, 3, 4, 5];
const copiedArray = [...originalArray];

In this example, originalArray is the original array, and copiedArray is a new array that contains all the elements of originalArray. The
spread operator (...) is used to "spread out" the elements of originalArray into copiedArray 1, 2.
It's important to note that the spread operator creates a shallow copy of the array. This means that if the original array contains objects,
the copied array will contain references to the same objects, not copies of the objects themselves. If you modify an object in the copied
array, it will also modify the object in the original array
33. Explain the purpose of Array.of() and Array.from() function in JavaScript.
Ans: The Array.of() method in JavaScript creates a new Array instance from a variable number of arguments, regardless of the number
or type of the arguments.
console.log(Array.of('foo', 2, 'bar', true));
// Expected output: Array ["foo", 2, "bar", true]
console.log(Array.of());
// Expected output: Array []

The Array.from() method in JavaScript creates a new, shallow-copied Array instance from an iterable or array-like object. This method
can be used to convert an iterable object (such as a Set or Map) or an array-like object (objects with a length property and indexed
elements) into an array
console.log(Array.from('foo'));
// Expected output: Array ["f", "o", "o"]
console.log(Array.from([1, 2, 3], (x) => x + x));
// Expected output: Array [2, 4, 6]

34. Explain with example the Rest Parameters and Arguments Object in the context of JavaScript function.
Ans: Rest parameters in JavaScript are used to represent an indefinite number of arguments as an array. It is a feature introduced in
ES6 that allows you to pass an arbitrary number of arguments to a function. The rest parameter is defined by prefixing the parameter
with three dots (...) in the function definition.

Here's an example of using rest parameters:


function myFun(a, b, ...manyMoreArgs) {
console.log("a", a);
console.log("b", b);
console.log("manyMoreArgs", manyMoreArgs);
}
myFun("one", "two", "three", "four", "five", "six");
// Console Output:
// a, one
// b, two
// manyMoreArgs, ["three", "four", "five", "six"]
The arguments object is an Array-like object that is available inside every function and contains the values of the arguments 12
passed to that function. It is not a real array, but it has some array-like properties and methods.
Here's an example of using the arguments object:
function myFun() {
console.log("a", arguments[0]);
console.log("b", arguments[1]);
console.log("manyMoreArgs", Array.from(arguments).slice(2));
}
myFun("one", "two", "three", "four", "five", "six");
// Console Output:
// a, one
// b, two
// manyMoreArgs, ["three", "four", "five", "six"]

In this example, the function myFun does not have any parameters, but it uses the arguments object to access the arguments passed to
the function.
Difference between Rest Parameters and Arguments Object
1. The arguments object is not a real array, while rest parameters are Array instances. This means that methods like sort(), map(),
forEach(), or pop() can be applied directly on rest parameters, but not on the arguments object.
2. The arguments object has the additional (deprecated) callee property.
3. The arguments object contains all of the parameters — including the parameters in the rest parameter array — bundled into one
array-like object. The rest parameter bundles all the extra parameters into a single array, but does not contain any named argument
defined before the rest parameter
35. State the purpose and example of following different type of expression in the context of javascript.
i) Function Definition Expression ii) Property Access Expression iii) Conditional Property Access
Ans: A function definition expression is a way to define a function inside an expression. It's similar to a function declaration, but the
function name can be omitted to create an anonymous function. A function definition expression can also be used as an Immediately
Invoked Function Expression (IIFE), which runs as soon as it is defined. Here's an example of a function definition expression:
const myFunction = function() {
console.log("Hello, world!");
};
myFunction(); // Outputs: "Hello, world!"

A property access expression is used to access the properties of an object. The dot notation (.) or bracket notation ([]) is used to access
the properties of an object. Here's an example of a property access expression:
const person = {
name: "John",
age: 30
};
console.log(person.name); // Outputs: "John"
console.log(person["age"]); // Outputs: 30

Conditional (ternary) property access is a way to access properties of an object conditionally. It's similar to a ternary operator, but used
for property access. Here's an example of conditional property access:

const adventurer = {
name: 'Alice',
cat: {
name: 'Dinah',
},
};
const dogName = adventurer.dog?.name;
console.log(dogName);
// Expected output: undefined
console.log(adventurer.someNonExistentMethod?.());
// Expected output: undefined
36. Give example of extending objects operation in JavaScript. 13
Ans: In JavaScript, you can extend objects in two main ways: through inheritance (using the extends keyword) and through object
merging (using the spread operator ...).
Inheritance (extends keyword) - Inheritance is a way of creating a new class using properties and methods of an existing class. The
extends keyword is used to create a child class that inherits the properties and methods of a parent class.
class Profile {
constructor(name, age) {
this.name = name;
this.age = age;
}
getName() {
return this.name;
}
getAge() {
return this.age;
}
}
class Student extends Profile {
constructor(name, age, languages) {
super(name, age);
this.lang = languages;
}
getDetails() {
console.log("Name : " + this.name);
console.log("Age : " + this.age);
console.log("Languages : " + this.lang);
}
}
var student1 = new Student("Ankit Dholakia", 24, ['Java', 'Python', 'PHP', 'JavaScript']);
student1.getDetails();

Object Merging (spread operator) - Object merging is a way of combining properties from multiple objects into a new object. The
spread operator ... is used to spread the properties of one or more objects into a new object.
var obj1 = {
name: 'Ankit',
age: 20
};
var obj2 = {
marks: 50
};
var object = {
...obj1,
...obj2
};
console.log(object); // { name: 'Ankit', age: 20, marks: 50 }

37. Justify the use of JSON.stringify() and JSON.parse() methods in Javascript.


Ans: The JSON.stringify() method in JavaScript is used to convert a JavaScript value into a JSON string. This method can be useful
when you need to send data to a server or save it to a file. The method can also be used to clone objects, as it creates a new string that
represents the object.
const obj = {
name: "John",
age: 30,
city: "New York"
};
const myJSON = JSON.stringify(obj);
console.log(myJSON); // Outputs: '{"name":"John","age":30,"city":"New York"}'
The JSON.parse() method in JavaScript is used to parse a JSON string and convert it into a JavaScript object. This method can be 14
useful when you receive data from a server or read it from a file. The method can also be used to clone objects, as it creates a new
object that represents the JSON string.
const myJSON = '{"name":"John","age":30,"city":"New York"}';
const obj = JSON.parse(myJSON);
console.log(obj.name); // Outputs: "John"

The JSON.stringify() method is used to convert the object into a JSON string, and then the JSON.parse() method is used to parse the
JSON string back into a new object. This creates a deep copy of the object, meaning that changes to the new object do not affect the
original object.
38. Write a JavaScript code to take some integers as a set of input and take a value to be searched, then find the position of the
value to be searched after sorting the integers.
Ans:
39. Using JavaScript extract the current date and display the day of the week as “Today Is MONDAY!!!”.
<body>
<div>
<span id="abc"></span> <br>
<span id="xyz"></span>
</div>
<button onclick="myFunc()" value="submit">Submit</button>
<script>
function myFunc() {
const date = new Date();
const day = date.getDay();
const hrs = date.getHours();
const min = date.getMinutes();
const sec = date.getSeconds();
const days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
var time = (hrs < 10 ? "0" + hrs : hrs) + ":" + (min < 10 ? "0" + min : min) + ":" + (sec < 10 ? "0" +
sec : sec);
document.getElementById("abc").innerHTML = "Today is " + days[day] + "!!!";
document.getElementById("xyz").innerHTML = "Time is " + time;
}
</script>
</body>

MODULE 3
1. What is a Servlet?
Ans: Servlet is a server side technology that handles client requests, processes the request and generates dynamic response..
2. Explain the life cycle of a servlet.
3. Describe step-by-step flow of execution of a Servlet in the Servlet Environment with diagram. 15
Ans: In a Servlet environment, the execution flow can be summarized into several key steps:
Step 1: Deployment and URL Mapping
Upon server startup, the web application is deployed into the Servlet container. The Servlet container, available in the main server,
establishes a virtual socket connection based on IP address and port number. URL mapping to servlet names is configured inside the
WEB-INF folder.
Step 2: Loading and Parsing of web.xml
The Servlet container recognizes and processes the web.xml file in the WEB-INF folder, loading, parsing, and extracting
application-level data like display names or context parameters.
Step 3: Identification of Welcome File
The container identifies the welcome file based on the "welcome file list" in the web.xml file, determining the initial page to display
on the client browser.
Step 4: Handling of Client Request
When a client sends a request, the protocol formats the request header and body. The server checks the request's validity and, if valid,
forwards it to the Servlet container.
Step 5: Identification and Execution of Servlet
The container identifies the servlet to execute based on URL patterns and resource names in the web.xml file. Once identified, the
servlet's life cycle begins, involving loading the .class file, executing the "doPost()" method, generating a response, and dispatching it
to the main server.
Step 6: Servlet Execution
If the servlet is not already available, the container loads the .class file into memory. After executing the "doPost()" method, the
response is generated, and the thread is destroyed. The container then dispatches the response to the main server.
Step 7: Preparation and Transfer of Response
The main server transfers the HTTP response to the protocol, which prepares and sends the response to the client browser.
4. Compare CGI and Servlet.

CGI (Common Gateway Interface) Servlet

It is process-based i.e. for every new request new process is It is thread based i.e. for every new request new thread is create
created.

The codes are written any programming language such as Perl, C, The codes are written in JAVA programming language.
Python.

It is not portable. It is portable.

It is removed from the memory after the completion of the It remains in the memory until it is not explicitly destroyed.
process-based request.

CGI applications consume more system resources because of the Servlets use fewer resources since they run in the server's addre
process creation for each request. are pooled for handling multiple requests.

Due to the process creation overhead, CGI may have slower Servlets generally offer better performance, as they operate with
performance compared to Servlets. server's process.

5. CGI is heavyweight and Servlet is lightweight — explain.


Ans: The terms "heavyweight" and "lightweight" in the context of CGI and Servlets refer to their resource utilization and architectural
characteristics. CGI is considered heavyweight due to the creation of a new process for each request, leading to significant overhead,
increased resource consumption, and slower performance. In contrast, Servlets are deemed lightweight as they operate within the
server's process, eliminating the need for constant process creation. Servlets' in-process execution and resource pooling contribute to
optimized resource usage, better scalability, and faster performance, making them more efficient for handling dynamic content in web
applications compared to the resource-intensive CGI approach.
6. State different packages required for the Servlet based server side implementation. 16
Ans: java.io.*;
java.util.*;
javax.servlet.*;
javax.servlet.http.*;
7. Explain which package, abstract class and interfaces are required to incorporate HTTPness in Servlet.
Ans: Abstract class - HttpServlet, Cookie
Interfaces - HttpServletRequest, HttpServletResponse, HttpSession
8. Why do we have to track session?
Ans: HTTP protocol and Web Servers are stateless, what it means is that for web server every request is a new request to process and
they can’t identify if it’s coming from client that has been sending request previously. But sometimes in web applications, we should
know who the client is and process the request accordingly. For example, a shopping cart application should know who is sending the
request to add an item and in which cart the item has to be added or who is sending checkout request so that it can charge the amount
to correct client. Session is a conversional state between client and server and it can consists of multiple request and response between
client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information
about the session (session id) is passed between server and client in every request and response.
9. How can a session be created?
Ans: In Java Servlets, a session is created using the HttpSession interface. The HttpSession interface is part of the javax.servlet.http
package and it provides methods to set attributes, get attributes, get session id, and other session related operations.
HttpSession session = request.getSession( );
Session.setAttribute("username", "password");

10. Write a Servlet to do session management with HttpSession class.


Ans: File name - DateServlet.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException,IOException {
HttpSession hs = request.getSession(true);
response.setContentType("text/html");
PrintWriter pw= response.getWriter();
pw.println("<B>");
//Display date/time of last access
Date date = (Date) hs.getAttribute("date");
if (date != null)
pw.println("Last access:" +date+ "<br>");
//Display current date/time
date = new Date();
hs.setAttribute("date",date);
pw.println("Current date:"+date);
}
}

11. Explain how the Cookies and URL rewriting help to do session management.
Ans: Cookies - Cookies are small piece of information that is sent by web server in response header and gets stored in the browser
cookies. When client make further request, it adds the cookie to the request header and we can utilize it to keep track of the session.
We can maintain a session with cookies but if the client disables the cookies, then it won’t work.
URL Rewriting - We can append a session identifier parameter with every request and response to keep track of the session. This is
very tedious because we need to keep track of this parameter in every response and make sure it’s not clashing with other parameters.
12. What is cookie? How can it be created?
Ans: In Java Servlets, you can create a cookie using the javax.servlet.http.Cookie class.
Cookie cookie = new Cookie("cookieName", "cookieValue" );
response.addCookie(cookie);
13. Create a cookie using servlet to store and display login information like username and password as entered by the user. 17
Ans: Filename : AddCookie.html
<html>
<head>
<title>Search</title>
</head>
<body>
<form name ="form1" action="AddCookieServlet" method="post">
<label for="username">Enter username: </label>
<input name="username" type="text">
<label for="password">Enter password: </label>
<input name="password" type="password">
</form>
<input type="submit" value="Submit">
</body>
</html>

Filename : AddCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response)throws
ServletException,IOException {
String username = request.getParameter("username");
Cookie cookie = new Cookie("name", username);
response.addCookie(cookie);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Username is ");
pw.println(username);
pw.close();
}
}

Filename : GetCookiesServlet.java
public class GetCookiesServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException,IOException {
//get cookies from request object
Cookie[] cookies = request.getCookies();
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
for(int i=0;i<cookies.length;i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("Cookie Name="+name+", Cookie Value="+value);
}
pw.close();
}
}

14. Write a Servlet for the currency conversion (Dollar to Rupees).


import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CurrencyServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException,IOException {
String d = request.getParameter("dollar");
double dollar = Double.parseDouble(d); 18
double rupees = dollar * 84;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("The amount in rupees is: " + rupees);
}
}

15. Using Servlet, calculate the area and circumference of a circle. The user enters the radius of a circle and clicks button
“Calculate”.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CircleServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException,IOException {
String r = request.getParameter("radius");
double radius = Double.parseDouble(r);
double area = Math.PI * radius * radius;
double circumference = 2 * Math.PI * radius;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Area of circle is: " + area);
pw.println("Circumference of circle is: " + circumference);
}
}

16. Write a Servlet to calculate the factorial of a given number.


import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FactorialServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException,IOException {
String n = request.getParameter("num");
int num = Integer.parseInt(n);
int fact = 1;
for(int i = 1; i <= num; i++)
fact = fact * i;
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("The factorial is: " + fact);
}
}

17. Write a servlet program to build a system clock with current date and time information.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.time.*;
public class SystemClockServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException,IOException {
Date date = new Date();
LocalTime time = LocalTime.now();
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("The date is: " + date);
pw.println("The time is: " + time); 19
}
}

18. Compare JSP and ASP.

JSP ASP

JSP stands for Java Server Pages, which helps developers to create ASP stands for Active Server Pages, which is used in web
dynamic web pages based on HTML, XML, etc. development to implement dynamic web pages.

JSP code is compiled at run-time. ASP code is not compiled, because it uses VB-script,
therefore it is an interpreted language.

It runs on JAVA programming language. It runs on Visual Basic language.

JSP is platform independent. ASP is not platform independent.

JSP have memory leak protection. ASP have not memory leak protection.

Extension of JSP is .jsp Extension of ASP is .asp

19. How does JSP help in MVC architecture?


Ans: Java Server Pages (JSP) plays a pivotal role in MVC architecture by providing a framework for efficient separation of concerns.
In MVC, JSP serves as the View, rendering Model data for user interaction. It allows embedding Java code in HTML, facilitating
dynamic content creation. Servlets or JSP pages act as Controllers, handling user input and directing Model updates. JSP's integration
into MVC enhances code organization, promotes maintainability, and facilitates the development of scalable and dynamic web
applications.
20. Draw and explain JSP life cycle.
Ans: The JSP (Java Server Pages) life cycle is a process that defines how a JSP page is processed from its creation to its destruction.
Translation Phase: This is the first step of the JSP life cycle. The JSP container translates the JSP page into a Servlet.
Compilation Phase: The generated Java servlet file (.java) is compiled into a class file (.class).
Loading and Instantiation Phase: This class file is then loaded into the memory by the classloader. An instance of the class is created.
Initialization: The jspInit() method is called only once during the life cycle immediately after the generation of the Servlet instance
from JSP. This method is used for any initialization tasks.
Request Processing Phase: The _jspService() method is used to serve the raised requests by JSP. It takes request and response objects
as parameters. This method cannot be overridden.
JSP Cleanup (Destruction) Phase: The jspDestroy() method is used to remove the JSP from use by the container or to destroy the
method for servlets. This method is called once, if you need to perform any cleanup task like closing open files, or releasing database
connections jspDestroy() can be overridden.

21. What are the implicit JSP objects?


Ans: JSP implicit objects are predefined objects that are available for use without any declaration or initialization. These objects are
automatically created by JSP Container and provide access to various functionalities and information related to JSP page. These are
out, request, response, session, config, application, pageContext, page, exception.
22. Write JSP to generate sum of two given numbers.
<html>
<head>
<title>Sum of Two Numbers</title>
</head>
<body>
<form method="post">
Enter First Number: <input type="text" name="num1"/><br/>
Enter Second Number: <input type="text" name="num2"/><br/>
<input type="submit" value="Calculate Sum"/>
</form>
<% 20
String num1 = request.getParameter("num1");
String num2 = request.getParameter("num2");

if(num1 != null && num2 != null) {


int val1 = Integer.parseInt(num1);
int val2 = Integer.parseInt(num2);
int sum = val1 + val2;
out.println("<br/>Sum = " + sum);
}
%>
</body>
</html>

23. Describe the different JSP elements in detail.


Ans: JavaServer Pages (JSP) uses various elements to embed Java code within HTML pages, facilitating the dynamic generation of
content. These elements include:
a. Directives:
Syntax: <%@ directive attribute="value" %>
Purpose: Specifies global settings for the entire JSP page, such as error handling or page language.
b. Declarations:
Syntax: <%! Java code %>
Purpose: Defines variables or methods that can be used throughout the JSP page, outside the main content.
c. Scriptlets:
Syntax: <% Java code %>
Purpose: Allows embedding Java code directly within HTML content to generate dynamic output.
d. Expressions:
Syntax: <%= Java expression %>
Purpose: Evaluates a Java expression and inserts the result directly into the HTML content.
e. Comments:
Syntax: <%-- This is a comment --%>
Purpose: Provides comments that are not included in the output HTML, useful for documentation.
f. Action Tags:
Syntax: <jsp:action attribute="value">...</jsp:action>
Purpose: Special tags like <jsp:include>, <jsp:forward>, and <jsp:param> for dynamic content inclusion, forwarding, and parameter
passing.
24. Write a JSP code which is used to read the value of check boxes from an HTML page and display the value. Write all
necessary assumptions.
<html>
<head>
<title>Checkbox Example</title>
</head>
<body>
<form method="post" action="checkbox.jsp">
<input type="checkbox" name="option" value="Option1"/> Option1<br/>
<input type="checkbox" name="option" value="Option2"/> Option2<br/>
<input type="checkbox" name="option" value="Option3"/> Option3<br/>
<input type="submit" value="Submit"/>
</form>
<%
String[] options = request.getParameterValues("option");
if (options != null) {
out.println("You have selected: ");
for (String option : options) {
out.println(option + "<br/>");
}
} else {
out.println("No options selected."); 21
}
%>
</body>

25. What is include directive and how does it work?


Ans: The include directive in JSP is used to include the contents of any resource such as a JSP file, HTML file, or text file. This
directive is processed at page translation time, which means the included content is merged with the current JSP during the translation
phase, and the actual page size grows at runtime. The syntax of the include directive is:
<%@ include file="resourceName" %>

The include directive is also used to create templates according to the developer's requirement and breaks the pages into parts like
header, footer, and sidebar. This is useful when you have common elements like headers, footers, or navigation bars that are used
across multiple pages. Here's an example of how the include directive can be used:
<%@ include file="header.jsp" %>
<center>
<p>Thanks for visiting my page.</p>
</center>
<%@ include file="footer.jsp" %>

Note that the include directive is a static include, which means it is resolved at compile time. If you need to include a file based on a
parameter value, which is only known at execution time, you should use a dynamic include, which is done using the <jsp:include> tag
26. Discuss page directives in brief.
Ans: JSP (Java Server Pages) directives are special instructions that provide information about the JSP page to the JSP container.
There are three types of directives in JSP: page directives, include directives, and taglib directives.
Page Directive: The page directive is used to define attributes that apply to the entire JSP page. The syntax of the page directive is:
<%@ page attribute="value" %>

Include Directive: The include directive is used to include the contents of another resource such as a JSP file, HTML file, or text file.
The syntax of the include directive is:
<%@ include file="resourceName" %>

Taglib Directive: The taglib directive is used to include a tag library in the JSP page. The syntax of the taglib directive is:
<%@ taglib prefix="prefix" uri="URI" %>

Here, prefix is the prefix that is used to identify the tags in the tag library, and URI is the Uniform Resource Identifier of the tag
library.
27. What is the purpose of declaration element in a JSP and how do we use them?
Ans: The declaration tag in JSP is used to declare variables, methods, and classes.The syntax of the declaration tag is:

<%! declaration; %>

Note that the code inside the declaration tag is static, which means it is shared among all instances of the servlet. Also, the code inside
the declaration tag cannot access implicit objects because it is not part of the service method
28. Write a JSP to do Miles to Kilometers conversion.
<html>
<head>
<title>Miles to Kilometers Conversion</title>
</head>
<body>
<form method="post" action="">
Enter Miles: <input type="text" name="miles"/><br/>
<input type="submit" value="Convert to Kilometers"/>
</form>
<%
String miles = request.getParameter("miles");
if(miles != null) {
double milesVal = Double.parseDouble(miles);
double kilometers = milesVal * 1.60934; 22
out.println("<br/>Kilometers = " + kilometers);
}
%>
</body>
</ht

29. Using JSP and JDBC technology create a form that is submitted along with the user name department and password. List
of borrowed library books and due date will be shown if the submitted details are correct.
<html>
<head>
<title>Library Login</title>
</head>
<body>
<form method="post" action="login.jsp">
Username: <input type="text" name="username"/><br/>
Department: <input type="text" name="department"/><br/>
Password: <input type="password" name="password"/><br/>
<input type="submit" value="Login"/>
</form>
<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username");
String department = request.getParameter("department");
String password = request.getParameter("password");
try {
// Load the database driver
Class.forName("oracle.jdbc.driver.OracleDriver");
// Establish the connection
Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@sid:1521:sid3",
"root", "password");
// Create a statement
Statement stmt = conn.createStatement();
// Execute the query
ResultSet rs = stmt.executeQuery("SELECT * FROM users WHERE username = '" + username
+ "' AND department = '" + department + "' AND password = '" + password + "'");
if (rs.next()) {
// User found, display the borrowed books and due dates
out.println("Borrowed Books: ");
ResultSet rs2 = stmt.executeQuery("SELECT * FROM books WHERE user_id = " +
rs.getInt("id"));
while (rs2.next()) {
out.println("Book: " + rs2.getString("title") + ", Due Date: " +
rs2.getDate("due_date"));
}
} else {
// User not found
out.println("Invalid username, department, or password.");
}
// Close the statement and the connection
stmt.close();
conn.close();
} catch (Exception e) {
out.println("Error: " + e.getMessage());
}
%>
</body>
</html>
30. What are custom tags? 23
Ans: Custom tags in JSP (JavaServer Pages) allow developers to define their own tags to encapsulate specific functionality and reuse
it across multiple pages. These custom tags enhance code modularity, readability, and maintainability. There are two types of custom
tags in JSP:
Syntax: <custom:tag attribute="value">...</custom:tag>
31. What are scriplets and explain with an example.
Ans: In JSP (JavaServer Pages), scriptlets allow developers to embed Java code directly within the HTML content of a JSP page.
Scriptlets are enclosed within <% and %> tags and are used for dynamic content generation.
32. Explain JSP Standard Template Library(JSTL) with example.
Ans: JSTL (JavaServer Pages Standard Tag Library) is a set of tags and functions that simplify the development of JavaServer Pages
(JSP) by providing a standard way to perform common tasks. JSTL includes tags for iteration, conditional processing, data formatting,
XML manipulation, and more.
Taglib Declaration:
Include the JSTL taglib declaration at the top of your JSP page.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Usage of JSTL Tags:


a. Iteration (c:forEach):
Iterate over a collection and display its elements.
<%@ page import="java.util.ArrayList" %>
<%
// Dummy data for illustration
ArrayList<String> colors = new ArrayList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
%>
<c:forEach var="color" items="<%= colors %>">
<p>${color}</p>
</c:forEach>

b. Conditional Processing (c:if):


Perform conditional processing to display content based on a condition.
<%@ page import="java.util.Calendar" %>
<%
// Get the current hour for illustration
int currentHour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
%>
<c:if test="${currentHour < 12}">
<p>Good morning!</p>
</c:if>
<c:else>
<p>Good afternoon!</p>
</c:else>

c. Formatting (c:out):
Output formatted content.
<%@ page import="java.util.Date" %>
<%
// Get the current date for illustration
Date currentDate = new Date();
%>
<c:out value="${currentDate}" formatPattern="yyyy-MM-dd" />

33. How does JSP handle runtime exceptions?


Ans: In JavaServer Pages (JSP), runtime exceptions can be handled in several ways. The default behavior is to let the exception
propagate up the call stack until it's caught, typically resulting in an error page being displayed to the user. However, JSP provides
mechanisms for customizing error handling:
a. Error Pages in Deployment Descriptor: In the web.xml deployment descriptor, you can define error pages that specify which JSP 24
or servlet should handle specific error codes or exceptions.
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>

In this example, if a java.lang.Exception occurs, the user is redirected to the error.jsp page.
b. Error Handling in JSP: - You can use the errorPage attribute in the <%@ page %> directive to specify a JSP page that will handle
exceptions for that particular page.
<%@ page errorPage="/error.jsp" %>

If an exception occurs in this JSP, the request will be forwarded to the specified error page.
c. Exception Object: - Within the error page, you can access information about the exception using the exception implicit object.
<%
Exception ex = (Exception) request.getAttribute("javax.servlet.error.exception");
%>

You can then use this object to obtain details about the exception, such as the message or stack trace, and display appropriate
information to the user.
d. Global Exception Handling: - Frameworks or application servers may provide global exception handling mechanisms. For example,
some frameworks have a central exception handler where you can define how to handle uncaught exceptions.
34. How comments are added in a JSP page?
Ans: In JavaServer Pages (JSP), you can add comments in three different ways:
a. HTML-Style Comments:
<!-- This is an HTML-style comment -->

b. JSP-Style Comments:
<%-- This is a JSP-style comment --%>

c. Java-Style Comments:
<%
// This is a Java-style comment
%>

or
<%
/*
This is a multiline Java-style comment
spanning multiple lines.
*/
%>

35. Create an application in JSP to redirect the request to any other page.
Ans: index.jsp
<html>
<head>
<title>Redirect Example</title>
</head>
<body>
<h2>Redirecting to Another Page...</h2>
<%
// Specify the URL to redirect to
String redirectURL = "targetPage.jsp";
// Perform the redirection
response.sendRedirect(redirectURL);
%>
</body>
</html>
targetPage.jsp 25
<html>
<head>
<title>Target Page</title>
</head>
<body>
<h2>Welcome to the Target Page!</h2>
</body>
</html>

36. How do <jsp:include/> and <jsp:forward/> actions differ from each other?
Ans: The <jsp:include> and <jsp:forward> actions in JSP are both used for including or forwarding content from one JSP page to
another, but they serve different purposes and have distinct characteristics:
<jsp:include>:
Purpose: Includes the content of another resource (JSP page, HTML file, or servlet) within the current JSP page during the execution
of the page.
Syntax: <jsp:include page="includedPage.jsp" />
<jsp:forward>:
Purpose: terminates the action of the current page and Forwards the request from the current JSP page to another resource (JSP page,
HTML file, or servlet) at the time the page is being processed. The forward action and
Syntax: <jsp:forward page="forwardedPage.jsp" />
37. Explain the importance of <jsp:useBean> action with example.
Ans: The <jsp:useBean> action in JavaServer Pages (JSP) is used to instantiate and access JavaBeans within JSP pages. JavaBeans are
reusable, modular components written in Java that encapsulate data and functionality. The <jsp:useBean> action simplifies the
creation and usage of JavaBeans within JSP, promoting modular and maintainable code. Example:
Suppose you have a simple JavaBean named Person:
// Person.java
public class Person {
private String name;
private int age;

// Getters and setters


// ...
}

Now, you can use <jsp:useBean> to instantiate and access this JavaBean in a JSP page:
<!-- Example.jsp -->
<%@ page import="example.Person" %>
<jsp:useBean id="personBean" class="example.Person" scope="session" />
<html>
<head>
<title>Using jsp:useBean</title>
</head>
<body>
<h2>Person Information</h2>
<jsp:setProperty name="personBean" property="name" value="John" />
<jsp:setProperty name="personBean" property="age" value="25" />
<p>Name: <jsp:getProperty name="personBean" property="name" /></p>
<p>Age: <jsp:getProperty name="personBean" property="age" /></p>
</body>
</html>

38. State advantages and disadvantages of JDBC.


Ans: Advantages of JDBC:

Database Independence: JDBC provides a way to connect to any database that has a JDBC driver, making it database-independent.
This means that you can write your Java code once and use it to connect to different databases.
Performance: JDBC drivers are optimized for performance. They are designed to handle the specific requirements of the database 26
they connect to, and they can execute SQL commands more efficiently than other methods.
Flexibility: JDBC allows for a high degree of flexibility. It supports a wide range of SQL commands, and it can handle complex
queries and updates.
Disadvantages of JDBC:
Driver Management: JDBC requires the installation of the correct drivers for each database type. This can be a time-consuming and
challenging task.
Lack of Support for Batch Updates: JDBC does not support batch updates. This means that if you want to update multiple tables in a
single sequence, you cannot do so with JDBC.
Complexity: JDBC can be complex to use, especially for beginners. It requires a good understanding of SQL and databases to use
effectively
39. Write a JSP application to show create, store and update operation in a database.
<%@ page import="java.sql.*" %>
<%
//initialize driver class
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (Exception e) {
out.println("Fail to initialize Oracle JDBC driver: " + e.toString() + "<P>");
}
String dbUser = "yourUserID";
String dbPasswd = "yourPassword";
String dbURL = "jdbc:oracle:thin:@sid3.comp.nus.edu.sg:1521:sid3";
//connect
Connection conn = null;
try {
conn = DriverManager.getConnection(dbURL,dbUser,dbPasswd);
out.println(" Connection status: " + conn + "<P>");
} catch(Exception e) {
out.println("Connection failed: " + e.toString() + "<P>");
}
String sql;
int numRowsAffected;
Statement stmt = conn.createStatement();
ResultSet rs;
// insert
try {
sql = "insert into employee values ('10', 'John')";
numRowsAffected = stmt.executeUpdate(sql);
out.println(numRowsAffected + " employee(s) inserted. <BR>");
} catch (SQLException e) {
out.println("Error encountered during row insertion for employee: " + e.toString() +
"<BR>");
}
// select
sql = "select id, name from employee";
rs = stmt.executeQuery(sql);
while (rs.next()) {
out.println("Id = " + rs.getString("ID") + ", Name = " + rs.getString("NAME") +
"<BR>");
}
out.println("<P>");

// delete
try {
sql = "delete from employee";
numRowsAffected = stmt.executeUpdate(sql);
out.println(numRowsAffected + " employee(s) deleted. <BR>");
} catch (SQLException e) {
out.println("Error encountered during deletion of employee: " + e.toString() + 27
"<BR>");
}
out.println("<P>");
rs.close();
stmt.close();
//commit
conn.commit();
//disconnect
conn.close();
%>
<HTML>
<BODY>
Bye bye! The system time is now <%= new java.util.Date()
</BODY>
</HTML>

40. Write a JSP page as an example of a preparedStatement for a INSERT operation.


<%@ page import="java.sql.*" %>
<%
//initialize driver class
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (Exception e) {
out.println("Fail to initialize Oracle JDBC driver: " + e.toString() + "<P>");
}
String dbUser = "yourUserID";
String dbPasswd = "yourPassword";
String dbURL = "jdbc:oracle:thin:@sid3.comp.nus.edu.sg:1521:sid3";
//connect
Connection conn = null;
try {
conn = DriverManager.getConnection(dbURL,dbUser,dbPasswd);
out.println(" Connection status: " + conn + "<P>");
} catch(Exception e) {
out.println("Connection failed: " + e.toString() + "<P>");
}
String sql;
int numRowsAffected;
// insert
try {
sql = "insert into employee values ('10', 'John')";
numRowsAffected = stmt.executeUpdate(sql);
out.println(numRowsAffected + " employee(s) inserted. <BR>");
} catch (SQLException e) {
out.println("Error encountered during row insertion for employee: " + e.toString() +
"<BR>");
}
out.println("<P>");
rs.close();
stmt.close();
//commit
conn.commit();
//disconnect
conn.close();
%>
<HTML>
<BODY>
</BODY>

</HTML>
MODULE 4 28
1. Explain 3-tier architecture of J2EE. State the advantages of 3-tier architecture over 2-tier architecture.
Ans: J2EE stands for Java Enterprise Edition and provides a standard for developing multitier, enterprise applications. J2EE
architecture supports component-based development of multi-tier enterprise applications. A J2EE application system typically
includes the following tiers:
a. Client Tier: The client tier consists of user programs that interact with the user for requests and responses. In the client tier, Web
components, such as Servlets and JavaServer Pages (JSPs), or standalone Java applications provide a dynamic interface to the
middle tier.
b. Middle tier (Server tier) - Usually contain enterprise beans and Web Services that encapsulate reusable, distributable business
logic for the application.
c. Enterprise Data Tier: Enterprise data is stored, preferably in a relational database. This tier contains containers, components, and
services. All the web components (Servlets, JSP) provide dynamic requests and responses from a web page. The EJB
components contain the server-side business logic for enterprise applications
Advantages of 3-tier architecture over 2-tier architecture :-
a. Separation of concerns - Business logic is separated from the client tier, making code cleaner and more maintainable.
b. Modularity and scalability - 3 tier-architecture is more modular, allowing independent development and scalability of each layer.
c. Improved security - The middle tier enhances security by acting as a buffer between the presentation and data layers, preventing
direct access to sensitive data.
2. Can all application servers run EJB? State when to use EJB.
Ans: Yes, all application servers that support Java Enterprise Edition (Java EE) can run EJB (Enterprise JavaBeans). EJB is a part of
the Java EE specification and is supported by application servers like Glassfish, JBoss, and others. EJB is typically used in the
following scenarios:
Scalability and Distributed Computing:
Transaction Management:
Security, Persistence:
Asynchronous Processing:
Component-Based Development:
3. What are the main parts of EJB Technology, explain them in brief.
Ans: Enterprise JavaBeans (EJB) is a server-side software component that encapsulates the business logic of an application. The main
parts of EJB technology are:
1. Enterprise Beans: These are the core components of EJB technology. They encapsulate the business logic of an application and can
be invoked by clients. There are three types of Enterprise Beans: Session Beans, Entity Beans, and Message-Driven Beans.
2. EJB Container: The EJB Container is a runtime environment that manages the lifecycle of Enterprise Beans. It provides services
such as transaction management, security, and object pooling. The EJB Container is part of the Java application server.
3. Java Application Server: The Java Application Server is the platform that runs the EJB Container. It provides the runtime
environment for EJB applications. Examples of Java Application Servers include Glassfish, JBoss, and WebLogic.
4. Java Persistence API (JPA): JPA is a part of EJB technology that provides a standard way to map Java objects to relational database
tables. It is used for the management of persistence and object/relational mapping.
5. Web Services: EJB technology also supports the development and deployment of web services applications. This makes it easier to
implement and deploy web services applications based on Java technology
4. State the benefits of EJB.
Ans: Enterprise JavaBeans (EJB) offers several benefits, making it a valuable component architecture for building scalable and
distributed enterprise-level applications:
Scalability: EJB provides a scalable architecture suitable for large-scale applications. It supports the distribution of components across
multiple servers, allowing applications to handle increased loads and user concurrency.
Transaction Management: EJB includes built-in support for distributed transactions. This ensures that a series of operations can be
performed atomically, maintaining data consistency and integrity across multiple components and databases.
Security: EJB provides a comprehensive security model, supporting declarative security annotations. Developers can define access
control rules, securing components and methods based on roles and permissions.
Persistence (via JPA): EJB integrates with the Java Persistence API (JPA) for object-relational mapping and database interaction. This
simplifies the management of persistent entities and ensures a standardized approach to data access.
Component-Based Development: EJB promotes component-based development, allowing developers to build modular and 29
reusable business components. This enhances code maintainability, fosters code reuse, and supports a more structured development
approach.
Asynchronous Processing: EJB includes Message-Driven Beans (MDB), enabling asynchronous processing of messages using the
Java Message Service (JMS). This is useful for handling background tasks and events without blocking the main application flow.
Portability: EJB applications are designed to be portable across different Java EE-compliant application servers. This enables
developers to deploy applications on various servers without major code changes.
Distributed Computing: EJB supports distributed computing, allowing components to be distributed across multiple servers. Remote
method invocation capabilities enable communication between components in a distributed environment.
5. Describe different types of EJB in brief.
Ans: Enterprise JavaBeans (EJB) is a server-side software component that encapsulates the business logic of an application. There are
three types of EJBs:
1. Session Beans: Session beans contain business logic that can be invoked by local, remote, or web service clients. There are three
types of session beans:
a. Stateful Session Bean: It maintains conversational state with the client between method invocations. It is used when the state of the
bean is not shared between multiple clients.
b. Stateless Session Bean: It does not maintain any conversational state with the client. It is used when the state of the bean is shared
between multiple clients.
c. Singleton Session Bean: It is a type of stateful session bean that is instantiated only once and shared among all clients. It is used
when the bean needs to maintain a shared state among all clients.
2. Entity Beans: Entity beans represent the persistent objects of the application. They map to a table in the database and contain the
business logic to interact with the database. They are used to create, read, update, and delete records in the database.
3. Message-Driven Beans (MDBs): Message-driven beans are used to process messages asynchronously. They are used to handle
messages that are sent to a JMS (Java Message Service) queue or topic. MDBs are used when the application needs to process
messages in a decoupled manner
6. State the deciding aspects between the Local and Remote Interfaces.
Ans: In Java EE, there are two types of interfaces for EJBs: Local and Remote. The choice between Local and Remote interfaces
depends on the context in which the EJB is being used.
Local Interfaces: Local interfaces are used for communication within the same application. They are typically used when the client and
the EJB are part of the same application. The Local interface provides a more efficient way to access the EJB because it avoids the
overhead of remote method invocation (RMI). However, Local interfaces can only be used if the client and the EJB are in the same
application.
Remote Interfaces: Remote interfaces, on the other hand, are used for communication across different applications or different JVMs.
They are used when the client and the EJB are not part of the same application. The Remote interface provides a way to access the
EJB from a remote application, but it comes with the overhead of remote method invocation (RMI). Therefore, it's less efficient than
Local interfaces, but it provides more flexibility.
7. Describe the several components of J2EE technologies.
Ans: Java 2 Platform, Enterprise Edition (J2EE) technologies, now known as Java Platform, Enterprise Edition (Java EE), is a set of
specifications and APIs that provide a robust and scalable platform for building enterprise-level applications. The key components of
Java EE include:
1. Enterprise JavaBeans (EJB):
Purpose: Component-based architecture for building distributed, scalable, and transactional business components.
Types: Session Beans (Stateless and Stateful), Entity Beans (deprecated in favor of Java Persistence API), Message-Driven Beans.
2. Java Servlets:
Purpose: Server-side components for handling HTTP requests and generating dynamic web content. Servlets are the foundation of
Java web applications.
Characteristics: Run on the server, handle requests, and generate dynamic responses.
3. JavaServer Pages (JSP):
Purpose: Technology for creating dynamic web content by embedding Java code in HTML pages.
Characteristics: Simplifies web page development by allowing the mixing of static HTML content with Java code.
4. JavaServer Faces (JSF):
Purpose: Java web application framework for building user interfaces in a component-based manner.
Characteristics: Provides a set of reusable UI components, simplifies page navigation, and supports event handling. 30
5. Java Message Service (JMS):
Purpose: API for messaging between distributed components in a loosely coupled, asynchronous manner.
Characteristics: Supports message-driven beans, point-to-point and publish-subscribe messaging.
6. Java Naming and Directory Interface (JNDI):
Purpose: API for accessing naming and directory services in a network.
Characteristics: Enables Java applications to look up and locate distributed objects.
7. Java Transaction API (JTA):
Purpose: API for managing distributed transactions in Java applications.
Characteristics: Coordinates transactions across multiple participating components and resources.
8. JavaMail API:
Purpose: API for sending and receiving email messages in Java applications.
Characteristics: Supports protocols like SMTP, IMAP, and POP3.
9. Java Persistence API (JPA):
Purpose: API for managing relational data in Java applications, providing a standard way to interact with databases.
Characteristics: Maps Java objects to database tables, supports object-relational mapping (ORM), and simplifies database operations.
8. Describe the multiplicity in container-managed relationships in the context of Entity Beans.
Ans: In the context of Entity Beans, multiplicity in container-managed relationships describes how many instances of an entity bean
can be related to instances of another entity bean. There are four types of multiplicities, all of which are supported by Oracle
Application Server:
One-to-One: Each instance of an entity bean is related to a single instance of another entity bean. This means that for every instance of
Entity Bean A, there is at most one instance of Entity Bean B, and vice versa.
One-to-Many: An instance of an entity bean is related to multiple instances of another entity bean. This means that for every instance
of Entity Bean A, there can be multiple instances of Entity Bean B.
Many-to-One: Multiple instances of an entity bean may be related to a single instance of another entity bean. This is the opposite of
one-to-many. This means that multiple instances of Entity Bean A can be related to a single instance of Entity Bean B.
Many-to-Many: The entity bean instances may be related to multiple instances of each other. This means that multiple instances of
Entity Bean A can be related to multiple instances of Entity Bean B.
These multiplicities are defined in the entity bean's deployment descriptor and are used by the EJB container to manage the
relationships between entity beans. The EJB container takes care of the relationships for you, which is why these relationships are
often referred to as container-managed relationships
9. Discuss the importance of abstract schema in the context of Entity Beans.
Ans: The abstract schema defines how the properties of an Entity Bean map to the columns of a relational database table.
Importance of Abstract Schema in Entity Beans:
1. Object-Relational Mapping (ORM): The abstract schema defines the mapping between the object-oriented world of Java and the
relational world of databases. It specifies how Java classes and their attributes correspond to tables and columns in a relational
database.
2. Consistent Data Model: The abstract schema helps maintain a consistent data model across the application. It ensures that different
components of the application use a uniform approach to interact with the underlying database, facilitating code readability and
maintainability.
3. Encapsulation of Database Details: The abstract schema encapsulates details related to the underlying database, providing a level of
abstraction. Developers can focus on defining the business logic within Entity Beans without being concerned about the specific SQL
statements or database-specific details.
4. Flexibility in Database Design: Abstract schema allows developers to design the database schema in a way that suits the
application's requirements. It abstracts away the complexities of the database structure, enabling changes in the database design
without affecting the Entity Bean's interface.
5. Code Reusability: A well-defined abstract schema encourages code reusability. Developers can use the same Entity Bean classes in
different applications or modules without rewriting database-related code, promoting a modular and reusable codebase.
10. What makes Message-Driven Beans different from Session and Entity Beans.

You might also like