What is J2EE?
1. J2EE stands for Java 2 Platform, Enterprise
Edition.
2. It is a platform-independent, Java-based
environment used to develop, build, and deploy
enterprise-level applications.
3. Developed by Sun Microsystems, later managed by
Oracle.
4. J2EE is now referred to as Jakarta EE (after 2017,
under Eclipse Foundation)
✅Key Features of J2EE:
1. Supports Multi-tier Architecture: Presentation
layer, business logic layer, and data layer.
2. Platform Independent: Runs on any operating
system with JVM.
3. Component-based Development: Uses reusable
components like Servlets, JSP, and EJB.
4. Built-in Security: Provides authentication,
authorization, and secure communication.
5. Supports Web Services: Enables communication
between different applications over the web.
✅Core Components of J2EE:
1. Servlets: Java classes used to handle HTTP requests
and responses.
2. JSP (JavaServer Pages): Allows embedding Java
code into HTML.
3. EJB (Enterprise JavaBeans): Used for business
logic in enterprise applications.
4. JDBC (Java Database Connectivity): Provides
access to relational databases.
5. JMS (Java Message Service): For asynchronous
communication between components.
6. JNDI (Java Naming and Directory Interface): For
looking up data and resources.
✅ J2EE Containers:
1. Web Container: Manages Servlets and JSP
components.
2. EJB Container: Manages enterprise beans and
business logic.
3. Application Client Container: Supports application
client programs.
4. Applet Container: Manages Java applets (less used
now).
✅ Uses of J2EE:
Online banking systems
E-commerce platforms
Enterprise resource planning (ERP) systems
Customer relationship management (CRM) systems
✅Need for J2EE:
1. Development of Enterprise Applications
o J2EE is specially designed to build large-scale,
reliable, and secure enterprise applications
such as banking, e-commerce, CRM, etc.
2. Platform Independence
o Applications developed using J2EE can run on
any operating system that supports Java,
ensuring cross-platform compatibility.
3. Simplifies Complex Architecture
o J2EE provides a multi-tier architecture (client,
web, business, and data layers) that organizes
application logic and simplifies development.
4. Reusability and Modularity
o J2EE components (like Servlets, JSP, EJB) are
modular and reusable, reducing code
duplication and increasing maintainability.
5. Scalability
o J2EE applications can scale horizontally and
vertically, making them suitable for both small
and large enterprise-level systems.
6. Built-in Security Features
o J2EE offers declarative security and supports
features like authentication, authorization, and
secure communication.
7. Supports Web Services
o J2EE allows integration with other applications
using SOAP, REST, and XML-based web
services.
8. Transaction Management
o It provides automatic transaction
management, which is essential for applications
dealing with financial or sensitive data.
9. Integration with Existing Systems
o J2EE supports legacy system integration,
enabling communication with older systems via
connectors and messaging.
10. Standardization and Vendor Independence
J2EE is a standard specification, so applications are
not tied to a specific vendor, allowing flexibility in
choosing tools and servers (like Tomcat, JBoss,
WebLogic).
✅J2EE Architecture Overview
The J2EE architecture follows a multi-tiered
architecture that separates concerns, improves
manageability, and enhances scalability. It mainly
consists of:
1. Client Tier
2. Web Tier
3. Business Tier
4. Enterprise Information System (EIS) Tier
🔷 1. Client Tier
The topmost layer of the architecture.
It interacts with the user and sends requests to the server.
Examples of clients:
Web browsers (HTTP clients)
Java applications
Mobile apps
Technologies used:
HTML, CSS, JavaScript (for browsers)
Java Applets or Java Swing apps
🔷 2. Web Tier (Presentation Layer)
Receives client requests and sends responses.
Acts as the middle layer between client and business logic.
Handles presentation and basic request processing.
Components:
Servlets – Java classes that handle HTTP requests.
JSP (JavaServer Pages) – Dynamic HTML generation
using embedded Java code.
Container:
Web Container (like Apache Tomcat): Manages lifecycle
of servlets and JSP.
🔷 3. Business Tier (Logic Layer)
Contains the business logic of the application.
Processes the client’s requests, interacts with the database,
and applies logic.
Components:
EJB (Enterprise JavaBeans) – Encapsulate business logic
in components like:
o Session Beans
o Entity Beans (deprecated)
o Message-Driven Beans
Container:
EJB Container: Manages EJB lifecycle, security,
transactions, etc.
🔷 4. Enterprise Information System (EIS) Tier / Data Tier
Manages the application’s interaction with the database
and legacy systems.
Stores and retrieves data used by the business logic.
Technologies used:
JDBC – For accessing relational databases.
JNDI – For directory services and resource lookup.
JCA – Java Connector Architecture to connect with legacy
systems.
🔁 Communication Flow in J2EE
1. Client sends request via web browser or application.
2. Web Tier receives it through Servlet or JSP.
3. Web Tier forwards it to the Business Tier (EJB) for logic
processing.
4. Business Tier accesses data from the EIS Tier using
JDBC or JCA.
5. Response is passed back to the Web Tier, and finally to the
Client Tier.
✅Benefits of J2EE Architecture:
Clear separation of concerns (UI, logic, data)
Scalable and maintainable
Supports reusability of components
Enables distributed application development
✅What is a J2EE Container?
A J2EE container is a runtime environment that
manages the execution of J2EE components (like
Servlets, JSPs, and EJBs).
It provides services like security, transaction
management, lifecycle management, and resource
pooling.
Each container runs within a J2EE application server
(e.g., GlassFish, JBoss, WebLogic, WebSphere).
🔁 Types of J2EE Containers
1. Client Container
Manages client-side components such as applets or
standalone Java applications.
Provides access to enterprise services (like JNDI, security,
etc.).
Example: A Java Swing app accessing an EJB through JNDI.
2. Web Container (Servlet Container)
Manages web components like Servlets and JSP.
Handles HTTP requests and responses.
Manages the lifecycle of servlets (init, service, destroy).
Supports session management, security, and request
dispatching.
Example Server: Apache Tomcat
3. EJB Container
Manages Enterprise JavaBeans (EJB) which contain
business logic.
Handles services like:
o Transaction Management
o Security
o Remote access
o Object pooling
o Concurrency
Supports different types of EJBs:
o Session Beans (Stateless, Stateful)
o Message-Driven Beans
Example Servers: JBoss, GlassFish, WebLogic
4. Application Client Container
Supports Java client applications that run outside the
server but need access to server-side components (like
EJBs).
Provides system-level services like:
o JNDI lookup
o Security
o Connection to EJBs
Use case: A Java desktop application calling remote EJBs
✅What is J2EE API?
J2EE APIs (Application Programming Interfaces) are
predefined Java libraries that provide ready-to-use
functionalities for developing enterprise-level applications.
These APIs support features like web development,
database access, messaging, security, and more.
🔁 Important J2EE APIs and Their Functions
1. Servlet API
Used to create dynamic web content.
Allows Java classes (Servlets) to handle HTTP requests
and responses.
Works inside a Web Container.
🧩 Example Use: Login forms, search functionality.
2. JSP (JavaServer Pages) API
Allows writing Java code inside HTML pages.
Simplifies the creation of dynamic web pages.
Internally converted to Servlets.
🧩 Example Use: Displaying data from a database in HTML
format.
3. EJB (Enterprise JavaBeans) API
Used to write business logic in a reusable and distributed
way.
Supports features like transactions, security, and remote
access.
Types: Session Beans, Entity Beans (deprecated), Message-
Driven Beans.
🧩 Example Use: Bank transaction logic.
4. JDBC (Java Database Connectivity) API
Allows Java programs to connect to databases like
MySQL, Oracle, etc.
Supports CRUD operations (Create, Read, Update,
Delete).
🧩 Example Use: Fetching user data from a MySQL database.
5. JNDI (Java Naming and Directory Interface) API
Provides a lookup service to find resources like EJBs,
database connections, etc.
Used for naming and directory services.
🧩 Example Use: Looking up a remote EJB from a client
application.
6. JTA (Java Transaction API)
Manages transactions across one or more databases.
Ensures data consistency (commit/rollback features).
🧩 Example Use: Bank system transferring money between
accounts.
7. JMS (Java Message Service) API
Enables asynchronous communication between
components.
Used in messaging systems (like sending order
confirmation).
🧩 Example Use: Sending messages to users when an order is
placed.
8. JavaMail API
Used to send and receive email messages from Java
applications.
🧩 Example Use: Sending password reset emails.
9. JAAS (Java Authentication and Authorization Service)
API
Provides security features like user login and role-based
access control.
🧩 Example Use: Restricting access to admin users only.
10. JAX-RS / JAX-WS (Java API for RESTful and SOAP
Web Services)
Used to build web services in Java.
o JAX-RS → RESTful Web Services
o JAX-WS → SOAP Web Services
🧩 Example Use: Creating APIs for mobile apps or third-party
integrations.
Servlet
✅What is a Servlet?
Java Servlet is a Java program that runs on a Java-
enabled web server or application server. It handles
client requests, processes them, and generates
responses dynamically. Servlets are the backbone of
many server-side Java applications due to their efficiency
and scalability.
A Servlet is a Java class used to handle HTTP
requests and responses in a web application.
It runs on a Web Server or Application Server in a
Web Container.
Servlets are part of the Java EE (now Jakarta EE)
platform and are used to create dynamic web
content
Key Features:
Servlets work on the server side.
Servlets are capable of handling complex requests
obtained from the web server.
Generate dynamic responses efficiently.
Creating a Basic Servlet:-
Example: Here's a simple example of how a servlet
works:
// Basic Java Servlet Demonstration
import java.io.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
public class HelloWorldServlet extends HttpServlet {
protected void doGet(HttpServletRequest
request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body><h1>Hello,
World!</h1></body></html>");
}}
Java Servlets Architecture:-
Java servlets container play a very important role. It
is responsible for handling important tasks like load
balancing, session management and resource
allocation,
it make sure that all the requests are process
efficiently under high traffic.
The container distribute requests accross multiple
instances, which helps improve the system
performance.
Execution of Java Servlets:-
Execution of Servlets basically involves Six basic steps:
The Clients send the request to the Web Server.
The Web Server receives the request.
The Web Server passes the request to the
corresponding servlet.
The Servlet processes the request and generates the
response in the form of output.
The Servlet sends the response back to the
webserver.
The Web Server sends the response back to the
client and the client browser displays it on the
screen
Life Cycle of Servlet:-
1. Loading a Servlet
The first stage of the Servlet lifecycle involves loading
and initializing the Servlet. The Servlet container
performs the following operations:
Loading: The Servlet container loads the Servlet class
into memory.
Instantiation: The container creates an instance of
the Servlet using the no-argument constructor.
🔹 2. Creating the Servlet Object
The container creates an instance (object) of the
servlet using the default constructor.
3. Initializing a Servlet (init() method)
After the Servlet is instantiated, the Servlet
container initializes it by calling the init(ServletConfig
config) method.
This method is called only once during the Servlet's
life cycle
Example- public void init() {
// initialization code
}
🔹 4. Handling Request(service() method)
Once the Servlet is initialized, it is ready to handle
client requests.
Called every time a request is made to the servlet.
Handles client requests (like GET, POST) and sends
responses.
Example-
public void service(HttpServletRequest req,
HttpServletResponse res) {
// process request and send response
}
5. Destroying a Servlet (destroy() method)
Called once before servlet is removed (like server
shutdown).
Used to release resources (close files, DB
connections).
Example-
public void destroy() {
// cleanup code
}
✅What is HttpServlet?
HttpServlet is a built-in abstract class in Java
(under javax.servlet.http package).
It simplifies the creation of web-based applications
by providing methods to handle HTTP requests (like
GET, POST, PUT, DELETE).
It extends GenericServlet and provides specialized
methods such as:
o doGet()
o doPost()
o doPut()
o doDelete()
🔁 Role of HttpServlet Class
1. Acts as a base class for creating HTTP-based web
applications.
2. Provides built-in methods to handle various HTTP
methods (GET, POST, etc.).
3. Manages request and response objects
(HttpServletRequest and HttpServletResponse).
4. Handles session tracking, cookies, headers, etc.
5. Makes web development easier by abstracting low-
level protocol details.
✅Handling HTTP Request and Response in Servlet
Application
🔷 Step-by-Step Process
1. Client Sends Request
A user (client) sends an HTTP request (e.g., by
clicking a link or submitting a form).
The request goes to a web server (e.g., Apache
Tomcat).
2. Web Container Receives the Request
The Servlet Container (Tomcat, etc.) receives the
request.
It creates two objects:
o HttpServletRequest – contains all request data
(parameters, headers, etc.)
o HttpServletResponse – used to build and send
the response
3. Servlet Handles the Request
The container calls the servlet's service() method.
service() checks the request type and calls:
o doGet() → for GET requests
o doPost() → for POST requests
4. Servlet Processes Request
Inside doGet() or doPost(), the servlet reads:
o Input data from request object
(req.getParameter())
o Then processes the logic (e.g., DB access)
5. Servlet Sends Response
Servlet uses HttpServletResponse to:
o Set content type:
res.setContentType("text/html");
o Write output using PrintWriter
Sends the response back to the browser (client)
🔁 Example: Simple HttpServlet Handling GET
Request
java
CopyEdit
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String name =
req.getParameter("username"); // Reading input
out.println("<h2>Hello, " + name +
"!</h2>"); // Sending response
}
}
✅What is Web Application Architecture?
Web Application Architecture is the structure that defines how
the client, server, and database interact in a web application. It
explains the flow of data and how components like browser,
server, and database work together.
🔁 Main Components of Web Application Architecture
🔷 1. Client (Browser)
The end-user interface (e.g., Chrome, Firefox).
Sends requests and displays responses (HTML, CSS, JS).
🔷 2. Web Server
Receives client requests and forwards them to the servlet or
controller.
Examples: Apache Tomcat, Jetty.
🔷 3. Servlet Container (Web Container)
Executes servlet classes.
Manages servlet life cycle.
Converts HTTP requests into Java objects.
🔷 4. Application Logic (Servlets, JSP, Business Classes)
Processes client data and applies business logic.
Communicates with the database.
🔷 5. Database
Stores application data (e.g., MySQL, Oracle).
Accessed using JDBC, Hibernate, etc.
Unit-2
Java Server Pages:-
JavaServer Pages (JSP) is a server-side technology that
creates dynamic web applications. It allows developers to
embed Java code directly into HTML or XML pages, and it
makes web development more efficient.
JSP is an advanced version of Servlets. It provides
enhanced capabilities for building scalable and platform-
independent web pages.
✅What is JSP?
1. JSP stands for JavaServer Pages – a server-side
technology used to create dynamic web pages using
Java.
2. JSP is a part of the Java EE (Jakarta EE) platform.
3. It allows embedding Java code directly into
HTML pages using special tags like .
4. JSP files have a .jsp extension.
5. It is mainly used to create the view part of an MVC-
based web application.
6. When a client requests a .jsp file, the server converts
it into a Servlet, compiles it, and executes it.
7. JSP is suitable for presentation logic, while servlets
are better for business logic.
8. It provides simpler and faster development of web
pages compared to servlets alone.
9. JSP supports tag libraries, JSTL, and custom tags
to separate Java code from HTML.
10. JSP automatically manages the response and
request objects, unlike servlets where they need to
be handled manually.
JSP Architecture:-
JSP architecture gives a high-level view of the working of JSP.
JSP architecture is a 3 tier architecture. It has a Client, Web
Server, and Database.
Main Components of JSP Architecture
JSP architecture is typically divided into three main
components:
1. Client
The user interacts with the application via a web
browser.
Sends HTTP requests to the server.
Receives and displays the final HTML response.
2. Web Server with JSP Engine
Hosts JSP pages.
Responsible for processing client requests.
The JSP Engine performs:
o Translation of JSP into Servlet.
o Compilation of Servlet.
o Execution of Servlet to generate HTML output.
🔸 Internal processing includes:
Translation: JSP → Servlet (.java)
Compilation: Servlet → Bytecode (.class)
Execution: Servlet generates HTML using request
data.
3. Database
Stores data that can be retrieved or modified using
Java code inside the JSP.
JSP can use JDBC or JavaBeans to interact with the
database.
JSP Architecture Flow:-
🔁 Architecture Workflow (Step-by-step)
1. Client sends a request to a .jsp file.
2. The web server receives the request.
3. JSP Engine:
o Converts the JSP to a Servlet ( .java file).
o Compiles the Servlet to .class file.
4. The Servlet is executed:
o Business logic is performed.
o Data may be fetched from the database.
5. The Servlet generates an HTML response.
6. The response is sent back to the client browser.
Lifecycle of JSP:-
Steps Involved in a JSP lifecycle:
Translation
Compilation
ClassLoading
Instantiation
Initialization
Request Processing
Destroy
🔁 1. Translation
The JSP engine translates the .jsp file into a Java servlet
source file (.java).
For example: home.jsp → home_jsp.java
This happens only once, when the page is requested for the
first time or modified.
🔷 2. Compilation
The translated Java servlet (.java file) is compiled into a
Java bytecode (.class) file.
Example: home_jsp.java → home_jsp.class
🔷 3. Class Loading
The compiled .class file is loaded into the JVM (Java
Virtual Machine) by the class loader.
This step prepares the servlet class to be instantiated and
used.
🔷 4. Instantiation
The servlet (generated from JSP) is instantiated (i.e., an
object of the class is created) by the container.
🔷 5. Initialization (jspInit() method)
The container calls the jspInit() method.
This method is executed once during the life of the JSP.
You can write code here to initialize resources, like
opening DB connections.
🔷 6. Request Processing (_jspService() method)
For every client request, the container calls the
_jspService() method.
It processes the HTTP request, executes business logic,
and generates a response (usually HTML).
This method is not overridden by developers.
🔷 7. Destroy (jspDestroy() method)
When the JSP is no longer needed or the server is shutting
down, the container calls the jspDestroy() method.
This is the place to release resources, such as closing files
or database connections.
✅JSP Tags and Expressions
JSP (JavaServer Pages) provides various types of tags and
expressions to embed Java code in HTML for dynamic web
page creation.
🔁 1. JSP Scriptlet Tag
➤Syntax:
<% Java code %>
➤Description:
Used to write any Java code block inside the JSP.
Code inside scriptlet runs every time the page is requested.
➤Example:
<%
int a = 10;
out.println("Value of a is: " + a);
%>
🔁 2. JSP Expression Tag
➤Syntax:
<%= expression %>
➤Description:
Outputs the result of the expression directly to the client.
Equivalent to out.print(expression).
➤Example:
<%= 10 + 20 %>
Output: 30
🔁 3. JSP Declaration Tag
➤Syntax:
<%! declaration %>
➤Description:
Used to declare methods or variables that can be used in
scriptlets.
Code here goes outside the _jspService() method (i.e., at
class level).
➤Example:
<%! int square(int x) {
return x * x;
} %>
<%= square(5) %>
Output: 25
🔁 4. JSP Directive Tag
➤Syntax:
<%@ directive attribute="value" %>
➤Description:
Provides instructions to the JSP container.
Common directives: page, include, taglib.
➤Examples:
👉 Page Directive:
<%@ page language="java" contentType="text/html" %>
👉 Include Directive:
<%@ include file="header.jsp" %>
🔁 5. JSP Action Tag
➤Syntax:
<jsp:action_name attributes />
➤Description:
Predefined XML-style tags used to control JSP execution
and interact with JavaBeans, forwarding, etc.
➤Examples:
👉 Forward:
<jsp:forward page="home.jsp" />
👉 UseBean:
<jsp:useBean id="user" class="com.example.User"
scope="session" />
🔁 6. JSP Comment Tag
➤Syntax:
<%-- comment --%>
➤Description:
JSP comment that is not sent to the client’s browser.
Different from HTML comments.
➤Example:
<%-- This is a JSP comment --%>
✅JSP Implicit Objects
In JSP, implicit objects are predefined objects created
by the JSP container. They are automatically available
in every JSP page without needing to declare or
instantiate them.
These objects make it easier to interact with HTTP
requests, responses, sessions, application context, etc.
🔁 List of JSP Implicit Objects
No. Object Type Description
Used to send output to the
1 out JspWriter
client.
No. Object Type Description
Represents the client's
2 request HttpServletRequest
request.
Used to send response to
3 response HttpServletResponse
the client.
4 session HttpSession Represents user's session.
Represents application-
5 application ServletContext
wide data.
Provides configuration info
6 config ServletConfig
of servlet.
Provides access to all other
7 pageContext PageContext
implicit objects.
Object (current JSP Refers to the current JSP
8 page
page) page.
Only available in error
9 exception Throwable
pages.
🔁 Detailed Description with Examples
1. out
Sends output to client.
<% out.println("Welcome to JSP!"); %>
2. request
Contains request data like parameters, headers.
<%= request.getParameter("username") %>
3. response
Used to modify the response, like redirecting.
<% response.sendRedirect("home.jsp"); %>
4. session
Stores user-specific data across multiple requests.
<% session.setAttribute("name", "Shafali"); %>
<%= session.getAttribute("name") %>
5. application
Stores global data accessible to all JSPs.
<% application.setAttribute("appName", "MyApp"); %>
6. config
Provides init parameters defined in web.xml.
<%= config.getInitParameter("dbUser") %>
7. pageContext
Access to page attributes and other implicit objects.
<%= pageContext.getRequest().getRemoteAddr() %>
8. page
Refers to the current page as an object.
<%= page.getClass().getName() %>
9. exception
Only used in error JSP pages (isErrorPage="true").
<%= exception.getMessage() %>
✅What are JSP Directives?
JSP directives are instructions to the JSP container
that affect the overall structure of the JSP page.
They are not displayed on the client-side and are
processed at translation time (i.e., when the JSP is
converted to a servlet).
Directives are enclosed within:
<%@ directive_name attribute="value" %>
🔁 Types of JSP Directives
There are three main types of JSP directives:
Directive
No. Description
Type
Defines page-level settings (like content type,
1. page
import classes, error pages)
Includes contents of another file at translation
2. include
time
3. taglib Declares use of custom tags using a tag library
✅1. Page Directive
🔷 Syntax:
<%@ page attribute="value" %>
🔷 Purpose:
Used to define page-level instructions for:
language
content type
buffer size
import packages
error handling
session control
🔷 Common Attributes of page Directive:
Attribute Description
Attribute Description
language Language used (default is Java)
import Imports Java packages (like java.util.*)
Defines MIME type (text/html, text/xml,
contentType
etc.)
session Whether to use session object (true or false)
buffer Sets buffer size (e.g., 8kb)
autoFlush Controls whether buffer auto-flushes
errorPage Defines error page for exceptions
Indicates if the page is an error page
isErrorPage
(true/false)
🔷 Example:
<%@ page language="java" contentType="text/html"
import="java.util.*" errorPage="error.jsp" %>
✅2. Include Directive
🔷 Syntax:
<%@ include file="filename.jsp" %>
🔷 Purpose:
Includes the content of another JSP file at translation
time (static inclusion).
Useful for including headers, footers, navigation
menus, etc.
🔷 Example:
<%@ include file="header.jsp" %>
The entire content of header.jsp is included at
compile time.
🧩 Note: This is different from <jsp:include />, which
is a runtime inclusion.
✅3. Taglib Directive
🔷 Syntax:
<%@ taglib uri="tag_library_URI" prefix="prefix"
%>
🔷 Purpose:
Used to declare a custom tag library (like JSTL - Java
Standard Tag Library) in JSP.
uri: Unique identifier (can be a URL or TLD file
path).
prefix: Prefix used to access custom tags.
🔷 Example (JSTL):
<%@ taglib
uri="http://java.sun.com/jsp/jstl/core"
prefix="c" %>
Usage:
<c:out value="${username}" />
✅What is JSTL?
JSTL stands for JavaServer Pages Standard Tag Library.
It is a collection of custom JSP tags that encapsulate core
functionality, allowing developers to write less Java code in JSP
and use tags instead.
JSTL provides tags for common tasks such as:
Iteration
Condition checking
Formatting
SQL operations
XML handling
✅Categories of JSTL Tags
JSTL tags are grouped into five categories:
🔷 1. Core Tags (c prefix)
Used for basic operations like conditionals, loops, URL
handling, etc.
Tag Description
<c:out> Displays value of an expression
Executes code block if a condition
<c:if>
is true
<c:choose>, <c:when>, Conditional branching (like
<c:otherwise> switch-case)
Loop through collection (like a for
<c:forEach>
loop)
<c:set> Sets a value to variable
<c:remove> Removes a scoped variable
✅Example:
<c:forEach var="i" begin="1" end="5">
<p>Number: ${i}</p>
</c:forEach>
🔷 2. Formatting Tags (fmt prefix)
Used for internationalization (i18n) and formatting of
numbers, dates, messages.
Tag Description
<fmt:formatNumber> Formats numbers
<fmt:formatDate> Formats date/time
Tag Description
<fmt:message> Loads messages from resource bundles
✅Example:
<fmt:formatNumber value="12345.678" type="currency" />
🔷 3. SQL Tags (sql prefix)
Used to access and manipulate databases directly from JSP (not
recommended for production).
Tag Description
<sql:setDataSource> Sets DB connection
<sql:query> Executes SELECT queries
<sql:update> Executes INSERT/UPDATE/DELETE
<sql:param> Passes parameters to SQL queries
✅Example:
<sql:setDataSource var="ds"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/test" user="root"
password="root"/>
<sql:query var="result" dataSource="${ds}">
SELECT * FROM students
</sql:query>
🔷 4. XML Tags (x prefix)
Used to work with XML data.
Tag Description
<x:parse> Parses XML data
<x:out> Outputs XML data
<x:forEach> Iterates over XML nodes
🔷 5. Function Tags (fn prefix)
Used to perform string manipulation functions.
Tag Description
Checks if string contains a
fn:contains()
substring
fn:length() Returns length of a string
fn:toLowerCase() /
Converts string case
fn:toUpperCase()
✅Example:
${fn:toUpperCase("hello")}
✅What is AJAX?
AJAX stands for Asynchronous JavaScript and XML.
It is a web development technique used to send and receive
data from the server without reloading the entire webpage.
🔁 Key Features of AJAX:
It allows asynchronous communication.
Works with XMLHttpRequest or Fetch API in
JavaScript.
Used to update parts of a web page dynamically (e.g., live
search, chat apps, form submissions).
✅Working of AJAX (with Diagram)
🔷 Steps:
1. User event occurs (e.g., button click).
2. JavaScript creates XMLHttpRequest object.
3. Request is sent to the server asynchronously.
4. Server processes the request and sends back a response
(data).
5. JavaScript receives the response.
6. Page content is updated dynamically without full reload.
✅AJAX Methods: load( ), get( ), post( )
These are shorthand methods provided by jQuery to perform
AJAX operations easily.
🔷 1. load() Method
Loads data from the server and places it into a selected
HTML element.
Uses GET request in the background.
✅Syntax:
$("#element").load("data.jsp");
✅Example:
$("#content").load("info.html");
Loads the content of info.html into the HTML element with id
content.
🔷 2. get() Method
Sends an HTTP GET request to fetch data from the server.
Used when no sensitive data is being sent.
✅Syntax:
$.get(URL, data, callback);
✅Example:
$.get("data.php", { name: "Shafali" },
function(response) {
$("#result").html(response);
});
🔷 3. post() Method
Sends an HTTP POST request (usually used for sending
form data).
More secure than GET (data not visible in URL).
✅Syntax:
$.post(URL, data, callback);
✅Example:
$.post("submit.php", { username: "admin", password:
"1234" }, function(response) {
$("#message").html(response);
});
✅Advantages of AJAX
S.No Advantage Description
1. ✅Faster Only updates part of the web page, so it
performance loads faster.
2. ✅No full page Data is fetched in the background without
reload refreshing the page.
3. ✅Improved user Smooth interactions, like live search, auto-
experience suggestions, etc.
4. ✅Reduced server Only necessary data is sent/received, not the
load whole page.
5. ✅Asynchronous User can continue interacting while data
communication loads.
When written properly or with libraries like
6. ✅Cross-browser
jQuery, AJAX works across all modern
support
browsers.
7. ✅Rich web Enables applications like Google Maps,
applications Gmail, Facebook feeds, etc.
❌Disadvantages of AJAX
S.No Disadvantage Description
1. ❌Requires AJAX won’t work if JavaScript is disabled in the
S.No Disadvantage Description
JavaScript browser.
Content loaded via AJAX may not be indexed by
2. ❌SEO limitations
search engines.
Prone to attacks like XSS (Cross-Site Scripting)
3. ❌Security risks and CSRF (Cross-Site Request Forgery) if not
handled securely.
4. ❌Browser Older browsers (like old Internet Explorer) may
compatibility issues require special handling.
5. ❌Debugging Asynchronous operations are harder to debug
difficulty and trace.
6. ❌Back button AJAX does not update browser history by
issues default, which can confuse users.
Unit-3
JDBC (Java Database Connectivity) is an API (Application
Programming Interface) in Java that allows Java applications to
connect and interact with databases.
JDBC is a Java standard for connecting to relational
databases like MySQL, Oracle, PostgreSQL, etc. It
enables executing SQL statements, retrieving results, and
managing database connections directly from Java code.
🔁 Key Features of JDBC:
Connects Java applications with a database.
Executes SQL queries (e.g., SELECT, INSERT, UPDATE,
DELETE).
Retrieves and updates data from databases.
Supports different databases using drivers.
Architecture of JDBC
the major components of JDBC architecture are as
follows:
1. Application
2. The JDBC API
3. DriverManager
4. JDBC Drivers
5. Data Sources
🔁 1. Application
These are Java programs like applets, servlets, or
desktop apps.
They use JDBC to communicate with a database.
The application sends SQL queries to the database
and processes the results.
🔷 2. JDBC API
API stands for Application Programming Interface.
It provides a set of classes and interfaces to interact
with databases.
Important classes and interfaces:
o DriverManager – Manages drivers and
connections
o Connection – Connects to the database
o Statement – Executes SQL queries
o ResultSet – Stores data returned from queries
🔷 3. DriverManager
It acts as a middleman between the Java application and
the drivers.
Acts as a controller that manages all database
drivers.
It is used to establish a connection to the database.
Method used:
Connection con =
DriverManager.getConnection(URL, username,
password);
🔷 4. JDBC Drivers
Drivers are programs that help Java talk to a
specific database.
Each database has its own driver (MySQL, Oracle,
MSSQL, etc.).
To use a driver, we load it using:
Class.forName("com.mysql.cj.jdbc.Driver");
🧩 Types of JDBC Drivers:
1. Type 1: JDBC-ODBC Bridge
2. Type 2: Native API
3. Type 3: Network Protocol
4. Type 4: Thin Driver (Pure Java – most commonly
used)
🔷 5. Data Sources
These are the actual databases like MySQL, Oracle,
PostgreSQL, etc.
JDBC helps Java applications connect to and use
these databases.
Data sources are where your application stores and
retrieves data.
Step-by-Step How It Works:
1. Java application loads the JDBC driver.
2. It uses DriverManager to open a connection to the
database.
3. Then, the app sends an SQL query like SELECT *
FROM users.
4. The JDBC driver translates this into a form the
database understands.
5. The database processes the query and sends back
the data.
6. The Java app receives the result and uses it.
✅Types of JDBC Drivers
JDBC drivers are categorized into four types. Each type
tells us how Java communicates with the database.
🔁 Type 1: JDBC-ODBC Bridge Driver
🔷 Description:
This driver uses ODBC (Open Database
Connectivity) driver to connect to the database.
It acts as a bridge between JDBC calls and ODBC
calls.
✅ Advantages:
Easy to use.
Useful for testing applications on local systems.
❌ Disadvantages:
Slow performance (goes through multiple layers).
Requires ODBC driver installed on client machine.
Not platform independent.
Deprecated in Java 8 and removed in later versions.
🔁 Type 2: Native-API Driver
🔷 Description:
Uses native (C/C++) libraries of the database to convert
JDBC calls.
Needs the client-side library of the database.
✅Advantages:
Better performance than Type 1.
Uses native API, so efficient for the specific database.
❌Disadvantages:
Requires native DB libraries installed.
Not portable (depends on OS).
Not suitable for internet-based applications.
🔁 Type 3: Network Protocol Driver (Middleware Driver)
🔷 Description:
Uses a middleware server to connect to the actual
database.
JDBC calls are converted to database-independent
protocol, then sent to middleware which talks to the
database.
✅Advantages:
No need for DB libraries on the client machine.
Good for web-based applications.
Allows connection pooling, load balancing, etc.
❌Disadvantages:
Requires middleware (adds complexity).
Slightly slower than Type 4 due to the extra layer.
🔁 Type 4: Thin Driver (Pure Java Driver)
🔷 Description:
Written entirely in Java.
Converts JDBC calls directly into the database’s
native protocol.
No need for native libraries or middleware.
✅ Advantages:
Fastest and most efficient.
100% platform independent (pure Java).
Ideal for web and enterprise applications.
❌ Disadvantages:
One driver is required for each type of database.
Components of JDBC
JDBC has four main components that are used to connect with a
database as follows:
1. JDBC API
2. JDBC Driver Manager
3. JDBC Test Suite
4. JDBC-ODBC Bridge Driver
🔁 1. JDBC API
It is a collection of classes and interfaces in Java used to
interact with databases.
These are defined in the packages:
o java.sql
o javax.sql
It allows developers to:
o Establish database connections
o Send SQL queries
o Retrieve results
o Handle transactions
🧩 Important interfaces/classes in JDBC API:
Connection
Statement, PreparedStatement
ResultSet
DriverManager
SQLException
🔷 2. JDBC Driver Manager
It is a class that handles loading JDBC drivers and
establishing a connection to the database.
It keeps track of all registered drivers.
🔷 3. JDBC Test Suite
This is a set of tools and tests provided by Sun
Microsystems (now Oracle) to test JDBC driver
implementations.
It ensures that a JDBC driver is compliant with the JDBC
specification.
Mainly used by database and driver vendors to verify that
their drivers work correctly with JDBC.
🔷 4. JDBC-ODBC Bridge Driver (Type 1 Driver)
This was an early solution to allow Java programs to
connect to ODBC-supported databases.
It translated JDBC calls to ODBC, then to the database.
Now considered obsolete and removed from Java 8
onwards.
🔁 Summary Table:
Component Purpose
Component Purpose
Provides classes/interfaces to write database code
JDBC API
in Java
JDBC Manages and loads appropriate JDBC driver for
DriverManager connection
Used to test and validate JDBC driver
JDBC Test Suite
implementations
Early driver for connecting Java apps to ODBC
JDBC-ODBC Bridge
databases (deprecated)
JDBC connenctivity :-
Steps to Establish a JDBC Connection
Below are the steps that explains how to connect to
Database in Java:
Step 1: Import the Packages
Step 2: Load the drivers using
the forName() method
Step 3: Register the drivers using DriverManager
Step 4: Establish a connection using
the Connection class object
Step 5: Create a statement
Step 6: Execute the query
Step 7: Close the connections
🔁 1. Import JDBC Packages
You must import the required classes to use JDBC.
import java.sql.*;
🔷 2. Load and Register JDBC Driver
Load the JDBC driver class into memory.
Class.forName("com.mysql.cj.jdbc.Driver");
🧩 This step registers the driver with DriverManager.
🔷 3. Establish a Connection
Use DriverManager.getConnection() to connect to the
database.
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/yourDB", "username",
"password");
🔷 4. Create a Statement
Create a Statement or PreparedStatement to send SQL queries.
Statement stmt = con.createStatement();
Or for a parameterized query:
PreparedStatement pstmt = con.prepareStatement("SELECT
* FROM users WHERE id = ?");
🔷 5. Execute the Query
Use the statement to execute your SQL command.
ResultSet rs = stmt.executeQuery("SELECT * FROM
users");
For update/insert:
int result = stmt.executeUpdate("INSERT INTO users
VALUES (1, 'John')");
🔷 6. Process the Results
Loop through the result using ResultSet.
while(rs.next()) {
System.out.println(rs.getString("name"));
}
🔷 7. Close the Connection
Always close the connection to free resources.
rs.close();
stmt.close();
con.close();
🔁 Full Code Example:
java
CopyEdit
import java.sql.*;
public class JdbcExample {
public static void main(String[] args) {
try {
// 1. Load driver
Class.forName("com.mysql.cj.jdbc.Driver");
// 2. Connect to database
Connection con =
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb",
"root", "password");
// 3. Create statement
Statement stmt = con.createStatement();
// 4. Execute query
ResultSet rs = stmt.executeQuery("SELECT *
FROM users");
// 5. Process result
while (rs.next()) {
System.out.println(rs.getString("name"));
}
// 6. Close
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
✅Process of Creating and Executing SQL Statement in
JDBC
To interact with a database (like inserting, updating, deleting, or
retrieving data), you use SQL statements in JDBC. This
process involves:
🔷 Step 1: Establish a Database Connection
Before executing any SQL, first connect to the database.
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "root",
"password");
🔷 Step 2: Create a Statement Object
Use the Connection object to create a Statement,
PreparedStatement, or CallableStatement.
👉 Option 1: Statement (for simple static SQL)
Statement stmt = con.createStatement();
👉 Option 2: PreparedStatement (for dynamic/parameterized
SQL)
PreparedStatement pstmt = con.prepareStatement(
"SELECT * FROM users WHERE id = ?");
🔷 Step 3: Execute the SQL Query
✅For SELECT queries (returns data):
Use executeQuery()
ResultSet rs = stmt.executeQuery("SELECT * FROM
users");
✅For INSERT, UPDATE, or DELETE (modifies data):
Use executeUpdate()
int rows = stmt.executeUpdate("INSERT INTO users VALUES
(1, 'John')");
🔷 Step 4: Process the Result (if applicable)
If your query is a SELECT, process the result using ResultSet:
while(rs.next()) {
System.out.println("Name: " +
rs.getString("name"));
}
🔷 Step 5: Close All Resources
Always close ResultSet, Statement, and Connection objects to
avoid memory leaks.
rs.close();
stmt.close();
con.close();
🔁 Full Code Example: (SELECT statement)
java
CopyEdit
import java.sql.*;
public class JdbcSelectExample {
public static void main(String[] args) {
try {
// Load driver (optional in newer Java
versions)
Class.forName("com.mysql.cj.jdbc.Driver");
// Connect to DB
Connection con =
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb",
"root", "password");
// Create Statement
Statement stmt = con.createStatement();
// Execute SQL query
ResultSet rs = stmt.executeQuery("SELECT *
FROM users");
// Process result
while (rs.next()) {
System.out.println("ID: " +
rs.getInt("id") +
", Name: " +
rs.getString("name"));
}
// Close resources
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
🔁 Summary:
Step Description
1. Load & connect Connect to DB using DriverManager
2. Create statement Use Connection object to create Statement
3. Execute SQL Use executeQuery() or executeUpdate()
4. Process result Use ResultSet for SELECT queries
5. Close all resources Free memory and avoid leaks