Advanced Java Programming
Advanced Java Programming
Unit-1
Introduction to Java
Java is a high-level, class-based, object-oriented programming language that is
designed to have as few implementation dependencies as possible. It is a general-
purpose programming language intended to let application developers write once,
run anywhere (WORA), meaning that compiled Java code can run on all platforms
that support Java without the need for recompilation.
Basic Syntax
Java syntax is the set of rules defining how a Java program is written and
interpreted.
Case Sensitivity: Java is case sensitive, which means identifier Hello and
hello would have different meaning in Java.
Class Names: For all class names the first letter should be in Upper Case. If
several words are used to form a name of the class, each inner word's first
letter should be in Upper Case.
Method Names: All method names should start with a Lower Case letter. If
several words are used to form the name of the method, then each inner
word's first letter should be in Upper Case.
File Name: The name of the program file should exactly match the class name.
public static void main(String args[]): Java program processing starts from
the main() method which is a mandatory part of every Java program.
After the first character, identifiers can have any combination of characters.
Java Modifiers
Like other languages, it is possible to modify classes, methods, etc., by using
modifiers. There are two categories of modifiers:
Variables
We would see following type of variables in Java:
Local Variables
Introduction to Java
Java Overview:
Features of Java:
Portable: Java programs can be easily moved from one computer system
to another.
Inheritance
Inheritance is a fundamental concept in object-oriented programming (OOP) that
allows a new class to inherit properties and behavior from an existing class. In
Java, inheritance enables code reuse and establishes relationships between
classes.
Subclass (Child Class): The class that inherits properties and methods from
another class.
Syntax
class Superclass {
// superclass members
Types of Inheritance
1. Single Inheritance
In single inheritance, a subclass inherits from only one superclass.
class Animal {
// Animal class members
}
2. Multilevel Inheritance
In multilevel inheritance, a subclass inherits from a superclass, and another class
inherits from this subclass.
class Animal {
// Animal class members
}
3. Hierarchical Inheritance
In hierarchical inheritance, multiple subclasses inherit from a single superclass.
class Animal {
// Animal class members
}
// Interface 1
interface A {
void methodA();
}
// Interface 2
interface B {
void methodB();
We then have two classes MyClass and AnotherClass , each implementing one of
the interfaces.
Example of Inheritance
// Superclass
class Vehicle {
void move() {
System.out.println("Vehicle is moving");
}
}
// Main class
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.move(); // Output: Vehicle is moving
car.accelerate(); // Output: Car is accelerating
}
}
Java supports single, multilevel, and hierarchical inheritance, but not multiple
inheritance (directly).
Exception Handling
Exception handling is a mechanism provided by Java to handle runtime errors,
known as exceptions, in a structured and graceful manner. By handling exceptions
effectively, developers can prevent unexpected program terminations and provide
meaningful feedback to users.
throws: Keyword used to declare that a method may throw a particular type of
exception.
Syntax
try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Handle ExceptionType1
} catch (ExceptionType2 e2) {
// Handle ExceptionType2
} finally {
// Code that always executes, regardless of whether an ex
message.
Example 2: ArrayIndexOutOfBoundsException
Example 3: NullPointerException
In this example, the try block contains code that may throw two different types of
exceptions ( ArrayIndexOutOfBoundsException and ArithmeticException ). Each catch block
handles a specific type of exception.
The finally block contains code that always executes, regardless of whether an
exception occurred or not. It is typically used for cleanup tasks like closing
resources (e.g., files, database connections).
throw:
Control jumps to the nearest enclosing try block to find a matching catch
handler.
throws:
Informs the calling code about the types of exceptions it needs to be prepared
to handle.
Example:
Explanation:
divide method:
main method:
Conclusion
Exception handling is crucial for writing robust and reliable Java programs. By
anticipating and handling exceptions, developers can ensure that their
applications gracefully recover from errors and continue executing smoothly.
Understanding exception handling mechanisms enables developers to write more
resilient code.
Multithreading
Multithreading is a programming concept that allows multiple threads to execute
concurrently within a single process. In Java, multithreading enables developers
to create applications that can perform multiple tasks simultaneously, improving
efficiency and responsiveness.
Basics of Multithreading
Thread: A lightweight process that executes independently within a program.
In this example, a thread is created by extending the Thread class and overriding
the run() method. The start() method initiates the execution of the thread.
class Counter {
private int count = 0;
thread1.start();
thread2.start();
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
System.out.println(e);
}
In this example, two threads ( thread1 and thread2 ) increment a shared counter
( Counter object) concurrently. The synchronized keyword ensures that only one
thread can execute the increment() method at a time, preventing race conditions
and ensuring data consistency.
Conclusion
Multithreading in Java allows developers to write efficient and responsive
applications by leveraging the power of concurrency. By creating and managing
multiple threads, developers can perform tasks concurrently, making the most out
Applet Programming
Applet programming in Java enables developers to create dynamic and interactive
content that can be embedded within web pages. Java applets provide a platform-
independent way to enhance web pages with features such as animations, games,
and interactive forms.
import java.applet.Applet;
import java.awt.Graphics;
In this example, we create a simple applet that displays the text "Hello, World!" at
coordinates (20, 20) on the applet's surface.
import java.applet.Applet;
import java.awt.Graphics;
This example demonstrates drawing basic shapes (rectangle, oval, line) using the
Graphics object provided by the paint() method.
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
// MouseListener methods
public void mouseClicked(MouseEvent e) {
x = e.getX(); // Get X-coordinate of mouse click
In this example, the applet responds to mouse clicks by updating the coordinates
of the click and redrawing the applet to display the new coordinates.
Example 4: Animation
import java.applet.Applet;
import java.awt.Graphics;
This example creates an animated applet where text moves horizontally across the
applet's surface.
Conclusion
Java applets provide a versatile platform for creating interactive content within
web pages. By leveraging the Applet class and its associated methods,
developers can design engaging and dynamic experiences for users directly
within their web browsers. Understanding applet programming enables
developers to enhance web pages with animations, graphics, and interactivity,
enriching the overall user experience.
Additional Points:
Certainly! Here are some additional points that can be added to the topics we
discussed:
Inheritance:
Method Overriding: Subclasses can provide a specific implementation for a
method defined in the superclass, allowing for polymorphic behavior.
Exception Handling:
Checked vs Unchecked Exceptions: Java distinguishes between checked
exceptions (which must be caught or declared in a throws clause) and
unchecked exceptions (which do not need to be explicitly handled).
Multithreading:
Thread Pools: Instead of creating and managing individual threads,
applications can use thread pools to efficiently manage a pool of reusable
threads, reducing overhead and improving performance.
Multi-Threading
Multi-threading is a programming concept that allows concurrent execution of
multiple threads within a single process. Threads are lightweight processes that
share the same memory space and resources of a process but can execute
independently. Multi-threading is commonly used in applications to achieve
parallelism, improve performance, and enhance responsiveness by executing
multiple tasks simultaneously.
Usage Example:
import java.io.*;
import java.net.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
executor.shutdown();
}
}
@Override
public void run() {
try {
URL url = new URL(imageUrl);
In this example:
For each image URL, we create a new ImageDownloadTask object and submit it to
the thread pool for execution.
Each thread reads the image data from the URL and writes it to a file on the
local file system.
Once all tasks are completed, we shut down the thread pool.
Applet Programming:
Applet Lifecycle: Understand the sequence of methods invoked during the
lifecycle of an applet, such as init() , start() , stop() , and destroy() , and their
respective purposes.
Adding these additional points can enhance the understanding and depth of
knowledge on the respective topics.
Connecting to a Server
Connecting to a server in Java typically involves network communication, where a
client application communicates with a server over a network protocol such as
TCP/IP or UDP. Here's a basic outline of how to connect to a server in Java using
sockets, which is a low-level networking API:
import java.io.*;
import java.net.*;
2. Server Side:
import java.io.*;
import java.net.*;
Explanation:
It then gets the output stream from the socket and sends data to the server
using a PrintWriter .
The server creates a ServerSocket object bound to a specific port and listens
for incoming connections using serverSocket.accept() .
Upon accepting a connection, it gets the input stream from the client socket
and reads data from it using a BufferedReader .
Once communication is complete, both client and server close their respective
sockets.
Additional Considerations:
Handling Multiple Clients: For handling multiple clients, you would typically
create a new thread for each client connection in the server code.
Implementing Servers
Implementing servers in Java involves creating applications that listen for
incoming connections from clients and handle those connections according to the
desired functionality. Here's a basic outline of how to implement a simple server in
Java using sockets:
import java.io.*;
import java.net.*;
import java.io.*;
import java.net.*;
Explanation:
The server creates a ServerSocket object bound to a specific port number (e.g.,
12345).
The ClientHandler thread reads data from the client, processes it, and sends a
response back.
Each client connection is handled independently in its own thread, allowing the
server to handle multiple clients simultaneously.
Additional Considerations:
Thread Safety: Ensure thread safety when accessing shared resources or
performing concurrent operations.
import java.io.*;
import java.net.*;
2. Open a Connection:
Additional Considerations:
Handle Errors: Handle exceptions appropriately, including connection
timeouts, invalid URLs, and network errors.
Security: Sanitize user inputs and validate URL inputs to prevent security
vulnerabilities like injection attacks.
This example demonstrates the basic steps for making URL connections in Java.
Depending on your use case, you may need to customize the request headers,
handle redirects, or handle other aspects of HTTP communication.
Implementing Servers:
Thread Pooling: Instead of creating a new thread for each incoming client
connection, consider using a thread pool to limit the number of concurrently
running threads and prevent resource exhaustion.
Performance Tuning: Profile and optimize your server code for performance
by identifying bottlenecks, optimizing resource usage, and fine-tuning
configuration parameters such as thread pool size and socket buffer sizes.
2. Socket:
Sockets are classified into two types: client sockets and server sockets.
Provides input and output streams for communicating with the server.
2. ServerSocket Class:
Accepts incoming client connections and creates a new socket for each
client.
Server Code:
import java.io.*;
import java.net.*;
Client Code:
import java.io.*;
import java.net.*;
import java.io.*;
import java.net.*;
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Client connected: " + cli
out.println("Hello, Client!");
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
Conclusion:
Socket programming in Java allows applications to communicate over the network
using sockets. By understanding the concepts of sockets, Socket and ServerSocket
classes, and their usage in Java, you can develop client-server applications for
various networking tasks. These examples provide a solid foundation for
understanding socket programming and can help you prepare for UG level
engineering exams.
UNIT-II
Preparing a class to be a Java Bean
Preparing a class to be a Java Bean involves adhering to a specific set of
conventions and requirements to ensure interoperability and compatibility with
various Java frameworks and tools. Here's a detailed explanation of how to
prepare a class to be a Java Bean:
This allows frameworks and tools to instantiate the bean using reflection.
Provide public setter methods (mutators) to set the values of the fields.
Follow the naming convention for getter and setter methods: getFieldName()
and setFieldName() .
4. Consistency:
Follow JavaBeans naming conventions for class names, field names, and
method names.
import java.io.Serializable;
// Constructor
public Person() {
// Default constructor
}
import java.io.Serializable;
Conclusion:
By following these steps, you can create a Java Bean that encapsulates data and
behavior within a self-contained unit. Java Beans adhere to specific conventions
such as providing getter and setter methods, which facilitate interoperability and
compatibility with various Java frameworks and tools. Creating Java Beans allows
for reusable and modular components in Java applications.
Definition:
A Java Bean property is a named attribute that defines the state of a Java Bean.
Properties provide a way to access and modify the internal state of an object in a
controlled manner, while encapsulating the implementation details.
2. Getter Methods: Each property has a corresponding getter method that allows
access to its value. Getter methods are named according to the JavaBeans
naming convention, usually in the form getPropertyName() .
3. Setter Methods: Properties also have setter methods that allow modification
of their values. Setter methods follow the naming convention
// Constructor
public Person() {
// Default constructor
}
Usage:
Benefits:
Encapsulation: Properties encapsulate the state of an object, hiding its
internal implementation details.
Access Control: Getter and setter methods provide controlled access to the
bean's state, enabling validation, security, and other logic.
By defining Java Bean properties and providing getter and setter methods, you
create reusable and modular components that facilitate the development of robust
and maintainable Java applications.
Types of beans
1. Standard JavaBeans:
These are regular Java classes that adhere to the JavaBeans specification,
providing properties (with getter and setter methods), constructors, and optionally
implementing the Serializable interface. Standard JavaBeans are used in various
Java frameworks and tools for building reusable components.
Example:
// Constructor
public Person() {
// Default constructor
}
@Stateless
public class ShoppingCartBean implements ShoppingCart {
// Implementation of business logic
}
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class UserBean {
private String username;
private String password;
4. Spring Beans:
Spring Beans are components managed by the Spring Framework's Inversion of
Control (IoC) container. These beans are configured and managed by the Spring
container, and they can be wired together to form the application's architecture.
Example:
@Component
public class UserService {
// Implementation of service methods
}
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
@Named
@SessionScoped
public class ShoppingCart {
// Implementation of shopping cart functionality
}
Conclusion:
The state stored in SFSBs persists across multiple client interactions until
the client explicitly terminates the session or the session times out.
2. Client Affinity:
Each client interacting with an SFSB gets its instance, ensuring that the
conversational state is isolated between clients.
3. Lifecycle Management:
Serializable state allows the container to store and retrieve the state of
SFSBs from secondary storage as needed.
5. Scoped Context:
import javax.ejb.Stateful;
@Stateful
public class ShoppingCartBean implements ShoppingCart {
private List<String> items = new ArrayList<>();
Conclusion:
Stateful Session Beans provide a mechanism for maintaining conversational state
between multiple method invocations for a specific client in Java EE applications.
They allow developers to build applications with stateful interactions, such as
shopping carts, wizards, or transactional workflows, by managing the state of
client sessions within the EJB container. Understanding the characteristics and
usage of Stateful Session Beans is crucial for developing stateful and
conversational Java EE applications.
2. Lightweight:
3. Concurrency:
4. Transaction Management:
5. Scoped Context:
import javax.ejb.Stateless;
@Stateless
public class CalculatorBean implements Calculator {
public int add(int a, int b) {
return a + b;
}
Conclusion:
Stateless Session Beans are lightweight components used in Java EE applications
for executing stateless business logic efficiently. They do not maintain
conversational state between method invocations, allowing for scalable and
concurrent processing of client requests. Understanding the characteristics and
usage of Stateless Session Beans is crucial for developing efficient and scalable
Java EE applications.
Use of Instance Often utilizes instance variables Typically avoids using instance
Variables to store state variables for state
Entity Beans:
Entity beans are Enterprise JavaBeans (EJBs) used to represent persistent data
entities in a Java EE application. They typically map to tables in a relational
database and provide a way to interact with the underlying data through an
object-oriented interface. Entity beans encapsulate the data and business logic
related to a specific entity, such as a customer, product, or order.
Overview:
Persistent Data Representation: Entity beans represent persistent data
entities, allowing developers to interact with database tables using object-
oriented programming constructs.
ORM Framework Integration: Entity beans are often used in conjunction with
Object-Relational Mapping (ORM) frameworks like JPA (Java Persistence API)
to simplify database interactions and mapping between Java objects and
database tables.
CRUD Operations: Entity beans support Create, Read, Update, and Delete
(CRUD) operations, enabling developers to manipulate persistent data entities
using standard Java methods.
Architecture:
Entity Bean Class: Represents a persistent data entity and typically
corresponds to a database table. It contains attributes representing table
columns and methods for accessing and manipulating entity data.
Entity Beans were a part of the earlier versions of Enterprise JavaBeans (EJB)
specifications. They were designed to represent data entities, typically mapped to
database tables, and provided persistence services. However, Entity Beans have
been deprecated since EJB 3.0, and JPA (Java Persistence API) has become the
preferred approach for handling persistence in Java EE applications.
Despite being deprecated, I can still provide an example of how Entity Beans were
used in older versions of EJB. Let's create a simple example of an Entity Bean
representing a "User" entity:
import javax.ejb.*;
import java.io.Serializable;
@Entity
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
public User() {
}
In this example:
The User class is marked with the @Entity annotation, indicating that it is an
entity bean.
The username and email fields represent the attributes of the User entity.
Constructors, getters, and setters are provided for accessing and manipulating
the entity's attributes.
Please note that in modern Java EE applications, it's recommended to use JPA
entities along with other persistence technologies such as Hibernate for ORM
(Object-Relational Mapping). JPA provides a more flexible and powerful approach
to managing entities and persistence operations compared to the older Entity
Beans model.
Servlets:
Servlets are Java classes used to extend the functionality of web servers and
handle HTTP requests and responses. They provide a way to generate dynamic
web content, process form submissions, and interact with clients over the HTTP
protocol.
Overview:
HTTP Request Handling: Servlets receive HTTP requests from clients (e.g.,
web browsers) and generate dynamic content or perform processing based
on the request parameters.
Web Application Logic: Servlets encapsulate the application logic for web-
based interactions, such as user authentication, data validation, and business
process execution.
Architecture:
Servlet Container: Manages the lifecycle of servlets and provides the runtime
environment for servlet execution. The servlet container is responsible for
loading servlet classes, initializing servlet instances, and dispatching HTTP
requests to the appropriate servlets.
Integration:
Entity beans and Servlets are often used together in Java EE applications to
implement web-based data management systems. Servlets handle incoming
HTTP requests, perform data processing, and invoke business logic implemented
in entity beans to interact with persistent data entities. This integration allows
developers to build robust and scalable web applications that leverage the
capabilities of both technologies.
Conclusion:
Entity beans and Servlets are essential components in Java EE applications,
serving distinct roles in the development of web-based systems. While entity
beans represent persistent data entities and provide a high-level abstraction for
database interactions, Servlets handle HTTP requests, process client interactions,
and generate dynamic web content. Integrating entity beans with Servlets allows
developers to build powerful and efficient web applications that leverage the
strengths of both technologies.
3. destroy() :
This stage occurs only once during the lifecycle of the servlet.
2. Initialization:
This stage allows the servlet to perform any one-time initialization tasks,
such as loading configuration parameters or initializing resources.
3. Servicing Requests:
Inside the service() method, the servlet processes the client request and
generates an appropriate response.
4. Destruction:
The destroy() method allows the servlet to release any resources held
during its lifetime, such as closing database connections or releasing file
handles.
Lifecycle Events:
Servlet containers may provide mechanisms for registering listeners to receive
notifications about lifecycle events of servlets.
Example
First, let's create a servlet by implementing the javax.servlet.Servlet interface. We'll
override the init() , service() , and destroy() methods, which represent the servlet
lifecycle events.
import javax.servlet.*;
import java.io.*;
// Servlet initialization
public void init(ServletConfig config) throws ServletExce
ption {
// Initialization code here (optional)
}
// Servlet cleanup
public void destroy() {
// Cleanup code here (optional)
}
This servlet will respond to HTTP requests with a simple "Hello, World!" message.
Now, to deploy this servlet, you typically need to configure it in a web.xml file in
your web application. Here's a basic web.xml file that maps URL patterns to
servlets:
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
In this web.xml , we're mapping the servlet to the URL pattern /hello , so any
requests to http://localhost:8080/yourwebapp/hello will be handled by our
HelloWorldServlet .
That's it! With these files in place, you can deploy your servlet to a servlet
container like Apache Tomcat and access it through a web browser. When you
access http://localhost:8080/yourwebapp/hello , you should see the "Hello, World!"
message rendered in your browser.
Conclusion:
The Servlet interface defines the standard protocol for building Java servlets,
which are server-side components used in Java EE web applications.
Understanding the servlet life cycle is crucial for developing servlets that perform
initialization, request processing, and resource cleanup tasks efficiently. By
Handling
Handling HTTP GET Requests:
HTTP GET requests are commonly used for retrieving data from a server. In the
context of servlets, handling HTTP GET requests typically involves extracting
information from the request (such as query parameters or path variables),
processing the request, and generating an appropriate response.
In the servlet class, override the doGet() method to handle HTTP GET
requests.
Write the response content, such as HTML, JSON, or XML, to the response
output stream ( PrintWriter or OutputStream ).
In the servlet class, override the doPost() method to handle HTTP POST
requests.
Extract data from the request body, such as form parameters or JSON
payloads, using methods provided by the HttpServletRequest object
( getReader() or getInputStream() ).
Write the response content, such as HTML, JSON, or XML, to the response
output stream ( PrintWriter or OutputStream ).
example:
Certainly! Let's expand the previous example to handle both HTTP GET and POST
requests. We'll modify the service() method to differentiate between GET and
POST requests and respond accordingly.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
methods to handle GET and POST requests respectively. However, in the interest
of simplicity, we've overridden the service() method instead to handle both GET
and POST requests.
Now, let's create a simple HTML form to send POST requests to our servlet:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HelloWorldServlet POST Form</title>
</head>
<body>
<form action="/yourwebapp/hello" method="post">
Enter your name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
</body>
</html>
When a user submits this form, a POST request will be sent to /yourwebapp/hello
with the name parameter. The servlet will then read this parameter and respond
with a personalized greeting.
With these changes, your servlet now handles both HTTP GET and POST
requests.
Conclusion:
Handling HTTP requests (both GET and POST) in servlets involves extracting data
from the request, processing it, and generating an appropriate response. By
overriding the doGet() and doPost() methods in a servlet class, developers can
Session Tracking
Session tracking is a mechanism used in web development to maintain the state of
user interactions across multiple requests within a session. Sessions allow web
applications to associate data with a specific user's browsing session, enabling
features like user authentication, shopping carts, and personalized experiences. In
Java web applications, session tracking is commonly implemented using
mechanisms such as cookies, URL rewriting, and HttpSession objects. Let's
explore each of these methods:
How it works: When a user visits a website, the server sends a cookie
containing a unique session identifier. The browser stores this cookie locally
and includes it in subsequent requests to the same website. The server uses
the session identifier to retrieve session-specific data associated with the
user.
2. URL Rewriting:
URL rewriting involves appending session identifiers to URLs within a web
application. This allows the server to associate requests with specific sessions.
How it works: When a user accesses a web application, the server creates an
HttpSession object to represent the session. The server associates a unique
session identifier with the HttpSession object, which is then used to retrieve
the session data for subsequent requests.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
In this example:
We retrieve the "visitCount" attribute from the session to track how many
times the user has visited the page.
If the "visitCount" attribute is null, it means it's the user's first visit, so we set it
to 1 and display a welcome message.
You can deploy this servlet in your servlet container (e.g., Apache Tomcat) and
access it through a web browser. Each time you access the servlet, it will display a
message indicating whether it's your first visit or a return visit, along with the
number of times you've visited the page. Additionally, it will display your session
ID and set a cookie to store it.
Conclusion:
Session tracking is essential for maintaining user state and enabling personalized
interactions in web applications. In Java web development, session tracking can
be achieved using mechanisms such as cookies, URL rewriting, and HttpSession
objects. Understanding how to implement session tracking effectively is crucial for
building dynamic and interactive web applications.
Cookies
Cookies are small pieces of data stored by the web browser on the user's device.
They are sent back and forth between the client (browser) and the server with
each HTTP request and response. Cookies are commonly used for various
purposes in web development, including session management, personalization,
tracking user behavior, and storing user preferences.
Here are some key aspects and types of cookies:
1. Types of Cookies:
a. Session Cookies:
Session cookies are temporary cookies that are stored in the browser's
memory only during a user's session.
They are deleted when the user closes the browser or after a certain period of
inactivity.
b. Persistent Cookies:
Persistent cookies are stored on the user's device even after the browser is
closed.
They have an expiration date/time set by the server, and they remain valid until
that date/time or until manually deleted by the user.
c. Secure Cookies:
Secure cookies are transmitted over HTTPS connections only, ensuring that
they are encrypted and protected from interception by unauthorized parties.
d. HttpOnly Cookies:
They can only be transmitted over HTTP or HTTPS protocols and are
inaccessible to JavaScript, providing protection against cross-site scripting
(XSS) attacks.
e. SameSite Cookies:
SameSite cookies restrict the browser from sending cookies along with cross-
site requests.
They can be set to "Strict" (cookies are not sent with cross-origin requests) or
"Lax" (cookies are sent with top-level navigations and same-site requests).
2. Example Usage:
a. Session Management:
b. Personalization:
3. Special Considerations:
Apache ActiveMQ
RabbitMQ
Apache Kafka
IBM MQ
Conclusion:
JMS and message queues are essential components of modern distributed
systems, providing reliable, asynchronous communication between distributed
components. By leveraging JMS APIs and message queue implementations,
developers can build scalable, decoupled, and resilient applications capable of
handling complex messaging requirements.
Java Reflection API allows you to inspect and manipulate the fields,
methods, and constructors of a class at runtime.
You can use reflection to retrieve information about the properties (fields),
methods, and annotations of a JavaBean class.
Example:
2. JavaBeans Introspector:
Example:
Example:
PropertyUtils.getProperty(bean, "propertyName");
PropertyUtils.setProperty(bean, "propertyName", value);
// Perform introspection using BeanUtils methods
4. Spring BeanWrapper:
Example:
Persistence
Persistence refers to the ability of data to outlive the execution of a program. In
software engineering, persistence typically involves storing and retrieving data
from a durable storage medium, such as a database, file system, or cloud storage
service. The goal of persistence is to maintain the state of an application's data
across different sessions or instances of the program.
Key Concepts in Persistence:
1. Data Storage: Persistence involves storing data in a structured format that can
be efficiently accessed and manipulated. This may involve relational
databases, NoSQL databases, flat files, or other storage mechanisms.
3. Object Storage: Object storage services like Amazon S3, Google Cloud
Storage, and Azure Blob Storage are commonly used for persisting large
volumes of unstructured data, such as images, videos, and documents, in a
distributed manner.
5. File Systems: For simple data storage needs, file systems provide a
straightforward approach to persistence. Applications can read from and write
to files on disk using file I/O operations.
1. Lifecycle Management:
2. Transaction Management:
3. Security Services:
4. Concurrency Management:
5. Resource Management:
They inject resources, such as data sources, JMS queues, and other EJB
components, into EJB instances at runtime, improving modularity and
testability.
Applet vs Application
Feature Java Applet Java Application
Limited support for GUI Full support for Swing, JavaFX, etc.
GUI Components
components components
Note:
While both applets and applications are written in Java, they serve different
purposes and have different deployment models and execution contexts.
Unit - 3
JavaServer Pages (JSP)
1. Introduction to JSP
2. Lifecycle of JSP
The lifecycle of a JSP page consists of several phases:
Translation: The JSP page is translated into a servlet by the JSP engine.
Loading: The class file is loaded into the web server's memory.
Analogy: Think of a JSP page as a blueprint (HTML and Java code), which is first
translated into a building plan (servlet), then constructed (compiled), and finally
used by people (requests processed).
3. JSP Architecture
JSP architecture follows a Model-View-Controller (MVC) pattern:
Analogy: Imagine an online store where the products (Model) are managed in a
database, the storefront (View) is the JSP page the customer sees, and the store
manager (Controller) decides what products to show based on customer input.
4. JSP Elements
Analogy: These objects are like default tools in a toolkit, always available for use
in any project (JSP page).
6. JSP Standard Tag Library (JSTL)
In this example:
Expressions ( <%= ... %> ) are used to insert dynamic content from the request
object.
8. Advantages of JSP
Reusable Components: Custom tags and tag libraries can be reused across
multiple pages.
Ease of Use: JSP is more convenient for web designers who are familiar with
HTML.
Conclusion
JavaServer Pages (JSP) is a powerful technology for developing dynamic web
applications. By embedding Java code within HTML, JSP provides a seamless
1. Servlets vs. JSP: Servlets and JSP are both Java technologies used for web
development. Servlets are Java classes that extend the capabilities of servers
that host applications accessed by means of a request-response programming
model. On the other hand, JSP is a technology that simplifies the development
of web pages that are dynamically generated from HTML or XML formatted
templates, containing embedded Java code.
3. JSP Directives: JSP directives are instructions to the container that control the
translation phase of a JSP page into its servlet form. There are three types of
directives: page directive, include directive, and taglib directive.
Scriptlet: Used to insert Java code directly into the service method of the
JSP page. Syntax: <% ... %>
5. Implicit Objects: JSP provides several implicit objects that are automatically
available to developers. These objects include request, response, session,
application, out, config, page, and exception.
6. JSP Actions: JSP actions are XML tags that direct the server to use existing
components or control the behavior of the JSP engine. Common JSP actions
include jsp:useBean, jsp:setProperty, jsp:getProperty, jsp:include, jsp:forward,
etc.
Advantages of JSP:
Simplicity: JSP allows for the easy development of dynamic web pages by
embedding Java code into HTML.
Reusability: JSP allows for the reuse of JavaBeans and custom tags,
enhancing code modularity.
Seamless Integration: JSP pages can easily integrate with other Java
technologies like servlets, JDBC, EJBs, etc.
Performance: JSP pages are compiled into servlets by the container, leading
to efficient execution.
Conclusion:
Java Server Pages (JSP) provide a powerful mechanism for creating dynamic web
content using Java technology. By combining HTML or XML with embedded Java
code, developers can create feature-rich web applications that are both scalable
3. session: Represents the user's session with the server. It allows developers to
store session-specific data that persists across multiple requests from the
same client. The session object is useful for implementing user authentication,
maintaining shopping carts, and storing user preferences.
5. out: Represents the output stream for sending content to the client. It is
equivalent to the PrintWriter object in Java servlets. Developers can use this
object to write HTML, text, or other content directly to the client's web
browser.
7. page: Represents the current JSP page itself. It provides methods for
including other resources, forwarding requests, and managing error handling.
Developers can use this object to perform page-specific tasks and access
page attributes.
8. exception: Represents any exception that occurs during the execution of the
JSP page. It is available only if an error-page directive is specified in the JSP
page or in the deployment descriptor. Developers can use this object to
handle and display error messages to the user.
Example Usage:
Conclusion:
Implicit objects in JSP provide convenient access to various aspects of the JSP
1. Declaration:
Purpose: Declarations are used to declare variables and methods that can be
accessed throughout the JSP page.
Example:
<%!
int count = 0;
public void incrementCount() {
count++;
}
%>
2. Scriptlet:
Purpose: Scriptlets are used to insert Java code directly into the service
method of the generated servlet.
Example:
<%
String name = "John";
3. Expression:
Example:
Best Practices:
Code Readability: Write clear and concise code within scriptlets and
expressions to enhance readability and maintainability.
Avoid Complexity: Minimize the use of complex Java logic within JSP pages
to maintain code simplicity and ease of debugging.
Example Usage:
Conclusion:
Scripting in Java Server Pages (JSP) provides a powerful mechanism for
embedding Java code within HTML pages, facilitating dynamic content generation
and interaction with server-side resources. By understanding the different types
of scripting elements and following best practices, developers can create efficient
and maintainable JSP applications.
1. jsp:include:
Purpose: Includes the content of another resource (JSP page, HTML file,
or servlet) within the current JSP page.
Attributes:
Example:
2. jsp:forward:
Purpose: Forwards the request to another resource (JSP page, HTML file,
or servlet).
Attributes:
Example:
3. jsp:param:
Attributes:
Example:
4. jsp:useBean:
Attributes:
Example:
5. jsp:setProperty:
Attributes:
Example:
6. jsp:getProperty:
Attributes:
Example:
7. jsp:plugin:
Conclusion:
Standard actions in JSP provide a convenient way to incorporate dynamic
functionality and control the behavior of JSP pages. By using these actions
effectively, developers can enhance the functionality and interactivity of their web
applications while maintaining clean and maintainable code. Understanding the
purpose and attributes of each standard action is essential for leveraging the full
power of JSP technology.
1. Page Directive:
Common Attributes:
language : Specifies the scripting language used in the JSP page (e.g.,
"java").
Example:
2. Include Directive:
Example:
3. Taglib Directive:
Purpose: Declares and configures custom tag libraries for use in the JSP
page.
Attributes:
uri: Specifies the URI (Uniform Resource Identifier) of the tag library
descriptor (TLD) file.
prefix : Specifies the prefix used to reference tags from the tag library.
Example:
Best Practices:
Conclusion:
Directives in JSP play a crucial role in configuring page-specific settings,
including external resources, and declaring custom tag libraries. By understanding
the purpose and usage of each directive type, developers can effectively manage
the behavior and functionality of their JSP pages while adhering to best practices
for clean and maintainable code.
Tag handler classes are Java classes that implement the logic for custom
tags.
The TLD file is an XML document that defines the custom tags provided by
the tag library.
It specifies tag names, tag handlers, tag attributes, and other metadata.
In JSP pages, custom tags are referenced using the tag prefix and tag
name defined in the TLD file.
Tags can include attributes whose values are passed to the corresponding
tag handler.
Custom tags can be used like any other HTML or JSP tag within the JSP
page.
package com.example.tags;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
Best Practices:
Conclusion:
Custom tag libraries in JSP offer a powerful mechanism for encapsulating
reusable functionality and improving the modularity of web applications. By
following best practices and guidelines for creating and using custom tags,
developers can enhance code maintainability and productivity in JSP-based
projects.
Unit - 4
Roles of Client and Server in Web Applications
In the context of web applications, the client and server play distinct roles in
facilitating communication, processing requests, and delivering content.
Understanding these roles is crucial for effective design, development, and
deployment of web-based systems.
1. Client:
Definition: The client refers to the user's device (such as a web browser or mobile
device) that initiates requests to access web resources or services.
Key Responsibilities:
Response Handling: The client receives and processes HTTP responses from
the server, rendering content such as HTML, CSS, JavaScript, and multimedia
elements.
Local Data Storage: It may store cookies, session data, or cache resources
locally to improve performance and provide personalized experiences.
Examples of Clients:
2. Server:
Key Responsibilities:
Request Handling: The server receives and processes HTTP requests from
clients, determining the appropriate action based on the request type, URL,
headers, and parameters.
Examples of Servers:
Conclusion:
In web applications, the client and server play complementary roles in enabling
communication, processing, and delivery of content and services. While the client
interacts directly with users and renders the user interface, the server processes
requests, manages resources, and generates responses to fulfill client needs.
Understanding the roles and responsibilities of both client and server is essential
for building efficient, secure, and scalable web-based systems.
1. Remote Interface:
A Java interface that declares the methods that can be invoked remotely.
The server provides the implementation for the remote methods and
makes them accessible to remote clients.
The stub acts as a proxy for the remote object on the client side. It
marshals method calls and parameters, sends them over the network to
the server, and receives the results.
The skeleton acts as a proxy for the remote object on the server side. It
unmarshals method calls and parameters, invokes the corresponding
methods on the remote object, and sends back the results.
4. Registry:
Clients use the registry to look up remote objects by their names and
obtain stubs for communication.
Implement the business logic for the remote methods in this class.
compiler.
Use the rmic tool (RMI Compiler) to generate stub and skeleton classes for
the remote object implementation.
Bind the remote object to a name in the RMI registry using the bind()
method.
On the client side, look up the remote object from the registry using the
lookup() method.
Invoke remote methods on the obtained stub as if they were local method
calls.
Advantages of RMI:
Limitations of RMI:
Java-Centric: RMI is tightly coupled with the Java programming language and
is not interoperable with non-Java systems by default.
import java.rmi.Remote;
import java.rmi.RemoteException;
// Remote interface
public interface MyRemoteInterface extends Remote {
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
// Remote implementation
public class MyRemoteImpl extends UnicastRemoteObject impleme
nts MyRemoteInterface {
// Constructor
protected MyRemoteImpl() throws RemoteException {
super();
}
rmic MyRemoteImpl
rmiregistry
You can start the registry in the directory containing your compiled classes.
import java.rmi.Naming;
// Server class
public class MyRemoteServer {
public static void main(String[] args) {
try {
MyRemoteImpl remoteObj = new MyRemoteImpl();
Naming.rebind("RemoteObject", remoteObj);
System.out.println("Remote object bound to regist
ry.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.rmi.Naming;
// Client class
public class MyRemoteClient {
public static void main(String[] args) {
try {
MyRemoteInterface remoteObj = (MyRemoteInterface)
Naming.lookup("RemoteObject");
System.out.println(remoteObj.sayHello());
} catch (Exception e) {
e.printStackTrace();
}
}
}
Then, run the client program ( MyRemoteClient ) to look up the remote object and
invoke its methods.
Make sure to include all necessary security policies and permissions, especially if
you encounter security-related exceptions during the RMI setup process.
These steps provide a basic setup for RMI in a Java application. Adjustments may
be necessary based on your specific application requirements and environment.
All parameter types, including primitive types, objects, arrays, and custom
classes, must be serializable to be passed as parameters in RMI.
2. Serializable Interface:
interface.
By default, most Java built-in classes (e.g., String , Integer , ArrayList) are
serializable, but custom classes need to implement Serializable explicitly.
3. Parameter Constraints:
Example:
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
@Override
public String processRequest(String request) throws Remot
eException {
// Process request and return result
return "Processed: " + request;
On the client side, you can invoke this remote method by passing parameters as
you would with local methods:
import java.rmi.Naming;
Conclusion:
Parameter passing in RMI involves serializing parameters into byte streams for
transmission over the network and deserializing them on the receiving end. By
ensuring that all parameters are serializable and following best practices for
remote method invocation, developers can build robust and efficient distributed
systems using Java RMI.
Introduction of HB
It seems like you're referring to Hibernate (HB), a popular object-relational
mapping (ORM) framework for Java applications. Hibernate simplifies the task of
interacting with relational databases by providing an abstraction layer over JDBC
(Java Database Connectivity), allowing developers to work with Java objects
instead of SQL queries directly. Here's an introduction to Hibernate:
2. Create Entity Classes: Define Java entity classes that represent database
tables and annotate them with Hibernate annotations or XML mappings.
Conclusion:
1. Application Layer:
The application layer represents the topmost layer of the architecture and
includes the Java application or web application that utilizes Hibernate for
database interaction.
3. SessionFactory:
4. Session:
The Session represents a single unit of work in Hibernate and serves as the
main interface for performing database operations.
Session instances are not thread-safe and should be obtained from the
SessionFactory as needed.
5. Transaction Management:
6. Persistent Objects:
7. Mapping Metadata:
Hibernate uses mapping metadata to generate SQL queries and map database
results to Java objects.
8. Query Language:
9. Database:
Conclusion:
The architecture of Hibernate provides a robust framework for object-relational
mapping in Java applications, offering features such as transparent persistence,
transaction management, and query capabilities. By understanding the different
layers and components of Hibernate architecture, developers can effectively
leverage its capabilities to build scalable and maintainable database-driven
applications.