1.
Wildcard and Its Types (in Java Generics)
What is a Wildcard?
A wildcard (?) in Java Generics represents an unknown type.
It is used to make code more flexible and reusable when working with generic classes,
methods, or interfaces.
Why use Wildcards?
● To allow methods to work with different data types
● To achieve type safety
● To reduce code duplication
Why Wildcards Are Needed
● Generic classes become too restrictive
● You cannot easily work with related types (like parent and child classes
Wildcards solve this by allowing controlled flexibility while still maintaining compile-time
safety.
Types of Wildcards
1. Unbounded Wildcard (?)
● Accepts any type >>The actual type is unknown
● Used when you don't care about the specific type
● Mostly used for reading data
● When you only want to access data >> when to use
Example:
import [Link].*;
public class Test {
static void display(List<?> list) {
for (Object obj : list) {
[Link](obj);
}
}}
2. Upper Bounded Wildcard (? extends Type)
● Accepts the specified type or its subclasses
● Used for reading data safely
● Restricts the wildcard to a specific inheritance hierarchy
● When you want to read values >>when to use
Example:
static void sum(List<? extends Number> list) {
for (Number n : list) {
[Link](n);
✔ Accepts Integer, Float, Double
3. Lower Bounded Wildcard (? super Type)
● Accepts the specified type or its superclasses
● Used for writing data
● When you want to add or store data >>>when to use
Example:
static void addNumber(List<? super Integer> list) {
[Link](10);
✔ Accepts Integer, Number, Object
2. POJO Programming Model (with Example)
Generally, a POJO class contains variables and their Getters and
Setters.
The POJO classes are similar to Beans as both are used to define the
objects to increase the readability and re-usability.
The only difference between them that Bean Files have some
restrictions but, the POJO files do not have any special restrictions.
POJO simply means a class that is not forced to implement any
interface, extend any specific class, contain any pre-described
annotation or follow any pattern due to forced restriction.
POJO class is used to define the object entities. For example, we can
create an Employee POJO class to define its objects.
Below is an example of Java POJO class:
POJO stands for Plain Old Java Object.
It is a simple Java object that does not depend on any special framework, library, or
container.
A POJO follows normal Java rules and is not forced to extend, implement, or annotate
anything to work.
The POJO programming model focuses on:
● Simplicity >>Easy to read and understand
● Loose coupling >>Classes are independent of frameworks
● Reusability >>Web applications >Desktop application
● Maintainability >>Changes are easy to manage
● Easy testing >>POJOs can be tested using simple unit tests
POJO (Plain Old Java Object) is a simple Java class that:
● Does not extend any special class
● Does not implement special interfaces
● Uses private fields + getters/setters
Structure of a POJO Class (Conceptual)
A typical POJO contains:
● Private variables
● Getter and setter methods
● Optional business logic methods
● Optional constructors
Advantades of its
● Clean and readable code
● Framework-independent design
● Better performance
● Easy debugging
● Encourages best practices like encapsulation
The POJO class must be public.
✓ It must have a public default constructor.
✓ It may have the arguments constructor.
✓ All objects must have some public Getters and Setters to access the
object values by other Java Programs.
✓ The object in the POJO Class can have any access modifies such as
private, public, protected. But, all instance variables should be private
for improved security of the project.
✓ A POJO class should not extend predefined classes.
✓ It should not implement prespecified interfaces.
✓ It should not have any prespecified annotation.
Example of POJO Class
public class Student {
private int id;
private String name;
public int getId() {
return id;
public void setId(int id) {
[Link] = id;
}
public String getName() {
return name;
public void setName(String name) {
[Link] = name;
}}
3. Dependency Injection (DI) in Spring
● Dependency Injection (DI) is a design principle where an object’s
dependencies are provided by the Spring container instead of the
object creating them itself.
● Spring manages object creation and injects required dependencies
automatically, improving loose coupling and testability.
● The container injects these dependencies when it creates the
object.
Why DI?
● Removes tight coupling between classes
● Improves code reusability
● Makes unit testing easier
● Centralizes configuration
● Follows Inversion of Control (IoC) principle
How DI Works in Spring
Dependencies Definition: A class declares its dependencies (other objects it needs to function)
through constructors, setter methods, or fields.
Container Management: The Spring IoC container (ApplicationContext) creates, configures, and
manages these objects, which are known as Beans.
Injection: The container "injects" the required dependencies into the dependent object.
Types of Dependency Injection in Spring
1. Constructor Injection – Dependencies provided through constructor
2. Setter Injection – Dependencies provided through setter methods
3. Field Injection – Dependencies injected directly into fields
Simple DI Example (2–3 lines only)
@Autowired
private Service service;
Spring Configuration
<bean id="engine" class="Engine"/>
<bean id="car" class="Car">
<constructor-arg ref="engine"/>
</bean>
Dependency Injection allows Spring to manage dependencies externally, making applications
modular, flexible, and maintainable.
4. JSP Implicit Objects (with Example)
Implicit objects in JSP are predefined objects that are automatically created by the JSP
container and made available to JSP pages without any declaration.
They help developers easily access request data, response data, session information,
application context, and output stream.
They simplify access to:
● Request data
● Session data
● Application data
● Server output
Advantages of JSP Implicit Objects
● No object creation required
● Reduces boilerplate code
● Easy access to web resources
List of JSP Implicit Objects
Object Description
request Client request
response Server response
session User session
application Application scope
out Output to browser
config Servlet config
page Current JSP page
pageContext All scopes access
exception Error handling
Example Using Implicit Objects
<%= [Link]("name") %>
<%= [Link]("user") %>
Scope of Implicit Objects
● Request scope → request
● Session scope → session
● Application scope → application
● Page scope → pageContext
Explanation
● request → gets form data
● session → stores user data
● out → prints output to browser
Conclusion
Implicit objects are built-in JSP objects that simplify interaction with the web container by
providing ready-to-use access to request, response, session, and application data.
They are essential for efficient JSP development.
5. What is Configuration Metadata?
Configuration metadata is information used by a framework (especially Spring) to define how
application components (beans) are created, wired, and managed at runtime.
Configuration Metadata in Spring is information that tells the Spring container how to create,
configure, and manage objects (beans) in an application.
It tells the container:
● Which classes to instantiate
● How objects depend on each other
● Lifecycle and scope of objects
Configuration metadata can be provided using:
● XML configuration
● Java-based configuration (@Configuration)
● Annotations (@Component, @Autowired)
Types of Configuration Metadata in Spring:
1. XML-based configuration
● Traditional and verbose
● Defined in XML files
● Suitable for large enterprise applications
<bean id="student" class="[Link]">
<property name="name" value="John"/>
</bean>
2. Annotation-based configuration
● Uses annotations inside Java classes
● Reduces XML usage
● Introduced for simplicity
@Component
public class Student {
3. Java-based configuration
● Uses @Configuration and @Bean
● Type-safe
● Recommended for modern Spring applications
@Configuration
public class AppConfig {
@Bean
public Student student() {
return new Student(); }}
Purpose:
● Separates configuration from business logic
● Makes applications flexible and easy to maintain
6. What are Custom Tags in JSP?
Custom tags in JSP are user-defined tags that encapsulate reusable functionality, making JSP
pages cleaner and easier to maintain.
They are created using Tag Libraries (TLD files) or SimpleTagSupport.
They:
● Reduce Java code in JSP pages
● Improve readability and maintainability
● Promote separation of presentation and business logic
Custom tags are created using:
● Tag Handler classes
● Tag Library Descriptor (TLD) file.
Advantages:
● Reduces Java code in JSP pages
● Improves readability
● Promotes reusability
Types of JSP Tags
1. Simple Tags
○ Implement SimpleTagSupport
○ Used for simple logic
2. Classic Tags
○ Implement Tag or BodyTag
○ More complex and older
Lifecycle of Custom Tag
1. JSP container loads tag handler
2. Attributes are set
3. doTag() method executes
4. Output is rendered
Example:
Custom Tag Class
public class HelloTag extends SimpleTagSupport {
public void doTag() throws IOException {
getJspContext().getOut().println("Hello JSP Custom Tag");
TLD File
<tag>
<name>hello</name>
<tag-class>HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
Usage in JSP
<mytag:hello />
7. Explain Data Access Object (DAO) in Detail
DAO (Data Access Object) is a design pattern that provides an abstraction layer between the
application and the database.
DAO (Data Access Object) is a design pattern that separates data access logic from
business logic in an application.
The DAO acts as an interface between the application and the database, handling all CRUD
(Create, Read, Update, Delete) operations.
DAO Architecture
○ Controller → Service → DAO → Database
● Controller: Handles user input
● Service: Contains business logic
● DAO: Handles database interaction
Responsibilities of DAO
● Establish database connections
● Execute SQL queries
● Convert result sets into objects
● Handle exceptions
Types of DAO Implementation
● JDBC-based DAO
● Hibernate/JPA-based DAO
● Spring JDBC / Spring Data DAO
Purpose:
● Provides an abstract interface to the database
● Makes code easier to test and maintain
● Supports loose coupling
Structure:
● DAO Interface – defines operations
● DAO Implementation – contains JDBC/Hibernate code
● Model/Entity Class – represents database table
Example:
DAO Interface
public interface StudentDAO {
Student getStudent(int id);
DAO Implementation
public class StudentDAOImpl implements StudentDAO {
public Student getStudent(int id) {
// JDBC code to fetch student
return new Student(id, "John");
Usage
StudentDAO dao = new StudentDAOImpl();
Student s = [Link](1);
Benefits:
● Database-independent code
● Better scalability
● Easy migration to new persistence technologies
8. Define Circular Dependency with Example
A circular dependency occurs when two or more classes depend on each other directly or
indirectly, forming a cycle.
This can cause:
Bean creation failure
Runtime errors in Spring
Poor design structure
Types of Circular Dependency
1. Direct Circular Dependency
Explanation
Occurs when two classes depend directly on each other.
Concept
Class A depends on Class B
Class B depends on Class A
This is the simplest and most common type.
2. Indirect Circular Dependency
Explanation
Occurs when more than two classes form a dependency loop.
Concept
Class A depends on Class B
Class B depends on Class C
Class C depends on Class A
This type is harder to detect and debug.
3. Constructor-Based Circular Dependency
Explanation
Occurs when circular dependency is created through constructor injection.
Characteristics
Spring cannot resolve this type
Causes application startup failure
Considered the most dangerous form
Problems:
● Object creation fails
● Causes runtime errors (especially in constructor injection)
In Spring:
● Constructor injection → ❌
circular dependency
● Setter injection → ✔ can resolve circular dependency
How to Resolve
● Use setter injection
● Apply @Lazy
● Redesign architecture
9. Explain Lambda Expression with a Suitable Example
Explain the syntax and use of a lambda expression with a suitable program
A lambda expression refers to a method that has no name and no access
specifier (private, public, or protected) and no return value declaration. This
type of method is also known as ‘Anonymous methods’, ‘Closures’ or
simply ‘Lambdas’. It provides a way to represent one method interface
simply by using an expression
A Lambda Expression in Java is a short, anonymous function used to represent a block of
code as data.
It was introduced in Java 8 to support functional programming and to make code simpler,
cleaner, and more readable.
Why Lambda Expressions Were Introduced
Before Java 8, developers had to write:
● Anonymous inner classes
● Large amounts of boilerplate code
Uses of Lambda Expressions
1. Simplifies code by removing boilerplate (like anonymous classes)
2. Works with collections (Streams, forEach, filter)
3. Improves readability and maintainability
4. Supports functional programming in Java
5. Useful in event handling, multithreading, and callbacks
Key Characteristics of Lambda Expressions
1. Anonymous
○ No method name is required
2. Functional Interface Based
Works only with functional interfaces (interfaces with exactly one abstract method)
3. Compact Syntax
○ Eliminates unnecessary code like class names and return statements
4. Type Inference
○ Java automatically detects parameter types
5. Stateless by Nature
○ Prefer immutability and avoid side effects
Syntax:
(parameters) -> expression
Explanation:
● (parameters) → input parameters of the function
● -> → lambda operator
● expression or { statements } → implementation of the abstract method
Types of Lambda Expressions
1. No parameters
() -> [Link]("Hello")
2. Single parameter
x -> x * x
3. Multiple parameters
(a, b) -> a + b
Advantages
● Reduces boilerplate code
● Improves readability
● Enables parallel processing
● Works seamlessly with Streams API
Example with Lambda:
Runnable r = () -> [Link]("Running thread");
Lambda Expression Example :
[Link](list, (a, b) -> [Link](b));
public class LambdaExample {
public static void main(String[] args) {
// Lambda expression implementing the sayHello method
Greeting greet = (name) -> [Link]("Hello, " + name);
[Link]("Alice"); // Output: Hello, Alice
Explanation:
● Greeting is a functional interface
● (name) -> [Link]("Hello, " + name) is the lambda expression
● It provides the implementation of the sayHello method
10. Explain JSP architecture with a suitable example
What is JSP Architecture?
JSP (JavaServer Pages) architecture describes the interaction between JSP pages, servlet
engine, and web server to generate dynamic web content.
It is part of Java EE technology and follows the MVC (Model-View-Controller) approach
where JSP acts mainly as the View.
Components of JSP Architecture
1. Client (Browser)
○ Sends HTTP requests to the web server.
2. Web Server / JSP Container
○ Receives the request and forwards it to the JSP engine or servlet container.
3. JSP Engine
○ Converts JSP pages into Servlets.
○ Compiles JSP into a Java Servlet class.
4. Servlet
○ Handles the request and generates dynamic content.
○ Interacts with JavaBeans, EJB, or database if needed.
5. Response
○ Generated HTML is sent back to the client browser.
JSP Processing Steps
1. Client requests a JSP page.
2. JSP engine checks if the JSP is compiled. If not:
○ Converts JSP to Servlet
○ Compiles the Servlet
3. Servlet executes and interacts with backend (optional).
4. Servlet generates dynamic HTML.
5. Web server sends HTML response to the client.
Key Points
● JSP is server-side technology; client sees only HTML.
● JSP gets converted into Servlet for execution.
● Supports dynamic content generation and separation of presentation & business
logic.
11. Aspect-Oriented Programming (AOP) with Spring
What is Aspect-Oriented Programming (AOP)?
Aspect-oriented programming (AOP) is one of the major components of the
Spring Framework. The Spring AOP helps in breaking down the logic of
the program into several distinct parts called as concerns. Cross-cutting
concerns is the functions which span multiple points of an application.
Aspect-Oriented Programming (AOP) is a programming paradigm that separates
cross-cutting concerns from the main business logic of an application.
Cross-cutting concerns are functionalities that are common across multiple modules, such
as:
● Logging
● Security
● Transaction management
● Exception handling
● Performance monitoring
Instead of repeating this code everywhere, AOP modularizes it into aspects.
Why AOP is Needed in Spring
In traditional OOP:
● Common logic is scattered across many classes
● Code becomes hard to maintain
● Changes require modifications in multiple places
Spring AOP solves this by applying common behavior without modifying business classes,
improving modularity and maintainability.
Core Concepts of AOP
1. Aspect
An aspect is a module that encapsulates a cross-cutting concern (e.g., logging or security).
2. Join Point
A join point is a point during program execution where an aspect can be applied
(e.g., method execution).
3. Advice
Advice is the action taken by an aspect at a particular join point.
Types of Advice:
● Before – runs before method execution
● After – runs after method execution
● After Returning – runs after successful execution
● After Throwing – runs when an exception occurs
● Around – runs before and after method execution
4. Pointcut
A pointcut is an expression that defines where the advice should be applied.
5. Weaving
Weaving is the process of linking aspects with the target objects.
Spring performs weaving at runtime using proxies.
6. Target Object
The target object is the business object whose method is being advised.
How Spring AOP Works
● Spring AOP uses proxy-based mechanism
● Only supports method-level join points
● Works mainly with Spring-managed beans
Advantages of Spring AOP
● Clean separation of concerns
● Reusable cross-cutting logic
● No changes to business code
● Easy integration with Spring framework
Suitable Code Example (2–3 Lines Only)
@Aspect
@Before("execution(* [Link].*.*(..))")
This aspect runs before every method in the service package.
Real-Life Analogy
Think of AOP like a security check at an airport:
● Every passenger (method) passes through
● Security (aspect) is applied without changing the passenger
Limitations of Spring AOP
● Only method-level interception
● Not suitable for field access
● Proxy-based limitations
Conclusion
Aspect-Oriented Programming in Spring provides a powerful way to handle cross-cutting
concerns separately from business logic, resulting in cleaner, modular, and maintainable
applications.
12. Spring Framework with example and Diagram
What is Spring Framework?
Spring is a lightweight, open-source Java framework used to build enterprise
applications.
It provides comprehensive infrastructure support, allowing developers to focus on business
logic rather than boilerplate code.
Spring follows the Inversion of Control (IoC) and Dependency Injection (DI) principles to
manage application components.
Key Features of Spring
1. Lightweight – Spring’s core container is lightweight.
2. IOC/DI Support – Objects are created and injected by the framework.
3. Aspect-Oriented Programming (AOP) – Supports cross-cutting concerns like logging,
transactions, and security.
4. Data Access – Integrates with JDBC, Hibernate, JPA for database operations.
5. Transaction Management – Declarative transaction support.
6. MVC Framework – Supports building web applications.
7. Integration – Can work with other frameworks like Quartz, JMS, etc.
Components of Spring Framework
1. Core Container – BeanFactory, ApplicationContext (IoC & DI)
2. AOP Module – Aspect-oriented programming support
3. Data Access / Integration Module – JDBC, ORM, JMS, Transactions
4. Web Module – Spring MVC for web applications
5. Messaging – JMS, AMQP support
How Spring Works
● Spring creates and manages beans in the IoC container.
● Beans are injected where needed using DI (constructor, setter, or field injection).
● Cross-cutting concerns are handled using AOP.
● Business logic interacts with databases via Spring's data access modules.
Summary Table
Module Purpose Example Use Case
Core Container IoC & DI management Injecting a Service bean into Controller
AOP Module Cross-cutting concerns Logging, security, transactions
Data Access / Database and transaction Save object to DB via Spring
Integration support JDBC/Hibernate
Web Module Build web apps using MVC Handle form submission and display
results
Messaging Asynchronous Send/receive messages via JMS or
communication RabbitMQ
13. What is Collections? Explain any two interfaces with its
all their operations
Collections in Java
What is a Collection?
A Collection in Java is a framework that provides an architecture to store, manage, and
manipulate groups of objects.
It is part of the Java Collections Framework (JCF), introduced in Java 2 (JDK 1.2).
Key Features:
● Can store multiple objects (single object per index in some collections like List).
● Provides common methods for adding, removing, searching, and sorting elements.
● Supports generic types to enforce type safety.
● Reduces boilerplate code compared to arrays.
Java Collections Framework Hierarchy
Collection (Interface)
/ \
List Set
| |
ArrayList HashSet
LinkedList
● Collection – root interface for List, Set, Queue.
● Map – separate hierarchy for key-value pairs (not a true Collection).
Two Important Interfaces in Collections
1. List Interface
Definition:
List is an ordered collection (sequence) that allows duplicates and provides index-based
access.
Implementing Classes:
● ArrayList
● LinkedList
● Vector
Common Operations of List
Method Description
add(E e) Adds element at the end
add(int index, E Adds element at specified index
e)
get(int index) Retrieves element at given
index
set(int index, E Replaces element at index
e)
remove(int index) Removes element at index
size() Returns number of elements
contains(Object Checks if element exists
o)
isEmpty() Checks if list is empty
clear() Removes all elements
indexOf(Object o) Returns index of first occurrence
lastIndexOf(Objec Returns index of last occurrence
t o)
iterator() Returns iterator for traversal
Example (Minimal Code)
List<String> names = new ArrayList<>();
[Link]("Alice");
[Link]("Bob");
[Link]([Link](0)); // Output: Alice
2. Set Interface
Definition:
Set is a collection that contains no duplicate elements and does not guarantee order
(except some implementations like LinkedHashSet).
Implementing Classes:
● HashSet
● LinkedHashSet
● TreeSet
Common Operations of Set
Method Description
add(E e) Adds element if not already
present
remove(Object Removes the element
o)
contains(Objec Checks if element exists
t o)
size() Returns number of elements
isEmpty() Checks if set is empty
clear() Removes all elements
iterator() Returns iterator for traversal
Example (Minimal Code)
Set<Integer> numbers = new HashSet<>();
[Link](10);
[Link](20);
[Link](10); // Duplicate ignored
[Link](numbers); // Output: [10, 20]
Key Points
● List allows duplicates; Set does not.
● List preserves insertion order; Set may not (HashSet).
● Both are part of the Collection interface.
14. Explain Spring Boot RESTful Web Service with an
example
REST stands for REpresentational State Transfer. It is developed
by Roy Thomas Fielding, who also developed HTTP. The main goal
of RESTful web services is to make web services more effective.
RESTful web services try to define services using the different
concepts that are already present in HTTP. REST is an architectural
approach, not a protocol.
10.5.1 Why REST is popular:
1. It allows the separation between the client and the server.
2. It doesn’t rely on a single technology or programming language.
3. You can build the scalable application or even integrate two
different applications using REST APIs
Spring Boot RESTful Web Service
What is a RESTful Web Service?
REST (Representational State Transfer) is an architectural style for building web services
that allows communication between client and server using HTTP methods.
A Spring Boot RESTful Web Service is a Spring Boot application that exposes REST APIs
to perform CRUD operations and automatically handles HTTP requests/responses.
Key Features of Spring Boot for REST
1. Embedded Server – No need for external Tomcat setup.
2. Auto-Configuration – Reduces boilerplate code.
3. Standalone Application – Can run as a JAR file.
4. REST Annotations – Simplifies controller and API creation.
5. JSON Support – Automatically converts Java objects to JSON using Jackson.
Core Concepts
● @RestController – Marks the class as a REST controller (combines @Controller +
@ResponseBody).
● @RequestMapping / @GetMapping / @PostMapping / @PutMapping /
@DeleteMapping – Maps HTTP requests to methods.
● @RequestBody – Binds HTTP request body to Java object.
● @PathVariable – Extracts variables from URL path.
● @ResponseBody – Sends Java object as HTTP response (JSON/XML).
Minimal Example
1. Maven Dependencies ([Link])
<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2. REST Controller
import [Link].*;
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Spring Boot!";
}
@GetMapping("/user/{name}")
public String getUser(@PathVariable String name) {
return "Hello, " + name;
}
}
3. Main Application Class
import [Link];
import [Link];
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
[Link]([Link], args);
}
}
How It Works
1. Client sends HTTP GET request to /api/hello.
2. Spring Boot maps the request to sayHello() method.
3. Method returns a string. Spring converts it to HTTP response automatically.
4. For /api/user/{name}, Spring extracts {name} using @PathVariable.
Advantages of Spring Boot RESTful Web Service
● Fast and easy to set up REST APIs.
● Auto-configuration and embedded server simplify development.
● Supports JSON/XML serialization automatically.
● Scalable and maintainable architecture.
● Integrates easily with front-end frameworks and mobile apps.
Diagram: Spring Boot RESTful Web Service
This setup allows you to quickly create REST APIs with minimal configuration, leveraging
Spring Boot’s auto-configuration and embedded server.
15. What are directives? Explain different types of directives
in JSP
It is used to give some specific instructions to web container when the jsp
page is translated. It has three subcategories:
Page:<%@ page...>
Include:<%@ include...%>
Taglib:<%@ taglib....%>
There are five different Scriptlet elements in JSP are:-
1) Comments
2) Directives
3) Declaration
4) JSP scriptlet Tag
5) Expressions
Directives in JSP
What is a Directive?
A directive in JSP is a special instruction that provides global information to the JSP
container about how to process the JSP page.
● Directives do not produce any output on the client side.
● They affect the overall structure or behavior of the JSP page.
Syntax of a Directive:
<%@ directive attribute="value" %>
Types of Directives in JSP
There are three main types of JSP directives:
1. Page Directive (<%@ page %>)
● Defines page-level settings such as content type, error page, buffer size, and session
management.
Common Attributes:
Attribute Description
language Specifies scripting language (default is java)
import Imports Java classes ([Link].*,
[Link].*)
contentTy Sets MIME type and character encoding
pe
session true or false – enables or disables session
errorPage Specifies JSP page to handle exceptions
isErrorPa true if the JSP itself handles exceptions
ge
Example:
<%@ page language="java" contentType="text/html; charset=UTF-8" %>
<%@ page import="[Link]" %>
2. Include Directive (<%@ include %>)
● Used to include another file during translation phase (compile time).
● The included file becomes part of the JSP page.
● Useful for header, footer, or reusable content.
Syntax:
<%@ include file="[Link]" %>
Key Points:
● Compile-time inclusion
● Changes in included file require recompilation of JSP
3. Taglib Directive (<%@ taglib %>)
● Declares a custom tag library to be used in JSP.
● Required when using JSTL (JSP Standard Tag Library) or user-defined tags.
Common Attributes:
Attribute Description
prefix Short name to use in JSP
tags
uri URI of the tag library
Example:
<%@ taglib prefix="c" uri="[Link] %>
● After declaration, JSTL tags like <c:forEach> or <c:if> can be used in the JSP
page.
Summary Table
Directiv Purpose Phase Example
e
Page Page-level Translatio <%@ page import="[Link].*" %>
configuration n
Include Include file at Translatio <%@ include file="[Link]" %>
compile-time n
Taglib Declare Translatio <%@ taglib prefix="c"
custom/JSTL n uri="[Link]
tags re" %>
Key Points
● Directives provide global instructions to JSP container.
● They do not generate output to the client.
● Affect page compilation, included files, and tag libraries.
16. Explain the data access operation with the JDBC template
class and ROWmapper interface
Data Access with JDBC Template and RowMapper in
Spring
Spring provides the JDBC Template class to simplify database access and reduce boilerplate
JDBC code like connection handling, statement creation, and exception management.
1. JDBC Template
Definition:
JdbcTemplate is a Spring class in the [Link] package that
provides ready-to-use methods to execute SQL queries, updates, and stored procedures.
Advantages:
● Simplifies database access
● Automatically manages connections, statements, and result sets
● Handles SQLException and converts it to DataAccessException
● Supports query, update, batch operations
Common Methods of JdbcTemplate:
Method Description
update(String sql) Execute insert, update, or delete
query(String sql, RowMapper rm) Execute select query and map
results
queryForObject(String sql, Class<T> Return a single object
requiredType)
batchUpdate(String[] sql) Execute batch updates
Example:
@Autowired
private JdbcTemplate jdbcTemplate;
public int addUser(User user) {
String sql = "INSERT INTO users(name, email) VALUES(?, ?)";
return [Link](sql, [Link](), [Link]());
}
● No need to manually handle connection, statement, or exception.
● Simple and concise compared to plain JDBC.
2. RowMapper Interface
Definition:
RowMapper<T> is a callback interface used by JdbcTemplate to map each row of a
ResultSet to a Java object.
Advantages:
● Separates mapping logic from query execution
● Makes code cleaner and reusable
● Works with query() and queryForObject() methods
Common Method:
T mapRow(ResultSet rs, int rowNum) throws SQLException;
● rs → The current row of the ResultSet
● rowNum → Row number (starting from 0)
● Returns a mapped Java object
Example:
public class UserMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User();
[Link]([Link]("id"));
[Link]([Link]("name"));
[Link]([Link]("email"));
return user;
}
}
// Using JdbcTemplate with RowMapper
List<User> users = [Link]("SELECT * FROM users", new UserMapper());
Explanation:
● Each row of the users table is mapped to a User object.
● No manual iteration over the ResultSet is required.
● Works seamlessly with Spring’s JdbcTemplate for clean data access.
Key Points
1. JdbcTemplate reduces boilerplate JDBC code.
2. RowMapper maps database rows to Java objects.
3. Together, they provide clean, maintainable, and efficient database access in Spring.
4. Supports CRUD operations, batch updates, and custom queries.
If you want, I can also create a diagram showing how JdbcTemplate and RowMapper work
together for easy exam understanding.
Do you want me to do that?
17. Types of Advice in Java (Spring AOP)
In Java, Advice is mainly used in Aspect-Oriented Programming (AOP). The most common
implementation is in Spring Framework.
📌 What is Advice?
Advice is the action taken by an aspect at a particular join point (like before or after method
execution).
✅ Types of Advice
There are 5 main types of Advice in AOP:
1️⃣ Before Advice
● Runs before the method execution.
@Before("execution(* [Link].*.*(..))")
public void beforeAdvice() {
[Link]("Before method execution");
}
2️⃣ After Advice (Finally)
● Runs after the method execution, whether it throws an exception or not.
@After("execution(* [Link].*.*(..))")
public void afterAdvice() {
[Link]("After method execution");
}
3️⃣ After Returning Advice
● Runs only if method executes successfully.
@AfterReturning("execution(* [Link].*.*(..))")
public void afterReturningAdvice() {
[Link]("Method executed successfully");
}
4️⃣ After Throwing Advice
● Runs if method throws an exception.
@AfterThrowing("execution(* [Link].*.*(..))")
public void afterThrowingAdvice() {
[Link]("Exception occurred");
}
5️⃣ Around Advice
● Runs before and after method execution.
● Gives full control over method execution.
@Around("execution(* [Link].*.*(..))")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws
Throwable {
[Link]("Before method");
Object result = [Link]();
[Link]("After method");
return result;
}
18. JSP Actions and its types
JSP stands for Java Server Pages. It is part of JavaServer Pages.
📌 What are JSP Actions?
JSP Action tags are used to control the behavior of the servlet engine.
They are written using:
✅ Any Four JSP Actions (With Example)
1️⃣ <jsp:useBean>
Used to create or locate a JavaBean.
<jsp:useBean id="student" class="[Link]"
scope="session"/>
✔ Creates an object of Student class.
2️⃣ <jsp:setProperty>
Used to set property values in bean.
<jsp:setProperty name="student" property="name" value="Ali"/>
✔ Sets the name property.
3️⃣ <jsp:getProperty>
Used to display property value.
Name: <jsp:getProperty name="student" property="name"/>
✔ Prints the student name.
4️⃣ <jsp:include>
Used to include another JSP file at request time.
<jsp:include page="[Link]" />
✔ Includes [Link] dynamically.
19. Pointcut Designator by Annotation (Spring AOP)
In Aspect-Oriented Programming (AOP) using the Spring Framework, a Pointcut Designator
(PCD) is an expression that specifies where advice should be applied.
When we use annotations to define pointcuts, we are targeting methods or classes that are
marked with specific annotations.
✅ Definition
👉 Pointcut Designator by Annotation is used to apply advice to methods or classes that are
annotated with a specific annotation.
Spring provides special annotation-based pointcut designators such as:
● @annotation
● @within
● @target
● @args
🔹 1️⃣ @annotation Designator
✔ Meaning:
Matches methods that are annotated with a specific annotation.
📌 Step 1: Create Custom Annotation
package [Link];
import [Link].*;
@Target([Link])
@Retention([Link])
public @interface LogExecution {
}
Working Flow Diagram
Client Calls Method
│
▼
@LogExecution present?
│
Yes
│
Before Advice Runs
│
▼
Target Method Executes