0% found this document useful (0 votes)
33 views

Advanced Java Programming

Uploaded by

crackiit2021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

Advanced Java Programming

Uploaded by

crackiit2021
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 129

Advanced Java Programming

report errors or suggest changes at telegram @ yash707


Unit-1
Introduction to Java
Key Features of Java
Basic Syntax
Java Identifiers
Java Modifiers
Variables
Introduction to Java
Inheritance
Superclass and Subclass
Syntax
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (Not Supported)
Example of Inheritance
Key Points
Exception Handling
Basics of Exception Handling
Syntax
Example 1: Arithmetic Exception

Advanced Java Programming 1


Example 2: ArrayIndexOutOfBoundsException
Example 3: NullPointerException
Handling Multiple Exceptions
The finally Block
throw and throws
Conclusion
Multithreading
Basics of Multithreading
Example 1: Creating a Thread by Extending Thread Class
Example 2: Creating a Thread by Implementing Runnable Interface
Example 3: Thread Synchronization
Conclusion
Applet Programming
Basics of Applet Programming
Example 1: Simple Applet
Example 2: Drawing Shapes
Example 3: Handling Mouse Events
Example 4: Animation
Conclusion
Additional Points:
Inheritance:
Exception Handling:
Multithreading:
Multi-Threading
Applet Programming:
Connecting to a Server
Using Sockets for Client-Server Communication
Explanation:
Additional Considerations:
Implementing Servers
Server Implementation Steps:
Explanation:
Additional Considerations:
Making URL Connections
Making URL Connections:
Additional Considerations:
Making URL Connections:
Implementing Servers:

Advanced Java Programming 2


Socket Programming in Java
Basic Concepts:
Java Socket Classes:
Example 1: Simple Client-Server Communication
Server Code:
Client Code:
Example 2: Multi-Threaded Server
Conclusion:
UNIT-II
Preparing a class to be a Java Bean
What is a Java Bean?
Requirements for a Java Bean:
Example of a Java Bean Class:
Usage of Java Bean:
Conclusion:
Creating a Java Bean
Step 1: Define the Class
Step 2: Implement Serializable Interface (Optional)
Step 3: Usage of the Java Bean
Conclusion:
Java Bean Properties
Definition:
Characteristics of Java Bean Properties:
Example of Java Bean Properties:
Usage:
Benefits:
Types of beans
1. Standard JavaBeans:
2. Enterprise JavaBeans (EJB):
3. Managed Beans (JSF Managed Beans):
4. Spring Beans:
5. CDI Beans (Contexts and Dependency Injection):
Conclusion:
Stateful Session bean
Characteristics of Stateful Session Beans:
Example of Stateful Session Bean:
Conclusion:
Stateless Session bean

Advanced Java Programming 3


Characteristics of Stateless Session Beans:
Example of Stateless Session Bean:
Conclusion:
Entity bean Servlet Overview and Architecture
Entity Beans:
Overview:
Architecture:
Servlets:
Overview:
Architecture:
Integration:
Conclusion:
Interface Servlet and the Servlet Life Cycle
1. Interface Servlet:
Key Methods in the Servlet Interface:
2. Servlet Life Cycle:
Stages in the Servlet Life Cycle:
Lifecycle Events:
Conclusion:
Handling
Handling HTTP GET Requests:
Steps for Handling HTTP GET Requests in a Servlet:
Handling HTTP POST Requests:
Steps for Handling HTTP POST Requests in a Servlet:
Conclusion:
Session Tracking
1. Cookies:
2. URL Rewriting:
3. HttpSession Object:
Cookies
1. Types of Cookies:
Mid Sem Topics
JMS/ Queue
Define introspection and explain different ways of implementing introspection for a bean
class.
Persistence
State and Explain EJB container services
Applet vs Application
Unit - 3

Advanced Java Programming 4


JavaServer Pages (JSP)
Java Server Pages (JSP) Overview
Implicit Objects in Java Server Pages (JSP)
Scripting in Java Server Pages (JSP)
Standard Actions in Java Server Pages (JSP)
Directives in Java Server Pages (JSP)
Custom Tag Libraries in Java Server Pages (JSP)
Unit - 4
Roles of Client and Server in Web Applications
Remote Method Invocations (RMI) in Java
Setup for Remote Method Invocation
Parameter Passing in Remote Methods
Introduction of HB
HB Architecture

Unit-1
Introduction to Java
Java is a high-level, class-based, object-oriented programming language that is
designed to have as few implementation dependencies as possible. It is a general-
purpose programming language intended to let application developers write once,
run anywhere (WORA), meaning that compiled Java code can run on all platforms
that support Java without the need for recompilation.

Key Features of Java


Platform Independent: Java works on the 'write once, run anywhere'
principle. Once you write a Java code, it can run on any platform that has Java
installed.

Object-Oriented: Everything in Java is an object which makes it a fully object-


oriented programming language. It has various concepts of OOPs like Object,
Class, Inheritance, Polymorphism, Abstraction, and Encapsulation.

Robust: Java has a strong memory management system. It helps in eliminating


error as it checks the code during compile and runtime.

Advanced Java Programming 5


Secure: Java does not use explicit pointers and run the programs inside the
sandbox to prevent any activities from untrusted sources. It enables to
develop virus-free, tamper-free systems/applications.

Multi-threaded: With Java's multithreaded feature it is possible to write


programs that can perform many tasks simultaneously.

Basic Syntax
Java syntax is the set of rules defining how a Java program is written and
interpreted.

Case Sensitivity: Java is case sensitive, which means identifier Hello and
hello would have different meaning in Java.

Class Names: For all class names the first letter should be in Upper Case. If
several words are used to form a name of the class, each inner word's first
letter should be in Upper Case.

Method Names: All method names should start with a Lower Case letter. If
several words are used to form the name of the method, then each inner
word's first letter should be in Upper Case.

File Name: The name of the program file should exactly match the class name.

public static void main(String args[]): Java program processing starts from
the main() method which is a mandatory part of every Java program.

public class MyFirstJavaProgram {


/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello Worl
d
}
}

This will print 'Hello World' as the output.

Advanced Java Programming 6


Java Identifiers
All Java components require names. Names used for classes, variables, and
methods are called identifiers. In Java, there are several points to remember about
identifiers. They are as follows:

All identifiers should begin with a letter (A to Z or a to z), currency character


($) or an underscore (_).

After the first character, identifiers can have any combination of characters.

A key word cannot be used as an identifier.

Most importantly identifiers are case sensitive.

Examples of legal identifiers: age, $salary, _value, __1_value.

Examples of illegal identifiers: 123abc, -salary.

Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using
modifiers. There are two categories of modifiers:

Access Modifiers: default, public , protected, private

Non-access Modifiers: final, abstract, strictfp

We will be looking in more detail about modifiers in the next sections.

Variables
We would see following type of variables in Java:

Local Variables

Class Variables (Static Variables)

Instance Variables (Non-static variables)

Introduction to Java
Java Overview:

Java is a high-level, object-oriented programming language developed by


Sun Microsystems (now owned by Oracle Corporation).

Advanced Java Programming 7


It is platform-independent, which means Java programs can run on any
device with the Java Virtual Machine (JVM) installed.

Features of Java:

Object-oriented: Encapsulation, Inheritance, Polymorphism, Abstraction.

Platform-independent: "Write once, run anywhere" (WORA) capability.

Robust: Strong memory management, exception handling, and type


checking.

Secure: Built-in security features like bytecode verification.

Multithreaded: Supports concurrent execution of multiple threads.

Portable: Java programs can be easily moved from one computer system
to another.

Java Development Kit (JDK):

Includes the Java Runtime Environment (JRE), Java Development Tools,


and libraries necessary for developing Java applications.

Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that
allows a new class to inherit properties and behavior from an existing class. In
Java, inheritance enables code reuse and establishes relationships between
classes.

Superclass and Subclass


Superclass (Parent Class): The class whose properties and methods are
inherited by another class.

Subclass (Child Class): The class that inherits properties and methods from
another class.

Syntax

class Superclass {
// superclass members

Advanced Java Programming 8


}

class Subclass extends Superclass {


// subclass members
}

Types of Inheritance

1. Single Inheritance
In single inheritance, a subclass inherits from only one superclass.

class Animal {
// Animal class members
}

class Dog extends Animal {


// Dog class members
}

2. Multilevel Inheritance
In multilevel inheritance, a subclass inherits from a superclass, and another class
inherits from this subclass.

class Animal {
// Animal class members
}

class Mammal extends Animal {


// Mammal class members
}

class Dog extends Mammal {

Advanced Java Programming 9


// Dog class members
}

3. Hierarchical Inheritance
In hierarchical inheritance, multiple subclasses inherit from a single superclass.

class Animal {
// Animal class members
}

class Dog extends Animal {


// Dog class members
}

class Cat extends Animal {


// Cat class members
}

4. Multiple Inheritance (Not Supported)


In Java, multiple inheritance refers to a situation where a class extends more than
one class. However, Java does not support multiple inheritance of classes due to
the "diamond problem," where ambiguity can arise when a subclass inherits from
two superclasses that have a common superclass. To mitigate this issue, Java
supports multiple inheritance through interfaces.
Example:

// Interface 1
interface A {
void methodA();
}

// Interface 2
interface B {
void methodB();

Advanced Java Programming 10


}

// Class implementing Interface 1


class MyClass implements A {
public void methodA() {
System.out.println("Method A");
}
}

// Class implementing Interface 2


class AnotherClass implements B {
public void methodB() {
System.out.println("Method B");
}
}

// Class implementing both Interface 1 and Interface 2


class CombinedClass implements A, B {
public void methodA() {
System.out.println("Method A");
}

public void methodB() {


System.out.println("Method B");
}
}

// Main class to demonstrate multiple inheritance


public class Main {
public static void main(String[] args) {
CombinedClass combined = new CombinedClass();
combined.methodA();
combined.methodB();
}
}

Advanced Java Programming 11


Explanation:

We define two interfaces A and B , each containing a method.

We then have two classes MyClass and AnotherClass , each implementing one of
the interfaces.

Finally, we have a class CombinedClass implementing both interfaces.

In the Mainclass, we create an object of CombinedClass and call both methods


methodA() and methodB() , demonstrating multiple inheritance through interfaces
in Java.

Example of Inheritance

// Superclass
class Vehicle {
void move() {
System.out.println("Vehicle is moving");
}
}

// Subclass inheriting from Vehicle


class Car extends Vehicle {
void accelerate() {
System.out.println("Car is accelerating");
}
}

// Main class
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.move(); // Output: Vehicle is moving
car.accelerate(); // Output: Car is accelerating
}
}

Advanced Java Programming 12


Key Points
Inheritance promotes code reuse and maintains a hierarchical structure.

Subclasses can extend the functionality of the superclass by adding new


methods or overriding existing ones.

Java supports single, multilevel, and hierarchical inheritance, but not multiple
inheritance (directly).

These concepts are fundamental to understanding inheritance in Java, providing a


basis for building complex class hierarchies and designing robust

Exception Handling
Exception handling is a mechanism provided by Java to handle runtime errors,
known as exceptions, in a structured and graceful manner. By handling exceptions
effectively, developers can prevent unexpected program terminations and provide
meaningful feedback to users.

Basics of Exception Handling


Exception: An event that disrupts the normal flow of the program's execution.

try-catch: A block of code where exceptions are handled.

throw: Keyword used to throw an exception explicitly.

throws: Keyword used to declare that a method may throw a particular type of
exception.

Syntax

try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Handle ExceptionType1
} catch (ExceptionType2 e2) {
// Handle ExceptionType2
} finally {
// Code that always executes, regardless of whether an ex

Advanced Java Programming 13


ception occurred or not
}

Example 1: Arithmetic Exception

public class Main {


public static void main(String[] args) {
try {
int result = 10 / 0; // ArithmeticException: / by
zero
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

In this example, the division by zero operation ( 10 / 0 ) throws an


ArithmeticException . The catch block catches this exception and prints an error

message.

Example 2: ArrayIndexOutOfBoundsException

public class Main {


public static void main(String[] args) {
int[] array = {1, 2, 3};
try {
int value = array[3]; // ArrayIndexOutOfBoundsExc
eption
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Advanced Java Programming 14


Here, accessing an element at an index beyond the array's bounds ( array[3] )
results in an ArrayIndexOutOfBoundsException .

Example 3: NullPointerException

public class Main {


public static void main(String[] args) {
String str = null;
try {
int length = str.length(); // NullPointerExceptio
n
} catch (NullPointerException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

In this case, invoking a method ( length() ) on a null object ( str ) leads to a


NullPointerException .

Handling Multiple Exceptions

public class Main {


public static void main(String[] args) {
try {
int[] array = {1, 2, 3};
int value = array[3]; // ArrayIndexOutOfBoundsExc
eption
int result = 10 / 0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Error: " + e.getM
essage());
} catch (ArithmeticException e) {
System.out.println("Arithmetic Error: " + e.getMe
ssage());
}

Advanced Java Programming 15


}
}

In this example, the try block contains code that may throw two different types of
exceptions ( ArrayIndexOutOfBoundsException and ArithmeticException ). Each catch block
handles a specific type of exception.

The finally Block

public class Main {


public static void main(String[] args) {
try {
// Code that may throw an exception
} catch (Exception e) {
// Handle exception
} finally {
// Code that always executes, regardless of wheth
er an exception occurred or not
}
}
}

The finally block contains code that always executes, regardless of whether an
exception occurred or not. It is typically used for cleanup tasks like closing
resources (e.g., files, database connections).

throw and throws


The keywords throw and throws are fundamental concepts in Java's exception
handling mechanism. Here's a breakdown of their functionalities with a generic
example:

throw:

Used within a method to explicitly signal an exceptional condition.

Takes an exception object as an argument, typically an instance of a subclass


of Throwable .

Advanced Java Programming 16


Triggers the termination of the normal program flow at that point.

Control jumps to the nearest enclosing try block to find a matching catch

handler.

throws:

Declared in the method signature to indicate potential exceptions the method


might throw during execution.

Informs the calling code about the types of exceptions it needs to be prepared
to handle.

Does not throw an exception itself.

Example:

public class NumberUtils {

public static int divide(int numerator, int denominator) throw


if (denominator == 0) {
throw new ArithmeticException("Division by zero!"); // Thr
}
return numerator / denominator;
}

public static void main(String[] args) {


try {
int result = divide(10, 0); // Potentially throws Arithmet
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage()); // Handlin
}
}
}

Explanation:

divide method:

Advanced Java Programming 17


Throws ArithmeticException when the denominator is zero (using throw ).

Declares throws ArithmeticException in the signature to inform callers.

main method:

Calls divide with a zero denominator, potentially triggering the throw .

Encloses the call in a try-catch block.

block handles the thrown


catch ArithmeticException and prints the error
message.

Conclusion
Exception handling is crucial for writing robust and reliable Java programs. By
anticipating and handling exceptions, developers can ensure that their
applications gracefully recover from errors and continue executing smoothly.
Understanding exception handling mechanisms enables developers to write more
resilient code.

Multithreading
Multithreading is a programming concept that allows multiple threads to execute
concurrently within a single process. In Java, multithreading enables developers
to create applications that can perform multiple tasks simultaneously, improving
efficiency and responsiveness.

Basics of Multithreading
Thread: A lightweight process that executes independently within a program.

Concurrency: The ability of multiple threads to execute simultaneously.

Synchronization: Mechanism to control access to shared resources among


multiple threads.

Thread States: New, Runnable, Blocked, Waiting, Timed Waiting, Terminated.

Example 1: Creating a Thread by Extending Thread Class

Advanced Java Programming 18


class MyThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread: " + i);
try {
Thread.sleep(1000); // Pause for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

public class Main {


public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start(); // Start the thread
}
}

In this example, a thread is created by extending the Thread class and overriding
the run() method. The start() method initiates the execution of the thread.

Example 2: Creating a Thread by Implementing Runnable


Interface

class MyRunnable implements Runnable {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Runnable: " + i);
try {
Thread.sleep(1000); // Pause for 1 second
} catch (InterruptedException e) {
System.out.println(e);
}

Advanced Java Programming 19


}
}
}

public class Main {


public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start(); // Start the thread
}
}

In this example, a thread is created by implementing the Runnable interface and


providing the implementation for the run() method.

Example 3: Thread Synchronization

class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}

public int getCount() {


return count;
}
}

class MyThread extends Thread {


private Counter counter;

public MyThread(Counter counter) {


this.counter = counter;
}

public void run() {

Advanced Java Programming 20


for (int i = 0; i < 1000; i++) {
counter.increment();
}
}
}

public class Main {


public static void main(String[] args) {
Counter counter = new Counter();
MyThread thread1 = new MyThread(counter);
MyThread thread2 = new MyThread(counter);

thread1.start();
thread2.start();

try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println(e);
}

System.out.println("Count: " + counter.getCount());


}
}

In this example, two threads ( thread1 and thread2 ) increment a shared counter
( Counter object) concurrently. The synchronized keyword ensures that only one
thread can execute the increment() method at a time, preventing race conditions
and ensuring data consistency.

Conclusion
Multithreading in Java allows developers to write efficient and responsive
applications by leveraging the power of concurrency. By creating and managing
multiple threads, developers can perform tasks concurrently, making the most out

Advanced Java Programming 21


of modern multicore processors and improving overall application performance.
Understanding multithreading concepts is essential for building scalable and high-
performance Java applications.

Applet Programming
Applet programming in Java enables developers to create dynamic and interactive
content that can be embedded within web pages. Java applets provide a platform-
independent way to enhance web pages with features such as animations, games,
and interactive forms.

Basics of Applet Programming


Applet: A Java program that runs within a web browser.

Applet Class: The base class for creating applets in Java.

Lifecycle Methods: init() , start() , stop() , destroy() .

paint(Graphics g) Method: Used to render graphics on the applet's surface.

Example 1: Simple Applet

import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorldApplet extends Applet {


public void paint(Graphics g) {
g.drawString("Hello, World!", 20, 20);
}
}

In this example, we create a simple applet that displays the text "Hello, World!" at
coordinates (20, 20) on the applet's surface.

Example 2: Drawing Shapes

import java.applet.Applet;
import java.awt.Graphics;

Advanced Java Programming 22


public class ShapeApplet extends Applet {
public void paint(Graphics g) {
g.drawRect(20, 20, 100, 50); // Draw a rectangle
g.drawOval(150, 20, 80, 80); // Draw an oval
g.drawLine(300, 20, 400, 100); // Draw a line
}
}

This example demonstrates drawing basic shapes (rectangle, oval, line) using the
Graphics object provided by the paint() method.

Example 3: Handling Mouse Events

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class MouseApplet extends Applet implements MouseListe


ner {
int x = 0;
int y = 0;

public void init() {


addMouseListener(this); // Register mouse listener
}

public void paint(Graphics g) {


g.drawString("Click at (" + x + ", " + y + ")", 20, 2
0);
}

// MouseListener methods
public void mouseClicked(MouseEvent e) {
x = e.getX(); // Get X-coordinate of mouse click

Advanced Java Programming 23


y = e.getY(); // Get Y-coordinate of mouse click
repaint(); // Refresh applet
}

public void mousePressed(MouseEvent e) {}


public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
}

In this example, the applet responds to mouse clicks by updating the coordinates
of the click and redrawing the applet to display the new coordinates.

Example 4: Animation

import java.applet.Applet;
import java.awt.Graphics;

public class AnimationApplet extends Applet implements Runnab


le {
int x = 0;

public void init() {


Thread t = new Thread(this);
t.start(); // Start the animation thread
}

public void paint(Graphics g) {


g.drawString("Moving Text", x, 20);
}

public void run() {


while (true) {
x += 5; // Move text horizontally
if (x > getWidth()) {
x = 0; // Reset position

Advanced Java Programming 24


}
repaint(); // Refresh applet
try {
Thread.sleep(100); // Pause for 100 milliseco
nds
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

This example creates an animated applet where text moves horizontally across the
applet's surface.

Conclusion
Java applets provide a versatile platform for creating interactive content within
web pages. By leveraging the Applet class and its associated methods,
developers can design engaging and dynamic experiences for users directly
within their web browsers. Understanding applet programming enables
developers to enhance web pages with animations, graphics, and interactivity,
enriching the overall user experience.

Additional Points:
Certainly! Here are some additional points that can be added to the topics we
discussed:

Inheritance:
Method Overriding: Subclasses can provide a specific implementation for a
method defined in the superclass, allowing for polymorphic behavior.

Access Modifiers: Inherited members can have different access modifiers in


the subclass, such as public , protected , or private , affecting their visibility and
accessibility.

Advanced Java Programming 25


Constructor Inheritance: Constructors are not inherited in Java, but a
subclass constructor implicitly calls the superclass constructor using super() .

Exception Handling:
Checked vs Unchecked Exceptions: Java distinguishes between checked
exceptions (which must be caught or declared in a throws clause) and
unchecked exceptions (which do not need to be explicitly handled).

Custom Exceptions: Developers can create custom exception classes by


extending the Exception class or its subclasses to handle application-specific
error conditions.

Best Practices: Handle exceptions at an appropriate level in the application,


provide informative error messages, and log exceptions for debugging
purposes.

Multithreading:
Thread Pools: Instead of creating and managing individual threads,
applications can use thread pools to efficiently manage a pool of reusable
threads, reducing overhead and improving performance.

Thread Safety: Synchronization techniques such as locks ( synchronized


keyword) or concurrent data structures can ensure thread safety and prevent
data corruption in multithreaded environments.

Concurrency Utilities: Java provides high-level concurrency utilities in the


java.util.concurrent package, including ExecutorService , ThreadPoolExecutor , and
ConcurrentHashMap , for easier and more efficient multithreaded programming.

Multi-Threading
Multi-threading is a programming concept that allows concurrent execution of
multiple threads within a single process. Threads are lightweight processes that
share the same memory space and resources of a process but can execute
independently. Multi-threading is commonly used in applications to achieve
parallelism, improve performance, and enhance responsiveness by executing
multiple tasks simultaneously.
Usage Example:

Advanced Java Programming 26


Let's consider a simple example of a Java application that downloads images from
the internet concurrently using multiple threads.

import java.io.*;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ImageDownloader {

public static void main(String[] args) {


String[] imageUrls = {"url1", "url2", "url3", "url4",
"url5"};
ExecutorService executor = Executors.newFixedThreadPo
ol(imageUrls.length);

for (String url : imageUrls) {


executor.execute(new ImageDownloadTask(url));
}

executor.shutdown();
}
}

class ImageDownloadTask implements Runnable {

private String imageUrl;

public ImageDownloadTask(String imageUrl) {


this.imageUrl = imageUrl;
}

@Override
public void run() {
try {
URL url = new URL(imageUrl);

Advanced Java Programming 27


InputStream inputStream = url.openStream();
OutputStream outputStream = new FileOutputStream
("image_" + imageUrl.hashCode() + ".jpg");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) !=
-1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Downloaded: " + imageUrl);
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

In this example:

We have a ImageDownloader class that represents the main program.

The ImageDownloader class creates a fixed-size thread pool using ExecutorService

to manage multiple threads.

We have an array of image URLs that we want to download concurrently.

For each image URL, we create a new ImageDownloadTask object and submit it to
the thread pool for execution.

The ImageDownloadTask class represents a task that downloads an image from a


given URL.

Each ImageDownloadTask is executed concurrently by a separate thread in the


thread pool.

Each thread reads the image data from the URL and writes it to a file on the
local file system.

Once all tasks are completed, we shut down the thread pool.

Advanced Java Programming 28


This example demonstrates how multi-threading can be used to download
multiple images concurrently, improving the overall performance of the image
downloading process.
Thread Lifecycle:

Applet Programming:
Applet Lifecycle: Understand the sequence of methods invoked during the
lifecycle of an applet, such as init() , start() , stop() , and destroy() , and their
respective purposes.

Advanced Java Programming 29


Applet Parameters: Applets can accept parameters from the HTML
embedding them, providing configuration options and customization for the
applet's behavior.

Applet Security: Due to security concerns, modern web browsers have


deprecated or restricted the use of Java applets. Consider alternative
technologies like JavaScript and HTML5 for web development.

Adding these additional points can enhance the understanding and depth of
knowledge on the respective topics.

Connecting to a Server
Connecting to a server in Java typically involves network communication, where a
client application communicates with a server over a network protocol such as
TCP/IP or UDP. Here's a basic outline of how to connect to a server in Java using
sockets, which is a low-level networking API:

Using Sockets for Client-Server Communication


1. Client Side:

import java.io.*;
import java.net.*;

Advanced Java Programming 30


public class Client {
public static void main(String[] args) {
try {
// Create a socket to connect to the server
Socket socket = new Socket("server_address", p
ort_number);

// Get the output stream from the socket


OutputStream outputStream = socket.getOutputSt
ream();

// Create a PrintWriter for writing to the out


put stream
PrintWriter out = new PrintWriter(outputStrea
m, true);

// Send data to the server


out.println("Hello, Server!");

// Close the socket


socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

2. Server Side:

import java.io.*;
import java.net.*;

public class Server {


public static void main(String[] args) {

Advanced Java Programming 31


try {
// Create a server socket bound to a specific
port
ServerSocket serverSocket = new ServerSocket(p
ort_number);

// Listen for incoming connections from client


s
Socket clientSocket = serverSocket.accept();

// Get the input stream from the client socket


InputStream inputStream = clientSocket.getInpu
tStream();

// Create a BufferedReader for reading from th


e input stream
BufferedReader in = new BufferedReader(new Inp
utStreamReader(inputStream));

// Read data from the client


String message = in.readLine();
System.out.println("Message from client: " + m
essage);

// Close the sockets


clientSocket.close();
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Explanation:

Advanced Java Programming 32


The client creates a Socket object, specifying the server's address and port
number.

It then gets the output stream from the socket and sends data to the server
using a PrintWriter .

The server creates a ServerSocket object bound to a specific port and listens
for incoming connections using serverSocket.accept() .

Upon accepting a connection, it gets the input stream from the client socket
and reads data from it using a BufferedReader .

Once communication is complete, both client and server close their respective
sockets.

Additional Considerations:
Handling Multiple Clients: For handling multiple clients, you would typically
create a new thread for each client connection in the server code.

Error Handling: Handle exceptions such as IOException appropriately, including


closing resources in a finally block.

Protocol Design: Design a protocol for communication between client and


server to ensure data integrity and synchronization.

This is a basic example of client-server communication using sockets in Java.


Depending on your specific requirements and use case, you may need to explore
more advanced networking concepts and libraries for implementing robust client-
server applications.

Implementing Servers
Implementing servers in Java involves creating applications that listen for
incoming connections from clients and handle those connections according to the
desired functionality. Here's a basic outline of how to implement a simple server in
Java using sockets:

Server Implementation Steps:


1. Create a ServerSocket:

Advanced Java Programming 33


Create a ServerSocket object bound to a specific port number.

The server socket listens for incoming client connections.

import java.io.*;
import java.net.*;

public class Server {


public static void main(String[] args) {
try {
// Create a ServerSocket bound to port 12345
ServerSocket serverSocket = new ServerSocket(1
2345);
System.out.println("Server started. Waiting fo
r clients...");

// Accept client connections


while (true) {
Socket clientSocket = serverSocket.accept
();
System.out.println("Client connected: " +
clientSocket);

// Handle client connection in a separate


thread
ClientHandler clientHandler = new ClientHa
ndler(clientSocket);
clientHandler.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

2. Handle Client Connections:

Advanced Java Programming 34


Create a separate thread or class to handle each client connection.

Perform necessary communication and processing with the client.

import java.io.*;
import java.net.*;

public class ClientHandler extends Thread {


private Socket clientSocket;

public ClientHandler(Socket clientSocket) {


this.clientSocket = clientSocket;
}

public void run() {


try {
// Get input and output streams from the clien
t socket
BufferedReader in = new BufferedReader(new Inp
utStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocke
t.getOutputStream(), true);

// Read data from the client


String message = in.readLine();
System.out.println("Message from client: " + m
essage);

// Send a response to the client


out.println("Server received your message: " +
message);

// Close the client socket


clientSocket.close();
} catch (IOException e) {
e.printStackTrace();

Advanced Java Programming 35


}
}
}

Explanation:
The server creates a ServerSocket object bound to a specific port number (e.g.,
12345).

It enters a loop to continuously listen for incoming client connections using


serverSocket.accept() .

Upon accepting a connection, it creates a new ClientHandler thread to handle


communication with the client.

The ClientHandler thread reads data from the client, processes it, and sends a
response back.

Each client connection is handled independently in its own thread, allowing the
server to handle multiple clients simultaneously.

Additional Considerations:
Thread Safety: Ensure thread safety when accessing shared resources or
performing concurrent operations.

Error Handling: Handle exceptions appropriately, including closing resources


in a finally block.

Scalability: Consider scalability requirements and design the server to handle


multiple concurrent clients efficiently.

Protocol Design: Define a protocol for communication between clients and


server to ensure interoperability and data integrity.

This is a basic example of implementing a server in Java using sockets.


Depending on your specific requirements, you may need to implement more
advanced server functionalities such as authentication, encryption, and support
for multiple protocols.

Making URL Connections

Advanced Java Programming 36


Making URL connections in Java allows you to communicate with web servers
over the HTTP protocol, enabling tasks such as fetching data from a URL,
submitting form data, or downloading files. Java provides the java.net.URL and
java.net.HttpURLConnection classes to facilitate URL connections. Here's a basic
outline of how to make URL connections in Java:

Making URL Connections:


1. Create a URL Object:

Instantiate a URL object representing the desired URL.

Use this object to establish a connection with the web server.

import java.io.*;
import java.net.*;

public class URLConnectionExample {


public static void main(String[] args) {
try {
// Create a URL object
URL url = new URL("<https://www.example.com
>");

// Open a connection to the URL


HttpURLConnection connection = (HttpURLConnect
ion) url.openConnection();

// Set request method (GET, POST, etc.)


connection.setRequestMethod("GET");

// Set additional request headers if needed


// connection.setRequestProperty("User-Agent",
"Mozilla/5.0");

// Read response code from the server


int responseCode = connection.getResponseCode

Advanced Java Programming 37


();
System.out.println("Response Code: " + respons
eCode);

// Read response data


BufferedReader in = new BufferedReader(new Inp
utStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

// Print response data


System.out.println("Response Data: " + respons
e.toString());

// Close the connection


connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}

2. Open a Connection:

Use the openConnection() method of the URL object to establish a connection


with the web server.

Cast the returned URLConnection object to HttpURLConnection for HTTP-


specific operations.

3. Configure the Request:

Set request method, headers, timeouts, and other properties as needed


using methods such as setRequestMethod() and setRequestProperty() .

Advanced Java Programming 38


4. Read Response:

Read the response code from the server using getResponseCode() .

Read response data from the input stream of the connection.

Process the response data as required.

5. Close the Connection:

Close the connection using the disconnect() method to release system


resources.

Additional Considerations:
Handle Errors: Handle exceptions appropriately, including connection
timeouts, invalid URLs, and network errors.

HTTPS Support: Use HttpsURLConnection for HTTPS connections and consider


certificate validation for secure connections.

Performance: Optimize connection handling and data processing for better


performance, especially in high-traffic scenarios.

Security: Sanitize user inputs and validate URL inputs to prevent security
vulnerabilities like injection attacks.

This example demonstrates the basic steps for making URL connections in Java.
Depending on your use case, you may need to customize the request headers,
handle redirects, or handle other aspects of HTTP communication.

Making URL Connections:


Handling Response Codes: Besides checking the response code for success
(e.g., 200 for OK), handle other common HTTP response codes (e.g., 404 for
Not Found, 500 for Internal Server Error) appropriately in your code.

Timeout Configuration: Set appropriate connection and read timeouts using


methods like setConnectTimeout() and setReadTimeout() to avoid waiting
indefinitely for a response.

Handling Redirects: If your URL connection may encounter redirects, consider


handling them programmatically by checking the response code and location
header, and following the redirect if necessary.

Advanced Java Programming 39


Streaming Large Responses: For large responses, consider streaming the
response data directly to disk or processing it in chunks to avoid excessive
memory consumption.

Implementing Servers:
Thread Pooling: Instead of creating a new thread for each incoming client
connection, consider using a thread pool to limit the number of concurrently
running threads and prevent resource exhaustion.

Asynchronous I/O: Explore Java's asynchronous I/O capabilities (e.g.,


java.nio ) for building scalable servers that can handle a large number of
concurrent connections efficiently.

Security Considerations: Implement security measures such as


authentication, authorization, and encryption to protect against unauthorized
access, data breaches, and other security threats.

Performance Tuning: Profile and optimize your server code for performance
by identifying bottlenecks, optimizing resource usage, and fine-tuning
configuration parameters such as thread pool size and socket buffer sizes.

Socket Programming in Java


Socket programming allows communication between two applications over the
network. In Java, you can use the java.net package to create sockets and
establish network connections.

Advanced Java Programming 40


Basic Concepts:
1. Client-Server Model:

In socket programming, communication typically follows the client-server


model, where one application (client) initiates a connection request to
another application (server) to exchange data.

2. Socket:

A socket is one endpoint of a two-way communication link between two


programs running on the network.

It encapsulates the IP address and port number to establish a connection


with another socket.

Sockets are classified into two types: client sockets and server sockets.

Advanced Java Programming 41


3. Server Socket:

A server socket waits for client requests to arrive.

Once a request arrives, it creates a new socket to handle the client's


communication.

Java Socket Classes:


1. Socket Class:

Represents a client-side socket that initiates a connection to a server.

Provides input and output streams for communicating with the server.

2. ServerSocket Class:

Represents a server-side socket that listens for incoming client


connections.

Accepts incoming client connections and creates a new socket for each
client.

Example 1: Simple Client-Server Communication

Server Code:

import java.io.*;
import java.net.*;

public class Server {


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(1234
5); // Create a server socket
System.out.println("Server started. Waiting for c
lients...");

Socket clientSocket = serverSocket.accept(); // A


ccept client connection
System.out.println("Client connected.");

Advanced Java Programming 42


BufferedReader in = new BufferedReader(new InputS
treamReader(clientSocket.getInputStream())); // Input stream
PrintWriter out = new PrintWriter(clientSocket.ge
tOutputStream(), true); // Output stream

String message = in.readLine(); // Read client me


ssage
System.out.println("Message from client: " + mess
age);

out.println("Hello, Client!"); // Send response t


o client

clientSocket.close(); // Close client socket


serverSocket.close(); // Close server socket
} catch (IOException e) {
e.printStackTrace();
}
}
}

Client Code:

import java.io.*;
import java.net.*;

public class Client {


public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 12345);
// Connect to server
System.out.println("Connected to server.");

PrintWriter out = new PrintWriter(socket.getOutpu

Advanced Java Programming 43


tStream(), true); // Output stream
BufferedReader in = new BufferedReader(new InputS
treamReader(socket.getInputStream())); // Input stream

out.println("Hello, Server!"); // Send message to


server

String response = in.readLine(); // Receive respo


nse from server
System.out.println("Response from server: " + res
ponse);

socket.close(); // Close socket


} catch (IOException e) {
e.printStackTrace();
}
}
}

Example 2: Multi-Threaded Server

import java.io.*;
import java.net.*;

public class MultiThreadedServer {


public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(1234
5);
System.out.println("Server started. Waiting for c
lients...");

while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + cli

Advanced Java Programming 44


entSocket);

ClientHandler clientHandler = new ClientHandl


er(clientSocket);
clientHandler.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

class ClientHandler extends Thread {


private Socket clientSocket;

public ClientHandler(Socket clientSocket) {


this.clientSocket = clientSocket;
}

public void run() {


try {
BufferedReader in = new BufferedReader(new InputS
treamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.ge
tOutputStream(), true);

String message = in.readLine();


System.out.println("Message from client: " + mess
age);

out.println("Hello, Client!");

clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}

Advanced Java Programming 45


}
}

Conclusion:
Socket programming in Java allows applications to communicate over the network
using sockets. By understanding the concepts of sockets, Socket and ServerSocket
classes, and their usage in Java, you can develop client-server applications for
various networking tasks. These examples provide a solid foundation for
understanding socket programming and can help you prepare for UG level
engineering exams.

UNIT-II
Preparing a class to be a Java Bean
Preparing a class to be a Java Bean involves adhering to a specific set of
conventions and requirements to ensure interoperability and compatibility with
various Java frameworks and tools. Here's a detailed explanation of how to
prepare a class to be a Java Bean:

What is a Java Bean?


A Java Bean is a reusable software component modeled after real-world objects,
encapsulating data and behavior within a self-contained unit. Java Beans adhere
to a specific set of conventions to facilitate their use in various Java development
environments.

Requirements for a Java Bean:


To prepare a class to be a Java Bean, it must adhere to the following conventions:

1. Public Default Constructor:

The class must have a public default constructor with no arguments.

This allows frameworks and tools to instantiate the bean using reflection.

2. Private Fields with Public Getter and Setter Methods:

Advanced Java Programming 46


Define private instance variables (fields) to encapsulate the state of the
bean.

Provide public getter methods (accessors) to retrieve the values of the


fields.

Provide public setter methods (mutators) to set the values of the fields.

Follow the naming convention for getter and setter methods: getFieldName()

and setFieldName() .

3. Serializable Interface (Optional):

Implement the java.io.Serializable interface if the bean needs to be


serialized.

Serialization allows the bean to be converted into a stream of bytes for


storage or transmission.

4. Consistency:

Maintain consistency in naming conventions, access modifiers, and coding


style.

Follow JavaBeans naming conventions for class names, field names, and
method names.

Example of a Java Bean Class:

import java.io.Serializable;

public class Person implements Serializable {


// Private fields
private String name;
private int age;

// Public default constructor


public Person() {
}

// Getter and setter methods for 'name' field

Advanced Java Programming 47


public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

// Getter and setter methods for 'age' field


public int getAge() {
return age;
}

public void setAge(int age) {


this.age = age;
}
}

Usage of Java Bean:

public class Main {


public static void main(String[] args) {
// Create a new instance of the Person bean
Person person = new Person();

// Set values using setter methods


person.setName("John Doe");
person.setAge(30);

// Get values using getter methods


System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}

Advanced Java Programming 48


Conclusion:
Preparing a class to be a Java Bean involves adhering to conventions such as
providing a default constructor, using getter and setter methods, and optionally
implementing the Serializable interface. By following these conventions, you
ensure that your Java Bean is compatible with various Java frameworks, tools,
and environments, facilitating interoperability and reuse.

Creating a Java Bean


Creating a Java Bean involves defining a class that adheres to specific
conventions, such as providing a default constructor, private fields with public
getter and setter methods, and optionally implementing the Serializable interface.
Let's create a simple Java Bean class step by step:

Step 1: Define the Class


Create a Java class representing the bean. The class should encapsulate the state
of the bean using private fields.

public class Person {


// Private fields
private String name;
private int age;

// Constructor
public Person() {
// Default constructor
}

// Getter and setter methods for 'name' field


public String getName() {
return name;
}

public void setName(String name) {


this.name = name;

Advanced Java Programming 49


}

// Getter and setter methods for 'age' field


public int getAge() {
return age;
}

public void setAge(int age) {


this.age = age;
}
}

Step 2: Implement Serializable Interface (Optional)


If the bean needs to be serialized (e.g., for storage or transmission), implement
the Serializable interface.

import java.io.Serializable;

public class Person implements Serializable {


// Class definition remains the same
}

Step 3: Usage of the Java Bean


You can now create instances of the Person bean, set its properties using setter
methods, and retrieve its properties using getter methods.

public class Main {


public static void main(String[] args) {
// Create a new instance of the Person bean
Person person = new Person();

// Set values using setter methods


person.setName("John Doe");
person.setAge(30);

Advanced Java Programming 50


// Get values using getter methods
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}

Conclusion:
By following these steps, you can create a Java Bean that encapsulates data and
behavior within a self-contained unit. Java Beans adhere to specific conventions
such as providing getter and setter methods, which facilitate interoperability and
compatibility with various Java frameworks and tools. Creating Java Beans allows
for reusable and modular components in Java applications.

Java Bean Properties


Java Bean properties refer to the attributes or fields of a Java Bean class that
encapsulate its state. These properties are typically accessed and manipulated
using getter and setter methods. Let's delve into Java Bean properties in more
detail:

Definition:
A Java Bean property is a named attribute that defines the state of a Java Bean.
Properties provide a way to access and modify the internal state of an object in a
controlled manner, while encapsulating the implementation details.

Characteristics of Java Bean Properties:


1. Private Fields: Properties are typically backed by private instance variables
(fields) within the bean class.

2. Getter Methods: Each property has a corresponding getter method that allows
access to its value. Getter methods are named according to the JavaBeans
naming convention, usually in the form getPropertyName() .

3. Setter Methods: Properties also have setter methods that allow modification
of their values. Setter methods follow the naming convention

Advanced Java Programming 51


setPropertyName(Type value) .

4. Data Encapsulation: Properties facilitate data encapsulation by controlling


access to the internal state of the bean. Access to properties is typically
provided through public getter and setter methods, which enforce validation,
access control, or other logic if necessary.

Example of Java Bean Properties:


Consider a Person bean with properties name and age :

public class Person {


// Private fields (properties)
private String name;
private int age;

// Constructor
public Person() {
// Default constructor
}

// Getter and setter methods for 'name' property


public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

// Getter and setter methods for 'age' property


public int getAge() {
return age;
}

public void setAge(int age) {


this.age = age;

Advanced Java Programming 52


}
}

Usage:

public class Main {


public static void main(String[] args) {
// Create a new instance of the Person bean
Person person = new Person();

// Set property values using setter methods


person.setName("John Doe");
person.setAge(30);

// Get property values using getter methods


System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
}
}

Benefits:
Encapsulation: Properties encapsulate the state of an object, hiding its
internal implementation details.

Access Control: Getter and setter methods provide controlled access to the
bean's state, enabling validation, security, and other logic.

Interoperability: Java Bean properties adhere to conventions that enable


interoperability with various Java frameworks, tools, and libraries.

By defining Java Bean properties and providing getter and setter methods, you
create reusable and modular components that facilitate the development of robust
and maintainable Java applications.

Types of beans

Advanced Java Programming 53


In Java programming, there are several types of beans, each serving a specific
purpose and adhering to particular conventions. Let's explore the common types
of beans:

1. Standard JavaBeans:
These are regular Java classes that adhere to the JavaBeans specification,
providing properties (with getter and setter methods), constructors, and optionally
implementing the Serializable interface. Standard JavaBeans are used in various
Java frameworks and tools for building reusable components.
Example:

public class Person {


private String name;
private int age;

// Constructor
public Person() {
// Default constructor
}

// Getter and setter methods for 'name' property


public String getName() {
return name;
}

public void setName(String name) {


this.name = name;
}

// Getter and setter methods for 'age' property


public int getAge() {
return age;
}

public void setAge(int age) {

Advanced Java Programming 54


this.age = age;
}
}

2. Enterprise JavaBeans (EJB):


EJB is a server-side component architecture for building scalable and distributed
enterprise applications. There are several types of EJBs, including session beans,
entity beans, and message-driven beans, each serving different purposes in
enterprise application development.
Example:

@Stateless
public class ShoppingCartBean implements ShoppingCart {
// Implementation of business logic
}

3. Managed Beans (JSF Managed Beans):


Managed Beans are JavaBeans components managed by a JavaServer Faces
(JSF) framework, used for building user interfaces in web applications. Managed
Beans are annotated with @ManagedBean and are typically scoped (e.g., request
scope, session scope) to manage their lifecycle.
Example:

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

@ManagedBean
@SessionScoped
public class UserBean {
private String username;
private String password;

Advanced Java Programming 55


// Getter and setter methods
}

4. Spring Beans:
Spring Beans are components managed by the Spring Framework's Inversion of
Control (IoC) container. These beans are configured and managed by the Spring
container, and they can be wired together to form the application's architecture.
Example:

@Component
public class UserService {
// Implementation of service methods
}

5. CDI Beans (Contexts and Dependency Injection):


CDI beans are managed by the Java EE Contexts and Dependency Injection
framework. CDI beans are annotated with @Named , @RequestScoped , @SessionScoped ,
etc., and they are used for dependency injection and managing application
components.
Example:

import javax.inject.Named;
import javax.enterprise.context.SessionScoped;

@Named
@SessionScoped
public class ShoppingCart {
// Implementation of shopping cart functionality
}

Conclusion:

Advanced Java Programming 56


These are some of the common types of beans in Java programming. Each type
serves a specific purpose and is used in different contexts, such as building
enterprise applications, web applications, or components managed by
frameworks like Spring or Java EE. Understanding these types of beans and their
usage is essential for Java developers to build robust and scalable applications.

Stateful Session bean


A Stateful Session Bean (SFSB) is a type of Enterprise JavaBean (EJB) used in
Java EE (Enterprise Edition) applications for maintaining conversational state
between multiple method invocations for a specific client. Unlike Stateless
Session Beans (SLSB), which are stateless and handle each request
independently, Stateful Session Beans maintain conversational state across
multiple method invocations, providing a way to manage stateful interactions with
clients.

Characteristics of Stateful Session Beans:


1. Stateful Nature:

SFSBs maintain conversational state between multiple method invocations


for a specific client.

The state stored in SFSBs persists across multiple client interactions until
the client explicitly terminates the session or the session times out.

2. Client Affinity:

Each client interacting with an SFSB gets its instance, ensuring that the
conversational state is isolated between clients.

SFSBs maintain a one-to-one relationship with clients, allowing each client


to have its stateful session.

3. Lifecycle Management:

SFSBs have a lifecycle that includes creation, method invocation, and


removal.

The container manages the lifecycle of SFSBs, creating instances upon


client request, associating them with the client's session, and removing
them when the session ends or times out.

Advanced Java Programming 57


4. State Serialization:

Since SFSBs can be passivated (stored to disk) during periods of inactivity


to free up resources, the state of an SFSB must be serializable.

Serializable state allows the container to store and retrieve the state of
SFSBs from secondary storage as needed.

5. Scoped Context:

SFSBs can be scoped to various contexts, such as session scope or


conversation scope, depending on the application's requirements.

Contextual scoping allows SFSBs to maintain state within a particular


scope, ensuring that stateful interactions are isolated and managed
appropriately.

Example of Stateful Session Bean:

import javax.ejb.Stateful;

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

public void addItem(String item) {


items.add(item);
}

public List<String> getItems() {


return items;
}

public void clear() {


items.clear();
}
}

Advanced Java Programming 58


In this example, ShoppingCartBean is a Stateful Session Bean representing a
shopping cart. It maintains the state of the shopping cart (list of items) across
multiple method invocations for a specific client session.

Conclusion:
Stateful Session Beans provide a mechanism for maintaining conversational state
between multiple method invocations for a specific client in Java EE applications.
They allow developers to build applications with stateful interactions, such as
shopping carts, wizards, or transactional workflows, by managing the state of
client sessions within the EJB container. Understanding the characteristics and
usage of Stateful Session Beans is crucial for developing stateful and
conversational Java EE applications.

Stateless Session bean


A Stateless Session Bean (SLSB) is a type of Enterprise JavaBean (EJB) used in
Java EE (Enterprise Edition) applications for executing business logic in a
stateless manner. Unlike Stateful Session Beans (SFSB), which maintain
conversational state between method invocations for a specific client, Stateless
Session Beans are stateless and do not maintain any conversational state between
method invocations. Each method invocation on an SLSB is independent of
previous invocations, making them suitable for handling stateless operations and
processing client requests efficiently.

Characteristics of Stateless Session Beans:


1. Statelessness:

SLSBs do not maintain conversational state between method invocations.


Each method invocation is independent of previous invocations, and the
bean instance does not retain any state between invocations.

This statelessness simplifies the management of bean instances, allowing


the container to pool and reuse instances to handle multiple client
requests concurrently.

2. Lightweight:

Advanced Java Programming 59


SLSBs are lightweight components designed for executing business logic
without the overhead of managing conversational state.

Stateless nature eliminates the need for passivation/activation cycles and


serialization of state, resulting in improved performance and scalability.

3. Concurrency:

SLSBs can handle multiple client requests concurrently using a pool of


bean instances managed by the EJB container.

The container dynamically assigns incoming requests to available bean


instances from the pool, allowing efficient utilization of system resources.

4. Transaction Management:

SLSBs support transactional behavior, allowing methods to participate in


transactions managed by the container.

Methods annotated with transactional attributes (e.g., @TransactionAttribute )


specify the transactional behavior, such as REQUIRED , REQUIRES_NEW , or NEVER .

5. Scoped Context:

SLSBs can be scoped to various contexts, such as application scope or


session scope, depending on the application's requirements.

Contextual scoping allows SLSBs to manage stateless operations within a


particular scope, ensuring that stateless interactions are isolated and
managed appropriately.

Example of Stateless Session Bean:

import javax.ejb.Stateless;

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

public int subtract(int a, int b) {

Advanced Java Programming 60


return a - b;
}
}

In this example, CalculatorBean is a Stateless Session Bean representing a


calculator service. It provides stateless methods for performing addition and
subtraction operations, where each method invocation is independent of previous
invocations.

Conclusion:
Stateless Session Beans are lightweight components used in Java EE applications
for executing stateless business logic efficiently. They do not maintain
conversational state between method invocations, allowing for scalable and
concurrent processing of client requests. Understanding the characteristics and
usage of Stateless Session Beans is crucial for developing efficient and scalable
Java EE applications.

Feature Stateful Session Bean Stateless Session Bean

Maintains conversational state Does not maintain conversational


State Management
between method invocations state between method invocations

Typically one instance per client Shared among clients, instances


Instance per Client
(session) pooled and reused

Higher resource consumption Lower resource consumption as no


Performance
due to maintaining state state is maintained

Less scalable due to session- More scalable due to shared


Scalability
specific instances instances and statelessness

Transaction Supports transaction


Supports transaction management
Management management

Example Use Shopping cart in an e- Calculating shipping cost in an e-


Cases commerce application commerce application

Lifecycle Can be passivated and No passivation or activation


Management activated to conserve resources needed

Use of Instance Often utilizes instance variables Typically avoids using instance
Variables to store state variables for state

Advanced Java Programming 61


Entity bean Servlet Overview and Architecture
Entity beans and Servlets are two distinct components in Java EE applications that
serve different purposes. Let's discuss each of them briefly:

Entity Beans:
Entity beans are Enterprise JavaBeans (EJBs) used to represent persistent data
entities in a Java EE application. They typically map to tables in a relational
database and provide a way to interact with the underlying data through an
object-oriented interface. Entity beans encapsulate the data and business logic
related to a specific entity, such as a customer, product, or order.

Overview:
Persistent Data Representation: Entity beans represent persistent data
entities, allowing developers to interact with database tables using object-
oriented programming constructs.

ORM Framework Integration: Entity beans are often used in conjunction with
Object-Relational Mapping (ORM) frameworks like JPA (Java Persistence API)
to simplify database interactions and mapping between Java objects and
database tables.

CRUD Operations: Entity beans support Create, Read, Update, and Delete
(CRUD) operations, enabling developers to manipulate persistent data entities
using standard Java methods.

Transaction Management: Entity beans can participate in transactions


managed by the EJB container, ensuring data integrity and consistency during
database operations.

Architecture:
Entity Bean Class: Represents a persistent data entity and typically
corresponds to a database table. It contains attributes representing table
columns and methods for accessing and manipulating entity data.

Entity Manager: Manages the lifecycle of entity beans, including creation,


retrieval, updating, and removal. The entity manager is responsible for
persisting entity state changes to the underlying database.

Advanced Java Programming 62


Persistence Context: Represents the runtime environment in which entity
beans interact with the database. It manages entity instances and tracks
changes made to entity state, ensuring consistency during transactions.

Database: The underlying relational database stores the persistent data


entities represented by entity beans. Entity beans and database tables are
typically mapped using ORM configurations or annotations.

Entity Beans were a part of the earlier versions of Enterprise JavaBeans (EJB)
specifications. They were designed to represent data entities, typically mapped to
database tables, and provided persistence services. However, Entity Beans have
been deprecated since EJB 3.0, and JPA (Java Persistence API) has become the
preferred approach for handling persistence in Java EE applications.
Despite being deprecated, I can still provide an example of how Entity Beans were
used in older versions of EJB. Let's create a simple example of an Entity Bean
representing a "User" entity:

import javax.ejb.*;
import java.io.Serializable;

@Entity
public class User implements Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

private String username;


private String email;

// Constructors, getters, and setters

public User() {
}

public User(String username, String email) {

Advanced Java Programming 63


this.username = username;
this.email = email;
}

// Getters and setters

public Long getId() {


return id;
}

public void setId(Long id) {


this.id = id;
}

public String getUsername() {


return username;
}

public void setUsername(String username) {


this.username = username;
}

public String getEmail() {


return email;
}

public void setEmail(String email) {


this.email = email;
}
}

In this example:

The User class is marked with the @Entity annotation, indicating that it is an
entity bean.

Advanced Java Programming 64


The id field is annotated with @Id and @GeneratedValue to specify it as the
primary key, with automatic generation strategy.

The username and email fields represent the attributes of the User entity.

Constructors, getters, and setters are provided for accessing and manipulating
the entity's attributes.

Please note that in modern Java EE applications, it's recommended to use JPA
entities along with other persistence technologies such as Hibernate for ORM
(Object-Relational Mapping). JPA provides a more flexible and powerful approach
to managing entities and persistence operations compared to the older Entity
Beans model.

Servlets:
Servlets are Java classes used to extend the functionality of web servers and
handle HTTP requests and responses. They provide a way to generate dynamic
web content, process form submissions, and interact with clients over the HTTP
protocol.

Overview:
HTTP Request Handling: Servlets receive HTTP requests from clients (e.g.,
web browsers) and generate dynamic content or perform processing based
on the request parameters.

Web Application Logic: Servlets encapsulate the application logic for web-
based interactions, such as user authentication, data validation, and business
process execution.

Server-Side Processing: Servlets execute on the server-side, allowing


developers to implement server-side logic to complement client-side
interactions implemented using HTML, CSS, and JavaScript.

Lifecycle Management: Servlets have a well-defined lifecycle, including


initialization, request processing, and destruction. They are managed by the
servlet container (e.g., Apache Tomcat) within the Java EE environment.

Architecture:

Advanced Java Programming 65


Servlet Class: Represents the main logic for processing HTTP requests and
generating responses. Servlet classes extend the javax.servlet.http.HttpServlet
class and override methods like doGet() and doPost() to handle specific types
of HTTP requests.

Servlet Container: Manages the lifecycle of servlets and provides the runtime
environment for servlet execution. The servlet container is responsible for
loading servlet classes, initializing servlet instances, and dispatching HTTP
requests to the appropriate servlets.

HTTP Request/Response: Servlets interact with clients using HTTP requests


and responses. They receive requests from clients, extract request
parameters, process the requests, and generate dynamic content or data to be
sent back to clients in the form of HTTP responses.

Integration:
Entity beans and Servlets are often used together in Java EE applications to
implement web-based data management systems. Servlets handle incoming
HTTP requests, perform data processing, and invoke business logic implemented
in entity beans to interact with persistent data entities. This integration allows
developers to build robust and scalable web applications that leverage the
capabilities of both technologies.

Conclusion:
Entity beans and Servlets are essential components in Java EE applications,
serving distinct roles in the development of web-based systems. While entity
beans represent persistent data entities and provide a high-level abstraction for
database interactions, Servlets handle HTTP requests, process client interactions,
and generate dynamic web content. Integrating entity beans with Servlets allows
developers to build powerful and efficient web applications that leverage the
strengths of both technologies.

Advanced Java Programming 66


Interface Servlet and the Servlet Life Cycle
1. Interface Servlet:
The Servlet interface in Java provides a standard protocol for building Java
servlets, which are server-side components that handle client requests and
generate responses. Servlets are the foundation of Java EE web applications and
can process various types of requests, such as HTTP requests.

Key Methods in the Servlet Interface:


1. init(ServletConfig config) :

This method is called by the servlet container to initialize the servlet.

It is called only once during the lifecycle of the servlet.

It is used to perform any one-time initialization tasks, such as loading


configuration parameters or initializing resources.

2. service(ServletRequest req, ServletResponse res) :

This method is called by the servlet container to handle client requests.

It is invoked for each request received by the servlet.

Developers override this method to implement the logic for processing


client requests and generating responses.

3. destroy() :

Advanced Java Programming 67


This method is called by the servlet container to indicate that the servlet
instance is being destroyed.

It is called only once during the lifecycle of the servlet.

It is used to release any resources held by the servlet, such as closing


database connections or releasing file handles.

2. Servlet Life Cycle:


The life cycle of a servlet refers to the sequence of stages that a servlet goes
through from its initialization to its destruction. The servlet container manages the
life cycle of servlet instances and ensures that each stage is executed in the
correct order.

Stages in the Servlet Life Cycle:


1. Instantiation:

When a servlet is first requested by a client, the servlet container creates


an instance of the servlet class using its default constructor.

This stage occurs only once during the lifecycle of the servlet.

2. Initialization:

After instantiating the servlet, the servlet container calls the


init(ServletConfig config) method to initialize the servlet.

This stage allows the servlet to perform any one-time initialization tasks,
such as loading configuration parameters or initializing resources.

3. Servicing Requests:

Once initialized, the servlet is ready to handle client requests.

The servlet container invokes the service(ServletRequest req, ServletResponse

res) method for each request received by the servlet.

Inside the service() method, the servlet processes the client request and
generates an appropriate response.

4. Destruction:

Advanced Java Programming 68


When the servlet container decides to remove the servlet instance (e.g.,
due to application shutdown or servlet reloading), it calls the destroy()
method.

The destroy() method allows the servlet to release any resources held
during its lifetime, such as closing database connections or releasing file
handles.

Lifecycle Events:
Servlet containers may provide mechanisms for registering listeners to receive
notifications about lifecycle events of servlets.

Servlet context listeners ( ServletContextListener ) and servlet context attribute


listeners ( ServletContextAttributeListener ) can be used to perform tasks during
servlet initialization, destruction, and attribute changes.

Example
First, let's create a servlet by implementing the javax.servlet.Servlet interface. We'll
override the init() , service() , and destroy() methods, which represent the servlet
lifecycle events.

import javax.servlet.*;
import java.io.*;

public class HelloWorldServlet implements Servlet {

// Servlet initialization
public void init(ServletConfig config) throws ServletExce
ption {
// Initialization code here (optional)
}

// Service method to handle HTTP requests


public void service(ServletRequest request, ServletRespon
se response)
throws ServletException, IOException {
// Set the content type of the response

Advanced Java Programming 69


response.setContentType("text/html");

// Get a PrintWriter to send HTML response


PrintWriter out = response.getWriter();

// Write HTML response


out.println("<html>");
out.println("<head><title>Hello, World!</title></head
>");
out.println("<body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body>");
out.println("</html>");
}

// Servlet cleanup
public void destroy() {
// Cleanup code here (optional)
}

// Get servlet information


public ServletConfig getServletConfig() {
return null; // We won't use this in this example
}

// Get servlet information


public String getServletInfo() {
return null; // We won't use this in this example
}
}

This servlet will respond to HTTP requests with a simple "Hello, World!" message.
Now, to deploy this servlet, you typically need to configure it in a web.xml file in
your web application. Here's a basic web.xml file that maps URL patterns to
servlets:

Advanced Java Programming 70


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="<http://xmlns.jcp.org/xml/ns/javaee>"
xmlns:xsi="<http://www.w3.org/2001/XMLSchema-instanc
e>"
xsi:schemaLocation="<http://xmlns.jcp.org/xml/ns/jav
aee> <http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd>"
version="4.0">

<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>

</web-app>

In this web.xml , we're mapping the servlet to the URL pattern /hello , so any
requests to http://localhost:8080/yourwebapp/hello will be handled by our
HelloWorldServlet .
That's it! With these files in place, you can deploy your servlet to a servlet
container like Apache Tomcat and access it through a web browser. When you
access http://localhost:8080/yourwebapp/hello , you should see the "Hello, World!"
message rendered in your browser.

Conclusion:
The Servlet interface defines the standard protocol for building Java servlets,
which are server-side components used in Java EE web applications.
Understanding the servlet life cycle is crucial for developing servlets that perform
initialization, request processing, and resource cleanup tasks efficiently. By

Advanced Java Programming 71


implementing the Servlet interface and managing the servlet life cycle properly,
developers can build robust and scalable web applications in Java.

Handling
Handling HTTP GET Requests:
HTTP GET requests are commonly used for retrieving data from a server. In the
context of servlets, handling HTTP GET requests typically involves extracting
information from the request (such as query parameters or path variables),
processing the request, and generating an appropriate response.

Steps for Handling HTTP GET Requests in a Servlet:


1. Override the doGet() Method:

In the servlet class, override the doGet() method to handle HTTP GET
requests.

The doGet() method receives the request object ( HttpServletRequest ) and


response object ( HttpServletResponse ) as parameters.

2. Process the Request:

Extract information from the request, such as query parameters, using


methods provided by the HttpServletRequest object ( getParameter() ,
getParameterValues() , etc.).

Perform any necessary business logic or data processing based on the


request parameters.

3. Generate the Response:

Use the response object ( HttpServletResponse ) to set the response content


type, headers, and body.

Write the response content, such as HTML, JSON, or XML, to the response
output stream ( PrintWriter or OutputStream ).

Handling HTTP POST Requests:


HTTP POST requests are commonly used for submitting data to a server. In
servlets, handling HTTP POST requests involves receiving data sent in the request

Advanced Java Programming 72


body, processing the data, and generating an appropriate response.

Steps for Handling HTTP POST Requests in a Servlet:


1. Override the doPost() Method:

In the servlet class, override the doPost() method to handle HTTP POST
requests.

The doPost() method receives the request object ( HttpServletRequest ) and


response object ( HttpServletResponse ) as parameters.

2. Process the Request:

Extract data from the request body, such as form parameters or JSON
payloads, using methods provided by the HttpServletRequest object
( getReader() or getInputStream() ).

Perform any necessary business logic or data processing based on the


received data.

3. Generate the Response:

Use the response object ( HttpServletResponse ) to set the response content


type, headers, and body.

Write the response content, such as HTML, JSON, or XML, to the response
output stream ( PrintWriter or OutputStream ).

example:
Certainly! Let's expand the previous example to handle both HTTP GET and POST
requests. We'll modify the service() method to differentiate between GET and
POST requests and respond accordingly.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HelloWorldServlet extends HttpServlet {

// Service method to handle HTTP requests

Advanced Java Programming 73


protected void service(HttpServletRequest request, HttpSe
rvletResponse response)
throws ServletException, IOException {
// Set the content type of the response
response.setContentType("text/html");

// Get a PrintWriter to send HTML response


PrintWriter out = response.getWriter();

// Determine the HTTP method (GET or POST)


String method = request.getMethod();

// Handle GET requests


if (method.equals("GET")) {
// Write HTML response for GET request
out.println("<html>");
out.println("<head><title>Hello, World!</title></
head>");
out.println("<body>");
out.println("<h1>Hello, World!</h1>");
out.println("</body>");
out.println("</html>");
}
// Handle POST requests
else if (method.equals("POST")) {
// Read form data from the request
String name = request.getParameter("name");

// Write HTML response for POST request


out.println("<html>");
out.println("<head><title>Hello, " + name + "!</t
itle></head>");
out.println("<body>");
out.println("<h1>Hello, " + name + "!</h1>");
out.println("</body>");
out.println("</html>");

Advanced Java Programming 74


}
}
}

In this updated example, we've extended HttpServlet instead of implementing the


Servlet interface directly. This allows us to override the doGet() and doPost()

methods to handle GET and POST requests respectively. However, in the interest
of simplicity, we've overridden the service() method instead to handle both GET
and POST requests.
Now, let's create a simple HTML form to send POST requests to our servlet:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HelloWorldServlet POST Form</title>
</head>
<body>
<form action="/yourwebapp/hello" method="post">
Enter your name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
</body>
</html>

When a user submits this form, a POST request will be sent to /yourwebapp/hello

with the name parameter. The servlet will then read this parameter and respond
with a personalized greeting.
With these changes, your servlet now handles both HTTP GET and POST
requests.

Conclusion:
Handling HTTP requests (both GET and POST) in servlets involves extracting data
from the request, processing it, and generating an appropriate response. By
overriding the doGet() and doPost() methods in a servlet class, developers can

Advanced Java Programming 75


implement custom request-handling logic to meet the requirements of their web
applications. Understanding how to handle HTTP requests effectively is essential
for building robust and interactive web applications using servlet technology.

Session Tracking
Session tracking is a mechanism used in web development to maintain the state of
user interactions across multiple requests within a session. Sessions allow web
applications to associate data with a specific user's browsing session, enabling
features like user authentication, shopping carts, and personalized experiences. In
Java web applications, session tracking is commonly implemented using
mechanisms such as cookies, URL rewriting, and HttpSession objects. Let's
explore each of these methods:

Advanced Java Programming 76


1. Cookies:
Cookies are small pieces of data sent by a web server to a web browser and
stored locally on the user's device. They are commonly used for session tracking
in web applications.

How it works: When a user visits a website, the server sends a cookie
containing a unique session identifier. The browser stores this cookie locally
and includes it in subsequent requests to the same website. The server uses
the session identifier to retrieve session-specific data associated with the
user.

Advanced Java Programming 77


Implementation in Java Servlets: In servlets, cookies for session tracking can
be set and retrieved using the HttpServletResponse and HttpServletRequest
objects. For example, to set a session cookie:

Cookie sessionCookie = new Cookie("sessionId", "uniqueSess


ionId");
response.addCookie(sessionCookie);

To retrieve a session cookie:

Cookie[] cookies = request.getCookies();


if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("sessionId")) {
String sessionId = cookie.getValue();
// Use sessionId for session tracking
break;
}
}
}

2. URL Rewriting:
URL rewriting involves appending session identifiers to URLs within a web
application. This allows the server to associate requests with specific sessions.

How it works: When generating hyperlinks or redirects in a web application,


the server appends a session identifier to the URL. When the client sends a
request with the modified URL, the server extracts the session identifier and
associates the request with the corresponding session.

Implementation in Java Servlets: Servlets can use HttpServletResponse's


encodeURL() method to append session identifiers to URLs. For example:

String urlWithSessionId = response.encodeURL("example.js


p");

Advanced Java Programming 78


3. HttpSession Object:
The HttpSession object provides a server-side mechanism for tracking sessions in
Java web applications. It allows developers to store and retrieve session-specific
data.

How it works: When a user accesses a web application, the server creates an
HttpSession object to represent the session. The server associates a unique
session identifier with the HttpSession object, which is then used to retrieve
the session data for subsequent requests.

Implementation in Java Servlets: HttpSession objects can be accessed using


the HttpServletRequest object. For example, to store data in a session:

HttpSession session = request.getSession();


session.setAttribute("username", "JohnDoe");

To retrieve data from a session:

HttpSession session = request.getSession();


String username = (String) session.getAttribute("usernam
e");

Advanced Java Programming 79


Example:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class SessionTrackingServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServ


letResponse response)
throws ServletException, IOException {
// Get the current session or create a new one if it
doesn't exist
HttpSession session = request.getSession();

// Get the session ID


String sessionId = session.getId();

// Get the value of the "visitCount" attribute from t


he session
Integer visitCount = (Integer) session.getAttribute
("visitCount");

Advanced Java Programming 80


// If visitCount is null, it means this is the first
visit
if (visitCount == null) {
visitCount = 1;
session.setAttribute("visitCount", visitCount);
response.getWriter().println("Welcome! This is yo
ur first visit.");
} else {
visitCount++;
session.setAttribute("visitCount", visitCount);
response.getWriter().println("Welcome back! You h
ave visited " + visitCount + " times.");
}

// Set a cookie to store the session ID


Cookie cookie = new Cookie("sessionId", sessionId);
response.addCookie(cookie);

// Display session ID in the response


response.getWriter().println("Your session ID: " + se
ssionId);
}
}

In this example:

We use HttpServletRequest.getSession() to obtain the current session or create a


new one if it doesn't exist.

We retrieve the session ID using HttpSession.getId() .

We retrieve the "visitCount" attribute from the session to track how many
times the user has visited the page.

If the "visitCount" attribute is null, it means it's the user's first visit, so we set it
to 1 and display a welcome message.

Advanced Java Programming 81


If the "visitCount" attribute is not null, we increment it and display a welcome
back message.

We use HttpServletResponse.addCookie() to set a cookie named "sessionId" with


the value of the session ID.

Finally, we display the session ID in the response.

You can deploy this servlet in your servlet container (e.g., Apache Tomcat) and
access it through a web browser. Each time you access the servlet, it will display a
message indicating whether it's your first visit or a return visit, along with the
number of times you've visited the page. Additionally, it will display your session
ID and set a cookie to store it.
Conclusion:
Session tracking is essential for maintaining user state and enabling personalized
interactions in web applications. In Java web development, session tracking can
be achieved using mechanisms such as cookies, URL rewriting, and HttpSession
objects. Understanding how to implement session tracking effectively is crucial for
building dynamic and interactive web applications.

Cookies
Cookies are small pieces of data stored by the web browser on the user's device.
They are sent back and forth between the client (browser) and the server with
each HTTP request and response. Cookies are commonly used for various
purposes in web development, including session management, personalization,
tracking user behavior, and storing user preferences.
Here are some key aspects and types of cookies:

1. Types of Cookies:
a. Session Cookies:

Session cookies are temporary cookies that are stored in the browser's
memory only during a user's session.

They are deleted when the user closes the browser or after a certain period of
inactivity.

Advanced Java Programming 82


Used for session management, such as maintaining user authentication or
storing temporary session data.

b. Persistent Cookies:

Persistent cookies are stored on the user's device even after the browser is
closed.

They have an expiration date/time set by the server, and they remain valid until
that date/time or until manually deleted by the user.

Often used for long-term tracking, remembering user preferences, or


personalization.

c. Secure Cookies:

Secure cookies are transmitted over HTTPS connections only, ensuring that
they are encrypted and protected from interception by unauthorized parties.

Used for sensitive data, such as authentication tokens or session identifiers.

d. HttpOnly Cookies:

HttpOnly cookies cannot be accessed via client-side scripts (e.g., JavaScript).

They can only be transmitted over HTTP or HTTPS protocols and are
inaccessible to JavaScript, providing protection against cross-site scripting
(XSS) attacks.

e. SameSite Cookies:

SameSite cookies restrict the browser from sending cookies along with cross-
site requests.

They can be set to "Strict" (cookies are not sent with cross-origin requests) or
"Lax" (cookies are sent with top-level navigations and same-site requests).

2. Example Usage:
a. Session Management:

Storing session IDs in cookies to maintain user authentication across multiple


requests.

Advanced Java Programming 83


Tracking user sessions to customize user experiences or manage shopping
carts in e-commerce websites.

b. Personalization:

Remembering user preferences, such as language settings or website theme


choices.

Providing personalized content or recommendations based on past user


interactions.

c. Tracking and Analytics:

Analyzing user behavior, such as page views, clicks, and interactions, to


improve website usability and marketing strategies.

Tracking advertising campaigns or affiliate referrals by storing unique


identifiers in cookies.

d. Compliance and Consent:

Storing consent preferences for cookie usage in compliance with data


protection regulations, such as GDPR or CCPA.

Displaying cookie banners or pop-ups to inform users about the use of


cookies and obtain their consent.

3. Special Considerations:

Cookie Security: Always be mindful of security risks associated with cookies,


such as session hijacking, cross-site scripting (XSS), and cross-site request
forgery (CSRF). Use secure and HttpOnly flags when appropriate.

Privacy Concerns: Respect user privacy by providing transparency about


cookie usage and giving users control over their data through clear privacy
policies and cookie consent mechanisms.

Browser Compatibility: Be aware of browser limitations and differences in


cookie handling, such as maximum cookie size, domain restrictions, and
support for SameSite attributes.

In summary, cookies are versatile tools in web development for managing


sessions, personalizing user experiences, tracking user behavior, and ensuring
compliance with privacy regulations. However, it's essential to use them

Advanced Java Programming 84


responsibly, prioritize user privacy and security, and comply with relevant laws
and regulations.

Mid Sem Topics


JMS/ Queue
JMS (Java Message Service) and queues play crucial roles in messaging systems,
facilitating asynchronous communication between distributed applications. Here's
an overview of JMS and queues:
1. Java Message Service (JMS):
Java Message Service (JMS) is a Java API that provides a standard way for Java
applications to create, send, receive, and process messages asynchronously. It
abstracts away the complexities of communication protocols and allows
applications to interact with messaging systems in a platform-independent
manner.
Key Concepts of JMS:

Messages: JMS defines various types of messages, such as text messages,


object messages, and bytes messages, which encapsulate data to be sent or
received.

Producers: Producers are components that create and send messages to


destinations within a messaging system.

Consumers: Consumers are components that receive and process messages


from destinations within a messaging system.

Destinations: Destinations represent message queues or topics where


messages are stored until they are consumed by consumers.

Connection Factories: Connection factories are objects used to create


connections to JMS providers.

Sessions: Sessions provide a transactional context for producing and


consuming messages, allowing multiple operations to be grouped together as
a single unit of work.

Advanced Java Programming 85


2. Message Queues:
A message queue is a fundamental component of messaging systems that
provides a mechanism for storing and delivering messages between producers
and consumers. Messages sent by producers are stored in the queue until they
are consumed by consumers.
Key Characteristics of Message Queues:

Asynchronous Communication: Message queues enable asynchronous


communication between distributed components, allowing producers and
consumers to operate independently of each other.

Reliability: Message queues ensure reliable message delivery by persisting


messages until they are successfully consumed by consumers.

Load Balancing: Message queues can distribute messages evenly across


multiple consumers to achieve load balancing and scalability.

Guaranteed Delivery: Message queues provide guaranteed delivery


semantics, ensuring that messages are not lost even in the event of system
failures.

Decoupling: Message queues decouple producers and consumers, allowing


them to evolve independently without affecting each other's functionality.

Example Use Cases of Message Queues:

Asynchronous Communication: Sending notifications, event-driven


architectures, and decoupling of microservices.

Job Queues: Managing background tasks, processing batch jobs, and


distributing workloads across multiple workers.

Integration: Integrating heterogeneous systems, communicating between


applications, and enabling interoperability.

Popular Message Queue Implementations:

Apache ActiveMQ

RabbitMQ

Apache Kafka

Advanced Java Programming 86


Amazon Simple Queue Service (SQS)

IBM MQ

Conclusion:
JMS and message queues are essential components of modern distributed
systems, providing reliable, asynchronous communication between distributed
components. By leveraging JMS APIs and message queue implementations,
developers can build scalable, decoupled, and resilient applications capable of
handling complex messaging requirements.

Define introspection and explain different ways of


implementing introspection for a bean class.
Definition of Introspection:
Introspection is a mechanism in programming languages, particularly object-
oriented languages like Java, that allows the examination and analysis of an
object's properties, methods, and metadata at runtime. It enables programs to
inspect and manipulate the structure and behavior of objects dynamically, without
prior knowledge of their implementation details.
Ways of Implementing Introspection for a Bean Class:
In Java, introspection is commonly used with JavaBeans, which are classes that
adhere to specific conventions for property access and manipulation. Here are
different ways of implementing introspection for a JavaBean class:

1. Java Reflection API:

Java Reflection API allows you to inspect and manipulate the fields,
methods, and constructors of a class at runtime.

You can use reflection to retrieve information about the properties (fields),
methods, and annotations of a JavaBean class.

Example:

Class<?> beanClass = MyBean.class;


Field[] fields = beanClass.getDeclaredFields();

Advanced Java Programming 87


Method[] methods = beanClass.getDeclaredMethods();
// Perform introspection using fields and methods

2. JavaBeans Introspector:

JavaBeans Introspector is a utility class provided by Java that simplifies


the introspection process for JavaBean classes.

It allows you to retrieve information about the properties, methods, and


events of a JavaBean class.

Example:

BeanInfo beanInfo = Introspector.getBeanInfo(MyBean.cla


ss);
PropertyDescriptor[] propertyDescriptors = beanInfo.get
PropertyDescriptors();
// Perform introspection using property descriptors

3. Apache Commons BeanUtils:

Apache Commons BeanUtils is a library that provides utility methods for


manipulating JavaBean properties using reflection.

It offers convenient methods for getting and setting property values,


copying properties between beans, and accessing nested properties.

Example:

PropertyUtils.getProperty(bean, "propertyName");
PropertyUtils.setProperty(bean, "propertyName", value);
// Perform introspection using BeanUtils methods

4. Spring BeanWrapper:

Spring Framework provides the BeanWrapper interface and its


implementations, which allow you to introspect and manipulate JavaBean
properties programmatically.

Advanced Java Programming 88


BeanWrapper provides methods for getting and setting property values,
checking property types, and accessing nested properties.

Example:

BeanWrapper wrapper = new BeanWrapperImpl(myBean);


Object propertyValue = wrapper.getPropertyValue("proper
tyName");
wrapper.setPropertyValue("propertyName", newValue);
// Perform introspection using BeanWrapper

Each of these approaches offers different levels of abstraction and convenience


for performing introspection on JavaBean classes. The choice of method depends
on the specific requirements and preferences of the application.

Persistence
Persistence refers to the ability of data to outlive the execution of a program. In
software engineering, persistence typically involves storing and retrieving data
from a durable storage medium, such as a database, file system, or cloud storage
service. The goal of persistence is to maintain the state of an application's data
across different sessions or instances of the program.
Key Concepts in Persistence:

1. Data Storage: Persistence involves storing data in a structured format that can
be efficiently accessed and manipulated. This may involve relational
databases, NoSQL databases, flat files, or other storage mechanisms.

2. CRUD Operations: Persistence often revolves around CRUD operations


(Create, Read, Update, Delete) that allow applications to create, retrieve,
update, and delete data in the underlying storage system.

3. Object-Relational Mapping (ORM): ORM frameworks like Hibernate in Java or


Entity Framework in .NET provide abstraction layers that map database entities
to object-oriented programming constructs, enabling developers to work with
objects rather than raw SQL queries.

4. Transactions: Persistence mechanisms often support transactions, which


group multiple operations into atomic units of work. Transactions ensure data

Advanced Java Programming 89


consistency and integrity by either committing all operations or rolling back
changes if an error occurs.

5. Query Languages: Persistence mechanisms typically provide query


languages for retrieving data from the storage system. Examples include SQL
(Structured Query Language) for relational databases and MongoDB Query
Language for MongoDB.

6. Indexing and Optimization: To improve data retrieval performance,


persistence mechanisms may employ indexing techniques and optimization
strategies such as query optimization, caching, and denormalization.

Persistence in Modern Software Development:

1. Relational Databases: Relational databases like MySQL, PostgreSQL, Oracle,


and SQL Server are widely used for persisting structured data in applications.
They offer robust transaction support, ACID properties, and powerful querying
capabilities.

2. NoSQL Databases: NoSQL databases such as MongoDB, Cassandra, Redis,


and Amazon DynamoDB provide alternatives to relational databases for
handling unstructured or semi-structured data. They offer scalability,
flexibility, and high availability for modern web-scale applications.

3. Object Storage: Object storage services like Amazon S3, Google Cloud
Storage, and Azure Blob Storage are commonly used for persisting large
volumes of unstructured data, such as images, videos, and documents, in a
distributed manner.

4. ORM Frameworks: ORM frameworks like Hibernate (Java), Entity Framework


(C#), Django ORM (Python), and SQLAlchemy (Python) abstract away the
complexities of database interaction, allowing developers to work with objects
and entities directly.

5. File Systems: For simple data storage needs, file systems provide a
straightforward approach to persistence. Applications can read from and write
to files on disk using file I/O operations.

6. Cloud Storage: Cloud-based persistence solutions offer scalability, reliability,


and accessibility for modern cloud-native applications. They provide APIs for
storing and retrieving data from remote servers over the internet.

Advanced Java Programming 90


Conclusion:
Persistence is a fundamental concept in software engineering that enables
applications to store and retrieve data across different sessions or instances of
the program. By leveraging persistence mechanisms such as relational databases,
NoSQL databases, ORM frameworks, and cloud storage services, developers can
build robust, scalable, and maintainable software solutions to meet diverse
application requirements.

State and Explain EJB container services


Enterprise JavaBeans (EJB) containers provide a runtime environment for
executing EJB components within Java EE applications. EJB containers offer a
range of services and functionalities to manage the lifecycle, transactions,
security, concurrency, and resource management of EJB components. Here are
the key EJB container services:

1. Lifecycle Management:

EJB containers manage the lifecycle of EJB components, including


instantiation, initialization, invocation, passivation, and removal.

They create instances of EJB components as needed, pool and reuse


instances to improve performance, and destroy instances when they are
no longer in use.

2. Transaction Management:

EJB containers provide support for declarative transaction management,


allowing developers to specify transactional behavior using annotations or
deployment descriptors.

They manage the coordination of distributed transactions across multiple


EJB components and resource managers, ensuring ACID properties
(Atomicity, Consistency, Isolation, Durability) are maintained.

3. Security Services:

EJB containers enforce security policies and access controls to protect


EJB components from unauthorized access and ensure data integrity and
confidentiality.

Advanced Java Programming 91


They support role-based access control (RBAC), authentication,
authorization, and encryption of communication between clients and EJB
components.

4. Concurrency Management:

EJB containers manage concurrent access to EJB components by


controlling thread synchronization, concurrency policies, and instance
pooling.

They ensure thread safety and prevent race conditions by serializing


access to EJB components, managing locks, and coordinating concurrent
transactions.

5. Resource Management:

EJB containers handle the management of external resources such as


database connections, JMS (Java Message Service) connections, and
JNDI (Java Naming and Directory Interface) resources.

They pool and manage resource connections to optimize resource


utilization, improve performance, and prevent resource exhaustion.

6. Remote Method Invocation (RMI):

EJB containers provide support for remote method invocation, allowing


clients to invoke methods on EJB components located on remote servers.

They handle the marshalling and unmarshalling of method parameters and


return values, as well as the communication between client and server
over the network.

7. Dependency Injection (DI):

EJB containers support dependency injection, a design pattern where


objects are provided with their dependencies rather than creating them
internally.

They inject resources, such as data sources, JMS queues, and other EJB
components, into EJB instances at runtime, improving modularity and
testability.

8. Monitoring and Management:

Advanced Java Programming 92


EJB containers provide monitoring and management capabilities to
monitor the performance, health, and usage of EJB components.

They expose management interfaces and APIs for monitoring EJB


container metrics, logging, and debugging, enabling administrators to
diagnose and troubleshoot issues.

Overall, EJB containers offer a comprehensive set of services and functionalities


to simplify the development, deployment, and management of enterprise
applications, allowing developers to focus on business logic while offloading
infrastructure concerns to the container runtime.

Applet vs Application
Feature Java Applet Java Application

Execution Executed standalone on the client


Embedded within a web browser
Context machine

Loaded and executed from a web


Deployment Installed and executed locally
server

Limited interaction within browser


User Interaction Full-fledged GUI interaction
window

Restricted by browser sandbox, Has access to system resources


Security
limited privileges based on permissions

Can make network requests to Can make network requests to


Network Access
the server external services

Controlled by the web browser


Lifespan Runs until terminated by the user
session

Limited support for GUI Full support for Swing, JavaFX, etc.
GUI Components
components components

Accessible through a URL in a


Accessibility Accessed directly from the desktop
web page

Deployment Embedded as <applet> tag in Distributed as JAR files or


Model HTML pages executable binaries

Deprecated due to security and Widely used for desktop and


Usability
compatibility issues enterprise applications

Note:

Advanced Java Programming 93


Applets were once popular for adding dynamic content to web pages but have
become obsolete due to security vulnerabilities and lack of support in modern
browsers. It's recommended to use other technologies like JavaScript and
HTML5 for web development.

Java applications are standalone programs that run independently on the


client's machine and have full access to system resources. They are
commonly used for desktop applications, enterprise software, and backend
services.

While both applets and applications are written in Java, they serve different
purposes and have different deployment models and execution contexts.

Unit - 3
JavaServer Pages (JSP)
1. Introduction to JSP

Definition: JSP is a server-side technology that helps in creating dynamic,


platform-independent web applications. It allows the embedding of Java code
in HTML pages.

Purpose: The main purpose of JSP is to simplify the process of creating


dynamic web content.

2. Lifecycle of JSP
The lifecycle of a JSP page consists of several phases:

Translation: The JSP page is translated into a servlet by the JSP engine.

Compilation: The translated servlet is compiled into a class file.

Loading: The class file is loaded into the web server's memory.

Instantiation: An instance of the servlet is created.

Initialization: The jspInit() method is called.

Request Processing: The service() method is called to handle client requests.

Advanced Java Programming 94


Destruction: The jspDestroy() method is called before the instance is
destroyed.

Analogy: Think of a JSP page as a blueprint (HTML and Java code), which is first
translated into a building plan (servlet), then constructed (compiled), and finally
used by people (requests processed).
3. JSP Architecture
JSP architecture follows a Model-View-Controller (MVC) pattern:

Model: Represents the application's data and business logic. Typically


implemented using JavaBeans or other Java classes.

View: The JSP pages that define the presentation layer.

Controller: Handles client requests and determines the appropriate view to


display. Often implemented using servlets.

Analogy: Imagine an online store where the products (Model) are managed in a
database, the storefront (View) is the JSP page the customer sees, and the store
manager (Controller) decides what products to show based on customer input.
4. JSP Elements

Directives: Instructions for the JSP engine. Types include:

Page Directive: Defines page-dependent attributes like scripting language,


error pages, etc.

<%@ page language="java" contentType="text/html" %>

Include Directive: Includes a file during the translation phase.

<%@ include file="header.jsp" %>

Taglib Directive: Declares a tag library containing custom tags.

<%@ taglib uri="<http://java.sun.com/jsp/jstl/core>" pr


efix="c" %>

Scriptlets: Java code embedded in JSP.

Advanced Java Programming 95


<% int count = 0; %>

Expressions: Output Java values to the client.

<%= new java.util.Date() %>

Declarations: Declare variables and methods.

<%! int count = 0; %>

Actions: XML-like tags that invoke built-in web server functionalities.

<jsp:useBean id="user" class="com.example.User" />

5. JSP Implicit Objects


JSP provides several implicit objects that are automatically available:

request: Represents the HttpServletRequest object.

response: Represents the HttpServletResponse object.

out: Used to send content to the client.

session: Represents the HttpSession object.

application: Represents the ServletContext.

config: Represents the ServletConfig.

pageContext: Provides access to all the namespaces associated with a JSP


page.

page: Refers to the instance of the JSP page's servlet.

exception: Used in error pages to access the exception object.

Analogy: These objects are like default tools in a toolkit, always available for use
in any project (JSP page).
6. JSP Standard Tag Library (JSTL)

Advanced Java Programming 96


JSTL is a collection of useful tags that encapsulate core functionality common to
many JSP applications:

Core Tags: General-purpose tags like loops and conditionals.

<c:forEach var="item" items="${items}">


${item}
</c:forEach>

Formatting Tags: For formatting numbers, dates, etc.

<fmt:formatNumber value="${price}" type="currency" />

SQL Tags: For interacting with databases.

<sql:query var="result" dataSource="${dataSource}">


SELECT * FROM users
</sql:query>

XML Tags: For processing XML data.

<x:parse var="doc" xml="${xmlString}" />

Functions Tags: Common functions like string manipulation.

<c:out value="${fn:toUpperCase(name)}" />

7. Example of a JSP Page


Here is a simple example of a JSP page displaying user information:

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


8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>

Advanced Java Programming 97


<title>User Information</title>
</head>
<body>
<h1>User Information</h1>
<p>Name: <%= request.getParameter("name") %></p>
<p>Email: <%= request.getParameter("email") %></p>
</body>
</html>

In this example:

The page directive specifies the language and content type.

Expressions ( <%= ... %> ) are used to insert dynamic content from the request
object.

8. Advantages of JSP

Separation of Concerns: Separates business logic from presentation.

Ease of Maintenance: Easier to update the presentation without touching


business logic.

Reusable Components: Custom tags and tag libraries can be reused across
multiple pages.

Automatic Updates: Changes to the JSP page are reflected without


recompilation.

9. JSP vs. Servlets

Code Embedding: JSP allows embedding Java code in HTML, whereas


servlets embed HTML in Java code.

Ease of Use: JSP is more convenient for web designers who are familiar with
HTML.

Maintenance: JSP is easier to maintain and update compared to servlets.

Conclusion
JavaServer Pages (JSP) is a powerful technology for developing dynamic web
applications. By embedding Java code within HTML, JSP provides a seamless

Advanced Java Programming 98


way to create dynamic content. Understanding the lifecycle, architecture,
elements, and implicit objects is crucial for mastering JSP. Additionally, leveraging
JSTL can significantly simplify the development process by providing a rich set of
tags for common tasks.

Java Server Pages (JSP) Overview


Introduction to Java Server Pages (JSP):
Java Server Pages (JSP) is a technology that helps developers to create dynamic
web pages based on HTML or XML while using Java as the programming
language. JSP allows embedding Java code into HTML pages by using special
JSP tags. When a client request is made for a JSP page, the server generates a
response, which may include HTML content, dynamically generated based on the
Java code embedded in the JSP file.
Key Concepts:

1. Servlets vs. JSP: Servlets and JSP are both Java technologies used for web
development. Servlets are Java classes that extend the capabilities of servers
that host applications accessed by means of a request-response programming
model. On the other hand, JSP is a technology that simplifies the development
of web pages that are dynamically generated from HTML or XML formatted
templates, containing embedded Java code.

2. JSP Lifecycle: Like servlets, JSPs have a well-defined lifecycle, including


initialization, execution of service methods, and destruction. This lifecycle is
managed by the container (like Tomcat, Jetty, etc.) in which the JSP is
deployed.

3. JSP Directives: JSP directives are instructions to the container that control the
translation phase of a JSP page into its servlet form. There are three types of
directives: page directive, include directive, and taglib directive.

4. Scripting Elements: JSP provides three types of scripting elements:

Declaration: Used to declare variables or methods. Syntax: <%! ... %>

Scriptlet: Used to insert Java code directly into the service method of the
JSP page. Syntax: <% ... %>

Advanced Java Programming 99


Expression: Used to insert the result of a Java expression directly into the
output. Syntax: <%= ... %>

5. Implicit Objects: JSP provides several implicit objects that are automatically
available to developers. These objects include request, response, session,
application, out, config, page, and exception.

6. JSP Actions: JSP actions are XML tags that direct the server to use existing
components or control the behavior of the JSP engine. Common JSP actions
include jsp:useBean, jsp:setProperty, jsp:getProperty, jsp:include, jsp:forward,
etc.

Advantages of JSP:

Simplicity: JSP allows for the easy development of dynamic web pages by
embedding Java code into HTML.

Reusability: JSP allows for the reuse of JavaBeans and custom tags,
enhancing code modularity.

Seamless Integration: JSP pages can easily integrate with other Java
technologies like servlets, JDBC, EJBs, etc.

Performance: JSP pages are compiled into servlets by the container, leading
to efficient execution.

Examples and Use Cases:

Dynamic Content Generation: JSPs are commonly used to generate dynamic


content for web applications, such as displaying database records, processing
user input, etc.

User Authentication: JSPs can be used to create login pages, authenticate


users, and manage sessions.

E-commerce Applications: JSPs are widely used in e-commerce applications


for displaying product catalogs, shopping carts, order processing, etc.

Conclusion:
Java Server Pages (JSP) provide a powerful mechanism for creating dynamic web
content using Java technology. By combining HTML or XML with embedded Java
code, developers can create feature-rich web applications that are both scalable

Advanced Java Programming 100


and maintainable. Understanding the key concepts and best practices of JSP
development is essential for building robust web solutions.

Implicit Objects in Java Server Pages (JSP)


Introduction:
Implicit objects in Java Server Pages (JSP) are predefined objects that are
automatically available to developers without needing to be explicitly declared or
instantiated. These objects provide access to various aspects of the JSP
environment, including the request, response, session, application, and more.
Understanding implicit objects is essential for effective JSP development as they
provide convenient access to commonly used functionality.
List of Implicit Objects:

1. request: Represents the client's HTTP request to the server. It encapsulates


information such as request parameters, headers, and cookies. Developers
can use this object to retrieve data submitted by the client or to manipulate the
request attributes.

2. response: Represents the server's HTTP response to the client. It provides


methods for setting response headers, cookies, and sending content back to
the client. Developers can use this object to generate dynamic content for the
client.

3. session: Represents the user's session with the server. It allows developers to
store session-specific data that persists across multiple requests from the
same client. The session object is useful for implementing user authentication,
maintaining shopping carts, and storing user preferences.

4. application: Represents the web application running on the server. It allows


developers to store application-wide data that is shared among all users and
sessions. The application object is typically used for caching, storing
configuration parameters, and managing resources shared across the
application.

5. out: Represents the output stream for sending content to the client. It is
equivalent to the PrintWriter object in Java servlets. Developers can use this
object to write HTML, text, or other content directly to the client's web
browser.

Advanced Java Programming 101


6. config: Represents the configuration of the JSP page. It provides access to
initialization parameters specified in the web deployment descriptor (web.xml)
or through annotations. Developers can use this object to retrieve
configuration settings specific to the JSP page.

7. page: Represents the current JSP page itself. It provides methods for
including other resources, forwarding requests, and managing error handling.
Developers can use this object to perform page-specific tasks and access
page attributes.

8. exception: Represents any exception that occurs during the execution of the
JSP page. It is available only if an error-page directive is specified in the JSP
page or in the deployment descriptor. Developers can use this object to
handle and display error messages to the user.

Example Usage:

<%@ page language="java" %>


<html>
<head><title>Implicit Objects Example</title></head>
<body>
<%
// Using implicit objects
out.println("Request Parameter: " + request.getParameter
("param"));
session.setAttribute("user", "John");
out.println("Session Attribute: " + session.getAttribute
("user"));
application.setAttribute("counter", 1);
out.println("Application Attribute: " + application.getAt
tribute("counter"));
%>
</body>
</html>

Conclusion:
Implicit objects in JSP provide convenient access to various aspects of the JSP

Advanced Java Programming 102


environment, simplifying the development of dynamic web applications. By
understanding and utilizing these implicit objects effectively, developers can
enhance productivity and create robust web solutions.

Scripting in Java Server Pages (JSP)


Introduction:
Scripting in Java Server Pages (JSP) allows developers to embed Java code
directly within HTML pages, enabling dynamic content generation and
manipulation. There are three types of scripting elements in JSP: declaration,
scriptlet, and expression, each serving different purposes and providing flexibility
in combining Java logic with HTML markup.

1. Declaration:

Purpose: Declarations are used to declare variables and methods that can be
accessed throughout the JSP page.

Syntax: <%! ... %>

Example:

<%!
int count = 0;
public void incrementCount() {
count++;
}
%>

2. Scriptlet:

Purpose: Scriptlets are used to insert Java code directly into the service
method of the generated servlet.

Syntax: <% ... %>

Example:

<%
String name = "John";

Advanced Java Programming 103


out.println("Hello, " + name + "!");
%>

3. Expression:

Purpose: Expressions are used to insert the result of a Java expression


directly into the HTML output.

Syntax: <%= ... %>

Example:

<p>The current date and time is: <%= new java.util.Date()


%></p>

Best Practices:

Separation of Concerns: Keep business logic separate from presentation


logic by using declarations for variables and methods, and scriptlets for logic
processing.

Code Readability: Write clear and concise code within scriptlets and
expressions to enhance readability and maintainability.

Avoid Complexity: Minimize the use of complex Java logic within JSP pages
to maintain code simplicity and ease of debugging.

Security Considerations: Be cautious when embedding user inputs directly


into JSP code to prevent security vulnerabilities such as cross-site scripting
(XSS) attacks.

Example Usage:

<%@ page language="java" %>


<html>
<head><title>Scripting Example</title></head>
<body>
<%-- Declaration --%>
<%! int count = 0; %>

Advanced Java Programming 104


<%-- Scriptlet --%>
<%
count++;
out.println("The count is: " + count);
%>

<%-- Expression --%>


<p>The current date and time is: <%= new java.util.Date() %>
</p>
</body>
</html>

Conclusion:
Scripting in Java Server Pages (JSP) provides a powerful mechanism for
embedding Java code within HTML pages, facilitating dynamic content generation
and interaction with server-side resources. By understanding the different types
of scripting elements and following best practices, developers can create efficient
and maintainable JSP applications.

Standard Actions in Java Server Pages (JSP)


Introduction:
Standard actions in Java Server Pages (JSP) are XML-based tags provided by JSP
technology to perform specific tasks or control the behavior of the JSP engine.
These actions enhance the functionality of JSP pages by enabling features such
as including other resources, controlling page flow, managing session attributes,
and more.

List of Standard Actions:

1. jsp:include:

Purpose: Includes the content of another resource (JSP page, HTML file,
or servlet) within the current JSP page.

Attributes:

page : Specifies the URL of the resource to be included.

Example:

Advanced Java Programming 105


<jsp:include page="header.jsp" />

2. jsp:forward:

Purpose: Forwards the request to another resource (JSP page, HTML file,
or servlet).

Attributes:

page : Specifies the URL to which the request should be forwarded.

Example:

<jsp:forward page="error.jsp" />

3. jsp:param:

Purpose: Used within jsp:include or jsp:forward to pass parameters to the


included or forwarded resource.

Attributes:

name : Specifies the parameter name.

value : Specifies the parameter value.

Example:

<jsp:param name="id" value="123" />

4. jsp:useBean:

Purpose: Instantiates a JavaBean or retrieves an existing instance from


the specified scope (page, request, session, or application).

Attributes:

id : Specifies the name of the bean object.

class : Specifies the fully qualified class name of the bean.

scope : Specifies the scope in which the bean should be stored.

Example:

Advanced Java Programming 106


<jsp:useBean id="user" class="com.example.User" scope
="session" />

5. jsp:setProperty:

Purpose: Sets properties of a JavaBean from request parameters or other


sources.

Attributes:

name : Specifies the name of the bean object.

property : Specifies the name of the bean property to be set.

value : Specifies the value to be set.

Example:

<jsp:setProperty name="user" property="name" value="${p


aram.name}" />

6. jsp:getProperty:

Purpose: Retrieves the value of a property from a JavaBean and outputs it


to the response.

Attributes:

name : Specifies the name of the bean object.

property : Specifies the name of the bean property to be retrieved.

Example:

<jsp:getProperty name="user" property="name" />

7. jsp:plugin:

Purpose: Generates HTML for embedding applets or other browser-


specific plugins.

Attributes: Varies depending on the plugin being embedded.

Advanced Java Programming 107


Example:

<jsp:plugin type="applet" code="MyApplet.class" />

Conclusion:
Standard actions in JSP provide a convenient way to incorporate dynamic
functionality and control the behavior of JSP pages. By using these actions
effectively, developers can enhance the functionality and interactivity of their web
applications while maintaining clean and maintainable code. Understanding the
purpose and attributes of each standard action is essential for leveraging the full
power of JSP technology.

Directives in Java Server Pages (JSP)


Introduction:
Directives in Java Server Pages (JSP) are special instructions that provide
information to the JSP container during the translation phase of a JSP page. They
are used to configure settings, import Java packages, define scripting language,
and more. JSP directives are not visible in the output sent to the client's web
browser.
Types of Directives:

1. Page Directive:

Purpose: Provides instructions to the JSP container regarding various


page-specific settings.

Syntax: <%@ page attribute="value" %>

Common Attributes:

language : Specifies the scripting language used in the JSP page (e.g.,
"java").

contentType : Specifies the MIME type and character encoding of the


response (e.g., "text/html; charset=UTF-8").

import : Specifies Java packages to be imported into the JSP page.

Advanced Java Programming 108


session : Specifies whether the JSP page participates in session
tracking (e.g., "true").

Example:

<%@ page language="java" contentType="text/html; charse


t=UTF-8" import="java.util.*" session="true" %>

2. Include Directive:

Purpose: Includes the content of another resource (JSP page or HTML


file) during the translation phase.

Syntax: <%@ include file="filename" %>

Example:

<%@ include file="header.jsp" %>

3. Taglib Directive:

Purpose: Declares and configures custom tag libraries for use in the JSP
page.

Syntax: <%@ taglib uri="uri" prefix="prefix" %>

Attributes:

uri: Specifies the URI (Uniform Resource Identifier) of the tag library
descriptor (TLD) file.

prefix : Specifies the prefix used to reference tags from the tag library.

Example:

<%@ taglib uri="<http://java.sun.com/jsp/jstl/core>" pr


efix="c" %>

Best Practices:

Positioning: Directives should be placed at the beginning of the JSP page,


before any HTML or Java code.

Advanced Java Programming 109


Clarity: Use clear and meaningful attribute names to enhance readability and
maintainability.

Consistency: Maintain consistency in directive usage across JSP pages within


the project.

Validation: Validate URIs and import statements to ensure correctness and


prevent runtime errors.

Conclusion:
Directives in JSP play a crucial role in configuring page-specific settings,
including external resources, and declaring custom tag libraries. By understanding
the purpose and usage of each directive type, developers can effectively manage
the behavior and functionality of their JSP pages while adhering to best practices
for clean and maintainable code.

Custom Tag Libraries in Java Server Pages (JSP)


Introduction:
Custom tag libraries in Java Server Pages (JSP) allow developers to create and
use their own custom tags, providing a way to encapsulate reusable functionality
and improve the modularity of JSP pages. Custom tags abstract complex behavior
into simple, easy-to-use tags, enhancing code readability and maintainability.

Creating Custom Tag Libraries:

1. Define Tag Handler Classes:

Tag handler classes are Java classes that implement the logic for custom
tags.

Tag handlers extend either the TagSupport or BodyTagSupport class provided


by the JSP Standard Tag Library (JSTL).

Override methods such as doStartTag() , doEndTag() , and doAfterBody() to


define tag behavior.

2. Create Tag Library Descriptor (TLD) File:

The TLD file is an XML document that defines the custom tags provided by
the tag library.

It specifies tag names, tag handlers, tag attributes, and other metadata.

Advanced Java Programming 110


The TLD file must be placed in the WEB-INF directory of the web
application.

3. Implement Tag Library Usage:

In JSP pages, custom tags are referenced using the tag prefix and tag
name defined in the TLD file.

Tags can include attributes whose values are passed to the corresponding
tag handler.

Custom tags can be used like any other HTML or JSP tag within the JSP
page.

Example of Custom Tag Library Usage:


Suppose we want to create a custom tag library for formatting dates.

1. Define Tag Handler Class ( DateTagHandler.java ):

package com.example.tags;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTagHandler extends TagSupport {


@Override
public int doStartTag() throws JspException {
try {
JspWriter out = pageContext.getOut();
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFo
rmat("dd-MM-yyyy");
out.print(dateFormat.format(currentDate));
} catch (IOException e) {
throw new JspException("Error in DateTagHandle

Advanced Java Programming 111


r", e);
}
return SKIP_BODY;
}
}

2. Create Tag Library Descriptor ( date.tld ):

<?xml version="1.0" encoding="UTF-8"?>


<taglib xmlns="<http://java.sun.com/xml/ns/j2ee>"
xmlns:xsi="<http://www.w3.org/2001/XMLSchema-insta
nce>"
xsi:schemaLocation="<http://java.sun.com/xml/ns/j2
ee/web-jsptaglibrary_2_0.xsd>"
version="2.0">
<tlib-version>1.0</tlib-version>
<short-name>date</short-name>
<uri><http://example.com/tags/date></uri>
<tag>
<name>currentDate</name>
<tag-class>com.example.tags.DateTagHandler</tag-cl
ass>
<body-content>empty</body-content>
</tag>
</taglib>

3. Use Custom Tag in JSP Page:

<%@ taglib prefix="date" uri="<http://example.com/tags/dat


e>" %>
<html>
<head><title>Custom Tag Example</title></head>
<body>
<p>Current Date: <date:currentDate /></p>

Advanced Java Programming 112


</body>
</html>

Best Practices:

Modularity: Encapsulate specific functionality into individual custom tags for


better code organization.

Reusability: Design tags to be reusable across multiple JSP pages and


projects.

Documentation: Provide clear documentation for custom tags, including


usage instructions and attribute descriptions.

Testing: Test custom tags thoroughly to ensure they function as expected in


various scenarios.

Conclusion:
Custom tag libraries in JSP offer a powerful mechanism for encapsulating
reusable functionality and improving the modularity of web applications. By
following best practices and guidelines for creating and using custom tags,
developers can enhance code maintainability and productivity in JSP-based
projects.

Unit - 4
Roles of Client and Server in Web Applications
In the context of web applications, the client and server play distinct roles in
facilitating communication, processing requests, and delivering content.
Understanding these roles is crucial for effective design, development, and
deployment of web-based systems.

1. Client:
Definition: The client refers to the user's device (such as a web browser or mobile
device) that initiates requests to access web resources or services.

Key Responsibilities:

Advanced Java Programming 113


User Interface: The client renders the user interface and interacts with the
user through input mechanisms like keyboards, mice, or touchscreens.

Request Generation: It generates HTTP requests to request resources or


services from a server based on user actions (e.g., clicking a link, submitting a
form).

Response Handling: The client receives and processes HTTP responses from
the server, rendering content such as HTML, CSS, JavaScript, and multimedia
elements.

Local Data Storage: It may store cookies, session data, or cache resources
locally to improve performance and provide personalized experiences.

Examples of Clients:

Web browsers (e.g., Chrome, Firefox, Safari)

Mobile browsers (e.g., Chrome for Android, Safari for iOS)

Mobile applications (native or hybrid) accessing web services

Internet of Things (IoT) devices with web browsing capabilities

2. Server:

Definition: The server refers to a computer system or software that provides


resources, services, or data to clients over a network, typically the internet.

Key Responsibilities:

Request Handling: The server receives and processes HTTP requests from
clients, determining the appropriate action based on the request type, URL,
headers, and parameters.

Resource Management: It manages resources such as files, databases, or


application logic to generate dynamic content or fulfill client requests.

Response Generation: The server generates HTTP responses containing


requested content, data, or error messages, adhering to the HTTP protocol
standards.

Security: It implements security measures to protect sensitive data,


authenticate users, authorize access to resources, and prevent unauthorized

Advanced Java Programming 114


activities (e.g., through encryption, authentication mechanisms, access control
lists).

Scalability and Performance: The server may be designed to scale


horizontally or vertically to handle increasing loads, optimize resource
utilization, and ensure responsiveness to client requests.

Examples of Servers:

Web servers (e.g., Apache HTTP Server, Nginx)

Application servers (e.g., Tomcat, WildFly, Node.js)

Database servers (e.g., MySQL, PostgreSQL, MongoDB)

Cloud computing platforms (e.g., AWS, Microsoft Azure, Google Cloud


Platform)

Conclusion:

In web applications, the client and server play complementary roles in enabling
communication, processing, and delivery of content and services. While the client
interacts directly with users and renders the user interface, the server processes
requests, manages resources, and generates responses to fulfill client needs.
Understanding the roles and responsibilities of both client and server is essential
for building efficient, secure, and scalable web-based systems.

Remote Method Invocations (RMI) in Java


Introduction:
Remote Method Invocation (RMI) is a Java technology that enables
communication between Java objects running in different Java Virtual Machines
(JVMs) over a network. RMI allows Java objects to invoke methods on remote
objects as if they were local objects, abstracting the complexities of network
communication.

Key Components of RMI:

1. Remote Interface:

A Java interface that declares the methods that can be invoked remotely.

Advanced Java Programming 115


Both the client and server must have access to the remote interface and its
implementation.

2. Remote Object (Server):

A Java class that implements the remote interface.

The server provides the implementation for the remote methods and
makes them accessible to remote clients.

3. Stub and Skeleton:

The stub acts as a proxy for the remote object on the client side. It
marshals method calls and parameters, sends them over the network to
the server, and receives the results.

The skeleton acts as a proxy for the remote object on the server side. It
unmarshals method calls and parameters, invokes the corresponding
methods on the remote object, and sends back the results.

4. Registry:

The RMI registry is a simple naming service provided by Java to bind


remote objects to names.

Clients use the registry to look up remote objects by their names and
obtain stubs for communication.

Steps for Implementing RMI:

1. Define the Remote Interface:

Declare the remote methods in a Java interface that extends


java.rmi.Remote .

Each method must declare java.rmi.RemoteException in its throws clause.

2. Implement the Remote Interface:

Create a Java class that implements the remote interface.

Implement the business logic for the remote methods in this class.

3. Compile the Remote Interface and Implementation:

Advanced Java Programming 116


Compile both the remote interface and its implementation using the javac

compiler.

4. Generate Stub and Skeleton:

Use the rmic tool (RMI Compiler) to generate stub and skeleton classes for
the remote object implementation.

5. Start the RMI Registry:

Start the RMI registry using the rmiregistry command-line tool or


programmatically in the server application.

6. Register Remote Object with the Registry:

Bind the remote object to a name in the RMI registry using the bind()

method.

7. Client Lookup and Invocation:

On the client side, look up the remote object from the registry using the
lookup() method.

Invoke remote methods on the obtained stub as if they were local method
calls.

Advantages of RMI:

Simplicity: RMI abstracts the complexities of network communication,


allowing developers to focus on application logic.

Language Neutrality: RMI allows communication between Java objects


regardless of the underlying platform or programming language.

Performance: RMI provides efficient communication mechanisms, such as


object serialization and transport optimization.

Limitations of RMI:

Java-Centric: RMI is tightly coupled with the Java programming language and
is not interoperable with non-Java systems by default.

Firewall Issues: RMI often requires special configurations to traverse firewalls,


which may introduce security concerns.

Advanced Java Programming 117


Conclusion:
Remote Method Invocation (RMI) in Java provides a convenient and efficient
mechanism for communication between Java objects running in separate JVMs.
By following the steps for implementing RMI and understanding its key
components, developers can create distributed applications with ease, enabling
seamless interaction between remote objects over a network. Despite its
limitations, RMI remains a powerful technology for building distributed systems in
Java environments.

Setup for Remote Method Invocation


Setting up Remote Method Invocation (RMI) involves several steps, including
defining remote interfaces, implementing server and client classes, compiling and
generating stubs and skeletons, starting the RMI registry, and deploying the
application. Below is a step-by-step guide to setting up RMI in a Java application:
Step 1: Define the Remote Interface:

import java.rmi.Remote;
import java.rmi.RemoteException;

// Remote interface
public interface MyRemoteInterface extends Remote {

Advanced Java Programming 118


// Remote method declaration
String sayHello() throws RemoteException;
}

Step 2: Implement the Remote Interface:

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

// Remote implementation
public class MyRemoteImpl extends UnicastRemoteObject impleme
nts MyRemoteInterface {
// Constructor
protected MyRemoteImpl() throws RemoteException {
super();
}

// Implement the remote method


public String sayHello() throws RemoteException {
return "Hello, Remote World!";
}
}

Step 3: Compile the Interface and Implementation:

javac MyRemoteInterface.java MyRemoteImpl.java

Step 4: Generate Stub and Skeleton:

rmic MyRemoteImpl

Step 5: Start the RMI Registry:

rmiregistry

You can start the registry in the directory containing your compiled classes.

Advanced Java Programming 119


Step 6: Register the Remote Object with the Registry (Server Side):

import java.rmi.Naming;

// Server class
public class MyRemoteServer {
public static void main(String[] args) {
try {
MyRemoteImpl remoteObj = new MyRemoteImpl();
Naming.rebind("RemoteObject", remoteObj);
System.out.println("Remote object bound to regist
ry.");
} catch (Exception e) {
e.printStackTrace();
}
}
}

Step 7: Look up and Invoke Remote Methods (Client Side):

import java.rmi.Naming;

// Client class
public class MyRemoteClient {
public static void main(String[] args) {
try {
MyRemoteInterface remoteObj = (MyRemoteInterface)
Naming.lookup("RemoteObject");
System.out.println(remoteObj.sayHello());
} catch (Exception e) {
e.printStackTrace();
}
}
}

Step 8: Run the Client and Server Programs:

Advanced Java Programming 120


Run the server program ( MyRemoteServer ) first to bind the remote object to the
RMI registry.

Then, run the client program ( MyRemoteClient ) to look up the remote object and
invoke its methods.

Make sure to include all necessary security policies and permissions, especially if
you encounter security-related exceptions during the RMI setup process.
These steps provide a basic setup for RMI in a Java application. Adjustments may
be necessary based on your specific application requirements and environment.

Parameter Passing in Remote Methods


In Remote Method Invocation (RMI), parameter passing involves passing data
between remote objects across the network. Java RMI uses serialization to pass
parameters and return values between client and server.

Parameter Passing in RMI:

1. Java Object Serialization:

Java RMI uses object serialization to marshal (serialize) parameters into a


byte stream before sending them over the network and unmarshal
(deserialize) them back into objects on the receiving end.

All parameter types, including primitive types, objects, arrays, and custom
classes, must be serializable to be passed as parameters in RMI.

2. Serializable Interface:

For an object to be serialized, it must implement the java.io.Serializable

interface.

By default, most Java built-in classes (e.g., String , Integer , ArrayList) are
serializable, but custom classes need to implement Serializable explicitly.

3. Parameter Constraints:

Parameters passed in remote methods should be simple types or


serializable objects.

Avoid passing non-serializable objects or objects with circular references,


as they may cause serialization errors.

Advanced Java Programming 121


4. Remote Exceptions:

Remote methods may throw remote exceptions ( java.rmi.RemoteException ) to


indicate communication or server-side errors.

Remote exceptions must also be serializable to propagate over the


network to the client.

Example:

Consider a remote interface with a method that takes parameters:

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface MyRemoteInterface extends Remote {


String processRequest(String request) throws RemoteExcept
ion;
}

And its implementation:

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class MyRemoteImpl extends UnicastRemoteObject impleme


nts MyRemoteInterface {
protected MyRemoteImpl() throws RemoteException {
super();
}

@Override
public String processRequest(String request) throws Remot
eException {
// Process request and return result
return "Processed: " + request;

Advanced Java Programming 122


}
}

On the client side, you can invoke this remote method by passing parameters as
you would with local methods:

import java.rmi.Naming;

public class MyRemoteClient {


public static void main(String[] args) {
try {
MyRemoteInterface remoteObj = (MyRemoteInterface)
Naming.lookup("RemoteObject");
String response = remoteObj.processRequest("Hello
from client");
System.out.println("Response: " + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Conclusion:
Parameter passing in RMI involves serializing parameters into byte streams for
transmission over the network and deserializing them on the receiving end. By
ensuring that all parameters are serializable and following best practices for
remote method invocation, developers can build robust and efficient distributed
systems using Java RMI.

Introduction of HB
It seems like you're referring to Hibernate (HB), a popular object-relational
mapping (ORM) framework for Java applications. Hibernate simplifies the task of
interacting with relational databases by providing an abstraction layer over JDBC
(Java Database Connectivity), allowing developers to work with Java objects
instead of SQL queries directly. Here's an introduction to Hibernate:

Advanced Java Programming 123


Hibernate Overview:

Hibernate is an open-source ORM framework that automates the mapping


between Java objects and database tables. It provides a set of APIs and tools for
performing CRUD (Create, Read, Update, Delete) operations on database records
using Java objects.

Key Features of Hibernate:

1. Object-Relational Mapping (ORM): Hibernate maps Java classes to database


tables and Java data types to SQL data types, allowing developers to work
with objects instead of database tables.

2. Transparent Persistence: Hibernate provides transparent persistence,


meaning it automatically manages the lifecycle of objects, including fetching,
storing, and updating data in the database, without the need for manual SQL
queries.

3. Lazy Loading: Hibernate supports lazy loading, allowing it to load associated


objects from the database only when they are accessed, improving
performance by minimizing unnecessary database queries.

4. Caching: Hibernate supports first-level and second-level caching


mechanisms to reduce database round-trips and improve application
performance by caching frequently accessed data in memory.

5. Query Language: Hibernate Query Language (HQL) is a powerful object-


oriented query language similar to SQL but operates on persistent objects and
their properties, making it easier to write database queries in a platform-
independent manner.

6. Transactions: Hibernate supports transaction management, allowing


developers to group database operations into atomic units of work, ensuring
data consistency and integrity.

7. Integration with Java EE: Hibernate integrates seamlessly with Java EE


(Enterprise Edition) frameworks like Spring and JavaServer Faces (JSF),
providing enhanced capabilities for building enterprise applications.

Getting Started with Hibernate:

Advanced Java Programming 124


To start using Hibernate in your Java application, you typically need to perform
the following steps:

1. Setup Hibernate Configuration: Configure Hibernate properties such as


database connection settings, dialect, and mapping files (XML or annotations).

2. Create Entity Classes: Define Java entity classes that represent database
tables and annotate them with Hibernate annotations or XML mappings.

3. Perform CRUD Operations: Use Hibernate APIs to perform CRUD operations


on database records using Java objects.

4. Handle Transactions: Manage transactions using Hibernate transaction APIs


to ensure data consistency and integrity.

5. Optimize Performance: Fine-tune Hibernate configurations, enable caching,


and optimize database queries to improve application performance.

Conclusion:

Hibernate simplifies database interaction in Java applications by providing an


ORM framework that abstracts the complexities of working with relational
databases. By leveraging Hibernate's features and best practices, developers can
build robust, scalable, and maintainable applications with ease.

Advanced Java Programming 125


HB Architecture
The architecture of Hibernate (HB) is designed to facilitate object-relational
mapping (ORM) between Java objects and relational databases. It consists of
several layers and components that work together to provide persistence services
and manage database interactions efficiently. Here's an overview of the
architecture of Hibernate:

1. Application Layer:

The application layer represents the topmost layer of the architecture and
includes the Java application or web application that utilizes Hibernate for
database interaction.

Application developers interact with Hibernate APIs to perform CRUD


operations, query data, and manage transactions.

Advanced Java Programming 126


2. Hibernate Configuration:

At the core of Hibernate architecture is its configuration, which includes


settings related to database connection, dialect, caching, and other properties.

Configuration settings can be specified using XML configuration files


( hibernate.cfg.xml ) or programmatically through the Configuration class.

3. SessionFactory:

The SessionFactory is a thread-safe object that serves as a factory for creating


Session instances.

It is responsible for initializing Hibernate based on the configuration settings,


parsing mapping metadata, and managing database connections.

The SessionFactory is typically created once during application startup and


reused throughout the application's lifecycle.

4. Session:

The Session represents a single unit of work in Hibernate and serves as the
main interface for performing database operations.

It encapsulates a connection to the database and provides methods for CRUD


operations, querying, and transaction management.

Session instances are not thread-safe and should be obtained from the
SessionFactory as needed.

5. Transaction Management:

Hibernate provides built-in support for transaction management through the


Transaction interface.

Transactions ensure the atomicity, consistency, isolation, and durability (ACID)


properties of database operations.

Transactions are typically managed programmatically using methods like


begin() , commit() , and rollback() on the Transaction object.

6. Persistent Objects:

Persistent objects are Java classes mapped to database tables using


Hibernate mapping files or annotations.

Advanced Java Programming 127


Hibernate manages the lifecycle of persistent objects, including loading,
saving, updating, and deleting them from the database.

Developers annotate persistent classes and their properties with metadata to


define the mapping between Java objects and database tables.

7. Mapping Metadata:

Mapping metadata describes the relationship between Java classes and


database tables, as well as the mapping of class properties to database
columns.

Metadata can be specified using Hibernate mapping files ( .hbm.xml ) or


annotations ( @Entity , @Table , @Column ) directly in Java code.

Hibernate uses mapping metadata to generate SQL queries and map database
results to Java objects.

8. Query Language:

Hibernate Query Language (HQL) is a powerful object-oriented query


language similar to SQL but operates on persistent objects and their
properties.

HQL queries are platform-independent and can be used to retrieve, update,


and delete data from the database using object-oriented syntax.

9. Database:

The database layer represents the underlying relational database management


system (RDBMS) where data is stored persistently.

Hibernate supports various databases, including MySQL, PostgreSQL, Oracle,


SQL Server, and others, through dialect-specific implementations.

Conclusion:
The architecture of Hibernate provides a robust framework for object-relational
mapping in Java applications, offering features such as transparent persistence,
transaction management, and query capabilities. By understanding the different
layers and components of Hibernate architecture, developers can effectively
leverage its capabilities to build scalable and maintainable database-driven
applications.

Advanced Java Programming 128


Updated: https://yashnote.notion.site/Advanced-Java-Programming-
fa0a79e50a8b4945be9f86a08b0ec425?pvs=4

Advanced Java Programming 129

You might also like