0% found this document useful (0 votes)
2 views16 pages

Section C Ajava

The document discusses various types of session beans in Enterprise JavaBeans, including Stateless, Stateful, and Singleton session beans, along with their advantages and disadvantages. It also explains session tracking mechanisms in servlets, such as cookies, URL rewriting, hidden form fields, and the HttpSession API. Additionally, it covers the JSP development process, MVC architecture, CORBA architecture, and the concept of POJO files in Java development.

Uploaded by

kaurqueen268
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)
2 views16 pages

Section C Ajava

The document discusses various types of session beans in Enterprise JavaBeans, including Stateless, Stateful, and Singleton session beans, along with their advantages and disadvantages. It also explains session tracking mechanisms in servlets, such as cookies, URL rewriting, hidden form fields, and the HttpSession API. Additionally, it covers the JSP development process, MVC architecture, CORBA architecture, and the concept of POJO files in Java development.

Uploaded by

kaurqueen268
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

1. Discuss various types of session beans in enterprise JavaBeans.

List the advantages and


disadvantages of each.

Ans. In Enterprise JavaBeans (EJB), Session Beans are used to manage the business logic of an
application. They represent a "worker" on the server that performs tasks on behalf of a client.

There are three primary types of Session Beans: Stateless, Stateful, and Singleton.

1. Stateless Session Beans (SLSB)

These beans do not maintain any conversational state with the client. Each time a client calls a
method, the container can pick any available instance from a pool to handle the request.

 Advantages:

o High Scalability: Because they are pooled, a small number of beans can serve a large
number of clients.

o Low Memory Overhead: The server doesn't need to store data for every individual
user.

o Performance: No overhead for session activation or passivation.

 Disadvantages:

o No Continuity: Cannot "remember" data from a previous method call. All required
data must be passed as arguments in every call.

o Limited Use Cases: Not suitable for workflows like shopping carts or multi-step
wizards.

2. Stateful Session Beans (SFSB)

These beans maintain a dedicated state for a specific client across multiple method calls. The bean is
"tied" to the client for the duration of the session.

 Advantages:

o Conversational State: Ideal for tasks where the server needs to remember previous
interactions (e.g., a "Current User" profile or a banking transaction wizard).

o Simplified Client Logic: The client doesn't have to pass all context data back and
forth; the bean keeps it.

 Disadvantages:

o Resource Intensive: The server must keep the bean in memory for as long as the
session is active.

o Passivation/Activation: To save RAM, the container might move the bean to disk
(Passivation), which adds a performance hit when it is moved back (Activation).

o Scalability Issues: Harder to scale because the bean and the client are tightly
coupled to a specific server node.
3. Singleton Session Beans

Introduced in EJB 3.1, a Singleton bean is instantiated once per application. Every client request for
that bean goes to the exact same instance.

 Advantages:

o Data Sharing: Perfect for global data like application configurations, caches, or
counters shared by all users.

o Startup Control: Can be configured to initialize automatically when the application


starts using @Startup.

o Concurrency Control: Provides built-in mechanisms (Container-Managed


Concurrency) to manage multiple threads accessing the same data.

 Disadvantages:

o Bottleneck Risk: If many clients request a "Write" lock on a Singleton


simultaneously, it can slow down the entire system.

o Single Point of Failure: If the bean logic hangs or fails, it affects all users relying on
that shared resource.

2. What do you mean by session tracking? Explain various mechanisms used for session tracking in
servlets.

Ans. Session tracking is a mechanism used by web applications to maintain the state of a user across
multiple HTTP requests.

Since HTTP is a stateless protocol, the server treats every request as a completely new interaction.
Without session tracking, the server would not "remember" that a user has already logged in or
what items they added to a shopping cart in a previous click. Session tracking links a series of
requests from the same user into a single "conversation."

Mechanisms for Session Tracking in Servlets

There are four primary ways to track sessions in Java Servlets, each with its own use cases and
limitations.

1. Cookies

This is the most common method. The server creates a unique Session ID, sends it to the browser,
and the browser stores it as a small text file (cookie). Every subsequent request from the browser
automatically includes this cookie.

 Pros: Transparent to the user; handles large amounts of data on the server side.

 Cons: Will not work if the user disables cookies in their browser settings.

2. URL Rewriting

If cookies are disabled, the server can append the Session ID to every URL link within the application.
 Format: [Link]

 Implementation: In Servlets, this is done using [Link]().

 Pros: Works even when cookies are disabled.

 Cons: Tedious to implement (every link must be encoded); the Session ID is visible in the
browser's address bar, which is a security risk.

3. Hidden Form Fields

Session information is stored in a hidden input field within an HTML form. When the form is
submitted, the field is sent back to the server.

 Format: <input type="hidden" name="sessionID" value="12345">

 Pros: Simple for form-heavy applications.

 Cons: Only works with form submissions (POST/GET); does not track users who simply click
on links or navigate away.

4. HttpSession API

This is the standard high-level approach in Java. The Servlet Container (like Tomcat) manages the
heavy lifting. You simply call [Link](), and the container automatically decides whether
to use Cookies or URL Rewriting.

 Storage: Data is stored in the server's memory as "Attributes" (key-value pairs).

 Pros: Cleanest code; highly secure; can store complex Java objects (not just strings).

 Cons: Consumes server memory if sessions are not timed out properly.

3. Explain the complete process of JSP development with the help of a suitable example.

Ans. Developing a JSP application involves a specific workflow that transitions from a high-level text
file to an executable Java class handled by the server.

To explain this process, we will follow a "User Greeting" example where a user enters their name in
an HTML form, and the JSP processes and displays a personalized message.

The 4-Stage Development Process

1. Creation of the Web Resource (JSP File)

The developer writes the JSP file using a mix of HTML and JSP tags.

 Scriptlets (<% ... %>): For Java logic.

 Expressions (<%= ... %>): To print data directly to the page.

 Directives (<%@ ... %>): To set page-wide configurations.

2. Deployment
The JSP is placed in the web application directory (e.g., inside the webapps folder of Tomcat). The
folder structure must follow the standard Java EE layout to ensure the server can locate the
associated classes and libraries.

3. Translation and Compilation (Internal)

The first time a user requests the page, the JSP Container performs the "heavy lifting":

 It translates the .jsp into a .java Servlet source file.

 It compiles the .java into a .class bytecode file.

4. Execution

The container loads the class, creates an instance, and executes the _jspService() method to
generate the HTML response sent back to the browser.

Step-by-Step Example: The Greeting App

Step A: The Input Form ([Link])

First, we need a simple HTML page to collect user data.

HTML

<html>

<body>

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

Enter your name: <input type="text" name="userName">

<input type="submit" value="Greet Me">

</form>

</body>

</html>

Step B: The Processing Page ([Link])

This page captures the parameter and displays it using JSP elements.

Java

<%@ page language="java" contentType="text/html; charset=UTF-8" %>

<html>

<head><title>Greeting Page</title></head>

<body>

<%

// 1. Logic: Retrieve data from the implicit 'request' object

String name = [Link]("userName");


// 2. Handling null/empty values

if(name == null || [Link]().isEmpty()) {

name = "Guest";

%>

<h2>Hello, <%= name %>!</h2>

<p>Current Server Time: <%= new [Link]() %></p>

</body>

</html>

How it works at Runtime

1. Request: The user enters "Gemini" and clicks submit. The browser requests [Link]?
userName=Gemini.

2. Container Action: Tomcat checks its work directory. If greet_jsp.class doesn't exist or is older
than the .jsp file, it triggers the Translation phase.

3. Generated Servlet: The logic inside the <% %> tags is moved into the _jspService() method
of the generated servlet.

4. Output: The server executes the code, replaces <%= name %> with "Gemini", and sends a
pure HTML page back to the browser.

Best Practices in JSP Development

 Avoid Scriptlets: In advanced development, try to use EL (Expression Language) and JSTL
instead of Java code blocks to keep the page clean.

 Error Handling: Use the errorPage attribute in the page directive to manage exceptions
gracefully.

 MVC Pattern: Keep heavy business logic (like database queries) in a Servlet or JavaBean,
using the JSP only to display the final result.

4. (a) Model-view-controller architecture.

Ans. The Model-View-Controller (MVC) architecture is a structural design pattern that separates an
application into three main logical components. This separation helps manage complex applications,
as you can work on the business logic, the data, and the user interface independently.

In the context of Java Web Development (like Servlets and JSP), this is often referred to as MVC
Model 2 architecture.

The Three Components

1. The Model
The Model represents the data and the business logic of the application. It manages the state of the
application and responds to requests for information or instructions to change its state from the
Controller.

 Java Implementation: Plain Old Java Objects (POJOs), JavaBeans, or EJB.

 Responsibility: Database interaction, data validation, and logic processing.

2. The View

The View is the presentation layer. It is responsible for rendering the data provided by the Model
into a user-friendly format (HTML).

 Java Implementation: JSP, Thymeleaf, or FreeMarker.

 Responsibility: Displaying the UI and sending user input to the Controller.

3. The Controller

The Controller acts as an interface between the Model and the View. It intercepts user requests,
determines which Model logic to trigger, and decides which View to display next.

 Java Implementation: Servlets.

 Responsibility: Request handling, routing, and session management.

MVC Workflow in Java

The interaction between these components follows a specific lifecycle:

1. Request: The user interacts with the View (e.g., clicks a "Submit" button) and an HTTP
request is sent to the Controller.

2. Processing: The Controller receives the request, processes the data, and invokes the
appropriate Model (e.g., a service class to save data).

3. Data Retrieval: The Model performs business logic (like a database query) and returns the
result to the Controller.

4. Forwarding: The Controller attaches the data to the request and forwards it to the specific
View.

5. Response: The View pulls data from the request/session and renders the final HTML
response back to the browser.

(b) Explain CORBA architecture in detail.

Ans. CORBA (Common Object Request Broker Architecture) is a standard architecture defined by
the Object Management Group (OMG) that enables software components written in different
languages and running on different operating systems to communicate with each other.

It acts as a "software bus" that provides location transparency—the client does not need to know
where the server object resides or what language it is written in.

The Core Components of CORBA

The architecture is built around the Object Request Broker (ORB), which serves as the message
backbone.
1. Object Request Broker (ORB)

The ORB is the heart of CORBA. It is responsible for finding the object implementation, preparing it
to receive the request, and communicating the data. It handles the complexities of network
protocols and data representation.

2. IDL (Interface Definition Language)

To achieve language independence, CORBA uses IDL. A developer defines the interface of an object
(its methods and parameters) in an IDL file. This file is then compiled into "stubs" for the client (in
Java, C++, etc.) and "skeletons" for the server.

3. Stub and Skeleton

 IDL Stub (Client Side): Acts as a local proxy for the remote object. When the client calls a
method, the stub packs the arguments (marshalling) and sends them to the ORB.

 IDL Skeleton (Server Side): Receives the request from the ORB, unpacks the arguments
(unmarshalling), and calls the actual method on the server object.

4. Dynamic Invocation and Skeleton Interface

 DII (Dynamic Invocation Interface): Allows a client to call methods on objects that were not
known at compile time.

 DSI (Dynamic Skeleton Interface): Allows the server to handle requests for objects that do
not have compile-time skeletons.

5. Object Adapter (OA)

The Object Adapter (most commonly the Portable Object Adapter or POA) sits between the ORB
and the actual object implementation. It assists the ORB in delivering requests to the objects and
manages the object's lifecycle.

The Communication Process

1. Registration: The server object registers itself with the ORB.

2. Request: The client calls a method on the Stub.

3. Marshalling: The Stub converts the Java/C++ data types into a generic wire format (Common
Data Representation or CDR).

4. Transport: The ORB locates the server and sends the request over the network using the
GIOP/IIOP protocol.

5. Unmarshalling: The Skeleton converts the data back into the server's native format and
executes the logic.

6. Response: The result travels back through the same path.

Key Protocols in CORBA

 GIOP (General Inter-ORB Protocol): Defines the abstract syntax for messages between
ORBs.
 IIOP (Internet Inter-ORB Protocol): A specific implementation of GIOP that runs over TCP/IP.
This is what allows different vendors' ORBs to talk to each other over the internet.

6. What is a POJO files? Why of we create a POJO class? Explain in detail.

Ans. In Java development, POJO stands for Plain Old Java Object. The term was coined by Martin
Fowler and others to describe a simple Java object that is not burdened by the complexities of
specific framework requirements (like EJB) or heavy-weighted interfaces.

What is a POJO?

A POJO is a Java class that does not extend any specialized class and does not implement any
specialized interface from a framework. It is just a "plain" object that follows the standard Java
language rules.

Characteristics of a Strict POJO:

 It does not extend pre-specified classes (e.g., extends [Link]).

 It does not implement pre-specified interfaces (e.g., implements [Link]).

 It does not contain any "prescribed" annotations from a framework (though modern POJOs
often use annotations for mapping).

The Components of a POJO Class

While a POJO is "plain," it usually follows the JavaBean convention to make it useful for frameworks
like Struts, Hibernate, or Spring:

1. Private Fields: Data is hidden from direct access (Encapsulation).

2. Public Getter/Setter Methods: Used to read and write to the fields.

3. Public No-argument Constructor: Allows frameworks to instantiate the class via reflection.

Example Code:

Java

public class Student {

private String name;

private int id;

// No-argument constructor

public Student() {}

// Getter and Setter

public String getName() { return name; }


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

public int getId() { return id; }

public void setId(int id) { [Link] = id; }

POJOs are the backbone of modern Java architecture for several critical reasons:

1. Reusability and Portability

Since a POJO is not tied to a specific framework (like Struts or Spring), you can use the same class in
a desktop application, a web application, or a mobile app without modification. It is "framework-
agnostic."

2. Testability

Because POJOs don't require a server or a complex container (like an EJB container) to run, you can
write JUnit tests for them very easily. You can instantiate them like any other Java object and test
the logic.

3. Simplifies Code (Readability)

Before POJOs became popular, developers had to write "Heavyweight" beans that required a lot of
boilerplate code and inheritance. POJOs keep the focus on the Data and the Domain Logic, making
the code much cleaner.

4. Loose Coupling

By using POJOs, your application's business logic is decoupled from the infrastructure. If you decide
to switch from one framework to another, your core data objects (POJOs) don't need to change.

POJO vs. JavaBean

People often use these terms interchangeably, but there is a slight technical difference:

Feature POJO JavaBean

Serializable Not required. Must implement [Link].

Constructor Any constructor. Must have a public no-arg constructor.

Accessors Any method name. Must use getXXX and setXXX naming.

Complexity The simplest form of a class. A POJO that follows specific conventions.

7. How Java Bean is created? Explain with the help of a program.

Ans. A JavaBean is essentially a standard Java class that follows specific naming conventions. Think
of it as a "capsule" used to wrap multiple objects into a single object (the bean), so that they can be
passed around as a single entity.

To be considered a true JavaBean, a class must follow these three strict rules:

1. It must implement [Link] (to allow saving its state).


2. It must have a public, no-argument constructor.

3. It must provide getter and setter methods for its private properties.

The Workflow of Creating a JavaBean

Creating a bean involves moving from a private data state to a public access state via standardized
methods.

Step 1: Define the Class and Implement Serializable

This allows the bean to be converted into a byte stream, which is necessary for transferring data
over a network or saving it to a file.

Step 2: Declare Private Properties

We use the private keyword to hide the data from direct outside interference (Encapsulation).

Step 3: Create the No-Arg Constructor

This is vital because many frameworks (like Struts or JSF) use Reflection to instantiate your bean
automatically. They won't know what arguments to pass, so they rely on the empty constructor.

Step 4: Provide Getters and Setters

These follow the getFieldName() and setFieldName() naming convention.

Programmatic Example: [Link]

Here is a complete implementation of a JavaBean designed to store student information.

Java

package [Link];

import [Link];

// Rule 1: Implement Serializable

public class StudentBean implements Serializable {

// Rule 2: Private properties (Encapsulation)

private int id;

private String name;

private double marks;

// Rule 3: Public No-argument constructor

public StudentBean() {

// Initializing with default values if necessary

// Rule 4: Standardized Getters and Setters

public int getId() {


return id;

public void setId(int id) {

[Link] = id;

public String getName() {

return name;

public void setName(String name) {

[Link] = name;

public double getMarks() {

return marks;

public void setMarks(double marks) {

[Link] = marks;

How to use the Bean in another Class

Once the bean is created, you can easily set and get data from it.

Java

public class TestBean {

public static void main(String[] args) {

StudentBean st = new StudentBean();

// Setting values using the setter

[Link]("Rehansh");

[Link](101);

// Getting values using the getter

[Link]("Student Name: " + [Link]());

}
8. Explain Hibernate architecture in detail.

Ans. Hibernate is an open-source, lightweight ORM (Object-Relational Mapping) tool that simplifies
Java application development by managing the interaction between Java objects and relational
databases.

Its architecture is layered to isolate the application from the underlying database and configuration
details.

The Core Architecture of Hibernate

Hibernate operates between the Java application and the database. It uses configuration data (XML
or Annotations) and persistent objects (POJOs) to perform its duties.

The architecture is divided into several key components:

1. Configuration Object

The Configuration object is the first Hibernate object you create in any Hibernate application. It is
usually created once during application initialization. It reads the configuration file
([Link]) and the mapping files (.[Link] or annotations).

2. SessionFactory Object

The SessionFactory is a thread-safe, immutable cache of compiled mappings for a single database. It
is a "heavyweight" object, usually created once per database. Its primary responsibility is to provide
Session instances.

3. Session Object

A Session is a "lightweight," non-thread-safe object that represents a single unit of work with the
database. It wraps a physical JDBC connection.

 It is used to perform CRUD (Create, Read, Update, Delete) operations.

 Lifecycle: It is opened when needed and must be closed as soon as the work is finished.

4. Transaction Object

The Transaction object is optional but highly recommended. It abstracts the underlying transaction
implementation (JDBC, JTA). It ensures that database operations are atomic (either all succeed or all
fail).

5. Query and Criteria Objects

 Query: Uses HQL (Hibernate Query Language) or native SQL to retrieve data.

 Criteria: A programmatic, object-oriented way to fetch data without writing strings of


SQL/HQL.

High-Level vs. Low-Level Architecture


Hibernate can be viewed in two ways depending on how much of its power you use:

Lite Architecture

The application provides its own JDBC connections and manages its own transactions. Hibernate only
handles the mapping and SQL generation.

Full Architecture

Hibernate manages everything: the connection pooling (via C3P0 or Proxool), the transactions, and
the object-relational mapping.

Detailed Component Interaction

Component Responsibility

Persistent Objects Your POJO classes that represent database tables.

Mapping Files Tell Hibernate which POJO property maps to which DB column.

The Session object acts as a mandatory cache for all objects within a
First-Level Cache
transaction.

An optional, pluggable cache (like Ehcache) that stores data across different
Second-Level Cache
sessions.

JNDI/JTA Used for integrating with enterprise application servers.

Advantages of Hibernate Architecture

 Database Independence: You can change your database (e.g., MySQL to Oracle) by simply
changing one line in the configuration file.

 Boilerplate Reduction: It eliminates the need to write repetitive JDBC code (creating
connections, preparing statements, closing result sets).

 Caching: It improves performance significantly by reducing the number of hits to the


database through internal caching mechanisms.

 Relationship Management: It handles complex table relationships (One-to-One, One-to-


Many, Many-to-Many) automatically.

9. (a) List and explain any 2 classes available in Javabeans package.

Ans. The [Link] package provides the classes and interfaces necessary for creating and
managing JavaBeans. While there are many utilities, the following two are fundamental for
introspection (discovering bean properties) and event handling.

1. Introspector

The Introspector class is the primary utility used to learn about the properties, events, and methods
supported by a target Java Bean. It follows the "Design Patterns" of the JavaBean specification to
analyze a class at runtime.
 Key Function: It uses the getBeanInfo() method to return a BeanInfo object. This object
contains all the metadata about the bean.

 How it Works: It first looks for a specific BeanInfo class (e.g., MyBeanBeanInfo). If that
doesn't exist, it uses Reflection to analyze the class's methods and find anything matching
the get<Name> or set<Name> pattern.

 Importance: This is what allows IDEs and visual builders to automatically display a list of
editable properties for a bean without the developer writing manual configuration.

2. PropertyChangeSupport

This is a utility class that can be used by beans that support bound properties. A bound property is
one that notifies "listeners" whenever its value changes.

 Key Function: It manages a list of PropertyChangeListener objects and handles the firing of
PropertyChangeEvent objects to those listeners.

 Core Methods: * addPropertyChangeListener(PropertyChangeListener l): Registers a


listener.

o firePropertyChange(String propertyName, Object oldValue, Object newValue):


Notifies all listeners that a change has occurred.

 Importance: It simplifies the implementation of the Observer Pattern. Instead of writing the
logic to manage a list of listeners in every bean, you simply delegate the work to an instance
of PropertyChangeSupport.

In a typical MCA-level coding scenario, you would use them like this:

Java

import [Link].*;

public class MyBean {

private String data;

// Helper to manage listeners

private PropertyChangeSupport support = new PropertyChangeSupport(this);

public void setData(String newData) {

String oldData = [Link];

[Link] = newData;

// Notify everyone who is watching this bean

[Link]("data", oldData, newData);

}
(b) What is the difference between stateful and stateless session beans?

Ans. The primary difference between Stateful and Stateless session beans lies in how the EJB
container manages the conversational state (the data shared between method calls) for a specific
client.

Comparative Analysis

Feature Stateless Session Bean (SLSB) Stateful Session Bean (SFSB)

Does not maintain state. Each request Maintains state for a specific client
State Retention
is independent. across multiple calls.

Client-Bean 1:Many. One bean can serve many 1:1. One bean instance is dedicated to
Relationship clients sequentially. one client session.

Pooled by the container. Reused Created for a client and destroyed


Lifecycle
constantly. when the session ends.

No passivation needed (no state to Can be passivated (stored to disk) to


Passivation
save). save RAM.

Lower scalability due to memory


Performance High performance and high scalability.
consumption per user.

Generic tasks: Sending emails, unit User-specific tasks: Shopping carts,


Common Use Case
conversions, CRUD. multi-step tax forms.

1. Stateless Session Beans (SLSB)

In a Stateless bean, the instance variables may contain data during a method execution, but once the
method returns, that data is not guaranteed to be there for the next call. The EJB container uses a
Bean Pool to manage these.

 How it works: When a client calls a method, the container grabs any available bean from the
pool. Once the task is done, the bean goes back to the pool.

 Why use it: It is the most efficient way to build a scalable system because 10 bean instances
might be enough to serve 1,000 users.

2. Stateful Session Beans (SFSB)

A Stateful bean acts like an extension of the client on the server. It "remembers" who the client is
and what they did in the previous step.

 How it works: The bean is created specifically for one client. It stays in memory (or disk)
until the client removes it or it times out.
 Passivation/Activation: If the server runs low on memory, it moves "idle" Stateful beans to
secondary storage (Passivation). When the client returns, the server moves the bean back to
RAM (Activation).

Programmatic Difference

Stateless Example

Java

@Stateless

public class CalculatorBean {

public int add(int a, int b) {

return a + b; // No data is stored after the return

Stateful Example

Java

@Stateful

public class ShoppingCartBean {

private List<Item> cart = new ArrayList<>();

public void addItem(Item item) {

[Link](item); // The list 'cart' is remembered for the next call

You might also like