wt-unit4
wt-unit4
Unit 4 2024-25
B.TECH (CSIT) SEMESTER -V
1: Enterprise Java Bean
2. Creating a JavaBeans
3. JavaBeans Properties, Types of beans, Stateful Session bean, Stateless Session bean, Entity
bean.
5. Environment Setup
6. REPL Terminal
Faculty
Dr. Aadarsh Malviya
(Associate Professor Department of CSE)
Affiliated to
2. Creating a JavaBeans
Creating a JavaBean is different from working with Enterprise JavaBeans (EJB). While EJB is for server-side
enterprise-level applications, JavaBeans are simple reusable software components that can be manipulated
visually in development tools. They are primarily used for encapsulating data in Java desktop applications but can
also be used in other Java environments.
1
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
import java.io.Serializable;
2
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
No-Argument Constructor: A default constructor (Person()) is provided to allow easy instantiation of the
bean without specifying any initial values.
3. Using the JavaBean:
You can create and use an instance of the JavaBean in a Java application like this:
3. JavaBeans Properties, Types of beans, Stateful Session bean, Stateless Session bean, Entity bean.
JavaBeans Properties
In JavaBeans, properties represent the data that can be accessed and modified through getter and setter methods.
Properties follow a naming convention where the method names reflect the property name and are used for
encapsulation.
Types of Properties:
1. Simple Property:
o Holds a single value, such as a String or int.
o Example:
Indexed Property:
Holds an array of values, and the setter/getter methods allow for specific indices to be accessed or
modified.
Example
3
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
Bound Property:
When a property changes, the bean notifies listeners about the change.
Uses PropertyChangeListener to observe changes.
Example
Constrained Property:
A property that can veto changes if they are deemed invalid.
Listeners can throw a PropertyVetoException if a change is unacceptable.
Types of Beans
1. JavaBeans:
Standard reusable components in desktop applications.
They encapsulate many objects into a single object (bean), accessible via properties, events, and methods.
Example: A Person bean to manage the name and age of a person.
2. Enterprise JavaBeans (EJB):
Components in the enterprise environment for building scalable, transactional, and distributed
applications.
EJBs are primarily used in server-side applications.
Types of EJB:
1. Stateful Session Bean
2. Stateless Session Bean
3. Entity Bean (deprecated, now replaced by Java Persistence API - JPA)
4. Message-Driven Beans (used for handling asynchronous messaging)
4
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
Banking transaction sessions where each client’s data needs to be maintained during the session.
Lifecycle of a Stateful Session Bean:
1. Creation: A new bean instance is created when the client requests the first method call.
2. Passivation: If not in use, the bean may be passivated (i.e., its state is saved to disk).
3. Activation: If the client calls a method again, the bean is activated.
4. Destruction: When the session ends or times out, the bean is destroyed.
Code Example:
import javax.ejb.Stateful;
@Stateful
public class ShoppingCartBean {
private List<String> cartItems = new ArrayList<>();
import javax.ejb.Stateless;
@Stateless
public class CalculatorBean {
5
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class Customer {
@Id
private Long id;
private String name;
Summary:
JavaBeans: Reusable components for encapsulating data in Java applications.
Stateful Session Beans: Maintain state across multiple method calls in server-side applications.
Stateless Session Beans: Do not retain state between method calls and are used for stateless business
logic.
Entity Beans: Represent persistent data in databases (replaced by JPA in modern applications).
Each bean type serves a different purpose depending on whether state needs to be maintained and the scope of the
application logic.
Introduction to Node.js
6
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
Introduction to Node.js
Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside
of a browser. It is built on the V8 JavaScript engine developed by Google and is designed for building scalable
network applications. Node.js uses an event-driven, non-blocking I/O model, which makes it highly efficient and
suitable for real-time applications.
Key Features of Node.js:
1. Asynchronous and Event-Driven:
o All APIs of Node.js are asynchronous (non-blocking), which means it can handle multiple
operations concurrently without waiting for one operation to complete before starting another.
o Event-driven architecture allows Node.js to manage multiple requests simultaneously using events
and callbacks.
2. Single-Threaded but Scalable:
o Although Node.js operates in a single thread, it is designed for scalability. It uses the event loop to
handle requests asynchronously and delegates heavy I/O operations (like database access, file
reading) to worker threads, allowing it to handle thousands of requests without blocking.
3. Non-Blocking I/O:
o Node.js uses a non-blocking I/O model, meaning it can initiate an I/O operation and continue
executing other code while waiting for the result of the I/O operation, improving performance.
4. Cross-Platform:
o Node.js can be run on various operating systems like Windows, macOS, and Linux, making it
versatile and widely adopted in development environments.
5. NPM (Node Package Manager):
o NPM is the default package manager for Node.js. It provides a vast ecosystem of libraries and
modules that developers can install and use in their applications, significantly speeding up
development.
6. JavaScript Everywhere:
o With Node.js, developers can write both client-side and server-side code in JavaScript, making
full-stack JavaScript development possible and more consistent.
Node.js Architecture
Node.js uses an event-driven architecture, where an event loop continuously listens for events and dispatches
them to event handlers when appropriate. This architecture allows Node.js to handle many connections
concurrently with low overhead compared to traditional multi-threaded models.
1. Event Loop: Handles asynchronous operations by executing callbacks when events are triggered. It
eliminates the need for multiple threads, which reduces overhead.
2. V8 Engine: The underlying JavaScript engine that compiles JavaScript into native machine code for faster
execution.
3. Libuv: A library that provides Node.js with the event-driven architecture and asynchronous I/O
capabilities.
Applications of Node.js
Node.js is particularly well-suited for building applications that require real-time interaction, high concurrency,
and fast data processing. It’s widely used in a variety of scenarios:
1. Web Servers and APIs:
Node.js can be used to build lightweight, high-performance web servers without the need for third-party
software like Apache or Nginx.
It is ideal for building RESTful APIs and GraphQL APIs due to its non-blocking I/O and asynchronous
nature.
const http = require('http');
7
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
Introduction to Node.js
Node.js is an open-source, cross-platform, JavaScript runtime environment that executes JavaScript code outside
of a browser. It is built on the V8 JavaScript engine developed by Google and is designed for building scalable
network applications. Node.js uses an event-driven, non-blocking I/O model, which makes it highly efficient
and suitable for real-time applications.
Key Features of Node.js:
1. Asynchronous and Event-Driven:
o All APIs of Node.js are asynchronous (non-blocking), which means it can handle multiple
operations concurrently without waiting for one operation to complete before starting another.
o Event-driven architecture allows Node.js to manage multiple requests simultaneously using events
and callbacks.
2. Single-Threaded but Scalable:
o Although Node.js operates in a single thread, it is designed for scalability. It uses the event loop to
handle requests asynchronously and delegates heavy I/O operations (like database access, file
reading) to worker threads, allowing it to handle thousands of requests without blocking.
3. Non-Blocking I/O:
o Node.js uses a non-blocking I/O model, meaning it can initiate an I/O operation and continue
executing other code while waiting for the result of the I/O operation, improving performance.
4. Cross-Platform:
o Node.js can be run on various operating systems like Windows, macOS, and Linux, making it
versatile and widely adopted in development environments.
5. NPM (Node Package Manager):
o NPM is the default package manager for Node.js. It provides a vast ecosystem of libraries and
modules that developers can install and use in their applications, significantly speeding up
development.
6. JavaScript Everywhere:
o With Node.js, developers can write both client-side and server-side code in JavaScript, making
full-stack JavaScript development possible and more consistent.
Node.js Architecture
Node.js uses an event-driven architecture, where an event loop continuously listens for events and dispatches
them to event handlers when appropriate. This architecture allows Node.js to handle many connections
concurrently with low overhead compared to traditional multi-threaded models.
1. Event Loop: Handles asynchronous operations by executing callbacks when events are triggered. It
eliminates the need for multiple threads, which reduces overhead.
2. V8 Engine: The underlying JavaScript engine that compiles JavaScript into native machine code for faster
execution.
3. Libuv: A library that provides Node.js with the event-driven architecture and asynchronous I/O
capabilities.
Applications of Node.js
Node.js is particularly well-suited for building applications that require real-time interaction, high concurrency,
and fast data processing. It’s widely used in a variety of scenarios:
1. Web Servers and APIs:
Node.js can be used to build lightweight, high-performance web servers without the need for third-party
8
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});
2. Real-Time Applications:
Node.js is great for real-time applications like chat applications, collaboration tools, and gaming
servers due to its event-driven, non-blocking architecture.
WebSockets can be used to establish a real-time, two-way communication between the client and the
server.
Example: Real-time chat application using Socket.io.
server.listen(3000, () => {
console.log('listening on *:3000');
});
3. Microservices:
Node.js is commonly used to develop microservices—small, independent services that work together to
form a large application. Its lightweight nature and support for RESTful APIs make it ideal for breaking
down monolithic applications into microservices.
9
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
Conclusion
Node.js is a powerful, flexible, and efficient runtime for building a variety of applications, especially those that
require high concurrency, real-time interaction, and scalability. Its non-blocking, event-driven architecture makes
it well-suited for I/O-heavy applications, and its extensive ecosystem of packages through NPM allows
developers to rapidly build and deploy applications across different industries.
Environment Setup
Setting up the Node.js environment involves installing Node.js, its package manager (NPM), and setting up the
basic tools needed to develop and run Node.js applications. Below is a step-by-step guide to get Node.js up and
running on your system:
1. Download and Install Node.js
For Windows, macOS, and Linux:
Official Website: Go to the official Node.js website.
You will see two versions available for download:
o LTS (Long Term Support): Recommended for most users because it's more stable and receives
long-term updates.
10
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
o
Current Version: Contains the latest features but may be less stable.
Choose the LTS version unless you specifically need the latest features in the current release.
For Linux (Alternative via Terminal):
Ubuntu/Debian-based systems:
1. Update the package repository and install Node.js
CentOS/RHEL-based systems:
1. Use curl to fetch and add the Node.js repository:
Verify Installation:
After installation, verify that Node.js and NPM are installed correctly by running the following commands:
mkdir my-node-app
cd my-node-app
npm init
This command will prompt you for various inputs such as project name, version, description, entry point, and
author. You can hit "Enter" to accept the defaults or customize them as per your needs.
Alternatively, you can use the -y flag to skip all the prompts and create a default package.json file:
npm init –y
{
"name": "my-node-app",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
11
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
"author": "",
"license": "ISC"
}
touch index.js
// Configure the HTTP server to respond with "Hello, World!" to all requests.
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
});
node index.js
12
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
});
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
node index.js
Visit http://localhost:3000/, and you will see the message: Hello from Express!.
nodemon index.js
Now, the server will automatically restart whenever you make changes to any files in the project.
PORT=4000
MESSAGE="Hello from the environment"
13
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
});
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
nodemon index.js
The server will now run on port 4000 (from the .env file), and the message will be read from the environment
variable.
my-node-app/
├── node_modules/ # Installed packages
├── public/ # Static files (CSS, JS, images)
├── routes/ # Route handlers
│ └── index.js # Example route handler
├── views/ # Views for rendering HTML (if using a templating engine)
├── .env # Environment variables
├── package.json # Project metadata and dependencies
├── index.js # Main entry point
└── README.md # Project documentation
7. Conclusion
By following these steps, you can easily set up a Node.js environment, create a basic application, manage
packages, and improve your workflow with tools like nodemon. Once set up, you're ready to start building
scalable, high-performance web applications using Node.js!
REPL Terminal
Node.js REPL (Read-Eval-Print-Loop) Terminal
The REPL is an interactive shell that allows you to execute JavaScript and Node.js code directly in a terminal. It
stands for Read-Eval-Print Loop:
Read: The REPL reads your input (JavaScript code).
Eval: It evaluates your code.
Print: It prints the result of the evaluation.
Loop: It loops, waiting for more code or commands.
The REPL is very useful for quickly testing small pieces of code, debugging, or experimenting with Node.js
functionality.
Accessing the Node.js REPL
To start the Node.js REPL:
1. Open your terminal (Command Prompt, PowerShell, or terminal in macOS/Linux).
2. Simply type the following command and press Enter
Node
14
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
>
Now, you're inside the REPL environment, and you can execute JavaScript code interactively.
Example Usage of REPL
Basic Math Operations
You can perform simple math operations directly:
>2+3
5
> 10 * 4
40
Multi-line Code
The REPL also supports multi-line input. For example, you can define a function block like this:
REPL Commands
The Node.js REPL has several built-in commands:
1. .help: Displays help and lists all REPL commands.
15
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
> .help
> .exit
> .clear
> 10 + 20
30
>_
30
> console.log(unknownVar);
ReferenceError: unknownVar is not defined
16
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
with other developers. NPM also serves as a repository of open-source libraries that developers can integrate into
their Node.js projects.
NPM is automatically installed when you install Node.js.
NPM Commands
Here are some of the most commonly used NPM commands:
1. Installing Packages
Local Installation: To install a package locally (specific to the project):
npm install <package-name>
This installs the package inside the node_modules/ folder of your project and adds it to your package.json file
under "dependencies".
Example:
Global Installation: To install a package globally (available system-wide, outside of the current project):
Example:
2. Uninstalling Packages
To uninstall a package from your project:
This removes the package from node_modules/ and updates the package.json file.
3. Creating a package.json File
To initialize a new Node.js project with a package.json file, use the following command in the root of your
project directory:
17
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
npm init
This will prompt you with a series of questions about your project (name, version, description, etc.) and create the
package.json file. If you want to skip the prompts and create a default file, use:
npm init –y
4. Updating Packages
To update a package to the latest version:
npm list
For globally installed packages:
6. Package Versions
Install a specific version of a package
Example:
npm install [email protected]
{
"scripts": {
"start": "node index.js",
"test": "mocha"
}
}
For example:
18
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
Understanding package.json
The package.json file is a crucial part of any Node.js project. It holds metadata about the project and contains
information about the project's dependencies, scripts, and version control.
Here’s an example of a basic package.json file:
{
"name": "my-node-app",
"version": "1.0.0",
"description": "A simple Node.js app",
"main": "index.js",
"scripts": {
"start": "node index.js",
"test": "echo \"No test specified\" && exit 1"
},
"author": "Your Name",
"license": "ISC",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"nodemon": "^2.0.12"
}
}
NPM Cache: NPM caches packages after downloading them to make future installs faster. If you encounter
issues with cached files, you can clear the cache using:
19
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
2. Publishing a Private Package: You need to be logged into your NPM account to publish a private package.
To publish a package:
NPM vs Yarn
Yarn is an alternative package manager to NPM that was created by Facebook. It was introduced to address some
of the shortcomings of NPM (e.g., speed, consistency) but both have improved over time.
Key differences between NPM and Yarn:
Speed: Yarn was initially faster due to better caching, but NPM has significantly improved with features
like npm ci.
Lock Files: Both use lock files (package-lock.json for NPM, yarn.lock for Yarn) to ensure consistency in
installed packages.
Community: NPM has a larger user base, but Yarn is popular in some large organizations.
Conclusion
NPM is an essential tool for any Node.js developer. It simplifies the management of packages, dependencies, and
version control, making the development process faster and more efficient. With its wide range of features like
scripts, versioning, and task automation, NPM is at the core of the modern JavaScript ecosystem.
1. Callbacks in Node.js
A callback is a function that is passed as an argument to another function and is executed after the first function
has completed its operation. In Node.js, callbacks are widely used to handle asynchronous operations such as file
reading, database queries, and API requests.
Example of a Callback Function:
function fetchData(callback) {
console.log("Fetching data...");
setTimeout(() => {
console.log("Data fetched.");
callback("Here is the data.");
}, 2000);
}
function processData(data) {
console.log("Processing: " + data);
}
fetchData(processData);
In this example, fetchData simulates an asynchronous operation using setTimeout, and processData is passed as a
callback to execute after the data is fetched.
Callback Pattern in Node.js APIs
Node.js follows the common convention of passing the error as the first argument in callback functions, known as
error-first callbacks.
Example using fs.readFile():
20
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
const fs = require('fs');
Here, err will hold any error that occurs during file reading, and data will contain the file's content if the operation
is successful.
2. Events in Node.js
Node.js has a built-in event-driven architecture, where certain objects (like EventEmitter) can emit named
events that other objects can listen to and react to. This makes Node.js powerful for handling asynchronous tasks
like network operations, file I/O, and server requests.
EventEmitter in Node.js
The events module in Node.js provides the EventEmitter class that allows you to create, emit, and listen for
custom events.
Example of Using EventEmitter:
// Emit an event
eventEmitter.emit('dataReceived', 'Hello from Node.js!');
In this example, the dataReceived event is emitted and caught by a listener, which then processes the data.
3. Packaging in Node.js
In Node.js, packages are collections of modules (libraries) that you can use in your project. A package typically
includes a set of JavaScript files and a package.json file that defines the metadata of the package.
Package Creation
To create your own package:
1. Initialize a new project: Use the following command to create a package.json file
npm init
1. Share your package: You can publish your package to the npm registry so others can install it.
Package Structure Example:
21
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
my-package/
├── index.js
├── package.json
└── node_modules/
4. Express Framework
Express.js is a minimalist web framework for Node.js that simplifies building web applications and APIs. It
provides utilities to manage HTTP requests, define routes, and handle middleware.
Key Features of Express:
Routing: Express allows you to define routes for different HTTP methods (GET, POST, PUT, DELETE,
etc.).
Middleware: Middleware functions in Express are used to process requests and responses. They are
executed in the order they are defined.
Templating Engines: You can render dynamic HTML using template engines like EJS, Pug, or
Handlebars.
Example of Express.js Setup:
1. Install Express:
This code starts a basic HTTP server on port 3000 and responds with "Hello from Express!" when visiting
http://localhost:3000/.
Middleware Example:
const express = require('express');
const app = express();
// Middleware function
app.use((req, res, next) => {
console.log('Request received at: ' + new Date());
next();
});
// Route
app.get('/', (req, res) => {
res.send('Hello with middleware!');
});
22
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
// Start server
app.listen(3000);
In this example, the middleware logs the date and time of each request before proceeding to the route handler.
5. RESTful API
A RESTful API (Representational State Transfer) is an architectural style for designing networked applications,
particularly web services. A RESTful API uses HTTP methods to perform CRUD (Create, Read, Update, Delete)
operations on resources.
HTTP Methods in REST:
GET: Retrieve data (read).
POST: Create new data (create).
PUT: Update existing data (update).
DELETE: Remove data (delete).
Example of a RESTful API with Express:
const express = require('express');
const app = express();
23
Web Technology (BCS502) 2024-25 (Odd Semester) [ Dr. Aadarsh Malviya DGI]
book.title = req.body.title;
book.author = req.body.author;
res.json(book);
});
books.splice(bookIndex, 1);
res.send('Book deleted');
});
Conclusion
Callbacks in Node.js handle asynchronous operations.
Events are emitted and listened to in Node.js, using the event-driven architecture.
Packaging in Node.js involves using and managing third-party libraries through NPM.
Express is a popular Node.js web framework for handling HTTP requests, routing, and middleware.
RESTful APIs enable interaction with resources over the web using HTTP methods (GET, POST, PUT,
DELETE).
Together, these concepts form a foundation for building powerful, scalable, and efficient web applications using
Node.js.
24