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

Java4

The Client-Server Model is a distributed computing architecture where clients request services from servers, forming the basis of modern networking and web technologies. It features a request-response communication cycle and can be implemented in two-tier or three-tier architectures, providing advantages such as centralized data management and scalability, while also presenting challenges like security risks and server dependency. Remote Method Invocation (RMI) allows for remote method calls in Java, simplifying distributed programming, while Hibernate is an ORM framework that facilitates database interactions, promoting database independence and reducing boilerplate code.

Uploaded by

ustatsinghji249
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)
1 views21 pages

Java4

The Client-Server Model is a distributed computing architecture where clients request services from servers, forming the basis of modern networking and web technologies. It features a request-response communication cycle and can be implemented in two-tier or three-tier architectures, providing advantages such as centralized data management and scalability, while also presenting challenges like security risks and server dependency. Remote Method Invocation (RMI) allows for remote method calls in Java, simplifying distributed programming, while Hibernate is an ORM framework that facilitates database interactions, promoting database independence and reducing boilerplate code.

Uploaded by

ustatsinghji249
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

CLIENT–SERVER MODEL

The Client–Server Model is a distributed compu ng architecture in which tasks are divided
between:

 Clients (service requesters)

 Servers (service providers)

It is the founda on of modern networking and web technologies, especially the Internet.

The Client–Server Model is a system where:

 A client sends a request for data or service

 A server processes the request and returns a response

This communica on occurs over a network (LAN/WAN/Internet).

Features:

 Distributed system

 Centralized control of data (server-side)

 Request–Response communica on

 Independent client systems

 Scalable architecture

Components of Client–Server Model

Client: A client is a device or program that requests services/data from a server and displays
or uses the received data.

Func ons:

 Sends request (HTTP/HTTPS)


 Receives response

 Handles user interac on

Examples

 Web browsers (Chrome, Firefox)

 Mobile apps

 Desktop applica ons

Server: A server is a system that provides data/services to clients and processes client
requests

Func ons

 Stores data (database)

 Processes requests

 Sends responses

Types of Servers

 Web Server (serves web pages)

 Database Server (stores data)

 File Server

 Mail Server

Working of Client–Server Model (Step-by-Step Process)

1. User Input

o User enters URL (e.g., [Link])

2. DNS Resolu on

o Browser contacts DNS server

o DNS converts domain name → IP address

3. Request Sent

o Browser sends HTTP/HTTPS request to server

4. Server Processing

o Server receives request

o Processes logic (may involve database)


5. Response Sent

o Server sends data (HTML, CSS, JS)

6. Rendering

o Browser renders page using:

 DOM (Document Object Model)

 CSS Engine

 JavaScript Engine

Request–Response Cycle

Step Descrip on

Request Client sends request

Processing Server processes it

Response Server sends result

This cycle con nues for every interac on.

Architecture Types

1. Two-Tier Architecture

 Client ↔ Server

 Direct communica on

 Example: Simple database applica ons

2. Three-Tier Architecture
 Client ↔ Applica on Server ↔ Database Server

 More secure and scalable

Advantages

1. Centralized Data Management

 Data stored in one loca on

 Easy to manage and update

2. Cost Efficiency

 Lower maintenance costs

 No need for powerful client systems

3. Scalability

 Servers and clients can be upgraded independently

4. Data Recovery

 Easy backup from central server

5. Resource Sharing

 Mul ple clients can access same resources

Disadvantages

1. Security Risks

 Clients vulnerable to:

o Viruses

o Trojans

o Worms
2. Server Dependency

 If server fails → en re system stops

3. Network Dependency

 Requires stable network connec on

4. Cyber A acks

 DoS (Denial of Service)

 MITM (Man-in-the-Middle)

 Phishing a acks

5. Data Integrity Issues

 Data packets can be:

o Modified

o Spoofed

Security Threats

o DoS a ack: Server overwhelmed with requests → stops working

o MITM a ack: A acker intercepts communica on

o Phishing: Fake websites steal creden als

o Spoofing: Fake iden ty to access system

REMOTE METHOD INVOCATION (RMI)


RMI registry is a namespace on which all server objects are placed. Each me the server
creates an object, it registers this object with the RMI registry (using bind () or rebind ()
methods).

These are registered using a unique name known as bind name. To invoke a remote object,
the client needs a reference of that object. At that me, the client fetches the object from
the registry using its bind name (using lookup () method).

Marshalling and Unmarshalling

Marshalling

 Process of conver ng method parameters into a format (message) suitable for


transmission over a network.

 Done at the client side.

Unmarshalling

 Process of reconstruc ng the transmi ed data back into original form.

 Done at the server side.

Detailed Working

At Client Side (Marshalling)

 Client invokes a remote method

 Parameters are:
o Primi ve types → Packed with headers

o Objects → Converted into byte stream using serializa on

 Data is sent over the network

At Server Side (Unmarshalling)

 Server receives the message

 Data is:

o Unpacked

o Deserialized (if objects)

 Actual method is invoked with reconstructed parameters

Steps to Create RMI Applica on

Step 1: Create Remote Interface

 Extends Remote

 Methods throw RemoteExcep on

Step 2: Implement Remote Interface

 Provide actual method defini ons

Step 3: Compile and Generate Stub/Skeleton

 Use:

rmic ClassName

Step 4: Start RMI Registry

rmiregistry

Step 5: Create Server Applica on

 Register object with registry

Step 6: Create Client Applica on

 Lookup remote object

 Invoke methods

Working of RMI (Deep Understanding)

1. Client calls method on stub

2. Stub performs marshalling


3. Request sent over network

4. Server skeleton performs unmarshalling

5. Actual method executes

6. Result is marshalled back to client

Example:
Client calls add (x, y) method on remote server.

We create a remote method:

Add (int x, int y)

The client sends two numbers to the server, and the server returns their sum.

Step 1: Create the Remote Interface

Code

import [Link].*;

public interface Adder extends Remote {


public int add(int x, int y) throws RemoteExcep on;
}

Explana on

 Adder is the remote interface

 It extends Remote

 Remote methods must throw RemoteExcep on

Why needed?

This interface acts like a common contract between client and server.
Both know which method can be called remotely.

Step 2: Provide Implementa on of Remote Interface

Code

import [Link].*;
import [Link].*;

public class AdderRemote extends UnicastRemoteObject implements Adder {

AdderRemote() throws RemoteExcep on {


super();
}

public int add(int x, int y) {


return x + y;
}
}

Explana on

 AdderRemote implements Adder

 It extends UnicastRemoteObject

 This makes the object available for remote access

 Constructor must throw RemoteExcep on

Method Working

public int add(int x, int y) {


return x + y;
}

This is the actual business logic.

Step 3: Generate Stub and Skeleton

Command

rmic AdderRemote

Explana on

 rmic creates helper classes for remote communica on

 These are:

o Stub → client side proxy

o Skeleton → server side dispatcher

Simple Meaning

 Stub takes request from client and sends it to server

 Skeleton receives request on server and calls actual method

In old RMI architecture, both stub and skeleton were important in exams.
In modern Java, skeleton is not discussed much, but for university answers, write both.

Step 4: Start RMI Registry


Command

rmiregistry 5000

Explana on

 Registry acts like a directory or phonebook

 Server registers remote object in registry

 Client looks up object from registry

Here port number is 5000

Step 5: Create and Run Server Applica on

Easy Server Code

import [Link].*;
import [Link].*;

public class MyServer {


public sta c void main(String args[]) {
try {
AdderRemote obj = new AdderRemote();
[Link]("rmi://localhost:5000/sonoo", obj);
[Link]("Server started...");
} catch (Excep on e) {
[Link](e);
}
}
}

Explana on

 Server creates object of AdderRemote

 Registers it using [Link]()

 Remote object is bound with name sonoo

So now this object can be found by the client.

Step 6: Create and Run Client Applica on

Easy Client Code

import [Link].*;

public class MyClient {


public sta c void main(String args[]) {
try {
Adder stub = (Adder) [Link]("rmi://localhost:5000/sonoo");
[Link]("Sum = " + [Link](10, 20));
} catch (Excep on e) {
[Link](e);
}
}
}

Explana on

 Client uses [Link]() to get remote object reference

 stub behaves like a local object

 But actually method runs on remote server

 [Link](10,20) sends request to server

 Server returns result

How It Works Internally?

1. Client calls add(10,20)

2. Stub receives request

3. Parameters are marshalled

4. Request goes over network

5. Server receives request

6. Data is unmarshalled

7. Actual add() method runs

8. Result is sent back

9. Client displays output

Output of This RMI Example

Server Side Output

Server started...

Client Side Output

Sum = 30
Important Naming Class Methods

The Naming class is used to bind and access remote objects.

1. lookup()

[Link]("rmi://localhost:5000/sonoo");

 Finds remote object from registry

 Used by client

2. bind()

 Binds remote object with a name

 Used only if name is not already bound

3. rebind()

 Replaces old binding with new one

 Commonly used by server

4. unbind()

 Removes object from registry

5. list()

 Shows names of all bound remote objects

Goals of RMI (Remote Method Invoca on)

RMI is designed to make distributed programming simple and efficient.

Main Goals

1. Minimize Complexity

 Makes remote method calls look like local method calls

 Developers don’t need to handle low-level networking

2. Preserve Type Safety

 Java ensures strict type checking

 Method parameters and return types must match

 Prevents run me errors

3. Distributed Garbage Collec on


 Automa cally removes unused remote objects

 Works across JVMs

 Prevents memory leaks in distributed systems

4. Transparency (Local vs Remote)

 Reduces difference between:

o Local object calls

o Remote object calls

 Achieved using stub (proxy objects)

5. Pla orm Independence

 Uses Java → runs on any system with JVM

 Uses machine-independent format (serializa on)

Parameter Passing in RMI: RMI allows method calls with parameters and return values.

Types of Parameters in RMI:

a. Primi ve Parameters: Passed by Value

 JVM creates a copy of the value

 Sends the copy to remote method

 Original value remains unchanged

Example

add(5, 10)

 5 and 10 are copied and sent to server

b. Object Parameters: Object Passed by Value (Not Reference)

 En re object is serialized

 Sent over network as byte stream

 Reconstructed (deserialized) at server

Example

Student obj = new Student("Raghav");

 Full object is sent, not memory reference

c. Remote Object Parameters: Passed by Reference (Proxy)


 Instead of sending object, RMI sends:
→ Remote reference (stub/proxy)

Working

 Client gets proxy object

 Method calls go through proxy

 Actual execu on happens on remote server

Example

RemoteService obj = [Link](...);

 Client gets proxy, not actual object

HIBERNATE FRAMEWORK
Hibernate is a Java-based ORM (Object Relational Mapping) framework used to:

 Develop database-independent persistence logic

 Simplify interaction between Java objects and databases

Hibernate is an open-source, lightweight, non-invasive ORM framework that provides an


abstraction layer over JDBC to simplify database operations.

Hibernate is used to overcome the following problems of JDBC:

1. Database Dependency

 JDBC queries are database-specific (MySQL, Oracle, etc.)

 Changing database requires changing queries

2. Lack of Portability
 JDBC code is not portable across different databases

 Same logic cannot be reused easily

3. High Cost of Database Migration

 Changing DB in middle of project is time-consuming and costly

4. Mandatory Exception Handling

 JDBC requires extensive try-catch blocks

 Makes code complex and less readable


5. No Object-Level Relationship
 JDBC works with tables and primitive data

 Does not support object relationships (OOP concepts)

6. Boilerplate Code Problem

 Repetitive code for:

o Connection setup

o Statement creation

o Result handling

 Leads to:

o Increased code length

o Reduced readability

Hibernate provides:

 Automatic database connection


 Automatic query generation (CRUD operations)

 Mapping between objects and tables

 Database independence

Features of Hibernate

1. ORM (Object Relational Mapping)

 Maps:

o Java Class → Database Table


o Object → Row

o Attribute → Column

2. Database Independence

 Uses HQL (Hibernate Query Language)

 HQL is database-independent

3. Auto DDL Operations

 Automatically performs:
o Create table

o Drop table

o Alter table
4. Auto Primary Key Generation

 Automatically generates:

o Primary keys (IDs)

5. Built-in Caching

 Supports cache memory

 Improves performance

6. Simplified Exception Handling

 No need for extensive try-catch like JDBC

7. Open Source

 Free to use

 Source code available and modifiable

8. Lightweight
 Small size

 No heavy server/container required

 Can run independently or with frameworks

9. Non-Invasive

 No need to:

o Extend Hibernate classes

o Implement Hibernate interfaces


 Uses POJO classes (Plain Java Objects)

Hibernate vs JDBC

Feature JDBC Hibernate


Database Dependency Dependent Independent (HQL)

Code Length Large (boilerplate) Less

Exception Handling Mandatory Simplified

Object Mapping Not supported Supported (ORM)

Query Language SQL (DB-specific) HQL (DB-independent)

Caching Not available Available


Primary Key Handling Manual Automatic

DDL Operations Manual Automatic

How Hibernate Works?

1. Developer creates POJO class

2. Hibernate maps class to database table

3. Developer performs operations using:

o HQL or APIs
4. Hibernate:

o Generates SQL internally

o Executes it

o Returns result as objects

Hibernate Architecture

Hibernate architecture defines how different components interact to perform:

 Database connec on

 Object mapping

 CRUD opera ons

It acts as a bridge between Java applica on and database.

Hibernate architecture is divided into 4 layers:

1. Java Applica on Layer

 Contains:

o Java classes (POJO)

o Business logic

 Interacts with Hibernate APIs

2. Hibernate Framework Layer

 Core layer of Hibernate

 Contains:

o Session
o SessionFactory

o Transac on

o Query

 Performs ORM and data handling

3. Backend API Layer

 Hibernate internally uses:

o JDBC → Database connec vity

o JTA → Transac on management

o JNDI → Resource lookup

4. Database Layer

 Actual database (MySQL, Oracle, etc.)

 Stores persistent data

Core Components of Hibernate Architecture

1. Configura on Object: First object created in Hibernate applica on

 Loads:

o [Link]

o Mapping files

 Validates configura on

 Creates metadata

Code

Configura on cfg = new Configura on();


[Link]figure();

2. SessionFactory: Factory for crea ng Session objects

 Thread-safe

 Immutable

 Created once per database

Code

SessionFactory factory = [Link]();


Func ons

 Uses metadata from Configura on

 Creates database connec ons

3. Session Object: Represents a connec on with database

 Lightweight

 Not thread-safe

 Used for CRUD opera ons

Code

Session session = [Link]();

Func ons

 Insert, update, delete, fetch data

4. Transac on Object: Represents a unit of work

 Ensures data consistency

 Makes changes permanent using commit()

Code

Transac on tx = [Link] on();


[Link]();

5. Query Object: Used to execute HQL (Hibernate Query Language) queries

 Retrieve data

 Bind parameters

 Control result size

Code

Query query = [Link]("from Employee");

6. Criteria Object: Alterna ve to HQL for querying data

 Object-oriented query approach

 Uses condi ons (Restric ons)

Internal APIs Used by Hibernate

Hibernate internally uses:


1. JDBC

 For database connec on and execu on

2. JTA (Java Transac on API)

 For managing transac ons

3. JNDI

 For resource lookup (like DataSource)

You might also like