WebTechnology Questions
WebTechnology Questions
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());
}
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;
}
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>
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.
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};
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
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
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
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));
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
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>
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"];
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.
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 }
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.
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 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.
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();
}
}
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);
}
}
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
}
}
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.
JSP have memory leak protection. ASP have not memory leak protection.
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:
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" %>
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" />
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;
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>
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>
</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.