Java Programming
Java Programming
SYLLABUS
Structure of Units
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
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
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];
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);
}
}
});
[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].*;
// Client
import [Link].*;
import [Link].*;
[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 (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.
import [Link];
import [Link];
import [Link];
import [Link];
super();
return a + b;
import [Link];
try {
[Link](1099);
[Link]("CalculatorService", calculator);
[Link]("Server is ready...");
} catch (Exception e) {
[Link]();
import [Link];
try {
} 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 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 {
while (true) {
[Link](clientHandler);
new Thread(clientHandler).start();
} catch (IOException e) {
[Link]();
if (client != sender) {
[Link](8888);
Client:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link] = serverHost;
[Link] = serverPort;
[Link](clientName);
String message;
try {
[Link](message);
} catch (IOException e) {
[Link]();
}).start();
String userInput;
[Link](userInput);
} catch (IOException e) {
[Link]();
[Link]();
}
Client Handler (Server-Side):
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link] = clientSocket;
[Link] = chatServer;
try {
} catch (IOException e) {
[Link]();
[Link](message);
@Override
try {
clientName = [Link]();
// Continuously read messages from the client and broadcast them to others
String message;
[Link](message, this);
} catch (IOException e) {
[Link](this);
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.
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:
import [Link];
import [Link];
javac [Link]
rmic MyRemoteInterface
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];
super();
@Override
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];
super(id, port);
@Override
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.
import [Link];
import [Link];
import [Link];
import [Link];
super();
@Override
Server ([Link]):
import [Link];
import [Link];
try {
[Link](1099);
[Link]("MyRemoteObject", remoteObject);
[Link]("Server is ready.");
} catch (Exception e) {
[Link]();
}
}
Client ([Link]):
import [Link];
try {
} catch (Exception e) {
[Link]();
In this example:
MyRemoteInterface is the remote interface that extends Remote and declares a method sayHello.
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).
Space:
A space is a distributed shared memory repository where objects, known as entries, can be stored and
retrieved.
Entry:
Entries typically represent data or messages that are shared between different components.
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
[Link] = sender;
[Link] = message;
try {
} 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 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:
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.
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.
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.
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.
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].*;
try {
[Link]("[Link]");
statement = [Link]();
resultSet = [Link](query);
while ([Link]()) {
// Retrieve data from the result set
int id = [Link]("id");
[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 {
} catch (Exception e) {
[Link]();
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];
try {
[Link]("[Link]");
// Establish a connection
);
// Create a statement
while ([Link]()) {
[Link]([Link]("column_name"));
// Close resources
[Link]();
[Link]();
[Link]();
[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 using JDBC involves storing and retrieving multimedia data, such as
images, audio, or video, in a database.
Assuming you have a MySQL database named "multimedia_db," create a table to store multimedia data:
import [Link];
import [Link];
import [Link];
import [Link];
try {
[Link]("[Link]");
preparedStatement = [Link](insertQuery);
[Link](1, fileInputStream);
[Link]();
} catch (Exception e) {
[Link]();
} finally {
try {
[Link]();
import [Link].*;
import [Link].*;
try {
[Link]("[Link]");
int multimediaIdToRetrieve = 1;
[Link](1, multimediaIdToRetrieve);
if ([Link]()) {
int bytesRead;
[Link](buffer, 0, bytesRead);
} catch (Exception e) {
[Link]();
} finally {
try {
} 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 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].*;
try {
while ([Link]()) {
int id = [Link]("id");
[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 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].*;
[Link]("text/html");
[Link]("<html>");
[Link]("<head><title>Hello Servlet</title></head>");
[Link]("<body>");
[Link]("<h1>Hello, world!</h1>");
[Link]("</body></html>");
In this example:
We obtain a PrintWriter object from the response using [Link]() to send HTML content
back to the client.
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.
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].*;
[Link]("Content-type: text/html\n");
[Link]("<html>");
[Link]("<head><title>Add Numbers</title></head>");
[Link]("<body>");
[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.
The anatomy of a Java Servlet refers to the essential components and structure that make up a servlet.
Example
import [Link].*;
import [Link].*;
import [Link].*;
[Link]("text/html");
[Link]("<html><body>");
[Link]("<h1>Hello, World!</h1>");
[Link]("</body></html>");
[Link]();
}
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];
[Link]("text/html");
[Link]("<html><body>");
[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 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.
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
[Link]("text/html");
[Link]("<html><body>");
[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.
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.
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];
[Link]("text/html");
[Link](HttpServletResponse.SC_OK);
[Link]("<html><body>");
[Link]("<h1>Hello, World!</h1>");
[Link]("</body></html>");
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.
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.
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];
[Link](cookie);
[Link]("text/html");
[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".
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.
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:
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:
Scriptlet Tags: Scriptlet tags allow you to write Java code directly within the JSP page.
Example:
<%
int sum = 2 + 3;
%>
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:
Example:
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:
These tags provide a powerful mechanism for building dynamic and modular web applications using
JavaServer Pages.
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>
</head>
<body>
<h1>Welcome to My Website</h1>
</html>
JSP Directives:
JSP directives provide instructions to the JSP container about how to process the page.
Example:
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:
<%
%>
JSP Expressions:
JSP expressions are used to embed Java expressions within HTML content.
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.
Example:
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:
Comments:
There are two types of comments in JSP: HTML comments (<!-- -->) and JSP comments (<%-- --%>).
Example:
<!DOCTYPE html>
<html> <head>
</head>
<body>
<h1>Welcome to My Website</h1>
<%
%>
<p>Hello, <%= name %>! Your age is <%= age %> years old.</p>
</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.
Syntax:
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>
</head>
<body>
</body>
</html>
In this example:
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 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.
Syntax:
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>
<%
String greeting;
} else {
%>
</body>
</html>
In this example:
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.
Page Directive:
The page directive provides instructions specific to the JSP page itself, such as language, content type,
and other settings.
In this example:
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.
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.
In this example:
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.
In this example:
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.
Syntax:
Inside the tags, you can declare variables, methods, or other members that are accessible throughout
the JSP page.
<%!
%>
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>
<%
%>
<h1>Welcome</h1>
</body>
</html>
In this example:
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
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]:
[Link]("Hello, World!");
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]
We'll create a directory structure to organize our files. Here's how it might look:
MyProject/
└── com/
└── example/
└── [Link]
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.
You can verify the contents of the JAR file using the jar tool with the tf option. Execute the following
command:
jar tf [Link]
com/
com/example/
com/example/[Link]
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.
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].*;
// Create a frame
JFrame frame = new JFrame("Simple Swing Example");
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
// Create a button
[Link]().add(button);
[Link](true);
In this example:
We set the title, size, and default close operation for the frame.
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 {
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](new ActionListener() {
});
[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:
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];
[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 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).