0% found this document useful (0 votes)
4 views47 pages

Advanced Java EJB Programming Guide

The document provides an overview of Advanced Java Programming, focusing on Enterprise JavaBeans (EJB), including their advantages, lifecycle, and types such as Message-Driven Beans and Stateless EJBs. It also covers Java Message Service (JMS) architecture, the definition and writing process of beans, and JSP page forwarding. Additionally, it introduces the Java Mail API for sending and managing emails, highlighting its features and core components.

Uploaded by

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

Advanced Java EJB Programming Guide

The document provides an overview of Advanced Java Programming, focusing on Enterprise JavaBeans (EJB), including their advantages, lifecycle, and types such as Message-Driven Beans and Stateless EJBs. It also covers Java Message Service (JMS) architecture, the definition and writing process of beans, and JSP page forwarding. Additionally, it introduces the Java Mail API for sending and managing emails, highlighting its features and core components.

Uploaded by

adigupta3055
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

ADVANCED JAVA PROGRAMMING

UNIT - I
1. What is EJB? main advantages of EJB.
Ans. EJB stands for Enterprise JavaBeans. It is a part of Java EE (Enterprise Edition) used to build
server-side, scalable, transactional, and secure applications.
EJBs run inside an EJB container, which takes care of:
 Transactions
 Security
 Multithreading
 Lifecycle management
 Remote access
Advantages of EJB:
1. Simplifies Development: Developers can focus on business logic; the container handles technical stuff.
2. Transaction Management: Automatic handling of transactions.
3. Security: Role-based access control.
4. Remote Access: Business methods can be accessed remotely using RMI (Remote Method Invocation).
5. Scalability: Easily handles multiple users.
6. Reusability: Beans can be reused in different applications.

2. Explain EJB Lifecycle with neat and clean diagram.


Ans.
3. Describe Message Driven Beans within lifecycle.
Ans. A Message-Driven Bean is a special type of Enterprise JavaBean (EJB) used to receive and process
asynchronous messages from a Java Messaging Service (JMS) queue or topic.
MDB is used to listen to messages from a queue or topic and process them automatically in the background.
Simple Explanation:
 It works like a listener.
 When a message is sent to a JMS queue or topic, the MDB automatically receives and
processes it.
 Clients don’t call MDBs directly.

There are two main states in the MDB lifecycle shown in this diagram:
🟩 1. Does Not Exist
 This is the initial state.
 The MDB has not been created yet.
From here, the EJB container performs:
 Dependency injection (if any resources or services are required).
 Calls the @PostConstruct callback method (optional) for any startup configuration.
Then, the bean moves to the Ready state.

🟩 2. Ready
 In this state, the MDB is fully initialized and waiting for messages.
 When a message arrives from a JMS queue or topic, the container automatically calls the
onMessage() method.
 The onMessage() method processes the message.
📨 This method is called every time a new message comes in.

🧹 PreDestroy Callback
When the bean is no longer needed (e.g., the application is stopped or undeployed):
 The container may call the @PreDestroy method to clean up resources.
 After that, the bean returns to the Does Not Exist state.

4. Describe Session Beans with in Lifecycle.


Ans.
Session Bean:
 A Session Bean is a type of EJB (Enterprise JavaBean).
 It contains business logic that can be used by clients.
 Works during a client session (temporary interaction).
 Managed by the EJB container (handles lifecycle, security, transactions).
This diagram shows the lifecycle of a Stateful Session Bean in EJB
🧩 Stateful Session Bean means:
 It remembers the client’s data between method calls.
 Example: If a user logs in and adds items to a shopping cart, the bean remembers it
for that specific user.

🔄 Lifecycle Stages (Step-by-Step Explanation)


1. Does Not Exist
 Bean is not yet created.
 No memory, no activity.
 It will be created when the client requests it.

2. Creation: setSessionContext, ejbCreate()


 When the client calls the bean for the first time, the container:
o Calls setSessionContext(): sets up the environment (like references to other
services).
o Then calls ejbCreate(): this initializes the bean (like a constructor).
 Now the bean is in Ready state.

3. Ready State (Working State)

 The bean is active and ready to handle client requests.


 When a method is called (like addItem() or checkout()), the business method
executes.
 The bean stays in this state while the client keeps using it.

4. Passivation: ejbPassivate()
 If the bean is idle for too long, the container temporarily stores it to save memory.
 ejbPassivate() method is called to passivate (pause) the bean and move it to the
Passive state.

5. Passive State
 Bean is "asleep".
 Its data is stored but it’s not using memory or resources.
 It can be re-activated if the client comes back.

6. Activation: ejbActivate()
 When the client returns, the container activates the bean by calling ejbActivate().
 The bean comes back to Ready state and continues working.

7. Removal: ejbRemove()
 When:
o The client explicitly ends the session,
o Or the bean times out,
o Or the server shuts down,
 Then ejbRemove() is called.
 The bean is destroyed and goes back to Does Not Exist state.
5. Explain the uses of Message Driven Beans with proper example.
Ans. Message Driven Beans (MDBs) are used in Java EE (now Jakarta EE) for processing
asynchronous messages.
They help in handling background tasks without blocking the main application flow. Here’s how they
work:
Uses:
1. Asynchronous Processing: MDBs allow messages to be processed in the background without
making the application wait. When a message is sent, MDB processes it while the application
continues with other tasks.
2. Message Queue: MDBs listen to a message queue (like JMS) and retrieve messages from it when
available. Once an MDB is ready, it processes the messages asynchronously.
3. Decoupling: The sender and receiver of the message do not need to know about each other. The
sender just sends the message to a queue, and the MDB processes it. This reduces direct
dependency between different parts of the system.
4. Background Tasks: MDBs are ideal for tasks that don’t require immediate real-time responses,
such as sending emails, updating databases, or calling external services.
5. Scalability: MDBs efficiently handle a large number of messages, making it scalable for high
traffic systems.
6. Error Handling: If an error occurs while processing a message, the MDB can retry without
affecting the rest of the system
Example Use Case:
Imagine an application where users register. After a new user registers, a message is sent to a message
queue.
 After user registration, the application sends a message to the queue.
 The MDB listens for the message and, upon receiving it, processes it by sending a welcome email
to the user in the background.
This way, the main application flow continues while the MDB handles the message and background
task.

6. Describe JMS. Explain JMS Architecture with details.


Ans. JMS (Java Message Service) – Explained Simply
 JMS is a Java API (Application Programming Interface) that allows Java applications to
communicate with each other using messaging.
 It supports asynchronous communication, which means one application can send a message
and continue its work without waiting for a response.
🔹 Why JMS is Used:
 To allow loosely coupled communication between components.
 To reliably send and receive messages.
 To support asynchronous operations.
 To integrate with distributed systems.

🔹 JMS Architecture – Components and How It Works


JMS architecture consists of the following main components:

1. JMS Provider
This is the messaging system (middleware) that handles the messaging between sender and receiver.
Examples: Apache ActiveMQ, IBM MQ, RabbitMQ.

2. JMS Client
Java applications that send or receive messages. There are two types:
 Producer (Sender): Sends messages.
 Consumer (Receiver): Receives messages.

3. JMS Messages
The actual content sent from producer to consumer. A message has:
 Header: Contains metadata (like destination).
 Body: Contains actual data (text, object, byte, etc.).

4. Administered Objects
These are pre-configured JMS objects stored by the provider:
 ConnectionFactory: Helps clients create a connection with the provider.
 Destination: Represents the target of messages (either a Queue or a Topic).

5. Messaging Models (Two Types):


A. Point-to-Point (Queue-based)
 One sender sends a message to a queue.
 One receiver receives that message.
 Message is removed after it's read.
Example Use: Order processing system (one order is handled by one worker).
B. Publish/Subscribe (Topic-based)
 One sender publishes a message to a topic.
 Multiple receivers subscribed to the topic get a copy of the message.
Example Use: News notification system (one update goes to all subscribers).

7. Define the Bean. Explain the steps for bean writing process.
Ans. Definition of Bean (in Java EE)
A Bean in Java EE (Jakarta EE) is a reusable, self-contained software component that follows
specific conventions. It is used to represent a part of the application logic, such as handling user input,
processing data, or communicating with databases.
Beans are mainly of three types:
 Enterprise JavaBeans (EJB) – used for business logic.
 JavaBeans – used for simple reusable components (like UI).
 Managed Beans – used in frameworks like JSF or Spring.
In EJB (Enterprise JavaBeans), a Bean is a special Java class that is managed by the EJB container,
and is used to perform server-side operations.

🔹 Steps to Write a Bean (in simple and detailed way)


Let’s break it down step-by-step for writing an EJB (Enterprise Java Bean):

Step 1: Create the Bean Class


 Write a plain Java class that represents the business logic.
 Use appropriate EJB annotations based on the type (like @Stateless, @Stateful,
@MessageDriven).
Example (for a Stateless Bean):
@Stateless
public class CalculatorBean {
public int add(int a, int b) {
return a + b;
}
}

Step 2: Implement Business Logic


 Inside the bean class, write methods that contain the actual logic you want to run.
 These methods will be called by the client (another Java class or application).

Step 3: Use EJB Annotations


Use one of these to define the type of EJB:
 @Stateless – if the bean doesn’t maintain session state.
 @Stateful – if it remembers client state between method calls.
 @MessageDriven – if it listens to messages (from JMS).
Step 4: Deploy the Bean
 Package your bean in an EJB module (usually a .jar file).
 Deploy it to an EJB container (like WildFly, GlassFish, JBoss).

Step 5: Access the Bean from a Client


 The client can access the bean using dependency injection or JNDI lookup.
Example (Accessing Bean using injection):
@Inject
CalculatorBean calculator;
Now, the client can call:
int result = [Link](5, 3);

8. What is a stateless EJB explain with example.


Ans. What is a Stateless EJB
A Stateless EJB (Enterprise JavaBean) is a type of EJB that does not maintain any information
(state) about the client between method calls.
This means every time a client calls a method of a stateless bean, it's like a fresh call — the bean does
not remember anything from the previous interaction. All clients share the same bean instance to
save memory and improve performance.

Key Features of Stateless EJB:


1. No client-specific data is stored.
2. Fast and lightweight.
3. Suitable for reusable operations (like calculations, database queries).
4. Managed by EJB container, which handles lifecycle and resource management.

🔹 When to Use Stateless EJB:


Use it when:
 You don’t need to store data for a particular user between method calls.
 You want to perform simple tasks like adding numbers, checking availability, sending emails, etc.

🔹 Example (Simple and Clear)


Imagine you are creating a calculator service for your app.
✅ Step 1: Create a Stateless Bean
import [Link];

@Stateless
public class CalculatorBean {

public int add(int a, int b) {


return a + b;
}
public int subtract(int a, int b) {
return a - b;
}
}
✅ Step 2: Access the Bean from a Client Class
import [Link];
public class CalculatorClient {
@EJB
CalculatorBean calculator;
public void doMath() {
int result = [Link](10, 5);
[Link]("Result: " + result); // Output: Result: 15
}
}
Even if multiple users call add(), the bean won’t remember who called it or what values were used
before.

🔹 Advantages of Stateless EJB


Feature Benefit
No client state Fast performance
Reusable Same bean can be used by many clients
Easy to manage No complex session handling
Scalable Suitable for large-scale apps

UNIT – II
1. Explain which action element is used to forward JSP page to another page.
Ans. In JSP (JavaServer Pages), the action element used to forward a page to another page is:
<jsp:forward>
This tag is used to forward the request from one JSP page to another resource like another JSP
page, HTML page, or a servlet. It is handled on the server side before any output is sent to the
client (browser).

Syntax:
<jsp:forward page="[Link]" />
Here, "[Link]" is the name of the page where the request will be forwarded.

How It Works:
 When the server processes a JSP page and finds <jsp:forward>, it immediately stops processing
the current page.
 It then forwards the request and response objects to the specified page.
 The user only sees the content of the forwarded page — not the original one.

Example:
<%
String name = [Link]("username");
if(name == null || [Link]("")) {
%>
<jsp:forward page="[Link]" />
<%
}
%>
<h2>Welcome, <%= name %>!</h2>
In this example:
 If the user doesn't enter a name, the page is forwarded to [Link].
 If a name is entered, the welcome message is displayed.

Important Points:
1. <jsp:forward> is a JSP action tag used for page navigation.
2. It helps in server-side redirection.
3. No content is shown from the current page once forwarding happens.
4. It is useful in form handling, login systems, and access control.

Conclusion:
<jsp:forward> is a simple and powerful tag in JSP used to forward a request to another page before sending any
response to the browser. It ensures better control over page navigation and user flow.

2. Create a web application in JSP for sending some information to another page using session.
Ans. Web Application Example using Session
✅ Step 1: [Link] (Set data in session)
<%
String name = [Link]("username");
[Link]("userName", name);
%>

<jsp:forward page="[Link]" />


Explanation:
 The value entered by the user is fetched using [Link]().
 The data is stored in session using [Link]().

✅ Step 2: [Link] (Get data from session)


<%
String user = (String) [Link]("userName");
%>

<h2>Welcome, <%= user %>!</h2>


Explanation:
 The data is retrieved from session using [Link]().
 It is displayed to the user with a welcome message.
📌 Important Points:
1. [Link](key, value) is used to store data.
2. [Link](key) is used to retrieve data.
3. The data stored in session is available across all JSP pages for that user.
4. Session is active until the user closes the browser or the session times out.

3. Explain Java Mail API and create a Java program to send mail to specific user using Java Mail API.
4. Explain the overview of Java Mail API.
Ans. Introduction to JavaMail API

JavaMail API is a powerful set of Java classes and interfaces that allow Java
applications to send, receive, and manage emails.
It simplifies working with email systems by providing an easy-to-use interface to
communicate via SMTP, POP3, and IMAP protocols.
JavaMail can be used to send automated emails, read incoming emails, manage
mailboxes, and handle attachments.
Features of JavaMail API
1. Sending Emails: JavaMail provides the functionality to send emails through the Simple Mail
Transfer Protocol (SMTP).
2. Receiving Emails: It allows programs to receive and manage emails from mail servers using
IMAP or POP3 protocols.
3. Email Attachments: JavaMail supports sending emails with attachments such as images,
PDF files, etc.
4. HTML Emails: It allows sending HTML-formatted emails in addition to plain text.
5. Authentication: JavaMail supports user authentication to send emails via secure mail servers.
Core Components of JavaMail API
1. Session: The Session object represents a configuration for connecting to a mail
server. It holds the mail server's settings, like SMTP server address, port number,
and authentication details (username and password).
2. Message: A Message object represents the email that you want to send. It contains information
such as the sender, recipient, subject, and content of the email. It can also contain attachments.
3. Transport: The Transport class is responsible for sending the email to the recipient using the
SMTP protocol.
4. Store and Folder:
o Store represents the connection to a mail server for receiving emails.
o Folder represents a specific mailbox (like inbox or sent items) where you can read and
manage emails.
Supported Email Protocols
1. SMTP (Simple Mail Transfer Protocol): Used to send emails to a mail server.
2. IMAP (Internet Message Access Protocol): Used for retrieving emails from the server,
allowing email management directly on the server.
3. POP3 (Post Office Protocol): Another protocol for retrieving emails, but it downloads the
emails from the server and stores them locally.
How JavaMail API Works
1. Create a Session: First, you create a Session object, which contains all the configurations needed
to connect to the mail server.
2. Create a Message: After that, you create a Message object where you set the sender, recipient,
subject, and body of the email.
3. Send the Message: Finally, the [Link]() method sends the email through the mail server.
Common Use Cases of JavaMail API
1. Automated Notifications: JavaMail is widely used to send automated notifications such as
account registrations, password resets, or order confirmations.
2. Bulk Email: It is used in email marketing to send newsletters or promotional emails to multiple
recipients.
3. Alert Systems: JavaMail can send alerts or reports, for example, system monitoring
notifications.
4. Customer Support: JavaMail helps to automatically send customer support responses, ticket
updates, etc.
Security Considerations
JavaMail provides security features like:
 Authentication: It supports user authentication to securely send emails through services like
Gmail or Outlook.
 TLS/SSL Encryption: JavaMail can enable secure communication by using TLS/SSL protocols
to protect the email data during transmission.

5. Explain J2EE containers. Also explain its services.


Ans. J2EE Containers and Their Services
Introduction to J2EE Containers
J2EE containers are part of the Java 2 Enterprise Edition (J2EE) platform that manage the
execution of enterprise components like servlets, JSPs, and EJBs.
They provide an environment to run these components and offer essential services like transaction
management, security, and resource management.
There are two main types of J2EE containers:
1. Web Container: Manages servlets and JSPs.
2. EJB Container: Manages Enterprise JavaBeans (EJBs) and business logic.

Key Services Provided by J2EE Containers

1. Lifecycle Management: The container controls the creation, initialization, and


destruction of components like servlets and EJBs, ensuring they work efficiently
during their lifecycle.
2. Security: J2EE containers authenticate users and enforce security policies, ensuring
safe communication and role-based access control.
3. Transaction Management: The container manages transactions to ensure that
operations are either fully completed (commit) or rolled back in case of failure,
providing data consistency.
4. Concurrency Control: It ensures that multiple users can access components
without causing data conflicts, using thread management to avoid issues like
deadlocks.
5. Session Management: The web container manages HTTP sessions to maintain the
state of the user's interaction with the application, useful for features like shopping
carts and user authentication.
6. Persistence Management: Containers automatically handle data persistence, like
saving EJBs' data into a database, which reduces the complexity for developers.
7. Resource Management: The container manages connections to databases, message
queues, and other resources, improving performance and reducing resource
overhead.
6. What is MVC. Explain the MVC architecture with suitable diagram.
Ans. MVC Architecture - Introduction to MVC

MVC (Model-View-Controller) is a software design pattern used to separate the


concerns in an application, especially in web development.
It divides the application into three interconnected components: Model, View, and
Controller, allowing for more modular, maintainable, and scalable code.
Components of MVC Architecture
1. Model:
o Represents the data and business logic of the application.
o It directly manages the data, communicates with the database, and updates
the View when necessary.
o The Model is independent of the user interface and doesn't know how data
will be presented to the user.
2. View:
o Represents the user interface (UI) of the application.
o It displays the data from the Model to the user and provides the means for the
user to interact with the application.
o The View is only responsible for rendering data; it doesn't process or
handle the business logic.
3. Controller:
o Acts as an intermediary between the Model and the View.
o It receives input from the user (usually through the View), processes the data
(using the Model), and returns the results to the View.
o The Controller manages the flow of data between the Model and the View,
handling user actions and updates.

Working of MVC Architecture


1. The user interacts with the View (for example, clicking a button or submitting a form).
2. The Controller processes the user’s request and updates the Model based on the input.
3. The Model updates its data and notifies the View of the changes.
4. The View then displays the updated data to the user.

MVC Architecture Diagram

Explanation of the Diagram:


 Model: Holds data and logic (e.g., a class representing a user, database operations).
 View: The UI that displays data to the user (e.g., HTML pages, user forms).
 Controller: The mediator that handles the input, updates the Model, and refreshes the View.

Benefits of MVC Architecture


1. Separation of Concerns: The MVC pattern separates the business logic, UI, and user input
processing, making the application easier to maintain and extend.
2. Scalability: It allows the independent modification of components without affecting others. For
example, you can change the View without altering the Model.
3. Reusability: The Model can be reused across different applications or views, improving
efficiency and flexibility.
4. Testability: Since the business logic is separated from the UI, it is easier to test the Model
independently.
UNIT – III
1. JavaScript:
 Not a part of the Java platform, JavaScript is a scripting language that is object based.
 It helps to create web pages that are interactive. It doesn't need to be compiled before
running, making it easy to use directly in web pages.

2. Describe Document Object Model (DOM) in JavaScript.


Ans. Document Object Model (DOM) in JavaScript
Introduction:
• DOM stands for Document Object Model.
• When a web page is loaded in the browser, the browser creates a tree-like structure of the HTML
document.
• This structure is called the DOM.
• The DOM represents the HTML elements as objects that can be accessed and changed using
JavaScript.
• It allows JavaScript to interact with the web page.
• We can read, change, add, or delete HTML elements using the DOM.

Structure of the DOM:


A simple HTML:
<html>
<body>
<h1>Hello World</h1>
</body>
</html>
Becomes this DOM structure:
Document
└── html
└── body
└── h1
└── "Hello World"
Types of DOM Nodes:
1. Element Node – Represents HTML elements like <div>, <p>, <h1>, etc.
2. Text Node – The actual text inside an element.
3. Attribute Node – Represents attributes like class, id, etc.
4. Comment Node – Represents comments in HTML.

Example:
<p id="demo">Old Text</p>
<script>
[Link]("demo").innerHTML = "New Text";
</script>
This JavaScript code changes the paragraph content from "Old Text" to "New Text".

3. Write a JavaScript program to implement palindrome operations using an Array.


Ans. Here's a simple JavaScript program that uses an array to implement palindrome operations — such as
checking whether a word or sentence is a palindrome.
✅ Features:
 Accepts input as a string.
 Converts it into an array.
 Checks if it's a palindrome using array methods.

✅ JavaScript Code: Palindrome Using Array


🔍 Output:
"racecar" is a palindrome.
"Level" is a palindrome.
"hello" is not a palindrome.
"A man, a plan, a canal, Panama" is a palindrome.
This implementation demonstrates:
 String to array conversion using .split()
 Array reversal using .reverse()
 Clean input handling using regex

4. Write JavaScript program to validate student registration form for farewell event.
Ans.
✅ This version:
 Validates name (not empty)
 Checks @ in email
 Ensures roll number is numeric

5. Design a web page, which displays message "Welcome to JavaScript" whenever click on button.
Ans.
How it works:
 When the user clicks the button, the function showMessage() is called.
 It updates the <p> tag with the message.

6. Write a JavaScript program to check whether a number is palindrome or not.


Ans.
OUTPUT:
121 is a palindrome number.
123 is not a palindrome number.
7. Write JavaScript program to validate student registration form for annual football event.
Ans. Same as above question no. 3.
8. Explain implicit type conversion in JavaScript.
Ans. Implicit Type Conversion in JavaScript
Definition:
Implicit Type Conversion, also known as Type Coercion, is the automatic conversion of data from
one type to another by JavaScript during expression evaluation. This happens behind the scenes
without the programmer explicitly converting the data type.

How It Works:
JavaScript is a loosely typed language, which means variables can hold values of any type, and the engine converts
data types automatically when needed. This mostly happens in operations like addition, comparison, or
conditionals.

Examples:
1. String and Number:
let result = "5" + 2; // "52"
 Here, JavaScript converts the number 2 to a string and performs string concatenation, not
addition.
let result = "5" - 2; // 3
 In this case, the string "5" is converted to a number and subtraction is performed.

2. Boolean Conversion:
let result = "hello" == true; // false
 "hello" is not an empty string, so it's truthy, but when comparing to true, type coercion happens
and it results in false.
Boolean("") // false
Boolean("0") // true
Boolean(0) // false
Boolean(1) // true

3. Comparison Operators:
0 == "0" // true → string "0" is converted to number 0
false == 0 // true → both are considered falsy
null == undefined // true → special case in JavaScript
Why It Matters:
Implicit type conversion makes JavaScript more flexible, but it can also lead to unexpected results if not
understood properly. That’s why developers are often encouraged to use strict equality (===) to avoid unexpected
coercion.

Conclusion:
Implicit type conversion simplifies coding but may cause bugs due to unpredictable behavior. Understanding how
JavaScript handles type coercion is important for writing reliable and error-free code.

Note : Study about explicit type also.


9. Explain difference between Java and JavaScript.
Ans. Sir notes.
10. How to handling events using JavaScript explain with example.
Ans. Handling Events using JavaScript
Definition:
Event handling in JavaScript means writing code to respond to user actions on a web page — like clicking a button,
submitting a form, typing in a textbox, hovering over an element, etc. These user actions are called events.

✅ Common Types of Events:


 onclick – when an element is clicked
 onmouseover – when the mouse hovers over an element
 onkeydown – when a keyboard key is pressed
 onsubmit – when a form is submitted
 onload – when a page finishes loading

✅ How to Handle Events:


There are 3 common ways to handle events:
1. Inline in HTML:
<button onclick="showMessage()">Click Me</button>
2. Using JavaScript with DOM:

3. Using addEventListener() (Preferred):

✅ Example: Handling a Button Click


✅ Explanation:
 The onclick event is used on the button.
 When the button is clicked, it calls the greet() function.
 The function shows an alert with a message.

UNIT – IV
1. Explain JSTL functions and write the syntax to indicate JSTL function library in JSP.
Ans. JSTL Functions in JSP
JSTL (JavaServer Pages Standard Tag Library) is a collection of useful JSP tags that encapsulate core
functionalities.
The JSTL functions library (fn) provides utility functions for manipulating strings and performing common
operations in JSP without writing Java code.

1. Purpose of JSTL Functions Library (fn)


The JSTL functions library provides a set of standard functions, mainly for:
 String manipulation (e.g., length, contains, trim, toLowerCase, etc.)
 Checking string content
 Performing operations like replacing, splitting, and joining strings
This helps in reducing Java scriptlets in JSP and promotes clean and readable code.
2. Syntax to Include JSTL Functions Library in JSP

3. Common JSTL Functions with Examples

4. Example JSP Code Using JSTL Functions


5. Advantages of Using JSTL Functions
 Reduces Java code in JSP
 Improves readability and maintainability
 Promotes use of MVC by separating logic from view
2. Create a web application in JSP for sending user name and password from one page to another page
using session variable.
Ans. JSP Web Application Using Session Variable
To pass username and password from one JSP page to another using session variables, we need two JSP pages:
1. [Link] (Takes input and sets session variables)
2. [Link] (Retrieves session data)

Explanation
 In [Link], user enters the username and password.
 Form is submitted to [Link] using POST method.
 [Link] reads the form values using [Link](), then stores them in session
attributes using [Link]().
 These values are displayed using [Link]().

3. How to share data between JSP pages explain with an example.


Ans. Sharing Data Between JSP Pages –
 When building a website with JSP, we often need to send information from one page to another.
 Sharing data between JSP pages is essential for building dynamic, interactive web applications where
information must flow across multiple pages.
Data can be shared between JSP pages using the following techniques:

1. Using Request Scope:


Data is shared only while the request is being processed (for example, when we move from one
page to another using forward).
In the first JSP page ([Link]):
<%
[Link]("greeting", "Hello from the first page!");
RequestDispatcher rd = [Link]("[Link]");
[Link](request, response);
%>
In the second JSP page ([Link])
<%= [Link]("greeting") %>

2. Using Session Scope


Data is saved for the user as long as their browser is open (or until they logout). Good for things like login info. Set
session data in one JSP:
<%
[Link]("username","Mohit");
%>
• Get session data in another JSP:
<%= [Link]("username") %>
3. Using Application Scope
Data is shared with all users and pages as long as the website is running. Good for things like counters. • Set
application data:
<%
[Link]("siteName", "My Cool Website");
%>
• Get application data in any JSP:
<%= [Link]("siteName") %>

4. Passing Data via URL (Query String)


Send data by adding it to the link.
It is a method of sending data to the server by appending key-value pairs to the URL after a?, commonly used with
GET requests.
<a href="[Link]?color=blue">Go to next page</a>
In [Link]:
<%= [Link]("color") %>

Conclusion
JSP supports data sharing through request, session, application scopes, and URL/form parameters depending on
the data's lifetime and visibility.

4. Explain how to deploy Java beans in a JSP page with an example.


Ans. Deploying JavaBeans in a JSP Page
JavaBeans are reusable Java classes that follow specific conventions:
 Have a public no-argument constructor
 Use getter and setter methods for accessing properties
 Must be serializable
JavaBeans can be used in JSP pages using the <jsp:useBean>, <jsp:setProperty>, and <jsp:getProperty> tags.

Steps to Deploy JavaBean in JSP


1. Create a JavaBean Class
File: [Link]
2. Compile and Place Bean in /WEB-INF/classes/beans/ Folder
The compiled [Link] should be in:
/WEB-INF/classes/beans/[Link]

3. Use JavaBean in JSP


File: [Link]
<jsp:useBean id="user" class="[Link]" scope="request" />
<jsp:setProperty name="user" property="username" value="Himanshi" />

Hello, <jsp:getProperty name="user" property="username" />

Explanation of Tags
 <jsp:useBean>: Instantiates the JavaBean.
 <jsp:setProperty>: Sets a value to the bean property.
 <jsp:getProperty>: Retrieves the value of a bean property.
5. What are the components of tomcat architecture. Explain in brief.

Ans.

Tomcat:
 Tomcat is a container for Java web apps.
 It runs .jsp files and Servlets.
 It's made by the Apache Software Foundation.
 It's commonly used for deploying Java web projects during development and testing.
 Apache Tomcat is an open-source web server and servlet container.
Components of Tomcat Architecture
Its architecture includes several core components that work together to process HTTP requests and run Java web
applications.

1. Catalina (Servlet Container)


 Catalina is the core component of Apache Tomcat responsible for handling servlet-related operations.
 It manages the servlet lifecycle and maps incoming HTTP requests to the appropriate servlet.

2. Coyote (HTTP Connector)


 Handles HTTP protocol and receives HTTP requests and passes them to Catalina.
 Also supports AJP (Apache JServ Protocol) for integration with web servers.
3. Jasper (JSP Engine)
 Converts JSP files into Servlets.
 Compiles JSP into Java code and then into bytecode for execution.

4. Host (Virtual Host)


 Allows Tomcat to support multiple websites (domains) on a single server.
 Each host has its own web apps and configuration.

5. Engine
• It processes all incoming requests for a specific Service and decides where to send them.
• It contains one or more Hosts and maps each request to the correct Host and Context (web application).

6. Service
• A Service groups multiple Connectors with a single Engine to handle web requests.
• The Connector receives the client request, and the Engine processes it by sending it to the right web application.

7. Context (Web Application)


• A Context represents a single web application running in Tomcat.
• Each deployed application has its own Context, which contains its specific configuration and resources.

8. Realm (Security)
 Provides authentication and authorization.
 Supports user roles and permissions.

Diagram (Optional if space allows in exam):


Client → Coyote (HTTP Connector) → Catalina (Engine)
└── Host ── Context (Web App)
└── Servlet/JSP (via Jasper)

Conclusion
Tomcat’s architecture is modular, with Coyote handling requests, Catalina managing servlets, and Jasper
compiling JSPs, allowing efficient and secure execution of Java web applications.
UNIT – V
1. Examine the life cycle of Servlet with proper diagram.

Ans.
The diagram you provided illustrates the Servlet Life Cycle with clear stages and method calls. Here's a detailed
explanation of each phase as shown in the diagram:

Explanation of Servlet Life Cycle Diagram


1. START
 The servlet life cycle begins when the Servlet container (like Tomcat) starts up and receives a
request for a servlet.

2. Loading and Instantiation


 The container loads the servlet class into memory.
 Then it creates an instance of the servlet using its default constructor.
3. Initialization (init() method)
 The container calls the init() method once immediately after instantiation.
 Used to initialize resources (e.g., database connections, configuration parameters).
 After this step, the servlet is ready to serve client requests.

4. Handling Requests (service() method)


 For each client request, the container creates a new thread and calls the service() method.
 This method handles client requests and determines whether to call doGet(), doPost(), etc.,
depending on the request type.
 After the response is sent, the request thread ends, but the servlet instance remains active.

5. End of Life Cycle (destroy() method)


 When the servlet is being shut down (e.g., server stops or app is undeployed), the container calls
the destroy() method once.
 Used to release resources like memory, file handles, database connections.

6. END
 The servlet object is marked for garbage collection.
 This ends the life cycle of the servlet.

2. Explain the servlet hits example using Singleton Session Bean in detail with the help of program.
Ans. [Link]
Servlet Hits Example Using Singleton Session Bean
✅ Objective
To count how many times a servlet has been accessed (hits) using a Singleton Session Bean, which ensures only one
instance exists for the entire application.

✅ Why Singleton Session Bean?


A Singleton Session Bean is used when a single shared state is required across multiple clients—ideal for counting
hits.

✅ Step-by-Step Implementation

🔹 1. Create Singleton Session Bean


File: [Link]

✅ This bean is annotated with @Singleton, so only one instance will be shared.

🔹 2. Create Servlet to Use the Bean


File: [Link]
✅ Deployment Steps (Summary)
1. Deploy both HitCounterBean and HitServlet in a Java EE-supported server like GlassFish or
WildFly.
2. Access the servlet URL from a browser repeatedly.
3. The hit counter will increase with every request due to the shared singleton bean.

✅ Output Example
Welcome! This servlet has been accessed 1 times.
Welcome! This servlet has been accessed 2 times.
...

✅ Conclusion
Using a Singleton Session Bean with a servlet is an efficient way to share application-wide data, like a hit
counter, across multiple servlet requests and users.

3. Create a Servlet using Request Dispatcher Interface which will validate the password entered by the
user, if the user has entered "Servlet" as password, then he will be forwarded to "Welcome to Servlet"
else the user will stay on the [Link] page and an error message will be displayed.
Ans. Servlet Password Validation Using RequestDispatcher
🔹 Objective
 Validate password using a servlet.
 If correct ("Servlet"), forward to a welcome page.
 If incorrect, stay on [Link] and display an error message using RequestDispatcher
✅ 2. Servlet: [Link]

✅ Output Behavior
 Correct password: Redirects to [Link].
 Wrong password: Reloads [Link] with error message.

4. Create a Servlet using Request Dispatcher Interface which will validatė the username and password
entered by the user, if the user has entered correct password, then he will be forwarded to "Welcome to
Username" else the user will stay on the same page with an error message "Invalid Username or
Password".
Ans. DIY.
5. Explain the deployment of Servlet step by step in tomcat server.
Ans. Deployment of Servlet in Tomcat Server
Step 1: Write the Servlet Code
 Create a Java class extending HttpServlet.
 Override doGet() or doPost() methods.
 Compile the servlet to generate .class files.

Step 2: Create Directory Structure


 Inside Tomcat’s webapps folder, create a new folder for your web app, e.g., MyApp.
 Create subfolders:
o WEB-INF (mandatory)
o WEB-INF/classes (for compiled .class files)
o WEB-INF/lib (for external jars if needed)

Step 3: Place Servlet Class


 Copy your compiled servlet .class files into WEB-INF/classes following the package structure.

Step 4: Configure Deployment Descriptor ([Link])


 Inside WEB-INF, create or edit [Link] file.
 Declare servlet and servlet-mapping as follows:
<web-app>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>[Link]</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>

Step 5: Start Tomcat Server


 Run [Link] (Windows) or [Link] (Linux/Mac) from Tomcat’s bin directory.
 Ensure the server starts without errors.

Step 6: Access Servlet


 Open browser and go to:
[Link]
 Servlet should execute and display output.

Step 7: Deploy WAR (Optional)


 Package your web app as .war file.
 Copy .war to Tomcat’s webapps folder.
 Tomcat auto-deploys the application on startup or during runtime.

Summary
1. Write and compile servlet.
2. Create web app folder structure under Tomcat.
3. Put .class files in WEB-INF/classes.
4. Configure [Link] for servlet mapping.
5. Start Tomcat.
6. Access servlet via URL.

[Link]

2 Marks Questions
1. Illustrate any two main advantages of EJB.
Ans. Two main advantages of EJB
 Simplifies development: EJB handles complex middleware services like transactions, security, and
concurrency, so developers focus on business logic.
 Scalability and portability: EJB components can be deployed across different servers and can scale
automatically in response to load.

2. List out types of Enterprise Java Beans (EJB).


Ans. Types of EJB:-
 Session Beans: Perform tasks for clients; can be Stateful, Stateless, or Singleton.
 Entity Beans: Represent persistent data stored in a database (mostly replaced by JPA).
 Message-Driven Beans: Handle asynchronous processing using Java Message Service (JMS).

3. Explain MVC 2 model / Explain MVC model of web development.


Ans. MVC (Model-View-Controller) 2 is a design pattern for web apps:
 Model: Business logic and data.
 View: User interface (JSP or HTML).
 Controller: Servlet that handles requests, processes data using the model, and selects the view to render the
response.
This separation improves modularity and maintainability.

4. Explain types of dialog box in JavaScript.


Ans. Types of dialog box in JavaScript
 Alert: Displays a message with an OK button.
 Confirm: Displays a message with OK and Cancel buttons; returns true/false.
 Prompt: Displays a message and an input field for user input.

5. Explain objects in the reference of JavaScript.


Ans. In JavaScript, objects are collections of key-value pairs where keys are strings (properties) and values
can be any data type, including functions (methods). Objects allow grouping related data and functionality.

6. Explain Request and Response Handling in JSP with neat and clean diagram. / Explain Client and
Server Response in JSP with neat and clean diagram.
Ans. Request-Response cycle in JSP:
 Client sends HTTP request.
 JSP page processes request using implicit objects (request, response).
 JSP generates dynamic content.
 Server sends HTTP response back to client.
(Diagram: Client → HTTP Request → JSP → Process → HTTP Response → Client)

7. Explain different between Context and Config in reference of the Servlet.


Ans. Difference between Context and Config in Servlet
 ServletContext: Application-wide scope, shared among all servlets, used to share resources or info.
 ServletConfig: Servlet-specific configuration, used to pass initialization parameters to a single servlet.

8. Illustrate two main advantages of RMI.


Ans. RMI (Remote Method Invocation) allows a Java program to call methods on an object located in
another JVM, possibly on a different machine. It enables easy communication between distributed Java
applications by making remote calls look like local calls.
Two main advantages of RMI
 Transparency: Allows calling methods on remote Java objects as if they were local.
 Platform independence: Enables communication between Java programs running on different machines/OS.

9. Explain difference between let and var in JavaScript.


Ans. Difference between let and var in JavaScript
 var is function-scoped; let is block-scoped.
 var variables are hoisted and initialized as undefined; let variables are hoisted but not initialized (Temporal
Dead Zone).
 let prevents redeclaration within the same scope.

10. Explain promises in the reference of JavaScript.


Ans. promises in JavaScript
A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its
resulting value. It allows chaining .then() for success and .catch() for errors, improving async code readability.

11. What is session bean.


Ans. Session bean
A Session Bean is an EJB that represents a client’s interaction with the server. It performs tasks on behalf of
the client and can be:
 Stateless: No client-specific state.
 Stateful: Maintains state across method calls.
 Singleton: One instance shared across clients.

12. What do you understand by J2EE and four types of J2EE modules.
Ans. J2EE and four types of J2EE modules
J2EE (Java 2 Platform, Enterprise Edition) is a platform for developing multi-tier enterprise applications.
Four types of J2EE modules:
 EJB module: Contains enterprise beans.
 Web module: Contains servlets, JSPs.
 Application client module: Java applications run on client machines.
 Resource adapter module: Connects to enterprise information systems.

13. Explain hoisting in javascript.


Ans. hoisting in JavaScript
 JavaScript moves all variable and function declarations to the top of the code before running it.
 Only the declaration is moved, not the value assigned to the variable.
 Variables declared with var are set to undefined at the top automatically.
 Variables declared with let and const are not usable before their line (will cause an error if accessed early).
 You can call functions before you write them because function declarations are moved to the top.
 Hoisting means you don’t always have to write variables or functions before using them, but be careful to
avoid confusion.

14. What is JSP.


Ans. JSP (JavaServer Pages)
 Server-side technology used to create dynamic web pages.
 Allows embedding Java code directly into HTML using special tags.
 Runs on the server and generates HTML content sent to the client browser.
 Supports reusable components like JavaBeans and custom tags.
 Helps separate presentation logic from business logic.
 Simplifies web application development compared to pure servlets.

15. What is servlet.


Ans. Servlet
 A Servlet is a Java program that runs on a web server or application server.
 It handles client requests (usually HTTP requests from a web browser).
 It processes these requests, executes business logic, and generates dynamic responses (usually HTML).
 Servlets are the core components for building Java-based web applications.

You might also like