0% found this document useful (0 votes)
8 views21 pages

JavaBeans Classes and EJB Overview

JavaBeans is a component architecture for Java, primarily supported by the java.beans package, which includes classes like PropertyChangeSupport for managing property change listeners and Introspector for analyzing JavaBeans. The document also contrasts JavaBeans with Enterprise JavaBeans (EJB), highlighting differences in purpose, architecture, and usage. Additionally, it discusses session tracking in servlets, emphasizing its importance in maintaining state across multiple HTTP requests.

Uploaded by

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

JavaBeans Classes and EJB Overview

JavaBeans is a component architecture for Java, primarily supported by the java.beans package, which includes classes like PropertyChangeSupport for managing property change listeners and Introspector for analyzing JavaBeans. The document also contrasts JavaBeans with Enterprise JavaBeans (EJB), highlighting differences in purpose, architecture, and usage. Additionally, it discusses session tracking in servlets, emphasizing its importance in maintaining state across multiple HTTP requests.

Uploaded by

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

JavaBeans Classes Overview

list and explain any 2 classes available in javabeans


package

JavaBeans itself is not a specific package but rather a component architecture for the Java
language. However, JavaBeans functionality is supported by classes primarily from the
[Link] package.

Here are two important classes from the [Link] package:

1. PropertyChangeSupport
Purpose: This class is used to help JavaBeans manage listeners interested in changes to
bean properties.

Explanation: It supports the observer design pattern. When a property value in the bean
changes, this class can notify all registered listeners.

Use case: Commonly used in GUI or data-binding scenarios, where UI elements need to
be updated when the underlying data model changes.

Example:

java

PropertyChangeSupport support = new PropertyChangeSupport(this);


[Link](evt -> {
[Link]("Property changed: " + [Link]());
});
[Link]("name", "Alice", "Bob");

2. Introspector
Purpose: This class is used to analyze JavaBeans to discover their properties, events, and
methods.

1/21
Explanation: It performs introspection on JavaBeans classes and returns information
such as property descriptors, which can be used by frameworks or IDEs to automatically
generate forms, tables, etc.

Use case: Used by tools that manipulate or display bean components without needing to
hard-code property names.

Example:

java

BeanInfo info = [Link]([Link]);


for (PropertyDescriptor pd : [Link]()) {
[Link]("Property: " + [Link]());
}

Let me know if you’d like a quick example JavaBean class to go with this!

what is the difference between stateful and stateless


session beans

Great question! The difference between stateful and stateless session beans lies in how they
manage state between client interactions. These are part of Enterprise JavaBeans (EJB) in
the Java EE framework.

🌐 1. Stateless Session Beans


Definition: These beans do not maintain any state (data) between client requests.

Behavior: Every time a client calls a method, it’s like a fresh bean instance is serving the
request. No data from a previous interaction is remembered.

Use Case: Ideal for operations that don’t depend on data from previous calls (e.g.,
calculator, logging, sending notifications).

Benefits:

Easy to scale.

2/21
Lightweight and efficient.

Example: Imagine a bean that just adds two numbers:

java

@Stateless
public class CalculatorBean {
public int add(int a, int b) {
return a + b;
}
}

🧠 2. Stateful Session Beans


Definition: These beans maintain state across multiple method calls and transactions
for a specific client.

Behavior: Each client gets a dedicated bean instance, and that instance keeps data
between calls.

Use Case: Perfect for scenarios like shopping carts, user sessions, or wizards where the
application needs to remember what the user has done.

Drawbacks:

Heavier on memory.

Harder to scale.

Example: A shopping cart bean might look like:

java

@Stateful
public class ShoppingCartBean {
private List<String> items = new ArrayList<>();

public void addItem(String item) {


[Link](item);
}

public List<String> getItems() {

3/21
return items;
}
}

🔑 Key Differences:
Feature Stateful Bean Stateless Bean

Maintains state? Yes No

Client-specific instance? Yes (1:1 mapping) No (pooled/shared)

Memory usage Higher Lower

Use case Shopping cart, wizard, login Calculator, authentication

Let me know if you want a real-world analogy or diagram to go with it!

how applications are deployed in struts? explain in detail in


java

Sure! Here's a detailed explanation of how applications are deployed in Struts using Java:

🚀 Deploying Applications in Apache Struts (Struts 1 or


Struts 2)
Apache Struts is a popular MVC-based web framework for building Java EE web applications.
Here's a step-by-step breakdown of how applications are developed and deployed in Struts
(primarily Struts 2):

🔧 1. Develop the Application


4/21
Key Components in a Struts 2 App:

1. Action Class – Java class that handles user input.

2. JSP Pages – For the view layer.

3. [Link] – Configuration file mapping actions to classes and results.

4. [Link] – Deployment descriptor (used by the servlet container).

5. Libraries – All Struts JARs (and dependencies) must be added.

📁 2. Project Structure
A typical Struts 2 web project looks like:

pgsql

MyStrutsApp/
├── src/
│ └── com/myapp/action/[Link]
├── WebContent/
│ ├── WEB-INF/
│ │ ├── [Link]
│ │ ├── classes/
│ │ └── lib/ (Struts JARs)
│ ├── [Link]
│ └── [Link]
├── [Link]

🧩 3. Configure [Link]

xml

<web-app>
<filter>
<filter-name>struts2</filter-name>
<filter-
class>[Link]</filter-

5/21
class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<welcome-file-list>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
</web-app>

This sets up the Struts filter to intercept all requests.

📄 4. Configure [Link]

xml

<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="login" class="[Link]">
<result name="success">[Link]</result>
<result name="error">[Link]</result>
</action>
</package>
</struts>

Maps the URL [Link] to the LoginAction class.

Handles navigation based on the return value of the action.

✏️ 5. Write the Action Class


java

6/21
package [Link];

import [Link];

public class LoginAction implements Action {


private String username;
private String password;

// Getters and Setters

public String execute() {


if ("admin".equals(username) && "password".equals(password)) {
return SUCCESS;
} else {
return ERROR;
}
}
}

Struts calls the execute() method when [Link] is triggered.

🖼️ 6. Create JSP Files


[Link] :

jsp

<form action="[Link]" method="post">


Username: <input type="text" name="username" /><br/>
Password: <input type="password" name="password" /><br/>
<input type="submit" value="Login" />
</form>

[Link] :

jsp

<h1>Welcome, you are logged in!</h1>

7/21
📦 7. Build WAR File
You can build the .war (Web Application Archive) using:

Eclipse/IDE → Export → WAR file

Apache Maven → mvn package

Manual ZIP with correct folder structure

🚀 8. Deploy to Server (e.g., Apache Tomcat)


1. Copy the .war file to the webapps/ folder of your Tomcat installation.

2. Start Tomcat ( bin/[Link] or [Link] ).

3. Visit the application at:

arduino

[Link]

✅ Summary
Step Description

1 Develop Action classes and JSPs

2 Configure [Link] and [Link]

3 Package the app into a WAR

4 Deploy the WAR to a servlet container

8/21
Let me know if you'd like me to generate a complete example project or Maven structure for
this!

write a program to show the distributed object model using


remote method invocation

Sure! Below is a simple Java program that demonstrates the Distributed Object Model
using RMI (Remote Method Invocation).

This example includes:

1. Remote Interface

2. Remote Object Implementation

3. Server Program

4. Client Program

🔧 Step-by-Step RMI Example


1. Remote Interface ([Link])
java

import [Link];
import [Link];

public interface MyRemote extends Remote {


String sayHello() throws RemoteException;
}

2. Remote Object Implementation ([Link])

java

9/21
import [Link];
import [Link];

public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote {

protected MyRemoteImpl() throws RemoteException {


super();
}

@Override
public String sayHello() throws RemoteException {
return "Hello from the remote object!";
}
}

3. RMI Server ([Link])


java

import [Link];
import [Link];

public class RMIServer {


public static void main(String[] args) {
try {
// Create and export remote object
MyRemoteImpl remoteObj = new MyRemoteImpl();

// Start RMI registry programmatically on port 1099


[Link](1099);

// Bind the object in the registry


[Link]("rmi://localhost:1099/RemoteHello", remoteObj);

[Link]("Server is running...");
} catch (Exception e) {
[Link]();
}

10/21
}
}

4. RMI Client ([Link])

java

import [Link];

public class RMIClient {


public static void main(String[] args) {
try {
// Lookup the remote object
MyRemote remote = (MyRemote)
[Link]("rmi://localhost:1099/RemoteHello");

// Call the remote method


String response = [Link]();

[Link]("Response from remote: " + response);


} catch (Exception e) {
[Link]();
}
}
}

✅ How to Run:
1. Compile All Files:

bash

javac *.java

2. Start the Server (make sure port 1099 is free):

11/21
bash

java RMIServer

3. Run the Client in another terminal:

bash

java RMIClient

🧠 Output:
arduino

Server is running...

(Client Terminal:)

csharp

Response from remote: Hello from the remote object!

Let me know if you want the same example using Maven or a GUI-based RMI demo!

HOW java bean is created ? write with the help of program

Great! Let's go over how a JavaBean is created, and then I’ll walk you through a simple
JavaBean program with explanation.

💡 What is a JavaBean?
A JavaBean is a reusable software component that follows certain conventions:

12/21
✅ JavaBean Rules:
1. Must be public and have a public no-argument constructor.

2. Properties must be private, accessed via getter and setter methods.

3. Should be serializable (optional but recommended for persistence).

🧪 Example: Creating a JavaBean for a Student

📄 [Link]

java

import [Link];

public class StudentBean implements Serializable {


private String name;
private int age;

// No-arg constructor
public StudentBean() {
}

// Getter for name


public String getName() {
return name;
}

// Setter for name


public void setName(String name) {
[Link] = name;
}

// Getter for age


public int getAge() {
return age;
}

// Setter for age


public void setAge(int age) {

13/21
[Link] = age;
}
}

📄 [Link] (Using the Bean)

java

public class Main {


public static void main(String[] args) {
// Create an instance of the JavaBean
StudentBean student = new StudentBean();

// Set properties using setter methods


[Link]("Alice");
[Link](20);

// Get properties using getter methods


[Link]("Name: " + [Link]());
[Link]("Age: " + [Link]());
}
}

✅ Output:
makefile

Name: Alice
Age: 20

📦 Summary of Steps to Create a JavaBean:


14/21
Step Description

1 Create a public class

2 Add private properties

3 Add public no-arg constructor

4 Create public getters and setters

5 (Optional) Implement Serializable interface

Let me know if you'd like to see how JavaBeans are used in JSP or with property listeners!

Compare and contrast JavaBeans and Enterprise Java Beans


(EJB). Discuss the features
of any four classes provided by JavaBeans API.

Absolutely! Let's break this down into two parts:

✅ 1. Comparison: JavaBeans vs Enterprise JavaBeans


(EJB)

Feature JavaBeans Enterprise JavaBeans (EJB)

Purpose General-purpose reusable components Server-side components for enterprise-level


(GUI/data) apps

Architecture Simple, component-based Complex, supports distributed, transactional


systems

Environment Runs in any Java environment Requires EJB container (e.g., inside an
application server)

15/21
Feature JavaBeans Enterprise JavaBeans (EJB)

Dependency Lightweight, no container needed Requires JEE-compliant server (e.g., WildFly,


GlassFish)

Remote Access No support for remote access Supports RMI, remote clients

Transaction Not available Built-in support


Management

Security Not built-in Supports declarative security

Usage Examples Form beans, GUI controls, data models Banking systems, inventory apps, login
systems

📦 2. Features of Any Four Classes in JavaBeans API


( [Link] package)
Here are 4 important classes from the [Link] package along with their features:

🔹 1. PropertyChangeSupport

Purpose: Provides support for managing and notifying listeners when a bean's property
changes.

Use Case: Used in beans that support property change listeners, e.g., updating UI when
data changes.

Key Methods:

addPropertyChangeListener()

firePropertyChange(propertyName, oldValue, newValue)

16/21
🔹 2. PropertyDescriptor

Purpose: Describes a property of a JavaBean.

Use Case: Tools and frameworks use this class for introspection (like IDEs or
frameworks).

Key Features:

Provides access to getter/setter methods.

Used to analyze properties at runtime.

🔹 3. Introspector

Purpose: Performs introspection on a JavaBean class to discover its properties,


methods, and events.

Use Case: Automatically detecting bean structure in tools like NetBeans, Spring, or
JavaFX.

Key Methods:

getBeanInfo(Class<?> beanClass)

Returns BeanInfo object which contains metadata.

🔹 4. BeanInfo

Purpose: Provides information about a bean including properties, methods, and events.

Use Case: Used with Introspector to get structured metadata.

Key Methods:

getPropertyDescriptors()

getMethodDescriptors()

17/21
🧠 Summary of JavaBeans API Classes:
Class Name Key Feature

PropertyChangeSupport Notify listeners when a property changes

PropertyDescriptor Describe bean properties (getters/setters)

Introspector Discover bean structure (properties/methods)

BeanInfo Holds metadata about a bean

Let me know if you’d like a working code example showing these classes in action!

What do you mean by session tracking? Explain various


mechanisms used for session
tracking in servlets.

Great question! Let's break it down step by step:

🧭 What is Session Tracking?


Session Tracking is a technique used in web applications to maintain state information
(i.e., data) about a user's interaction across multiple HTTP requests.

❗ Why is it needed?
HTTP is stateless by default — each request is independent. So if a user logs in or adds an
item to a cart, the server forgets it on the next request unless session tracking is used.

🧰 Session Tracking Mechanisms in Servlets


Servlets provide several standard mechanisms to track user sessions:

18/21
🔹 1. Cookies
A cookie is a small piece of data stored on the client’s browser.

The server sends a cookie to the client, and the browser sends it back with every
subsequent request.

✅ Features:
Stored on the client side.

Easy to use.

Can persist across browser sessions (if not set as temporary).

🔧 Example:
java

Cookie userCookie = new Cookie("username", "Alice");


[Link](userCookie);

🔹 2. URL Rewriting
Session data is maintained by appending a session ID or data directly into the URL.

✅ Features:
Works even when cookies are disabled.

Not secure unless encoded properly.

🔧 Example:
java

String encodedURL = [Link]("[Link]");

It may look like:

arduino

19/21
[Link]

🔹 3. Hidden Form Fields


Stores session data in a hidden field in HTML forms.

The data gets submitted with each form submission.

✅ Features:
Simple.

Only works with form submissions, not with general navigation.

🔧 Example:
html

<form action="nextServlet" method="post">


<input type="hidden" name="userId" value="101">
<input type="submit" value="Continue">
</form>

🔹 4. HttpSession Object (Most Common)


The HttpSession object allows the server to store information specific to a user session.

The server assigns a session ID and manages the session automatically.

✅ Features:
Most secure and convenient.

Can store Java objects.

Supports timeouts and invalidation.

🔧 Example:
java

20/21
HttpSession session = [Link](); // creates new session if doesn't exist
[Link]("username", "Alice");

// Later retrieve it
String name = (String) [Link]("username");

🧠 Summary Table:
Mechanism Where Data is Stored Works Without Cookies? Security Use Case

Cookies Client (browser) ❌ Medium Simple tracking

URL Rewriting URL ✅ Low Cookie-disabled browsers

Hidden Form Field Form (HTML page) ✅ Medium Step-by-step wizards/forms

HttpSession Server memory ✅ High Most common & reliable

Let me know if you want a working servlet example demonstrating session tracking in action!

21/21

You might also like