Advanced Java

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 60

Advanced Java Programming

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
Key Points
Exception Handling
Basics of Exception Handling
Syntax
Example 1: Arithmetic Exception
Example 2: ArrayIndexOutOfBoundsException
Example 3: NullPointerException
Handling Multiple Exceptions
The finally Block
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

Advanced Java Programming 1


Example 2: Drawing Shapes
Example 3: Handling Mouse Events
Example 4: Animation
Conclusion
Additional Points:
Inheritance:
Exception Handling:
Multithreading:
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:
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:

Advanced Java Programming 2


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
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:

Advanced Java Programming 3


Conclusion:
Session Tracking
1. Cookies:
2. URL Rewriting:
3. HttpSession Object:
Conclusion:

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.

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.

Advanced Java Programming 4


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 Wo
rld
}
}

This will print 'Hello World' as the output.

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.

Advanced Java Programming 5


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).

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.

Advanced Java Programming 6


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
}

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 {

Advanced Java Programming 7


// 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 {


// 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)

Advanced Java Programming 8


Java does not support multiple inheritance directly to avoid the diamond
problem. However, it supports multiple inheritance through interfaces.

Example

// 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
}
}

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

Advanced Java Programming 9


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
exception 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());

Advanced Java Programming 10


}
}
}

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]; // ArrayIndexOutOfBoundsE
xception
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

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(); // NullPointerExcept
ion
} catch (NullPointerException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

Advanced Java Programming 11


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]; // ArrayIndexOutOfBoundsE
xception
int result = 10 / 0; // ArithmeticException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Error: " + e.ge
tMessage());
} catch (ArithmeticException e) {
System.out.println("Arithmetic Error: " + e.get
Message());
}
}
}

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 whe
ther an exception occurred or not
}

Advanced Java Programming 12


}
}

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).

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

class MyThread extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread: " + i);
try {

Advanced Java Programming 13


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);
}
}
}
}

public class Main {


public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());

Advanced Java Programming 14


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() {


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);

Advanced Java Programming 15


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 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.

Advanced Java Programming 16


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;

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;

Advanced Java Programming 17


import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class MouseApplet extends Applet implements MouseLis


tener {
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,
20);
}

// MouseListener methods
public void mouseClicked(MouseEvent e) {
x = e.getX(); // Get X-coordinate of mouse click
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;

Advanced Java Programming 18


public class AnimationApplet extends Applet implements Runn
able {
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
}
repaint(); // Refresh applet
try {
Thread.sleep(100); // Pause for 100 millise
conds
} 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

Advanced Java Programming 19


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.

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.

Advanced Java Programming 20


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.

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.

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

Advanced Java Programming 21


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.*;

public class Client {


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

// Get the output stream from the socket


OutputStream outputStream = socket.getOutput
Stream();

// Create a PrintWriter for writing to the o


utput stream
PrintWriter out = new PrintWriter(outputStre
am, true);

// Send data to the server


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

// Close the socket


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

2. Server Side:

Advanced Java Programming 22


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

public class Server {


public static void main(String[] args) {
try {
// Create a server socket bound to a specifi
c port
ServerSocket serverSocket = new ServerSocket
(port_number);

// Listen for incoming connections from clie


nts
Socket clientSocket = serverSocket.accept();

// Get the input stream from the client sock


et
InputStream inputStream = clientSocket.getIn
putStream();

// Create a BufferedReader for reading from


the input stream
BufferedReader in = new BufferedReader(new I
nputStreamReader(inputStream));

// Read data from the client


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

// Close the sockets


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

Advanced Java Programming 23


}
}

Explanation:
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:

Advanced Java Programming 24


1. Create a ServerSocket:

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
(12345);
System.out.println("Server started. Waiting
for clients...");

// Accept client connections


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

// Handle client connection in a separat


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

2. Handle Client Connections:

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

Advanced Java Programming 25


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 cli
ent socket
BufferedReader in = new BufferedReader(new I
nputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSock
et.getOutputStream(), true);

// Read data from the client


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

// 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 26


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


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:

Advanced Java Programming 27


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 = (HttpURLConne
ction) url.openConnection();

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


connection.setRequestMethod("GET");

// Set additional request headers if needed


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

// Read response code from the server


int responseCode = connection.getResponseCod
e();
System.out.println("Response Code: " + respo
nseCode);

// Read response data


BufferedReader in = new BufferedReader(new I
nputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null)

Advanced Java Programming 28


{
response.append(inputLine);
}
in.close();

// Print response data


System.out.println("Response Data: " + respo
nse.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() .

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:

Advanced Java Programming 29


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.

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.

Advanced Java Programming 30


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.

Basic Concepts:
1. Client-Server Model:

Advanced Java Programming 31


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.

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 {

Advanced Java Programming 32


ServerSocket serverSocket = new ServerSocket(12
345); // Create a server socket
System.out.println("Server started. Waiting for
clients...");

Socket clientSocket = serverSocket.accept(); //


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

BufferedReader in = new BufferedReader(new Inpu


tStreamReader(clientSocket.getInputStream())); // Input str
eam
PrintWriter out = new PrintWriter(clientSocket.
getOutputStream(), true); // Output stream

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


message
System.out.println("Message from client: " + me
ssage);

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


to 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) {

Advanced Java Programming 33


try {
Socket socket = new Socket("localhost", 12345);
// Connect to server
System.out.println("Connected to server.");

PrintWriter out = new PrintWriter(socket.getOut


putStream(), true); // Output stream
BufferedReader in = new BufferedReader(new Inpu
tStreamReader(socket.getInputStream())); // Input stream

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


to server

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


ponse from server
System.out.println("Response from server: " + r
esponse);

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(12
345);
System.out.println("Server started. Waiting for
clients...");

Advanced Java Programming 34


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

ClientHandler clientHandler = new ClientHan


dler(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 Inpu
tStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.
getOutputStream(), true);

String message = in.readLine();


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

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

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

Advanced Java Programming 35


e.printStackTrace();
}
}
}

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.

Advanced Java Programming 36


2. Private Fields with Public Getter and Setter Methods:

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


public String getName() {
return name;

Advanced Java Programming 37


}

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());
}
}

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

Advanced Java Programming 38


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;
}

// Getter and setter methods for 'age' field


public int getAge() {
return age;
}

public void setAge(int age) {

Advanced Java Programming 39


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);

// 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

Advanced Java Programming 40


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
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;

Advanced Java Programming 41


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;
}
}

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

Advanced Java Programming 42


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
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

Advanced Java Programming 43


}

// 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;
}
}

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.

Advanced Java Programming 44


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;

// 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:

Advanced Java Programming 45


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

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

Conclusion:
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:

Advanced Java Programming 46


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.

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);
}

Advanced Java Programming 47


public List<String> getItems() {
return items;
}

public void clear() {


items.clear();
}
}

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

Advanced Java Programming 48


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:

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:

Advanced Java Programming 49


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) {


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.

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.

Advanced Java Programming 50


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.

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.

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.

Advanced Java Programming 51


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:
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.

Advanced Java Programming 52


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.

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) :

Advanced Java Programming 53


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() :

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.

Advanced Java Programming 54


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

4. Destruction:

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.

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 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:

Advanced Java Programming 55


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 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.

Advanced Java Programming 56


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 ).

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 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 57


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.

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:

Advanced Java Programming 58


Cookie sessionCookie = new Cookie("sessionId", "uniqueSe
ssionId");
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");

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.

Advanced Java Programming 59


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");

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.

Updated: https://yashnote.notion.site/Advanced-Java-Programming-
fa0a79e50a8b4945be9f86a08b0ec425?pvs=4

Advanced Java Programming 60

You might also like