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

Java Programming

The document outlines the syllabus for an Advanced Java Programming course at Marudhar Kesari Jain College for Women, covering topics such as Java basics, Remote Method Invocation (RMI), JDBC, Servlets, and advanced techniques. It includes course objectives and expected outcomes for students, emphasizing skills in distributed application architecture and database interactions. Additionally, it provides examples of Java components, event handling, threading, networking, and multimedia techniques.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views66 pages

Java Programming

The document outlines the syllabus for an Advanced Java Programming course at Marudhar Kesari Jain College for Women, covering topics such as Java basics, Remote Method Invocation (RMI), JDBC, Servlets, and advanced techniques. It includes course objectives and expected outcomes for students, emphasizing skills in distributed application architecture and database interactions. Additionally, it provides examples of Java components, event handling, threading, networking, and multimedia techniques.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MARUDHAR KESARI JAIN COLLEGE FOR WOMEN, VANIYAMBADI

PG AND RESEARCH DEPARTMENT OF COMPUTER SCIENCE


SUBJECT NAME : ADVANCED JAVA PROGRAMMING
CLASS : I [Link] Computer Science

SYLLABUS

Structure of Units

Unit: 1 BASICS OF JAVA


Java Basics Review: Components and event handling–Threading concepts–Networking features
– Media techniques

Unit: 2 REMOTE METHOD INVOCATIONS


Remote Method Invocation-Distributed Application Architecture- Creating stubs and skeletons-
Defining Remote objects- Remote Object Activation-Object Serialization-Java Spaces

Unit: 3 DATABASE
Java in Databases-JDBC principles–database access-Interacting-database search–Creating
multimedia databases – Database support in web applications

Unit: 4 SERVLETS
Java Servlets: Java Servlet and CGI programming- A simple java Servlet-Anatomy of a java
Servlet-Reading data from a client-Reading http request header-sending data to a client and
writing the http response header-working with cookies.
Java Server Pages: JSP Overview-Installation-JSP tags-Components of a JSP page-Expressions-
Scriptlets-Directives-Declarations-A complete example

Unit: 5 ADVANCED TECHNIQUES


JAR file format creation–Internationalization–Swing Programming–Advanced java techniques

Course Objectives:
The main objectives of this course are to:
1. Enable the students to learn the basic functions, principles and concepts of advanced java
programming.
2. Provide knowledge on concepts needed for distributed Application Architecture.
3. Learn JDBC, Servlet packages, JQuery, Java Server Pages and JAR file format.
Expected Course Outcomes:
On the successful completion of the course, student will be able to :
1 Understand the advanced concepts of Java Programming K1,K2

2 Understand JDBC and RMI concepts K2,K3

3 Apply and analyze Java in Database K3,K4

4 Handle different event in java using the delegation event model, K5


event listener and class
5 Design interactive applications using Java Servlet, JSP and JDBC K5,K6

K1-Remember; K2-Understand; K3-Apply; K4-Analyze; K5-Evaluate; K6-Create


Unit 1

1. Components and Event Handling


Components: In Java, components are graphical elements that can be added to a graphical user
interface (GUI) to create interactive applications. Examples include buttons, text fields, labels,
and more.

Event Handling: Event handling in Java involves responding to user actions or system events,
such as button clicks or key presses. This is achieved by registering event listeners on
components that listen for specific events and trigger actions in response.

Components form the building blocks of a GUI. They are objects that users interact with, and
event handling allows developers to define what happens when a user interacts with these
components. For example, clicking a button triggers a button-click event, and the associated
event handler executes a set of instructions, responding to the user's action.

Example:
Consider a simple Java Swing application with a button. When the button is clicked, a message
is displayed.
import [Link].*;
import [Link];
import [Link];

public class SimpleGUI extends JFrame {


public SimpleGUI() {
JButton button = new JButton("Click me");
[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link](null, "Button clicked!");
}
});

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().add(button);
pack();
setLocationRelativeTo(null);
}
public static void main(String[] args) {
[Link](() -> new SimpleGUI().setVisible(true));
}
}
In this example, we create a simple GUI with a button. We use an ActionListener to handle the
button click event, and when the button is clicked, a message dialog is displayed.

Output:

2. Threading Concepts:
Threading in Java refers to the concurrent execution of multiple threads within a program. A
thread is a lightweight process and multithreading allows different tasks to be performed
simultaneously.

Java applications can have multiple threads of execution, each performing a specific task
concurrently. Multithreading is used to enhance the performance of applications, especially in
scenarios where tasks can be performed independently. Threads share the same process
resources but run independently, allowing for efficient utilization of system resources.

Example:
Consider a simple program that runs two threads concurrently.
public class ThreadExample {
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 5; i++) {
[Link]("Thread 1: " + i);
}
}
});

Thread thread2 = new Thread(new Runnable() {


public void run() {
for (int i = 0; i < 5; i++) {
[Link]("Thread 2: " + i);
}
}
});

[Link]();
[Link]();
}
}
In this example, two threads (thread1 and thread2) are created and started concurrently. They
each print a sequence of numbers.

Output:
Thread 1: 0
Thread 2: 0
Thread 1: 1
Thread 2: 1
Thread 1: 2
Thread 2: 2
Thread 1: 3
Thread 2: 3
Thread 1: 4
Thread 2: 4

3. Networking Features:
Networking in Java involves communication between different computing devices over a
network. Java provides classes like Socket and ServerSocket for creating networked
applications, enabling data exchange between clients and servers.

Java's networking features facilitate the development of client-server applications. The Socket
class allows programs to establish a connection and exchange data over a network. The server
waits for incoming connections using ServerSocket, and the client initiates a connection to the
server. This enables the creation of distributed applications and communication between
devices.

Example:
Consider a simple client-server communication using sockets.
// Server
import [Link].*;
import [Link].*;

public class SimpleServer {


public static void main(String[] args) throws IOException {
ServerSocket serverSocket = new ServerSocket(8080);
[Link]("Server waiting for client connection...");

Socket clientSocket = [Link]();


[Link]("Client connected");

BufferedReader in = new BufferedReader(new


InputStreamReader([Link]()));
String clientMessage = [Link]();
[Link]("Client says: " + clientMessage);
[Link]();
}
}

// Client
import [Link].*;
import [Link].*;

public class SimpleClient {


public static void main(String[] args) throws IOException {
Socket socket = new Socket("localhost", 8080);

PrintWriter out = new PrintWriter([Link](), true);


[Link]("Hello from client!");

[Link]();
}
}
In this example, the server waits for a client connection, and once connected, it reads a
message from the client. The client connects to the server and sends a message.

Output:
Server waiting for client connection...
Client connected
Client says: Hello from client!

4. Media Techniques
Media Techniques: In Java, media techniques involve handling multimedia elements such as
sound and images. Java provides libraries and classes for working with audio and visual content.

Java offers packages like [Link] for sound and [Link] for graphical
elements, allowing developers to incorporate multimedia features into their applications. For
example, the Clip class in [Link] can be used to play audio files, and classes in
[Link] can be used for displaying and manipulating images.

Example:
Consider a simple program that plays a sound using [Link].
import [Link].*;
public class SoundExample {
public static void main(String[] args) {
try {
Clip clip = [Link]();
AudioInputStream inputStream = [Link](
[Link]("/path/to/[Link]"));

[Link](inputStream);
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
In this example, a sound file is played using the Clip class from [Link].

Output:
Playing audio...
Playback completed.
Unit 2

Remote Method Invocation

Remote Method Invocation (RMI) is a Java-based framework that enables communication between
different Java Virtual Machines (JVMs) over a network. It allows a Java object in one JVM to invoke
methods on a remote Java object in another JVM. RMI facilitates distributed computing, allowing
programs to be distributed across multiple machines while interacting as if they were part of a single
application.

Let's consider a simple example of RMI with a "Calculator" service. This example will demonstrate a
remote interface, its implementation, and a client that invokes remote methods on the server.

Define the Remote Interface ([Link]):

import [Link];

import [Link];

public interface Calculator extends Remote {

int add(int a, int b) throws RemoteException;

Implement the Remote Interface ([Link]):

import [Link];

import [Link];

public class CalculatorImpl extends UnicastRemoteObject implements Calculator {

public CalculatorImpl() throws RemoteException {

super();

public int add(int a, int b) throws RemoteException {

return a + b;

Create the Server ([Link]):


import [Link];

import [Link];

public class CalculatorServer {

public static void main(String[] args) {

try {

// Create and export the remote object

Calculator calculator = new CalculatorImpl();

// Create the RMI registry (on port 1099)

[Link](1099);

// Bind the remote object to the registry with a name "CalculatorService"

[Link]("CalculatorService", calculator);

[Link]("Server is ready...");

} catch (Exception e) {

[Link]();

Create the Client ([Link]):

import [Link];

public class CalculatorClient {

public static void main(String[] args) {

try {

// Look up the remote object by its registered name

Calculator calculator = (Calculator) [Link]("rmi://localhost/CalculatorService");

// Invoke the remote method


int result = [Link](5, 7);

// Display the result

[Link]("Result from server: " + result);

} catch (Exception e) {

[Link]();

The server will print "Server is ready..." indicating that it's running and ready to accept remote method
invocations.

The client will print "Result from server: 12" indicating the result of the addition operation performed on
the remote server.

In this example, the client invokes the add method on the remote Calculator object, and the server
performs the addition operation and returns the result to the client. The RMI framework handles the
communication details, allowing the client and server to interact seamlessly across JVMs.

Distributed Application Architecture

Distributed Application Architecture involves designing applications that are distributed across multiple
machines. Components of the application are deployed on different servers, communicating over a
network.

Let's consider a simple example of a Distributed Application Architecture using a basic client-server
interaction. In this example, we'll create a server that accepts messages from clients and broadcasts
those messages to all connected clients.

Server:

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];
public class ChatServer {

private List<ClientHandler> clients = new ArrayList<>();

public void start(int port) {

try (ServerSocket serverSocket = new ServerSocket(port)) {

[Link]("Chat Server is running on port " + port);

while (true) {

Socket clientSocket = [Link]();

[Link]("New client connected: " + clientSocket);

// Create a new thread to handle the client

ClientHandler clientHandler = new ClientHandler(clientSocket, this);

[Link](clientHandler);

new Thread(clientHandler).start();

} catch (IOException e) {

[Link]();

public void broadcastMessage(String message, ClientHandler sender) {

for (ClientHandler client : clients) {

if (client != sender) {

[Link]([Link]() + ": " + message);

public static void main(String[] args) {


ChatServer server = new ChatServer();

[Link](8888);

Client:

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class ChatClient {

private String serverHost;

private int serverPort;

public ChatClient(String serverHost, int serverPort) {

[Link] = serverHost;

[Link] = serverPort;

public void start() {

try (Socket socket = new Socket(serverHost, serverPort);

BufferedReader reader = new BufferedReader(new


InputStreamReader([Link]()));

PrintWriter writer = new PrintWriter([Link](), true);

BufferedReader consoleReader = new BufferedReader(new InputStreamReader([Link]))) {

[Link]("Connected to Chat Server. Enter your name:");


String clientName = [Link]();

[Link](clientName);

new Thread(() -> {

String message;

try {

while ((message = [Link]()) != null) {

[Link](message);

} catch (IOException e) {

[Link]();

}).start();

String userInput;

while ((userInput = [Link]()) != null) {

[Link](userInput);

} catch (IOException e) {

[Link]();

public static void main(String[] args) {

ChatClient client = new ChatClient("localhost", 8888);

[Link]();

}
Client Handler (Server-Side):

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class ClientHandler implements Runnable {

private Socket clientSocket;

private ChatServer chatServer;

private BufferedReader reader;

private PrintWriter writer;

private String clientName;

public ClientHandler(Socket clientSocket, ChatServer chatServer) {

[Link] = clientSocket;

[Link] = chatServer;

try {

reader = new BufferedReader(new InputStreamReader([Link]()));

writer = new PrintWriter([Link](), true);

} catch (IOException e) {

[Link]();

public String getClientName() {


return clientName;

public void sendMessage(String message) {

[Link](message);

@Override

public void run() {

try {

// Read the client's name

clientName = [Link]();

[Link](clientName + " has joined the chat.");

// Continuously read messages from the client and broadcast them to others

String message;

while ((message = [Link]()) != null) {

[Link](message, this);

} catch (IOException e) {

[Link](clientName + " has left the chat.");

[Link](clientName + " has left the chat.", this);

[Link](this);

The ChatServer listens for incoming connections on a specified port.

When a client connects, the server creates a ClientHandler thread to handle communication with that
client.
Clients send their names to the server when they join.

Messages sent by clients are broadcasted to all other connected clients by the server.

The ChatClient connects to the server, enters a name, and can send and receive messages.

This example represents a simple chat application with a distributed architecture, where the server
manages communication between multiple connected clients.

Creating Stubs and Skeletons

Stubs

A stub is a client-side proxy for the remote object. When a client wants to invoke a method on a remote
object, it interacts with the stub. The client-side stub marshals the method parameters and sends them
over the network to the server.

Generation:

Stubs are usually generated automatically during the compilation or runtime process in modern Java
RMI.

In earlier versions of Java RMI (prior to Java 5), the rmic compiler was used to generate stub classes
explicitly. However, modern versions often use dynamic proxies or other mechanisms.

Responsibilities:

Marshalling: Stubs are responsible for converting the parameters and return values of remote method
calls into a format suitable for transmission over the network.

Network Communication: Stubs handle the communication with the remote server, transmitting the
marshaled data and receiving the results.

Skeletons

A skeleton is a server-side component responsible for receiving incoming remote method invocations,
unmarshalling parameters, invoking the actual implementation of the remote object, and marshalling
the results back to the client. The skeleton acts as a bridge between the network communication and
the actual remote object implementation.

Generation:

Similar to stubs, skeletons were generated explicitly in earlier versions of Java RMI using the rmic
compiler. In modern versions, their generation is often handled automatically.

Responsibilities:
Unmarshalling: Skeletons are responsible for converting the marshaled data received from the client
into parameters suitable for invoking the actual remote object's method.

Invoking Methods: Skeletons invoke the actual methods on the remote object, passing the unmarshalled
parameters.

Marshalling Results: After the method invocation, skeletons convert the results into a format suitable
for transmission back to the client.

In Java RMI, stubs and skeletons are generated automatically using the rmic tool or by using dynamic
stubs. The stub is a client-side proxy for the remote object, and the skeleton is a server-side object
responsible for dispatching remote method calls to the actual remote object.

Example:

Assume you have a remote interface MyRemoteInterface:

import [Link];

import [Link];

public interface MyRemoteInterface extends Remote {

String sayHello() throws RemoteException;

To generate stubs and skeletons:

# Compile the interface

javac [Link]

# Generate stub and skeleton

rmic MyRemoteInterface

Defining Remote Object

A remote object is an object whose methods can be invoked remotely. It must implement a remote
interface and extend [Link] or [Link] to enable
remote method invocation.

Example:

import [Link];
import [Link];

public class MyRemoteObject extends UnicastRemoteObject implements MyRemoteInterface {

protected MyRemoteObject() throws RemoteException {

super();

@Override

public String sayHello() throws RemoteException {

return "Hello from the remote object!";

Remote Object Activation

Remote object activation is a mechanism in Java RMI that allows remote objects to be activated on-
demand, rather than being pre-activated at startup. Activation is achieved using the
[Link] class.

Example:

import [Link];

import [Link];

import [Link];

import [Link];

public class MyActivatableObject extends Activatable implements MyRemoteInterface {

protected MyActivatableObject(ActivationID id, int port) throws RemoteException,


ActivationException {

super(id, port);

@Override

public String sayHello() throws RemoteException {

return "Hello from the activatable remote object!";


}

id: This is the activation identifier (ActivationID). The activation system assigns a unique identifier to
each activatable object. The activation identifier represents the specific instance of the activatable
object. It is typically obtained from the activation system when the object is activated.

port: This is an integer representing the TCP port number on which the activatable object's remote
object implementation will be exported. The activation system uses this port to listen for incoming calls
to activate the object.

Object Serialization

Serialization is the process of converting an object into a byte stream, and deserialization is the process
of reconstructing the object from the byte stream. In Java, the [Link] interface is used to
mark a class as serializable. Any class that implements this interface can be serialized.

When you use Java RMI, the objects passed between the client and server need to be serialized. This is
because the method parameters and return values are transmitted over the network, and the objects
must be converted to a format that can be easily transmitted and reconstructed.

Example:

Let's create a simple example to demonstrate object serialization in Java RMI. We'll create a remote
interface, a remote object, a server, and a client.

Remote Interface ([Link]):

import [Link];

import [Link];

public interface MyRemoteInterface extends Remote {

String sayHello() throws RemoteException;

Remote Object ([Link]):

import [Link];

import [Link];

public class MyRemoteObject extends UnicastRemoteObject implements MyRemoteInterface {


private static final long serialVersionUID = 1L;

protected MyRemoteObject() throws RemoteException {

super();

@Override

public String sayHello() throws RemoteException {

return "Hello from the remote object!";

Server ([Link]):

import [Link];

import [Link];

public class MyServer {

public static void main(String[] args) {

try {

// Create and export the remote object

MyRemoteInterface remoteObject = new MyRemoteObject();

// Create the registry and bind the remote object

[Link](1099);

[Link]("MyRemoteObject", remoteObject);

[Link]("Server is ready.");

} catch (Exception e) {

[Link]();

}
}

Client ([Link]):

import [Link];

public class MyClient {

public static void main(String[] args) {

try {

// Lookup the remote object

MyRemoteInterface remoteObject = (MyRemoteInterface)


[Link]("rmi://localhost/MyRemoteObject");

// Invoke a remote method

String result = [Link]();

[Link]("Response from server: " + result);

} catch (Exception e) {

[Link]();

In this example:

MyRemoteInterface is the remote interface that extends Remote and declares a method sayHello.

MyRemoteObject is the remote object that implements MyRemoteInterface. It extends


UnicastRemoteObject and provides the implementation for the remote method.

MyServer creates and exports the remote object, creates the RMI registry, and binds the remote object
to a name.

MyClient looks up the remote object by its name and invokes the sayHello method.

When the MyRemoteObject is passed between the client and server, the object serialization and
deserialization take place automatically, allowing the method invocation to occur across different JVMs.
JavaSpaces

JavaSpaces" refers to a distributed shared memory model for communication and coordination between
distributed objects. JavaSpaces is part of the JavaSpaces Technology, which is a specification provided by
Sun Microsystems (now part of Oracle).

Key concepts of JavaSpaces include:

Space:

A space is a distributed shared memory repository where objects, known as entries, can be stored and
retrieved.

It serves as a communication medium for distributed components in a network.

Entry:

An entry is a Java object that is stored in a space.

Entries typically represent data or messages that are shared between different components.

Tuple Space Model:

JavaSpaces follows the tuple space model, which is a model for distributed communication and
coordination.

In this model, components communicate by reading and writing entries to and from a shared space.

Operations:

The basic operations supported by JavaSpaces include write (to write an entry to the space) and read (to
read an entry from the space).

Entries can be matched using templates, allowing for selective retrieval based on specific criteria.

JavaSpaces provides a mechanism for loosely coupled components to communicate and coordinate in a
distributed environment. It enables components to share data and synchronize their activities without
requiring direct method invocation.

In this example, we'll create a basic chat application where clients can post messages to a shared space,
and other clients can read those messages from the space.

import [Link];

import [Link];

import [Link];

import [Link];
// Entry class representing a chat message

class ChatMessage implements Entry {

public String sender;

public String message;

public ChatMessage() {} // Empty constructor for template matching

public ChatMessage(String sender, String message) {

[Link] = sender;

[Link] = message;

public class ChatClient {

public static void main(String[] args) {

try {

// Get a reference to the JavaSpace

JavaSpace space = (JavaSpace) [Link](null, [Link]);

// Write a chat message to the space

ChatMessage chatMessage = new ChatMessage("User1", "Hello, JavaSpaces!");

[Link](chatMessage, null, [Link]);

// Read a chat message from the space

ChatMessage template = new ChatMessage();

ChatMessage receivedMessage = (ChatMessage) [Link](template, null, Long.MAX_VALUE);

// Print the received message

[Link]("Received message from " + [Link] + ": " +


[Link]);

} catch (Exception e) {

[Link]();
}

In this example:

The ChatMessage class implements the Entry interface, representing a chat message with a sender and a
message.

The ChatClient class uses the Jini API to obtain a reference to the JavaSpace.

It writes a chat message to the space using the write method.

It then reads a chat message from the space using the take method.
Unit 3

Database

Database refers to a structured collection of data that can be easily accessed, managed, and updated.
Java provides a rich set of APIs and libraries for working with databases. The most common types of
databases used with Java applications are relational databases, and JDBC (Java Database Connectivity) is
the standard API for connecting Java applications to relational databases.

Here are the key components and concepts related to databases in Java:

 JDBC (Java Database Connectivity): JDBC is a Java API that enables Java applications to interact
with databases. It provides a standard interface for connecting to relational databases,
executing SQL queries, and retrieving results. JDBC drivers are used to establish a connection
between a Java application and a specific database management system (DBMS).
 Java Database Libraries/Frameworks: In addition to JDBC, there are higher-level libraries and
frameworks that simplify database interactions in Java. Some popular ones include Hibernate,
Spring Data JPA, and MyBatis. These frameworks often provide object-relational mapping (ORM)
capabilities, making it easier to work with databases using Java objects.
 Object-Relational Mapping (ORM): ORM frameworks like Hibernate allow developers to work
with Java objects directly, and the framework handles the mapping of these objects to database
tables. This abstraction simplifies database interactions and reduces the need for writing raw
SQL queries.
 NoSQL Databases: While JDBC and traditional databases are prevalent, Java also supports
interaction with NoSQL databases such as MongoDB, Cassandra, and Couchbase. Specific
libraries or drivers are used to connect Java applications to these types of databases.

JDBC Principles

JDBC (Java Database Connectivity) is a Java API that provides a standard interface for connecting Java
applications to relational databases. The principles of JDBC are foundational concepts and practices that
developers follow when using JDBC for database access. Here are the key principles of JDBC:

1. Loading JDBC Driver:

JDBC drivers are platform-specific implementations that enable Java applications to communicate with a
particular database management system (DBMS). The [Link]() method is used to dynamically
load the JDBC driver class into memory.

[Link]("[Link]");

2. Establishing Connection:
Establishing a connection involves creating a link between the Java application and the database. The
[Link]() method is used to create a Connection object by providing the database
URL, username, and password.

Connection connection = [Link]("jdbc:mysql://localhost:3306/mydatabase",


"username", "password");

3. Creating Statement:

Statements in JDBC are used to execute SQL queries against the database. There are different types of
statements, such as Statement and PreparedStatement. The createStatement() method is used to
instantiate a Statement object.

Statement statement = [Link]();

4. Executing Queries:

JDBC allows the execution of SQL queries, which can be SELECT statements for fetching data, or INSERT,
UPDATE, DELETE statements for modifying data. The executeQuery() method is used for SELECT queries,
and executeUpdate() is used for other types of queries.

ResultSet resultSet = [Link]("SELECT * FROM mytable");

5. Handling Results:

Results obtained from executing a SELECT query are stored in a ResultSet. The next() method of
ResultSet is used to iterate through the results, and various methods like getString() retrieve data from
the result set based on the column name.

while ([Link]()) {

[Link]([Link]("column_name"));

6. Closing Resources:

It's crucial to close JDBC resources (Connection, Statement, ResultSet) after their use to release
database-related resources and prevent memory leaks. This is typically done using the close() method.

[Link]();

[Link]();

[Link]();

Database Access
Database access refers to the ability of a software application or system to interact with a database,
typically for storing, retrieving, updating, or deleting data. Database access is a crucial aspect of many
software applications, enabling them to persistently store and manage information. In the context of
Java programming, JDBC (Java Database Connectivity) is a common technology used for database
access.

Here are key components and concepts related to database access:

Connection Establishment:

Establishing a connection between the application and the database is the first step in database access.
This involves providing necessary connection details such as the database URL, username, and
password.

Data Querying:

Applications use SQL (Structured Query Language) or a similar query language to interact with the
database. Common operations include selecting data with SELECT queries, inserting new records with
INSERT queries, updating existing records with UPDATE queries, and deleting records with DELETE
queries.

Transaction Management:

Database access often involves multiple related operations that need to be treated as a single unit,
known as a transaction. Transaction management ensures that all operations within a transaction are
either completed successfully or rolled back if an error occurs.

Error Handling:

Robust database access includes mechanisms for handling errors and exceptions. This ensures that the
application can respond appropriately to issues such as connection failures, query errors, or other
database-related problems.

Resource Management:

Resources such as database connections, statements, and result sets need to be properly managed and
released after use. This helps prevent resource leaks and ensures efficient use of system resources.

Connection Pooling:

To improve performance and reduce overhead, connection pooling is often employed. Connection
pooling involves reusing existing database connections instead of creating a new connection for each
database operation, which can be resource-intensive.

In Java, JDBC is a standard API that provides a set of classes and interfaces for database access.
Developers use JDBC to connect Java applications to relational databases, execute SQL queries, and
handle the results. Additionally, there are higher-level frameworks and libraries in the Java ecosystem,
such as Hibernate and Spring Data JPA, that provide more abstracted and feature-rich approaches to
database access, often using Object-Relational Mapping (ORM) techniques.

Example

import [Link].*;

public class DatabaseAccessExample {

public static void main(String[] args) {

// JDBC URL, username, and password of MySQL server

String url = "jdbc:mysql://localhost:3306/mydatabase";

String username = "your_username";

String password = "your_password";

// JDBC variables for opening, closing, and managing database connections

Connection connection = null;

Statement statement = null;

ResultSet resultSet = null;

try {

// Step 1: Load the JDBC driver

[Link]("[Link]");

// Step 2: Establish a connection to the database

connection = [Link](url, username, password);

// Step 3: Create a statement

statement = [Link]();

// Step 4: Execute a SELECT query

String query = "SELECT * FROM mytable";

resultSet = [Link](query);

// Step 5: Process the results

while ([Link]()) {
// Retrieve data from the result set

int id = [Link]("id");

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

int age = [Link]("age");

// Print the data

[Link]("ID: " + id + ", Name: " + name + ", Age: " + age);

} catch (Exception e) {

[Link]();

} finally {

// Step 6: Close resources in a finally block to ensure they are always closed

try {

if (resultSet != null) [Link]();

if (statement != null) [Link]();

if (connection != null) [Link]();

} catch (Exception e) {

[Link]();

Interacting with the Database – Search

Interacting with the database in Java refers to the process of connecting a Java application to a
database, executing SQL queries, and manipulating data. This interaction is often facilitated through the
use of the JDBC (Java Database Connectivity) API, which provides a standard interface for Java
applications to interact with relational databases.
Database Search Example - Searching for Data:

import [Link];

import [Link];

import [Link];

import [Link];

public class DatabaseSearchExample {

public static void main(String[] args) {

try {

// Load the JDBC driver

[Link]("[Link]");

// Establish a connection

Connection connection = [Link](

"jdbc:mysql://localhost:3306/mydatabase", "username", "password"

);

// Create a statement

Statement statement = [Link]();

// Execute a search query

ResultSet resultSet = [Link]("SELECT * FROM mytable WHERE column_name =


'value'");

// Process the search results

while ([Link]()) {

[Link]([Link]("column_name"));

// Close resources

[Link]();

[Link]();
[Link]();

} catch (ClassNotFoundException | SQLException e) {

[Link]();

This example demonstrates the process of searching for data in a database. After loading the JDBC
driver and establishing a connection, a Statement object is created. The executeQuery() method is used
to perform a SELECT query, and the ResultSet obtained is iterated to retrieve and process the search
results. The SQL query specifies the search condition (e.g., WHERE column_name = 'value').

Creating multimedia databases

Creating multimedia databases using JDBC involves storing and retrieving multimedia data, such as
images, audio, or video, in a database.

Step 1: Create Database Table

Assuming you have a MySQL database named "multimedia_db," create a table to store multimedia data:

CREATE TABLE multimedia_data ( id INT PRIMARY KEY AUTO_INCREMENT, data BLOB);

Step 2: Storing Multimedia Data

import [Link];

import [Link];

import [Link];

import [Link];

public class StoreMultimediaData {

public static void main(String[] args) {

// JDBC URL, username, and password of MySQL server

String url = "jdbc:mysql://localhost:3306/multimedia_db";

String username = "your_username";

String password = "your_password";


// JDBC variables for opening, closing, and managing database connections

Connection connection = null;

PreparedStatement preparedStatement = null;

try {

// Step 1: Load the JDBC driver

[Link]("[Link]");

// Step 2: Establish a connection to the database

connection = [Link](url, username, password);

// Step 3: Prepare a statement for inserting multimedia data

String insertQuery = "INSERT INTO multimedia_data (data) VALUES (?)";

preparedStatement = [Link](insertQuery);

// Step 4: Read multimedia data from a file (e.g., image file)

FileInputStream fileInputStream = new FileInputStream("path/to/your/[Link]");

// Step 5: Set the multimedia data as a parameter in the prepared statement

[Link](1, fileInputStream);

// Step 6: Execute the insert query

[Link]();

[Link]("Multimedia data stored successfully!");

} catch (Exception e) {

[Link]();

} finally {

// Close resources in a finally block to ensure they are always closed

try {

if (preparedStatement != null) [Link]();

if (connection != null) [Link]();


} catch (Exception e) {

[Link]();

Step 3: Retrieving Multimedia Data

import [Link].*;

import [Link].*;

public class RetrieveMultimediaData {

public static void main(String[] args) {

String url = "jdbc:mysql://localhost:3306/multimedia_db";

String username = "your_username";

String password = "your_password";

try {

[Link]("[Link]");

Connection connection = [Link](url, username, password);

String retrieveQuery = "SELECT data FROM multimedia_data WHERE id = ?";

PreparedStatement preparedStatement = [Link](retrieveQuery);

int multimediaIdToRetrieve = 1;

[Link](1, multimediaIdToRetrieve);

ResultSet resultSet = [Link]();

if ([Link]()) {

InputStream inputStream = [Link]("data");

FileOutputStream fileOutputStream = new


FileOutputStream("path/to/your/retrieved_image.jpg");
byte[] buffer = new byte[1024];

int bytesRead;

while ((bytesRead = [Link](buffer)) != -1) {

[Link](buffer, 0, bytesRead);

[Link]("Multimedia data retrieved and saved successfully!");

} catch (Exception e) {

[Link]();

} finally {

try {

if (resultSet != null) [Link]();

if (preparedStatement != null) [Link]();

if (connection != null) [Link]();

} catch (Exception e) {

[Link]();

In these examples:

The multimedia_data table has a column named data of type BLOB (Binary Large Object) to store
multimedia data. The first example (StoreMultimediaData) demonstrates how to store multimedia data
in the database. It uses a FileInputStream to read the data from an image file and a PreparedStatement
to insert the data into the database.
The second example (RetrieveMultimediaData) shows how to retrieve multimedia data from the
database. It uses a PreparedStatement to execute a SELECT query, retrieves the data as an InputStream
from the ResultSet, and writes it to a file using a FileOutputStream.

Database support in web applications

Database support in web applications using JDBC (Java Database Connectivity) involves establishing a
connection to a database from a Java web application, executing SQL queries, and processing the
results. Below is a simple example in Java that demonstrates how to use JDBC to interact with a
database in a web application.

import [Link].*;

public class Main {

// JDBC URL, username, and password of MySQL server

private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydatabase";

private static final String USERNAME = "username";

private static final String PASSWORD = "password";

public static void main(String[] args) {

try {

// Establishing a connection to the database

Connection connection = [Link](JDBC_URL, USERNAME, PASSWORD);

// Example: retrieving data from the database

String sql = "SELECT * FROM users";

Statement statement = [Link]();

ResultSet resultSet = [Link](sql);

// Processing the result set

while ([Link]()) {

int id = [Link]("id");

String username = [Link]("username");

String password = [Link]("password");


// Displaying the retrieved data

[Link]("ID: " + id + ", Username: " + username + ", Password: " + password);

// Closing resources

[Link]();

[Link]();

[Link]();

} catch (SQLException e) {

[Link]();

In this example:

JDBC_URL, USERNAME, and PASSWORD are placeholders for your database URL, username, and
password respectively.

We establish a connection to the MySQL database using [Link]().

We execute a SELECT query to retrieve data from the users table.

We process the ResultSet obtained from the query and print the results.

Finally, we close the resources (ResultSet, Statement, and Connection) in the finally block to release
database resources.
Unit 4
Java Servlet

Java Servlets are server-side programs written in Java that run on a web server. They handle client
requests and generate dynamic responses, allowing Java developers to create dynamic web
applications. Servlets are a key component of the Java Enterprise Edition (Java EE) platform, which
provides a robust framework for building scalable, reliable, and secure web applications.

A Java Servlet is a Java class that extends the [Link] interface or one of its subinterfaces.
Servlets are typically deployed in a web container, such as Apache Tomcat or Jetty, which manages the
lifecycle of servlets and handles incoming HTTP requests.

Here's a simple example of a Java Servlet that responds to HTTP GET requests by displaying a basic
HTML page:

import [Link].*;

import [Link].*;

import [Link].*;

public class HelloServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html");

PrintWriter out = [Link]();

[Link]("<html>");

[Link]("<head><title>Hello Servlet</title></head>");

[Link]("<body>");

[Link]("<h1>Hello, world!</h1>");

[Link]("</body></html>");

In this example:

We create a class HelloServlet that extends HttpServlet.

We override the doGet() method to handle HTTP GET requests.


Inside doGet(), we set the content type of the response to text/html using [Link]().

We obtain a PrintWriter object from the response using [Link]() to send HTML content
back to the client.

We use the println() method to write HTML content to the response.

To deploy this servlet, you would typically package it into a WAR (Web Application Archive) file along
with the necessary configuration files ([Link] or annotations), and then deploy it to a web container
like Tomcat.

Java Servlet and CGI programming in Java

CGI programming involves creating scripts or programs that run on a web server to generate dynamic
content in response to client requests. Unlike Java Servlets, which are platform-independent and run
within a web container, CGI programs are typically separate executable files that are executed by the
web server when a request is made. While CGI programs can be written in various languages, including
Java, the use of CGI in Java is less common compared to servlets due to performance and other
advantages offered by servlet technology.

Example:

Suppose you want to create a simple CGI program in Java to add two numbers:

import [Link].*;

public class AddNumbersCGI {

public static void main(String[] args) throws IOException {

BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));

[Link]("Content-type: text/html\n");

[Link]("<html>");

[Link]("<head><title>Add Numbers</title></head>");

[Link]("<body>");

int num1 = [Link]([Link]("QUERY_STRING").split("=")[1]);

int num2 = [Link]([Link]());

int sum = num1 + num2;

[Link]("<h1>Sum: " + sum + "</h1>");

[Link]("</body></html>");
}

In this example, we're reading the environment variable QUERY_STRING to get the input parameters
passed from the web server. We expect the parameters to be in the format
num1=value1&num2=value2. We then read the second number from standard input. After adding the
numbers, we print the result as HTML output.

However, using CGI for Java is generally not recommended due to various issues such as performance
overhead, security concerns, and difficulty in managing stateful interactions. Servlets provide a more
efficient and scalable solution for handling dynamic content in Java-based web applications.

Anatomy of a Java Servlet

The anatomy of a Java Servlet refers to the essential components and structure that make up a servlet.

 Import required packages ([Link].*, [Link].*).


 Extend HttpServlet class.
 Override doGet() or doPost() method to handle HTTP GET or POST requests.
 Set the content type of the response.
 Get a PrintWriter from the response object to write HTML content.
 Close the PrintWriter.

Example

import [Link].*;

import [Link].*;

import [Link].*;

public class HelloServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

[Link]("text/html");

PrintWriter out = [Link]();

[Link]("<html><body>");

[Link]("<h1>Hello, World!</h1>");

[Link]("</body></html>");

[Link]();
}

Reading data from a client

Reading data from a client in the context of Java Servlets involves extracting information that the client
(usually a web browser) sends to the server as part of an HTTP request. This data can include
parameters sent through the URL (for GET requests) or through the request body (for POST requests), as
well as headers containing additional information about the request.

Here's how you can read data from a client in a servlet, along with a simple example:

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Reading data from the URL parameters

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

String age = [Link]("age");

// Displaying the received data

[Link]("text/html");

PrintWriter out = [Link]();

[Link]("<html><body>");

[Link]("<h1>Hello, " + name + "!</h1>");

[Link]("<p>Your age is: " + age + "</p>");

[Link]("</body></html>");
[Link]();

In this example, we're using the doGet() method to handle HTTP GET requests. Inside this method:

We use the HttpServletRequest object (request) to retrieve parameters sent in the URL. For example, if
the URL is [Link] then name and age are parameters
passed with values "John" and "30" respectively.

We then use these parameters to generate a response. In this case, we're simply printing a personalized
greeting along with the received age.

Finally, we set the content type of the response to "text/html" and use a PrintWriter to write HTML
content back to the client.

When a client (e.g., a web browser) makes a request to this servlet with URL parameters like
name=John&age=30, the servlet reads these parameters and generates a response accordingly,
resulting in a webpage displaying a greeting message and the provided age.

Reading HTTP request header

Reading HTTP request headers in a Java Servlet involves accessing the metadata sent by the client
(usually a web browser) as part of the HTTP request. These headers contain additional information
about the request, such as the user agent, content type, and cookies.

Here's how you can read HTTP request headers in a servlet,

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Reading the User-Agent header


String userAgent = [Link]("User-Agent");

// Reading other headers (example: Accept-Language)

String acceptLanguage = [Link]("Accept-Language");

// Displaying the received headers

[Link]("text/html");

PrintWriter out = [Link]();

[Link]("<html><body>");

[Link]("<h1>User-Agent: " + userAgent + "</h1>");

[Link]("<p>Accept-Language: " + acceptLanguage + "</p>");

[Link]("</body></html>");

[Link]();

We use the HttpServletRequest object (request) to retrieve specific headers sent by the client. In this
case, we're reading the "User-Agent" header, which typically contains information about the client's
browser and operating system.

String userAgent = [Link]("User-Agent");

We can also read other headers in a similar manner. For example, we're reading the "Accept-Language"
header, which specifies the preferred language of the client.

String acceptLanguage = [Link]("Accept-Language");

We then use these header values to generate a response. In this case, we're simply printing the received
headers back to the client.

Finally, we set the content type of the response to "text/html" and use a PrintWriter to write HTML
content back to the client.

When a client (e.g., a web browser) makes a request to this servlet, the servlet reads the specified
headers from the HTTP request and generates a response displaying these headers. This allows you to
access and utilize additional information sent by the client in the request.
Sending data to a client and writing the HTTP response header

Sending data to a client and writing the HTTP response header in a Java Servlet involves generating a
response that is sent back to the client (usually a web browser) after processing a request. This response
typically includes data and metadata such as the content type, status code, and cookies.

Here's how you can send data to a client and write the HTTP response header in a servlet, along with a
simple example:

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Set the content type of the response

[Link]("text/html");

// Get a PrintWriter object to write HTML content

PrintWriter out = [Link]();

// Write the HTTP response header (optional)

[Link](HttpServletResponse.SC_OK);

// Write data to the client

[Link]("<html><body>");

[Link]("<h1>Hello, World!</h1>");

[Link]("<p>This is a simple servlet example.</p>");

[Link]("</body></html>");

// Close the PrintWriter


[Link]();

In this example, we're using the doGet() method to handle HTTP GET requests. Inside this method:

We use the HttpServletResponse object (response) to set the content type of the response. Here,
we're setting it to "text/html" to indicate that the response will contain HTML content.

[Link]("text/html");

We then obtain a PrintWriter object (out) from the HttpServletResponse to write the HTML content
to the response.

PrintWriter out = [Link]();

Optionally, we can set the status code of the response using the setStatus() method. In this case,
we're setting it to HttpServletResponse.SC_OK, indicating that the request was successful.

[Link](HttpServletResponse.SC_OK);

We then use the PrintWriter to write HTML content to the response, which will be sent back to the
client.

Finally, we close the PrintWriter to release any resources associated with it.

When a client (e.g., a web browser) makes a request to this servlet, the servlet generates a
response with the specified content type and status code, and sends the HTML content back to
the client. The client then renders the HTML content in the browser for the user to view.

Cookies

A cookie is a small piece of data that a website stores on a user's computer or mobile device. Cookies
are sent from a website to the user's browser and are then stored on the user's device. They are
commonly used to remember information about the user, such as login credentials, site preferences,
shopping cart contents, and browsing activity.

Cookies serve several purposes, including:

Authentication: Cookies can be used to remember login credentials, allowing users to stay logged in
across different pages or visits to a website.

Session Management: Session cookies are temporary and are used to manage user sessions. They allow
websites to recognize users as they navigate between pages during a single browsing session.
Personalization: Cookies can store user preferences and settings, allowing websites to customize
content and layout based on individual user preferences.

Tracking: Some cookies are used for tracking user behavior across websites, enabling advertisers and
marketers to deliver targeted ads and analyze user interactions.

Analytics: Cookies can be used to collect data on how users interact with a website, helping website
owners understand usage patterns and improve their services.

Example

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class MyServlet extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws


ServletException, IOException {

// Creating a new cookie

Cookie cookie = new Cookie("username", "John");

// Adding the cookie to the response

[Link](cookie);

// Displaying a message to the client

[Link]("text/html");

PrintWriter out = [Link]();

[Link]("<html><body>");

[Link]("<h1>Cookie Set</h1>");

[Link]("<p>A cookie named 'username' with value 'John' has been set.</p>");
[Link]("</body></html>");

[Link]();

In this example, we're using the doGet() method to handle HTTP GET requests. Inside this method:

We create a new Cookie object representing the cookie we want to set. Here, we're creating a cookie
named "username" with the value "John".

Cookie cookie = new Cookie("username", "John");

We add this cookie to the response using the addCookie() method of the HttpServletResponse object.

[Link](cookie);

We then generate a response to send back to the client. In this case, we're simply displaying a message
to indicate that the cookie has been set.

JSP Overview

JavaServer Pages (JSP) is a technology that enables developers to create dynamic web pages by
combining Java code with HTML or XML markup. It simplifies the process of creating dynamic content
for web applications by allowing developers to embed Java code directly into web pages. When a JSP
page is requested, it is compiled into a servlet by the servlet container, and then the servlet is executed
to generate the dynamic content.

Dynamic Content Generation: JSP allows developers to embed Java code directly within HTML or XML
pages. This means that dynamic content, such as database queries, user authentication, or business
logic, can be incorporated directly into the web page.

Easy Integration with Java: Since JSP pages are essentially a mix of Java and HTML/XML, developers
with Java expertise find it easy to work with. They can use familiar Java constructs, libraries, and
frameworks within JSP pages to build complex web applications.

Separation of Concerns: JSP promotes a separation of concerns by allowing developers to separate


presentation logic (HTML markup) from application logic (Java code). This makes the code base more
maintainable and easier to understand.

Automatic Servlet Conversion: When a JSP page is requested by a client's browser, the servlet container
(e.g., Apache Tomcat) automatically translates the JSP page into a servlet. This servlet is then compiled
and executed to generate the dynamic content that is sent back to the client.
Built-in Tag Libraries: JSP provides built-in tag libraries, such as JSTL (JavaServer Pages Standard Tag
Library), which offer a set of custom tags for common tasks like iteration, conditionals, and formatting.
These tag libraries simplify the development process and promote code reuse.

Scalability and Performance: JSP pages can be compiled into servlets, which are highly optimized for
performance. This ensures that JSP-based web applications can scale to handle large volumes of traffic
efficiently.

JSP is a powerful technology for building dynamic and interactive web applications in Java. It combines
the strengths of Java for business logic with the flexibility of HTML/XML for creating user interfaces,
making it a popular choice for web development.

JSP tags

JSP tags are constructs within JSP documents that allow developers to perform various actions, control
flow, and interact with Java objects to generate dynamic content. There are several types of JSP tags,
including standard tags, directive tags, action tags, and custom tags. Let's discuss each type in detail:

Directive Tags: Directive tags are used to provide instructions to the JSP container about how to process
the page. There are three types of directive tags:

1. Page Directive: <%@ page attribute="value" %>: This tag is used to specify page-level attributes
such as language, contentType, import statements, session management, error handling, etc.
Example:
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
2. Include Directive: <%@ include file="filename" %>: This tag includes the contents of another file
during the translation phase.
Example:
<%@ include file="[Link]" %>
3. Taglib Directive: <%@ taglib uri="uri" prefix="prefix" %>: This tag declares a custom tag library
for use in the JSP page.
Example:
<%@ taglib uri="/WEB-INF/mytags" prefix="my" %>

<%@ taglib: This is the opening tag of the taglib directive. It indicates the start of the declaration
of a tag library.

uri="uri": The uri attribute specifies the URI (Uniform Resource Identifier) that identifies the
location of the tag library descriptor (TLD) file. The TLD file provides the necessary information
about the custom tags defined in the library.

prefix="prefix": The prefix attribute specifies the prefix that you will use to reference the custom
tags within your JSP page. This prefix is like a shorthand notation that allows you to differentiate
between standard JSP tags and custom tags.
%>: This is the closing tag of the taglib directive, indicating the end of the declaration.

Standard Tags: These are predefined tags provided by JSP for common tasks like data formatting,
looping, conditionals, etc. They are declared using the jsp: namespace.

Example:

<jsp:useBean id="user" class="[Link]" />

<jsp:setProperty name="user" property="name" value="John" />

 id: Specifies the name of the bean that will be used to reference it in the JSP page.
 class: Specifies the fully qualified class name of the JavaBean to be instantiated.
 name: Specifies the name of the bean to which the property will be set.
 property: Specifies the name of the property to set.
 value: Specifies the value to set for the property. Alternatively, you can use <jsp:attribute> to
set a value dynamically.

Expression Tags: Expression tags are used to evaluate Java expressions and output the result directly
into the HTML content.

Example:

<%= [Link]() %>

Scriptlet Tags: Scriptlet tags allow you to write Java code directly within the JSP page.

Example:

<%

int sum = 2 + 3;

[Link]("Sum: " + sum);

%>

Action Tags: Action tags are used to perform specific actions such as controlling the flow, including
content dynamically, iterating over collections, etc. Some commonly used action tags include:

<jsp:forward>: Forwards the request to another resource.

<jsp:include>: Includes content from another resource.

<jsp:param>: Defines parameters for the <jsp:forward> or <jsp:include> tags.

<jsp:useBean>: Instantiates and initializes a JavaBean.


<jsp:setProperty>: Sets properties of a JavaBean.

<jsp:getProperty>: Retrieves properties of a JavaBean.

Example:

<jsp:include page="[Link]" />

Custom Tags: Custom tags allow developers to define their own tags and reuse them across multiple JSP
pages. They are particularly useful for encapsulating complex logic or functionality into reusable
components.

Example:

<my:customTag attribute="value" />

These tags provide a powerful mechanism for building dynamic and modular web applications using
JavaServer Pages.

Components of a JSP page

JavaServer Pages (JSP) is a technology used to create dynamic web pages in Java. A JSP page consists of
several components that work together to generate dynamic content. Let's break down the components
of a JSP page with a simple example:

HTML Markup:

JSP pages can contain HTML markup to define the structure and layout of the web page.

HTML tags are used to create elements such as headers, paragraphs, forms, tables, etc.

Example:

<!DOCTYPE html>

<html>

<head>

<title>Simple JSP Example</title>

</head>

<body>

<h1>Welcome to My Website</h1>

<p>This is a simple JSP example.</p>


</body>

</html>

JSP Directives:

JSP directives provide instructions to the JSP container about how to process the page.

They are enclosed within <%@ %> tags.

Common directives include page, include, and taglib.

Example:

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

JSP Scriptlets:

JSP scriptlets are blocks of Java code embedded within <% %> tags.

They are used to perform server-side processing and generate dynamic content.

Example:

<%

String name = "John";

int age = 20;

%>

JSP Expressions:

JSP expressions are used to embed Java expressions within HTML content.

They are enclosed within <%= %> tags.

The result of the expression is converted to a string and inserted into the HTML output.

Example:

<p>Hello, <%= name %>! Your age is <%= age %> years old.</p>

JSP Declarations:

JSP declarations are used to declare variables and methods that can be used throughout the JSP page.

They are enclosed within <%! %> tags.


Declarations are typically placed at the beginning of the JSP page.

Example:

<%! int total = 0; %>

JSP Actions:

JSP actions are special XML-like tags that perform specific tasks.

They are used to include other files, control flow, handle exceptions, etc.

Common JSP actions include include, forward, useBean, setProperty, getProperty, etc.

Example:

<jsp:include page="[Link]" />

Comments:

JSP pages can contain comments for documentation purposes.

There are two types of comments in JSP: HTML comments (<!-- -->) and JSP comments (<%-- --%>).

Example:

<!-- This is an HTML comment -->

<%-- This is a JSP comment --%>

Here's a simple example of a JSP page that combines these components:

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

<!DOCTYPE html>

<html> <head>

<title>Simple JSP Example</title>

</head>

<body>

<h1>Welcome to My Website</h1>

<%

String name = "John";


int age = 20;

%>

<p>Hello, <%= name %>! Your age is <%= age %> years old.</p>

<%-- This is a JSP comment --%>

</body>

</html>

This JSP page includes HTML markup, JSP directives, scriptlets, expressions, and a JSP comment. It
dynamically generates a greeting message using Java variables name and age.

Expressions of JSP

In JavaServer Pages (JSP), expressions are used to insert dynamic content into the HTML output. They
allow you to embed Java expressions directly into the HTML markup. Expressions are evaluated at
runtime, and their results are converted to strings and inserted into the HTML output. Expressions are
enclosed within <%= %> tags.

Here's a breakdown of JSP expressions with a simple example:

Syntax:

JSP expressions are enclosed within <%= %> tags.

Inside the tags, you can write any valid Java expression. The result of the expression is converted to a
string and inserted into the HTML output.

Example:

Let's say you have a JSP page where you want to display the current date and time. You can use a JSP
expression to dynamically generate this content.

<!DOCTYPE html>

<html>

<head>

<title>Current Date and Time</title>

</head>

<body>

<h1>Current Date and Time</h1>


<p>The current date and time is: <%= new [Link]() %></p>

</body>

</html>

In this example:

<%= new [Link]() %> is a JSP expression.

It evaluates the expression new [Link]() to get the current date and time.

The result of the expression is converted to a string and inserted into the HTML output at the specified
location.

Characteristics:

Expressions are evaluated when the JSP page is executed on the server.

Expressions can include method calls, variables, arithmetic operations, etc.

Expressions cannot contain statements or semicolons. They are limited to single expressions.

Expressions automatically handle escaping, so you don't need to worry about HTML special characters.

Usage:

Expressions are commonly used to insert dynamic data such as variables, method results, or expressions
directly into HTML content.

They provide a concise way to generate dynamic content without the need for extensive scriptlet code.

Scriptlets

Scriptlets in JSP are blocks of Java code enclosed within <% %> tags. They allow you to embed Java code
directly into your JSP page for server-side processing. Scriptlets are executed when the JSP page is
translated into a servlet, and the resulting servlet contains the Java code from the scriptlets.

Here's an explanation of scriptlets in JSP with a simple example:

Syntax:

Scriptlets are enclosed within <% %> tags.

Inside the tags, you can write any valid Java code, including variable declarations, method calls, loops,
conditionals, etc.

Example:
Let's say you want to display a greeting message based on the time of day (morning, afternoon, or
evening). You can use a scriptlet to determine the time and generate the appropriate message.

<!DOCTYPE html>

<html>

<head>

<title>Greeting Message</title>

</head>

<body>

<h1>Greeting Message</h1>

<%

int hour = [Link]().getHour();

String greeting;

if (hour < 12) {

greeting = "Good morning";

} else if (hour < 18) {

greeting = "Good afternoon";

} else {

greeting = "Good evening";

%>

<p><%= greeting %>, welcome to our website!</p>

</body>

</html>

In this example:

<% %> is a scriptlet tag.

Inside the scriptlet, we declare a variable hour to store the current hour of the day.
We use the [Link]().getHour() method to get the current hour.

Based on the value of hour, we set the greeting variable to the appropriate message.

The greeting variable is then used in a JSP expression <%= greeting %> to display the greeting message in
the HTML output.

Characteristics:

 Scriptlets allow you to mix Java code with HTML markup to create dynamic web pages.
 They are executed on the server-side when the JSP page is translated into a servlet.
 Scriptlets can contain any valid Java code, including variable declarations, method calls, control
structures, etc.
 Scriptlets can make your JSP page less readable and maintainable if used excessively. It's
recommended to use them sparingly and favor JSP expressions, directives, and custom tags for
better separation of concerns.

Directives

In JavaServer Pages (JSP), directives provide instructions to the JSP container about how to process the
page. Directives are special commands that are processed when the JSP page is translated into a servlet.
There are three types of directives in JSP: page, include, and taglib.

Here's an explanation of directives in JSP with a simple example:

Page Directive:

The page directive provides instructions specific to the JSP page itself, such as language, content type,
and other settings.

It is used to define various attributes for the JSP page.

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

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

In this example:

<%@ page %> is the page directive.

language="java" specifies the programming language used in the JSP page (Java).

contentType="text/html; charset=UTF-8" sets the content type of the page to HTML with UTF-8
encoding.

pageEncoding="UTF-8" specifies the character encoding of the page.

Include Directive:
The include directive is used to include the content of another file (such as another JSP file or a text file)
into the current JSP page during translation.

It is useful for reusing common code across multiple pages.

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

<%@ include file="[Link]" %>

In this example:

<%@ include %> is the include directive.

file="[Link]" specifies the file to include ([Link]) relative to the current JSP page.

Taglib Directive:

The taglib directive is used to define and import custom tag libraries into the JSP page.

It allows you to use custom tags defined in external tag libraries within your JSP page.

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

<%@ taglib uri="[Link] prefix="c" %>

In this example:

<%@ taglib %> is the taglib directive.

uri="[Link] specifies the URI of the custom tag library (JSTL Core) to import.

prefix="c" assigns a prefix (c) to the imported tag library, which can be used to reference tags from that
library within the JSP page.

Declarations

In JavaServer Pages (JSP), declarations allow you to declare variables and methods that can be used
throughout the JSP page. Declarations are enclosed within <%! %> tags. They are typically placed at the
beginning of the JSP page and are processed once during the translation of the JSP page into a servlet.

Here's an explanation of declarations in JSP with a simple example:

Syntax:

Declarations are enclosed within <%! %> tags.

Inside the tags, you can declare variables, methods, or other members that are accessible throughout
the JSP page.
<%!

// Declaration of variables and methods

%>

Example:

Let's say you want to declare a variable to store a welcome message that can be used multiple times in
the JSP page.

<!DOCTYPE html>

<html>

<head>

<title>Welcome Message</title>

</head>

<body>

<%

String welcomeMessage = "Welcome to our website!";

%>

<h1>Welcome</h1>

<p><%= welcomeMessage %></p>

<p>This is a simple example of using JSP declarations.</p>

</body>

</html>

In this example:

<%! %> is a declaration tag.

Inside the declaration, we declare a variable welcomeMessage of type String.

This variable is initialized with the welcome message "Welcome to our website!".

The variable welcomeMessage is then used in a JSP expression <%= welcomeMessage %> to display the
welcome message in the HTML output.
Characteristics:

Declarations allow you to declare variables and methods that are accessible throughout the JSP page.

They are processed once during the translation of the JSP page into a servlet.

Declarations are typically used to initialize variables, declare utility methods, or define constants.

Declarations can improve code readability and maintainability by promoting code reuse and
organization.

Usage:

Use declarations to declare variables, methods, or other members that need to be accessed from
multiple parts of the JSP page.

Avoid using declarations for complex logic or extensive processing. For complex logic, consider using
scriptlets or custom tags instead.
Unit 5

JAR file Format Creation

A JAR (Java ARchive) file is a package file format typically used to aggregate many Java class files,
associated metadata, and resources (such as images and sounds) into a single file. This file format is
commonly used for distributing Java applications or libraries. Creating a JAR file in Java involves several
steps:

Suppose we have the following Java source code for a simple application called [Link]:

public class HelloWorld {

public static void main(String[] args) {

[Link]("Hello, World!");

Now, let's create a JAR file for this application.

Step 1: Compile the Java source code

First, we need to compile the [Link] file to generate the corresponding bytecode (.class) file.

Open your terminal or command prompt and navigate to the directory containing [Link], then
compile it using the javac command:

javac [Link]

This command will generate a file named [Link].

Step 2: Organize files

We'll create a directory structure to organize our files. Here's how it might look:

MyProject/

└── com/

└── example/

└── [Link]

Step 3: Create the JAR file

Now, we'll create the JAR file using the jar command-line tool. Navigate to the directory containing the
compiled .class files (MyProject in this case) and execute the following command:
jar cf [Link] com/

This command creates a JAR file named [Link] containing all files and directories under the
com/ directory.

Step 4: Verify the JAR file

You can verify the contents of the JAR file using the jar tool with the tf option. Execute the following
command:

jar tf [Link]

This command will display the contents of the JAR file:

com/

com/example/

com/example/[Link]

Step 5: Execute the JAR file

To run the application from the JAR file, you need to specify the main class ([Link])
explicitly since we didn't include a manifest file.

Execute the following command:

java -cp [Link] [Link]

This command executes the HelloWorld class inside the [Link] file, and you should see the
output:

Hello, World!

Swing Programming

Swing is a GUI toolkit for Java that allows developers to create rich graphical user interfaces (GUIs) for
their applications. It provides a set of lightweight components that are platform-independent and can
be easily customized. Here's a simple example to demonstrate Swing programming in Java:

Create a Swing Frame: We'll create a simple Swing frame with a button.

import [Link].*;

public class SimpleSwingExample {

public static void main(String[] args) {

// Create a frame
JFrame frame = new JFrame("Simple Swing Example");

// Set frame size

[Link](300, 200);

// Set default close operation

[Link](JFrame.EXIT_ON_CLOSE);

// Create a button

JButton button = new JButton("Click Me");

// Add the button to the frame

[Link]().add(button);

// Set frame visibility

[Link](true);

In this example:

We create a JFrame object to represent the main window.

We set the title, size, and default close operation for the frame.

We create a JButton object with the label "Click Me".

We add the button to the content pane of the frame.

Finally, we make the frame visible.

Compile and Run: Compile the Java file and run the application.

javac [Link]

java SimpleSwingExample

Handling Events: Let's add an event handler to the button so that it displays a message when clicked.

import [Link].*;

import [Link].*;
public class SimpleSwingExample {

public static void main(String[] args) {

JFrame frame = new JFrame("Simple Swing Example");

[Link](300, 200);

[Link](JFrame.EXIT_ON_CLOSE);

JButton button = new JButton("Click Me");

// Add action listener to the button

[Link](new ActionListener() {

public void actionPerformed(ActionEvent e) {

[Link](frame, "Button Clicked!");

});

[Link]().add(button);

[Link](true);

In this modified version, we add an action listener to the button using addActionListener() method.
When the button is clicked, the actionPerformed() method of the ActionListener interface is invoked,
displaying a message dialog.

Swing provides a wide range of components and features for building sophisticated GUIs, including text
fields, labels, checkboxes, radio buttons, menus, dialogs, and more. By combining these components
and handling events, you can create powerful and interactive Java applications with Swing.

Internationalization

Internationalization in Java refers to the process of designing software applications so that they can be
easily adapted to various languages and regions without modification. It involves separating the
program's functionality from its presentation, allowing for the display of messages, labels, and other
content in different languages and formats.

Let's say you have a simple Java application that greets the user with a message. You want this
application to display the greeting message in different languages based on the user's preferences.

First, you would externalize the strings used in your application into resource bundles. A resource
bundle is a set of key-value pairs where each key represents an identifier for a string, and the value is
the string itself in a particular language.
Here's how you can create resource bundles for different languages:

Create a properties file for each language. For example:

messages_en.properties for English

messages_fr.properties for French

messages_es.properties for Spanish

Populate these files with key-value pairs representing the messages in each language. For instance:

In messages_en.properties:

greeting=Hello, World!

In messages_fr.properties:

greeting=Bonjour, le monde!

In messages_es.properties:

greeting=¡Hola, mundo!

Next, in your Java code, you would load the appropriate resource bundle based on the user's locale and
retrieve the messages from it. Here's a simple example:

import [Link];

import [Link];

public class GreetingApp {

public static void main(String[] args) {

// Assume the user's preferred locale is French

Locale locale = new Locale("fr", "FR");

// Load the appropriate resource bundle based on the locale

ResourceBundle messages = [Link]("messages", locale);

// Get the greeting message from the resource bundle

String greeting = [Link]("greeting");

// Display the greeting message

[Link](greeting);

When you run this application, it will output "Bonjour, le monde!" because it loads the French resource
bundle (messages_fr.properties) based on the specified locale (fr_FR). If you change the locale to
Locale("en", "US"), it will output "Hello, World!", and similarly for Spanish, it will output "¡Hola,
mundo!".

Advanced Java Techniques

Advanced Java techniques encompass a wide range of practices and methodologies that go beyond the
basics of Java programming. These techniques are typically employed by experienced Java developers
to build robust, efficient, and maintainable software solutions. Here are some key advanced Java
techniques:

Design Patterns: Design patterns are reusable solutions to common software design problems. They
help in creating flexible, maintainable, and scalable code. Some popular design patterns used in Java
include Singleton, Factory, Observer, Strategy, and MVC (Model-View-Controller).

Concurrency: Java provides robust support for concurrent programming, allowing multiple tasks to run
simultaneously. Advanced Java developers must understand concepts like threads, synchronization,
locks, and concurrent collections to develop efficient and thread-safe applications. Java provides high-
level concurrency utilities like Executors, Concurrent Collections, and the [Link] package
to simplify concurrent programming.

Generics and Collections: Generics allow you to create classes, interfaces, and methods that operate on
objects of specified types. They provide compile-time type safety and enable the creation of more
reusable and flexible code. Understanding generics is crucial for working with Java collections, which
are used to store and manipulate groups of objects. Advanced techniques involve using parameterized
types, wildcards, and bounded types effectively.

Lambda Expressions and Stream API: Lambda expressions introduced in Java 8 enable functional
programming paradigms in Java. They allow you to treat functionality as a method argument, making
code more concise and expressive. The Stream API provides a fluent, functional-style API for processing
collections of objects. Advanced Java developers leverage lambda expressions and streams for parallel
processing, filtering, mapping, and reducing data efficiently.

Annotations and Reflection: Annotations are metadata that provide data about a program but are not
part of the program itself. Java annotations are used for various purposes, including compile-time
checks, runtime processing, and code generation. Reflection is a powerful feature that allows Java code
to examine and modify its own structure at runtime. Advanced Java developers use annotations and
reflection for tasks like dependency injection, testing, and framework development.

Java Persistence API (JPA) and Hibernate: JPA is a standard API for object-relational mapping (ORM) in
Java applications. It provides a framework for mapping Java objects to relational database tables and
vice versa. Hibernate is one of the most popular implementations of JPA, offering additional features
and functionalities. Advanced Java developers use JPA and Hibernate to simplify database access,
improve performance, and ensure data integrity in enterprise applications.

Dependency Injection and Inversion of Control (IoC): Dependency injection is a design pattern used to
manage dependencies between objects in a system. It promotes loose coupling and facilitates modular
design by allowing objects to be configured and wired together externally. IoC is a principle where the
control flow of a program is inverted, with control being passed to a container or framework that
manages object creation and lifecycle. Advanced Java developers utilize frameworks like Spring, Guice,
or CDI for implementing dependency injection and IoC in their applications.

Unit Testing and Test-Driven Development (TDD): Unit testing is a software testing method where
individual units or components of a program are tested in isolation to ensure they function correctly.
Test-driven development is a development approach where tests are written before the code is
implemented, driving the design and ensuring test coverage. Advanced Java developers follow best
practices for writing unit tests, including mocking, stubbing, and using testing frameworks like JUnit or
TestNG.

Performance Optimization: Advanced Java developers understand how to optimize the performance of
their applications by profiling, benchmarking, and identifying bottlenecks. Techniques such as caching,
lazy loading, connection pooling, and asynchronous processing are employed to improve scalability and
responsiveness.

Security: Security is a critical aspect of software development. Advanced Java developers implement
security measures such as encryption, authentication, authorization, and input validation to protect
against common security threats like SQL injection, cross-site scripting (XSS), and cross-site request
forgery (CSRF).

You might also like