Amritanshu
UNIT - 1
🔹 What is a Servlet?
A Servlet is a Java program that runs on a web server and handles
client requests (like from a browser) and sends responses.
👉 It is mainly used to create dynamic web applications.
📌 Example:
• Login system
• Form processing
• Online applications
🔹 Servlet Basics
✅ 1. Servlet Architecture
Client (Browser) → Web Server → Servlet → Response → Client
✅ 2. Key Features
• Platform independent (Java-based)
• Server-side processing
• Handles HTTP requests
• Faster than CGI (because no new process each time)
🔹 Servlet API (Important)
Servlet API is provided by Oracle Corporation.
It contains two main packages:
📦 1. [Link]
Contains core interfaces and classes.
Amritanshu
Important Interfaces:
• Servlet → root interface
• ServletRequest → request data
• ServletResponse → response data
Important Classes:
• GenericServlet → protocol-independent servlet
📦 2. [Link]
Used for HTTP-speci c servlets.
Important Classes:
• HttpServlet
• HttpServletRequest
• HttpServletResponse
Important Methods:
• doGet() → handles GET request
• doPost() → handles POST request
🔹 Types of Servlets
1. Generic Servlet
◦ Protocol independent
◦ Extend GenericServlet
2. HTTP Servlet (Most used)
◦ Works with HTTP protocol
◦ Extend HttpServlet
fi
Amritanshu
🔹 Servlet Life Cycle (Very Important ⭐)
The servlet life cycle is managed by the Servlet Container (like
Apache Tomcat).
🔄 Life Cycle Phases:
1⃣ Loading and Instantiation
• Servlet class is loaded by server
• Object is created
2⃣ Initialization → init()
• Called only once
• Used to initialize servlet
public void init() {
// initialization code
}
3⃣ Request Handling → service()
• Called for every request
• Decides which method to call (doGet, doPost)
👉 In HTTP Servlet:
• doGet() → for GET request
• doPost() → for POST request
4⃣ Destruction → destroy()
• Called once before servlet is removed
• Used to release resources
Amritanshu
public void destroy() {
// cleanup code
}
🔹 Servlet Life Cycle Flow
Load → init() → service() → destroy()
🔹 Advantages of Servlet
• Fast (no process creation like CGI)
• Secure
• Portable
• Scalable
🔹 Disadvantages
• Needs server (like Tomcat)
• More complex than static HTML
• Requires Java knowledge
🔥 Quick Exam Revision
• Servlet = Server-side Java program
• API packages = [Link], [Link]
• Life Cycle methods =
👉 init()
👉 service()
👉 destroy()
Amritanshu
🔹 Steps to Create a Servlet in Server
De nition:
The steps to create a servlet involve writing a Java class, con guring
it, and deploying it on a web server so that it can handle client
requests and generate responses.
Steps:
1. Create a Servlet Class
A servlet is created by writing a Java class that extends
HttpServlet.
public class MyServlet extends HttpServlet {
}
2. Override Service Methods
Override doGet() or doPost() methods to handle client requests.
3. Compile the Servlet
Compile the servlet using the servlet API (provided by the server like
Apache Tomcat).
4. Create Directory Structure
Place the compiled class inside the proper directory:
Project
└── WEB-INF
└── classes
└── [Link]
fi
fi
Amritanshu
5. Con gure the Servlet
Map the servlet to a URL using either:
(a) [Link] le
(b) Annotation
@WebServlet("/hello")
6. Deploy the Application
Copy the project folder into the webapps directory of the server
(e.g., Apache Tomcat).
7. Run the Servlet
Open a web browser and access:
[Link]
The servlet will execute and display the output.
✅ Conclusion
Thus, a servlet is created by writing a Java class, con guring it
with a URL, deploying it on a server, and accessing it through a
browser.
🎯 Tip to Remember (for exam):
👉 Create → Compile → Con gure → Deploy → Run
fi
fi
fi
fi
Amritanshu
🔹 Servlet Request
De nition:
A Servlet Request is an object created by the web server that contains
all the information sent by the client (browser) to the servlet, such as
form data, request type, and client details.
Explanation:
When a user sends a request (by clicking a link or submitting a form),
the server creates an object of HttpServletRequest and passes it
to the servlet.
The servlet uses this object to read user data.
Common Methods:
• getParameter(String name) → used to get form data
• getParameterValues() → get multiple values
• getHeader() → get request header information
• getMethod() → returns GET or POST
• getRequestURI() → returns requested URL
Example:
String name = [Link]("username");
Key Points:
• Represented by HttpServletRequest
• Created automatically by server
• Used to read client data
• Works together with response object
fi
Amritanshu
🔹 Servlet Collaboration
De nition:
Servlet Collaboration is a mechanism in which one servlet
communicates with another servlet to process a request or share data.
Explanation:
Sometimes a single servlet cannot handle the complete task.
So it transfers control or shares data with another servlet.
Types of Servlet Collaboration:
1. RequestDispatcher (Server-side)
It is used to forward the request from one servlet to another resource.
Methods:
• forward(request, response)
• include(request, response)
Features:
• Request object remains same
• URL does not change
• Faster process
2. SendRedirect (Client-side)
It is used to redirect the client to another resource.
Example:
[Link](“SecondServlet");
fi
Amritanshu
Features:
• New request is created
• URL changes in browser
• Slower than forward
🔥 Difference Between Forward and SendRedirect
Feature Forward SendRedirect
Request Same New
URL No change Changes
Speed Faster Slower
Type Server-side Client-side
✅ Conclusion
• Servlet Request is used to receive data from client
• Servlet Collaboration is used for communication between
servlets
🔹 Servlet Con g
De nition:
ServletCon g is an object created by the web container that is used to
provide initialization parameters to a speci c servlet.
Explanation:
• Each servlet has its own ServletConfig object
• It is created when the servlet is initialized
• It is used to read con guration data from [Link]
Key Points:
• One ServletConfig per servlet
fi
fi
fi
fi
fi
Amritanshu
• Used for servlet-speci c con guration
• Created by container during initialization
Common Methods:
• getInitParameter(String name) → get parameter
value
• getInitParameterNames() → get all parameter names
• getServletName() → returns servlet name
• getServletContext() → returns ServletContext object
Example (Servlet Code):
String user =
[Link](“username”);
🔹 ServletContext
De nition:
ServletContext is an object created by the web container that contains
global information shared among all servlets in a web application.
Explanation:
• Only one ServletContext per application
• Used to share data between servlets
• Also used to access application-wide parameters
Key Points:
• Shared by all servlets
• Used for application-level con guration
• Created once when application starts
fi
fi
fi
fi
Amritanshu
Common Methods:
• getInitParameter(String name) → get global
parameter
• setAttribute(String name, Object obj) → store
data
• getAttribute(String name) → retrieve data
• removeAttribute(String name) → remove data
🔥 Difference Between ServletCon g and ServletContext
Feature ServletCon g ServletContext
Scope Speci c to one servlet Whole application
Objects One per servlet One per application
Data Sharing Not shared Shared across servlets
Parameters init-param context-param
Created When servlet loads When app starts
🔹 Session Tracking
Session Tracking is a mechanism used in web applications to
maintain the state of a user across multiple requests.
Explanation:
HTTP is a stateless protocol, which means the server does not
remember previous requests.
Session tracking is used to identify a user and store their data during
multiple interactions.
Techniques of Session Tracking:
1. Cookies
• Small data stored in the browser
• Sent automatically with each request
fi
fi
fi
Amritanshu
Cookie c = new Cookie("user", "Raj");
[Link](c);
2. URL Rewriting
• Data is added to the URL
[Link]("next?user=Raj");
3. Hidden Form Fields
• Data stored in hidden input elds
<input type="hidden" name="user"
value="Raj">
4. HttpSession (Most Important)
• Server-side session management
HttpSession session =
[Link]();
[Link]("user", "Raj");
Key Points:
• Maintains user identity
• Used in login systems, shopping carts
• HttpSession is most secure and widely used
fi
Amritanshu
🔹 Filter
De nition:
A Filter is a Java component used to intercept and process requests
and responses before they reach the servlet or after they leave the
servlet.
Explanation:
Filters are used for tasks like:
• Authentication
• Logging
• Validation
• Data compression
Life Cycle of Filter:
1. init() → called once when lter is created
2. doFilter() → called for each request
3. destroy() → called when lter is removed
Key Points:
• Works before and after servlet
• Can modify request/response
• Improves security and performance
🔥 Difference (Important for Exam)
Feature Session Tracking Filter
Purpose Maintain user state Intercept request/response
Use Login, user data Authentication, logging
Scope User-speci c Application-wide
Type State management Processing component
fi
fi
fi
fi
Amritanshu
✅ Conclusion
• Session Tracking helps maintain user identity across requests
• Filters help control and process requests and responses
✍ JSP (Java Server Pages)
🔹 1. JSP Basics
De nition:
JSP (Java Server Pages) is a server-side technology used to create
dynamic web pages by embedding Java code into HTML.
Explanation:
• JSP allows mixing of HTML + Java code
• It is easier than servlets for UI development
• JSP is internally converted into a servlet by the web container
Key Features:
• Simple and easy to write
• Automatically converted into servlet
• Platform independent
• Supports reusable components (JSP tags, beans)
Basic Example:
<html>
<body>
<%= "Hello JSP" %>
</body>
</html>
fi
Amritanshu
🔹 JSP API (Important)
De nition:
JSP API provides classes and interfaces used to develop JSP pages. It
is part of the [Link] package.
Important Classes and Interfaces:
• JspPage
◦ Base interface for all JSP pages
• HttpJspPage
◦ Extends JspPage
◦ Used for HTTP-based JSP
• JspWriter
◦ Used to send output to client
• PageContext
◦ Provides access to all JSP implicit objects
Implicit Objects (from API):
• request → client request
• response → response
• out → output (JspWriter)
• session → session data
• application → ServletContext
• pageContext → access to all objects
🔹 JSP Life Cycle
De nition:
JSP life cycle describes the steps a JSP page goes through from
creation to destruction.
fi
fi
Amritanshu
Steps in JSP Life Cycle:
1. Translation Phase
JSP le is converted into a servlet (.java le)
2. Compilation Phase
Servlet is compiled into .class le
3. Class Loading
Class is loaded into memory by class loader
4. Initialization
jspInit() method is called (only once)
5. Request Processing
_jspService() method handles client requests
6. Destruction
jspDestroy() method is called when JSP is removed
Diagram Flow (write if needed):
JSP → Servlet → Class → Loaded → Init → Service →
Destroy
✅ Conclusion
JSP simpli es web development by allowing HTML with Java
code and follows a life cycle similar to servlets.
fi
fi
fi
fi
Amritanshu
✍ JSP Scripting Elements
De nition:
Scripting elements in JSP are used to insert Java code into HTML
pages to generate dynamic content.
🔹 Types of Scripting Elements:
1. Scriptlet Tag
Syntax:
<% Java code %>
Use:
• Write Java logic (loops, conditions, etc.)
Example:
<%
int a = 10;
[Link](a);
%>
2. Expression Tag
Syntax:
<%= expression %>
Use:
• Display output directly on browser
Example:
<%= "Hello JSP" %>
fi
Amritanshu
3. Declaration Tag
Syntax:
<%! variable or method %>
Use:
• Declare variables and methods
Example:
<%! int x = 5; %>
Key Points:
• Scriptlet → logic
• Expression → output
• Declaration → variables/methods
✍ JSP Implicit Objects
De nition:
Implicit objects are prede ned objects provided by JSP container that
can be used directly without declaration.
🔹 List of Implicit Objects:
1. request
• Type: HttpServletRequest
• Used to get client request data
2. response
• Type: HttpServletResponse
• Used to send response to client
fi
fi
Amritanshu
3. out
• Type: JspWriter
• Used to print output
4. session
• Type: HttpSession
• Used to store user data
5. application
• Type: ServletContext
• Used for application-wide data
6. pageContext
• Type: PageContext
• Provides access to all objects
7. con g
• Type: ServletConfig
• Contains servlet con guration
8. page
• Refers to current JSP page
9. exception
• Used for error handling (only in error pages)
✅ Conclusion
• Scripting elements are used to write Java code in JSP
• Implicit objects are prede ned objects used for handling request,
response, and data
fi
fi
fi
Amritanshu
✍ JSP Directive Elements
De nition:
Directive elements in JSP are used to provide instructions to the JSP
container about how the page should be processed.
🔹 Types of JSP Directives:
1. Page Directive
Syntax:
<%@ page attribute="value" %>
Use:
• De nes page-level settings like:
◦ language
◦ import packages
◦ error page
Example:
<%@ page import="[Link].*" %>
2. Include Directive
Syntax:
<%@ include file="[Link]" %>
Use:
• Includes content of another le at translation time
Example:
<%@ include file="[Link]" %>
fi
fi
fi
Amritanshu
3. Taglib Directive
Syntax:
<%@ taglib uri="URI" prefix="tag" %>
Use:
• Used to include custom tags (JSTL)
Key Points:
• Processed at translation time
• Used for con guration
• Do not produce output directly
✍ JSP Action Elements
De nition:
Action elements are XML-based tags used to perform actions at
request time (runtime).
🔹 Common JSP Action Tags:
1. <jsp:include>
Use:
• Includes another resource at runtime
2. <jsp:forward>
Use:
• Forwards request to another resource
fi
fi
Amritanshu
3. <jsp:param>
• Pass parameters to another resource
4. <jsp:useBean>
• Creates or locates a JavaBean
5. <jsp:setProperty>
• Sets bean property
6. <jsp:getProperty>
• Gets bean property
Key Points:
• Executed at runtime
• Used for dynamic behavior
• Written in XML format
🔥 Difference Between Directive and Action Elements
Feature Directive Elements Action Elements
Time Translation time Runtime
Purpose Con guration Perform actions
Syntax <%@ %> <jsp:...>
Output No direct output Can generate output
✅ Conclusion
• Directive elements control how JSP is processed
• Action elements perform tasks during execution
fi
Amritanshu
✍ MVC (Model View Controller)
MVC (Model-View-Controller) is a design pattern used to separate
application logic, user interface, and control ow in a web
application.
🔹 Components of MVC:
1. Model
• Represents data and business logic
• Interacts with database
👉 Example: Java classes, DAO, database operations
2. View
• Represents user interface (UI)
• Displays data to user
👉 Example: JSP, HTML
3. Controller
• Handles user requests and controls ow
• Connects Model and View
👉 Example: Servlet
🔹 Working of MVC:
1. User sends request
2. Controller (Servlet) receives request
3. Controller calls Model
4. Model processes data
5. Controller sends data to View
6. View (JSP) displays response
fl
fl
Amritanshu
🔹 Advantages of MVC:
• Separation of concerns
• Easy maintenance
• Reusable code
• Scalable applications
✍ AJAX (Asynchronous JavaScript and XML)
AJAX is a technique used to send and receive data from the
server asynchronously without reloading the entire web page.
🔹 Explanation:
• AJAX uses JavaScript to communicate with server
• Data is exchanged in formats like JSON or XML
• Only part of the page updates
🔹 Working of AJAX:
1. User performs action (click, input)
2. JavaScript sends request using XMLHttpRequest
3. Server processes request
4. Server sends response
5. Page updates without reload
🔹 Advantages of AJAX:
• Faster response
• No full page reload
• Better user experience
• Reduced server load
Amritanshu
🔥 Difference Between MVC and AJAX
Feature MVC AJAX
Type Design pattern Web technology
Purpose Structure application Improve interaction
Work Separates logic Asynchronous communication
Use Full application design Partial updates
✅ Conclusion
• MVC organizes application into Model, View, and
Controller
• AJAX improves user experience by updating data without
reloading the page
Amritanshu
UNIT - 2
✍ Hibernate
🔹 Introduction to Hibernate
Hibernate is an ORM (Object Relational Mapping) framework
in Java that is used to map Java objects to database tables and
perform database operations automatically.
Explanation:
• In JDBC, we write SQL manually
• Hibernate removes the need to write SQL
• It converts Java objects into database records
💡 Simple Understanding:
👉 Hibernate = Bridge between Java objects and Database
Example:
• Java class → Table
• Object → Row
• Variables → Columns
Features of Hibernate:
• Reduces boilerplate code
• Database independent
• Supports caching
• Automatic table mapping
• Provides HQL (Hibernate Query Language)
Amritanshu
🔹 Hibernate Architecture
De nition:
Hibernate architecture de nes how different components interact to
perform database operations.
🔹 Main Components
1. Con guration
• Loads Hibernate settings
• Reads [Link] le
2. SessionFactory
• Factory for creating Session objects
• Heavyweight object (created once)
3. Session
• Used to interact with database
• Performs CRUD operations
4. Transaction
• Used to ensure data consistency
• Begin, commit, rollback operations
5. Query (HQL/SQL)
• Used to retrieve data from database
6. Database
• Actual storage (MySQL, Oracle, etc.)
fi
fi
fi
fi
Amritanshu
🔹 Working Flow:
1. Load con guration
2. Create SessionFactory
3. Open Session
4. Begin Transaction
5. Perform operation (save/update/delete)
6. Commit Transaction
7. Close Session
🔥 Simple Flow Summary
👉 Con guration → SessionFactory → Session → Transaction →
Database
🔹 Advantages of Hibernate
• No need to write SQL
• Easy database handling
• Portable (works with multiple DBs)
• Improves performance using caching
✍ Hibernate IDE Integration
Hibernate IDE integration means con guring Hibernate in a
development environment (IDE) so that we can easily develop,
run, and manage Hibernate applications.
Explanation:
To use Hibernate, we need to integrate it with an IDE like Eclipse
IDE or IntelliJ IDEA.
fi
fi
fi
Amritanshu
🔹 Steps for Hibernate Integration:
1. Create a Java Project
• Open IDE and create a new project
2. Add Hibernate Libraries
• Add required JAR les:
◦ Hibernate core
◦ JDBC driver
◦ JPA libraries
3. Create Con guration File
• Create [Link]
4. Create Entity Class
• Create a POJO class mapped to table
5. Con gure Mapping
• Using annotations or XML mapping
6. Write Hibernate Code
• Use Session and Transaction
7. Run the Application
• Execute program inside IDE
Key Points:
• IDE makes development easier
• Helps manage libraries and con guration
fi
fi
fi
fi
Amritanshu
• Supports debugging and testing
✍ Hibernate Lifecycle
Hibernate lifecycle describes the states of an object from creation to
deletion in a Hibernate application.
🔹 Object States in Hibernate:
1. Transient State
• Object is created but not connected to database
Student s = new Student();
👉 No database interaction
2. Persistent State
• Object is connected with Hibernate session
• Changes are automatically saved
[Link](s);
3. Detached State
• Object was persistent but session is closed
[Link]();
👉 Changes are not saved automatically
4. Removed State
• Object is deleted from database
[Link](s);
Amritanshu
🔹 Lifecycle Flow:
👉 Transient → Persistent → Detached → Removed
Key Points:
• Lifecycle manages object state
• Important for database operations
• Controlled by Session object
✍ Generator Class (Hibernate)
De nition:
A Generator class in Hibernate is used to automatically generate
primary key values for entity objects.
Explanation:
• When we insert data, we don’t need to manually set ID
• Hibernate generates it automatically using generator strategies
🔹 Types of ID Generators:
1. increment
• Increases ID by 1
@GeneratedValue(strategy = [Link])
2. identity
• Uses database auto-increment
3. sequence
• Uses database sequence
fi
Amritanshu
4. uuid
• Generates unique ID (string format)
5. table
• Uses a separate table to generate IDs
Key Points:
• Automatically generates primary key
• Reduces manual work
• Ensures uniqueness
✍ Log4j
De nition:
Log4j is a logging framework used in Java applications to record log
messages (errors, warnings, info) for debugging and monitoring.
Explanation:
• Helps track application behavior
• Useful for debugging Hibernate applications
• Logs can be printed on console or saved in le
🔹 Components of Log4j:
1. Logger
• Used to log messages
2. Appender
• De nes where logs are stored (console/ le)
fi
fi
fi
fi
Amritanshu
3. Layout
• De nes format of log messages
🔹 Log Levels:
• DEBUG → Detailed information
• INFO → General information
• WARN → Warning messages
• ERROR → Errors
• FATAL → Serious errors
Key Points:
• Helps in debugging
• Improves monitoring
• Used widely with Hibernate
🔥 Difference
Feature Generator Class Log4j
Purpose Generate ID Logging
Type Hibernate feature Logging framework
Use Database operations Debugging
✅ Conclusion
• Generator class is used to automatically generate primary keys
• Log4j is used to log messages for debugging and monitoring
fi
Amritanshu
✍ Hibernate Mapping
De nition:
Hibernate Mapping is the process of linking a Java class with a
database table, where class elds are mapped to table columns.
🔹 Explanation:
Hibernate uses mapping to convert:
• Java Class → Database Table
• Object → Row (Record)
• Variables → Columns
👉 This allows Hibernate to perform database operations
automatically without writing SQL.
🔹 Types of Hibernate Mapping
1. XML Mapping (Traditional Method)
Mapping is de ned in an XML le (.[Link])
2. Annotation Mapping (Modern Method)
Mapping is done using annotations in Java class
🔹 Types of Relationships in Mapping
• One-to-One
• One-to-Many
• Many-to-One
• Many-to-Many
👉 Used to de ne relationships between tables
🔹 Key Features
• Eliminates need of writing SQL
fi
fi
fi
fi
fi
Amritanshu
• Supports automatic table mapping
• Provides database independence
• Supports associations (relationships)
🔹 Advantages
• Reduces code complexity
• Easy database operations
• Improves development speed
✍ HQL (Hibernate Query Language)
De nition:
HQL (Hibernate Query Language) is an object-oriented query
language used to retrieve data from the database using Java class
names and properties instead of table and column names.
Explanation:
• Similar to SQL but works on objects (classes)
• Database independent
• Used to perform operations like select, update, delete
Key Points:
• Uses class name (Student) instead of table name
• Uses property name (name) instead of column
• Supports joins, grouping, ordering
• Easy to write and understand
fi
Amritanshu
✍ HCQL (Hibernate Criteria Query Language)
De nition:
HCQL (Criteria API) is a query mechanism used to create queries
programmatically using Java objects instead of writing query
strings.
Explanation:
• No need to write HQL/SQL
• Queries are built using methods and objects
• Useful for dynamic queries
Key Points:
• Object-based query creation
• Type-safe and exible
• Good for dynamic conditions
• Avoids syntax errors
🔥 Difference Between HQL and HCQL
Feature HQL HCQL
Type Query language API (programmatic)
Writing String-based Object-based
Flexibility Medium High
Use Simple queries Dynamic queries
✅ Conclusion
• HQL is used to write queries using object-oriented syntax
• HCQL is used to build queries programmatically in Java
fi
fl
Amritanshu
✍ Caching in Hibernate
Caching in Hibernate is a technique used to store frequently
accessed data in memory so that it can be reused without querying
the database again, thereby improving performance.
🔹 Explanation:
• Normally, every request goes to the database
• With caching, data is stored in memory
• Next time, Hibernate fetches data from cache instead of database
👉 This reduces database load and increases speed
🔹 Types of Caching in Hibernate
1. First-Level Cache (Session Cache)
Explanation:
• Associated with Session object
• Enabled by default
• Data is stored for the duration of session
Key Points:
• Default caching
• Cannot be disabled
• Limited to one session
2. Second-Level Cache
Explanation:
• Shared across multiple sessions
• Requires con guration
• Uses cache providers (like EhCache)
fi
Amritanshu
3. Query Cache
Explanation:
• Stores results of queries
• Works with second-level cache
Key Points:
• Caches query output
• Useful for repeated queries
🔹 Advantages of Caching
• Improves performance
• Reduces database access
• Faster data retrieval
🔹 Disadvantages
• Extra memory usage
• Risk of stale (outdated) data
🔥 Summary Table
Cache Type Scope Default
First-Level Session Yes
Second-Level Application No
Query Cache Query result No
Amritanshu
UNIT-3
✍ Spring Framework
De nition:
Spring Framework is a lightweight, open-source Java framework
used to develop enterprise applications with features like
dependency injection, transaction management, and web development
support.
🔹 Explanation:
• Spring simpli es Java development
• It provides ready-made solutions for common problems
• It promotes loose coupling and modular design
🔹 Features of Spring
• Lightweight → small and easy to use
• Dependency Injection (DI) → reduces tight coupling
• Aspect-Oriented Programming (AOP) → handles cross-
cutting concerns
• Transaction Management → manages database transactions
• Integration Support → works with Hibernate, JDBC, etc.
🔹 Advantages of Spring
• Reduces code complexity
• Easy to test and maintain
• Promotes loose coupling
• Flexible and scalable
🔹 Disadvantages
• Learning curve for beginners
• Requires proper con guration
fi
fi
fi
Amritanshu
✍ Dependency Injection (DI)
Dependency Injection (DI) is a design pattern in which an object receives its dependencies from
an external source instead of creating them itself.
🔹 Explanation:
• In traditional programming, a class creates its own objects →
tight coupling
• In DI, objects are provided from outside → loose coupling
👉 This makes code more exible and easy to maintain
🔹 Example
❌ Without DI (Tight Coupling)
class A {
B obj = new B();
}
✅ With DI (Loose Coupling)
class A {
B obj;
A(B obj) {
[Link] = obj;
}
}
👉 Object is injected from outside
fl
Amritanshu
🔹 Types of Dependency Injection
1. Constructor Injection
• Dependency is provided through constructor
class A {
B obj;
A(B obj) {
[Link] = obj;
}
}
2. Setter Injection
• Dependency is provided using setter method
class A {
B obj;
void setB(B obj) {
[Link] = obj;
}
}
🔹 Advantages of DI
• Promotes loose coupling
• Easy to test (unit testing)
• Improves code reusability
• Easy to maintain and extend
Amritanshu
🔹 Disadvantages
• Slightly complex for beginners
• Requires con guration
✍ Inversion of Control (IoC)
Inversion of Control (IoC) is a principle in which the control of
object creation and management is transferred from the
programmer to the Spring container.
🔹 Explanation:
• Normally, a class creates its own objects
• In IoC, the container (Spring) creates and manages objects
👉 Control is inverted (reversed) from programmer to container
💡 Simple Understanding:
👉 “Don’t create objects, let Spring create them”
Example:
❌ Without IoC
class A {
B obj = new B();
}
✅ With IoC
class A {
B obj;
}
fi
Amritanshu
👉 Spring container injects object
🔹 IoC Container Types
1. BeanFactory
• Basic container
• Lazy initialization
2. ApplicationContext
• Advanced container
• Eager initialization
• Provides more features
🔹 Advantages of IoC
• Loose coupling
• Easy maintenance
• Better testability
✍ Autowiring
De nition:
Autowiring is a feature of Spring that automatically injects
dependencies into a bean without explicit con guration.
🔹 Explanation:
• Spring automatically connects objects
• No need to manually de ne dependencies in XML
fi
fi
fi
Amritanshu
🔹 Types of Autowiring
1. byName
• Matches bean name with property name
2. byType
• Matches bean type
3. constructor
• Injection through constructor
4. no
• Default (no autowiring)
🔹 Example (Annotation-based)
@Autowired
B obj;
🔹 Advantages of Autowiring
• Reduces con guration code
• Automatic dependency resolution
• Faster development
🔹 Disadvantages
• Less control
• Can cause confusion if multiple beans exist
fi
Amritanshu
🔥 Difference Between IoC and Autowiring
Feature IoC Autowiring
Concept Design principle Feature of Spring
Purpose Manage object creation Inject dependencies automatically
Scope Broad Speci c
✅ Conclusion
• IoC transfers control of object creation to Spring container
• Autowiring automatically injects dependencies
✍ Spring AOP (Aspect Oriented Programming)
De nition:
Spring AOP is a module of the Spring Framework used to
implement Aspect Oriented Programming, which helps in
separating cross-cutting concerns such as logging, security,
transaction management, and exception handling from the main
business logic.
Need of Spring AOP
In many applications, certain functionalities are required in
multiple modules, such as:
• Logging
• Security
• Transaction management
• Exception handling
Writing this code repeatedly causes duplication.
Spring AOP solves this by keeping such code in separate modules
called Aspects.
fi
fi
Amritanshu
Important Terms in Spring AOP
1. Aspect
A class that contains cross-cutting logic.
2. Advice
Action performed by an aspect at a speci c join point.
3. Join Point
A point during execution where aspect can be applied.
4. Pointcut
Expression that selects join points.
5. Target Object
The object whose method is being advised.
6. Weaving
Process of linking aspect with target object.
Types of Advice
• Before Advice → Executes before method
• After Advice → Executes after method
• After Returning Advice → Executes after successful
completion
• After Throwing Advice → Executes if exception occurs
• Around Advice → Executes before and after method
fi
Amritanshu
✍ Aspect using Annotation
De nition:
In annotation-based con guration, aspects are created using
Spring AOP annotations in Java classes.
Common Annotations Used
• @Aspect → Declares aspect class
• @Before → Executes before method
• @After → Executes after method
• @Around → Executes before and after method
• @Pointcut → De nes reusable pointcut
Example:
@Aspect
@Component
public class LoggingAspect {
@Before("execution(*
[Link].*.*(..))")
public void beforeAdvice() {
[Link]("Before method
execution");
}
}
Advantages
• Easy to read
• Less con guration
• Preferred in modern Spring applications
fi
fi
fi
fi
Amritanshu
✍ Aspect using XML
In XML-based con guration, aspects are de ned in the Spring
XML con guration le.
Example:
<aop:config>
<aop:aspect ref="loggingAspect">
<aop:before
method="beforeAdvice"
pointcut="execution(*
[Link].*.*(..))"/>
</aop:aspect>
</aop:config>
Explanation of Tags
• <aop:config> → Enables AOP
• <aop:aspect> → De nes aspect
• <aop:before> → De nes before advice
• <aop:pointcut> → De nes pointcut
🔥 Difference Between Annotation and XML Aspect
Con guration
Feature Annotation-based XML-based
Con guration Java Code XML File
Readability High Medium
Maintenance Easy Hard
Usage Modern Preferred Older Approach
fi
fi
fi
fi
fi
fi
fi
fi
fi
Amritanshu
✅ Conclusion
Spring allows aspect con guration using both annotations and
XML.
Annotation-based con guration is more commonly used due to
simplicity and maintainability.
✍ Spring JDBC Template
De nition:
JdbcTemplate is a class provided by the Spring Framework that
simpli es database operations using JDBC by handling resource
management and exception handling automatically.
Explanation:
In traditional JDBC, developers need to write repetitive code for:
• Loading driver
• Opening connection
• Creating statement
• Executing query
• Closing resources
Spring JDBC Template removes this boilerplate code and makes
database interaction easier.
Features of Jdbc Template
• Simpli es JDBC programming
• Automatically manages connections and resources
• Handles exceptions through Spring’s exception hierarchy
• Reduces amount of code
• Improves readability and maintainability
fi
fi
fi
fi
fi
Amritanshu
Common Methods of Jdbc Template
Method Purpose
update() Insert, Update, Delete operations
query() Retrieve multiple records
queryForObject() Retrieve single object/value
execute() Execute SQL statement
Advantages of JdbcTemplate
• Less code compared to JDBC
• Automatic exception handling
• Better performance and maintainability
• Easy integration with Spring applications
Disadvantages
• Less control compared to raw JDBC
• Requires Spring setup/con guration
✅ Conclusion
Spring JDBC Template simpli es JDBC database operations by
reducing boilerplate code and handling connection/resource
management automatically.
✍ Result Set Extractor
De nition:
Result Set Extractor is an interface in Spring JDBC used to
extract data from the entire ResultSet and convert it into an
object or collection.
fi
fi
fi
Amritanshu
Explanation:
• Processes the whole ResultSet at once
• Used for complex data extraction
• Suitable when custom logic is needed
Method:
T extractData(ResultSet rs)
Advantages
• Best for complex ResultSet processing
• Can process full ResultSet together
✍ RowMapper
RowMapper is an interface in Spring JDBC used to map each
row of ResultSet to a separate object.
Explanation:
• Processes one row at a time
• Best for simple row-to-object mapping
• JdbcTemplate internally loops through ResultSet
Method:
T mapRow(ResultSet rs, int rowNum)
Advantages
• Less code for simple mapping
• Easy to use and reusable
Amritanshu
🔥 Difference Between ResultSetExtractor and RowMapper
Feature ResultSetExtractor RowMapper
Processing Entire ResultSet One row at a time
Best For Complex extraction Simple mapping
Method extractData() mapRow()
Looping Manual loop required Automatic by JdbcTemplate
✅ Conclusion
• ResultSetExtractor is used for processing the complete
ResultSet at once
• RowMapper is used for mapping each row into an object
individually
✍ Named Parameter in Spring
A Named Parameter is a feature in Spring JDBC that allows SQL
queries to use named placeholders instead of positional (?)
placeholders.
Explanation:
In normal JDBC we write:
insert into student values(?, ?)
Using named parameters:
insert into student values(:id, :name)
👉 Here :id and :name are named parameters.
Class Used
• NamedParameterJdbcTemplate
Amritanshu
Advantages of Named Parameter
• Improves SQL readability
• Easy to understand query
• Avoids confusion with multiple ? placeholders
• Better maintainability
Disadvantages
• Slightly more setup than normal JdbcTemplate
• Not necessary for very simple queries
✅ Conclusion
Named Parameters make SQL queries more readable and
manageable by replacing positional parameters with meaningful
names.
✍ Spring ORM
De nition:
Spring ORM (Object Relational Mapping) is a module of the
Spring Framework that provides integration support for ORM
frameworks such as Hibernate, JPA, and iBatis.
Explanation:
Spring ORM simpli es the use of ORM frameworks by providing:
• Session management
• Transaction management
• Exception handling
• Dependency injection support
fi
fi
Amritanshu
Features of Spring ORM
• Integrates easily with Hibernate/JPA
• Reduces boilerplate code
• Simpli es transaction handling
• Provides consistent exception hierarchy
Advantages
• Easy ORM integration
• Better maintainability
• Improved code reusability
✍ Spring with Hibernate
Spring with Hibernate means integrating Spring Framework with
Hibernate to simplify database access and transaction
management.
Explanation:
• Spring manages beans, dependencies, and transactions
• Hibernate performs ORM and database operations
Together they provide a robust framework for enterprise
applications.
Architecture Flow
Client → Spring Bean → DAO → Hibernate → Database
Steps to Integrate Spring with Hibernate
1. Con gure DataSource
Provides database connection.
fi
fi
Amritanshu
2. Con gure SessionFactory
Creates Hibernate sessions.
3. Con gure Transaction Manager
Manages transactions.
4. Create DAO Layer
Performs database operations.
Advantages of Spring with Hibernate
• Simpli es Hibernate setup
• Automatic transaction management
• Better exception handling
• Reduces code complexity
🔥 Difference Between Spring ORM and Spring with
Hibernate
Feature Spring ORM Spring with Hibernate
Meaning Spring module for ORM support Speci c integration of Spring + Hibernate
Scope Supports multiple ORM frameworks Uses Hibernate only
Purpose General ORM integration Hibernate-based ORM implementation
✅ Conclusion
• Spring ORM provides support for integrating ORM
frameworks
• Spring with Hibernate speci cally integrates Spring and
Hibernate for ef cient database application development
fi
fi
fi
fi
fi
fi
Amritanshu
UNIT - 4
✍ Spring MVC
De nition:
Spring MVC (Model View Controller) is a web framework of
Spring used to develop web applications based on the MVC
design pattern.
Explanation:
Spring MVC separates application into three parts:
1. Model
• Contains data and business logic
2. View
• Displays data to user
• Example: JSP, HTML
3. Controller
• Handles user requests
• Communicates between Model and View
Working of Spring MVC
1. Client sends request
2. DispatcherServlet receives request
3. Controller processes request
4. Model prepares data
5. View displays response
fi
Amritanshu
Advantages of Spring MVC
• Clear separation of concerns
• Easy maintenance
• Supports annotations
• Flexible and scalable
✍ RequestParam
De nition:
@RequestParam is an annotation in Spring MVC used to
extract request parameters from the URL or form data and
bind them to method parameters.
Example:
@RequestMapping("/hello")
public String hello(@RequestParam("name")
String name) {
return "Hello " + name;
}
URL Example:
/hello?name=Raj
👉 name=Raj will be assigned to variable name
Advantages of RequestParam
• Easy parameter binding
• Reduces manual request handling
• Improves readability
fi
Amritanshu
✅ Conclusion
• Spring MVC is a framework for building web applications
using MVC architecture
• @RequestParam is used to get request parameters easily in
controller methods
✍ Form Tag Libraries in Spring MVC
De nition:
Form Tag Libraries in Spring MVC are a set of JSP custom tags
used to create HTML forms and bind form data directly to Java
model objects.
Explanation:
Spring form tags simplify form creation by:
• Reducing HTML code
• Automatically binding form elds to Java objects
• Supporting validation error display
Tag Library Declaration
<%@ taglib prefix="form" uri="http://
[Link]/tags/form" %>
Common Form Tags
1. <form:form>
Used to create a form.
fi
fi
Amritanshu
2. <form:input>
Used for text input.
3. <form:password>
Used for password eld.
4. <form:checkbox>
Used for checkbox.
5. <form:radiobutton>
Used for radio button.
6. <form:select>
Used for dropdown list.
7. <form:errors>
Displays validation errors.
Advantages of Form Tag Libraries
• Automatic form-data binding
• Reduces manual HTML coding
• Easy validation support
• Better readability and maintainability
✅ Conclusion
Form Tag Libraries in Spring MVC simplify form creation and
data binding between JSP pages and Java model objects.
fi
Amritanshu
✍ MVC Validation
De nition:
MVC Validation is the process of validating user input in a
Spring MVC application before processing the request.
Explanation:
Validation ensures that:
• Required elds are not empty
• Data format is correct
• Invalid data is rejected
Validation Annotations
Annotation Purpose
@NotNull Field cannot be null
@Size Checks length
@Email Valid email format
@Min / @Max Checks numeric range
@Pattern Regex-based validation
Example
public class Student {
@NotNull
@Size(min=3,max=20)
private String name;
}
fi
fi
Amritanshu
Advantages
• Prevents invalid data
• Improves security
• Better user experience
✍ MVC CRUD Operation
CRUD stands for Create, Read, Update, Delete operations
performed in an MVC-based web application.
Explanation:
In Spring MVC:
• Model → Represents data/entity
• View → Displays data/UI
• Controller → Handles requests
CRUD Operations
1. Create
Insert new record into database
2. Read
Fetch/display records
3. Update
Modify existing record
4. Delete
Remove record from database
Amritanshu
MVC CRUD Flow
1. User sends request
2. Controller receives request
3. Service/DAO processes data
4. Database operation performed
5. Result sent to View
Example URLs
Operation URL
Create /addStudent
Read /students
Update /editStudent/{id}
Delete /deleteStudent/{id}
Advantages
• Organized code structure
• Easy maintenance
• Clear separation of concerns
✅ Conclusion
• MVC Validation ensures valid user input before processing
• MVC CRUD operations implement Create, Read, Update,
and Delete functionality in MVC applications
Amritanshu
✍ Spring MVC Applications
De nition:
A Spring MVC Application is a web application developed using
the Spring MVC framework based on the Model-View-
Controller design pattern.
Explanation:
Spring MVC divides the application into three components:
1. Model
• Contains data and business logic
2. View
• Represents presentation layer
• Example: JSP, HTML
3. Controller
• Handles user requests
• Communicates between Model and View
Working of Spring MVC Application
1. Client sends request
2. DispatcherServlet receives request
3. Controller handles request
4. Model processes data
5. View displays response
fi
Amritanshu
Advantages
• Separation of concerns
• Easy maintenance
• Reusable components
• Supports annotations
✍ Security in Spring MVC
Security in Spring MVC refers to protecting web applications
from unauthorized access and attacks using authentication and
authorization mechanisms.
Common Security Features
1. Authentication
• Veri es user identity
• Example: Login username/password
2. Authorization
• Determines access rights
• Example: Admin/User roles
3. CSRF Protection
• Prevents Cross-Site Request Forgery attacks
4. Password Encryption
• Secures stored passwords
5. Session Management
• Manages user sessions securely
fi
Amritanshu
Spring Security
Spring provides Spring Security module for implementing
security in Spring MVC applications.
Example Features of Spring Security
• Login/Logout support
• Role-based access control
• Password encoding
• Security lters
✅ Conclusion
• Spring MVC applications use MVC architecture for web
development
• Security mechanisms protect the application from
unauthorized access and attacks
fi
Amritanshu
UNIT - 5
✍ Spring Boot
De nition:
Spring Boot is a framework built on top of Spring that simpli es
the development of stand-alone, production-ready Spring
applications.
Explanation:
It reduces con guration effort and provides built-in tools for rapid
application development.
Features of Spring Boot
• Auto con guration
• Embedded server (Tomcat/Jetty)
• Starter dependencies
• Minimal con guration
• Production-ready features
Advantages
• Faster development
• No XML con guration
• Easy deployment
• Simpli ed dependency management
fi
fi
fi
fi
fi
fi
fi
Amritanshu
✍ REST
De nition:
REST (Representational State Transfer) is an architectural style
used to develop web services that communicate over HTTP.
Explanation:
RESTful services allow clients and servers to exchange data using
HTTP methods.
HTTP Methods Used in REST
Method Purpose
GET Retrieve data
POST Create new data
PUT Update existing data
DELETE Remove data
REST API Example
@RestController
public class StudentController {
@GetMapping("/students")
public List<Student> getStudents() {
return [Link]();
}
}
fi
Amritanshu
✍ Spring Boot with REST
De nition:
Spring Boot with REST is used to create RESTful web services
easily using Spring Boot and annotations.
Common REST Annotations
Annotation Purpose
@RestController Marks class as REST controller
@GetMapping Handles GET request
@PostMapping Handles POST request
@PutMapping Handles PUT request
@DeleteMapping Handles DELETE request
Advantages of Spring Boot REST
• Easy REST API development
• Automatic JSON conversion
• Embedded server support
• Minimal setup required
✅ Conclusion
Spring Boot simpli es application development, and when
combined with REST, it helps build powerful and scalable web
services quickly.
fi
fi
Amritanshu
✍ Spring Boot Architecture
De nition:
Spring Boot Architecture refers to the layered structure and
internal components used to develop and run Spring Boot
applications ef ciently.
Architecture Layers
1. Presentation Layer
• Handles client requests
• Contains Controllers / REST Controllers
• Communicates with users
2. Business Layer
• Contains business logic
• Processes application data
• Contains Service classes
3. Persistence Layer
• Handles database operations
• Contains Repository / DAO classes
4. Database Layer
• Stores application data
Architecture Flow
Client → Controller → Service → Repository → Database
fi
fi
Amritanshu
Internal Components of Spring Boot
1. Starter Dependencies
• Prede ned dependency bundles for easy setup
2. Auto Con guration
• Automatically con gures application based on dependencies
3. Embedded Server
• Built-in web server like Apache Tomcat
4. Actuator
• Provides monitoring and management tools
Advantages of Spring Boot Architecture
• Layered and organized design
• Easy maintenance
• Fast development
• Minimal con guration
✅ Conclusion
Spring Boot Architecture uses a layered approach to separate
concerns and simplify enterprise application development.
fi
fi
fi
fi
Amritanshu
✍ JSON
JSON (JavaScript Object Notation) is a lightweight text-based
data format used for storing and exchanging data between client
and server.
Explanation:
• JSON is easy for humans to read and write
• Easy for machines to parse and generate
• Commonly used in web services and REST APIs
JSON Syntax Rules
• Data is stored in key–value pairs
• Keys and string values are enclosed in double quotes
• Objects are enclosed in { }
• Arrays are enclosed in [ ]
Example of JSON
{
"id": 1,
"name": "Raj",
"city": "Bhopal"
}
Uses of JSON
• Data exchange between client and server
• Used in REST APIs
• Con guration les
• Storing structured data
fi
fi
Amritanshu
Advantages of JSON
• Lightweight
• Fast data transfer
• Easy to understand
• Language independent
Disadvantages of JSON
• Less secure if not validated
• Limited support for comments
✅ Conclusion
JSON is a lightweight and widely used format for exchanging
structured data in modern web applications.
✍ Spring Boot Database
De nition:
Spring Boot Database support provides easy integration of
databases into Spring Boot applications using auto-con guration
and built-in database connectivity support.
Explanation:
Spring Boot simpli es database setup by automatically
con guring:
• Database connection
• DataSource object
• ORM integration
• Transaction management
fi
fi
fi
fi
Amritanshu
Database Con guration
Database details are con gured in
[Link] or [Link].
Supported Database Technologies
• JDBC
• JPA
• Hibernate
• Spring Data JPA
How It Works
1. Con gure database properties
2. Spring Boot creates DataSource automatically
3. Application connects to database
4. Repository/DAO performs operations
Advantages
• Minimal con guration
• Auto DataSource setup
• Easy integration with ORM frameworks
• Supports multiple databases
✅ Conclusion
Spring Boot Database support simpli es database connectivity and
integration, reducing manual con guration and speeding up
development.
fi
fi
fi
fi
fi
fi
Amritanshu
✍ Caching in Spring Boot
De nition:
Caching in Spring Boot is a mechanism used to store frequently
accessed data in memory so that future requests can be served
faster without repeatedly accessing the database.
Explanation:
• First time data is fetched from database
• Data is stored in cache
• Next time same data is returned from cache
👉 This improves performance and reduces database load.
Working of Caching
1. Client requests data
2. Application checks cache
3. If data exists → return from cache
4. If not → fetch from database and store in cache
Caching Annotations in Spring Boot
Annotation Purpose
@EnableCaching Enables caching in application
@Cacheable Stores method result in cache
@CachePut Updates cache
@CacheEvict Removes data from cache
fi
Amritanshu
Advantages of Caching
• Improves performance
• Faster response time
• Reduces database hits
• Enhances scalability
Disadvantages
• Extra memory consumption
• Risk of stale/outdated data
✅ Conclusion
Caching in Spring Boot improves application performance by
storing frequently used data in memory and reducing database
access.
✍ Spring Boot REST API and Spring Cloud Components
✍ Spring Boot REST API
De nition:
A Spring Boot REST API is a web service built using Spring
Boot that exposes application data and functionality over HTTP
using REST principles.
Explanation:
REST API allows communication between client and server using
HTTP methods.
fi
Amritanshu
HTTP Methods Used
Method Purpose
GET Retrieve data
POST Create data
PUT Update data
DELETE Delete data
REST API Example
@RestController
public class StudentController {
@GetMapping("/students")
public List<Student> getStudents() {
return [Link]();
}
}
Advantages
• Lightweight
• Platform independent
• Easy client-server communication
• Supports JSON/XML response
Amritanshu
✍ Spring Cloud Components
De nition:
Spring Cloud is a framework used for building distributed and
microservice-based applications by providing tools for
con guration, service discovery, routing, and fault tolerance.
Major Spring Cloud Components
1. Eureka Server
• Service registry/discovery
• Helps microservices nd each other
2. Con g Server
• Centralized con guration management
3. API Gateway
• Single entry point for all client requests
4. Load Balancer
• Distributes requests among multiple service instances
5. Circuit Breaker
• Prevents cascading failures in microservices
6. Feign Client
• Simpli es inter-service REST communication
fi
fi
fi
fi
fi
fi
Amritanshu
Advantages of Spring Cloud
• Supports microservices architecture
• Centralized con guration
• Better fault tolerance
• Service discovery and load balancing
✅ Conclusion
• Spring Boot REST API is used to create RESTful web
services
• Spring Cloud provides components for managing distributed
microservice-based systems
fi