You are on page 1of 58

(Critical) :- Answer Which Are Very Important

(Dotted):- Questions which are dotted in importance


Unit 1
(Dotted)
1). What is need of multi‐tier architecture and explain its functionality. (NOV 19)
Ans: Multitier architecture, also known as n-tier architecture, is a design pattern used in
software development where different components or layers of an application are separated into
distinct tiers or layers. Each tier is responsible for specific functionality, and the communication
between these tiers is well-defined.
1. Client Tier:
 Represents all system clients, including web browsers, applications, applets,
phones, and future devices.
 Can even include batch processes.
2. Presentation Tier:
 Manages client requests, offers single sign-on, conducts session management,
and controls access to business services.
 Servlets and JSP reside here, producing UI elements.
3. Business Tier:
 Provides business services, holding business data and logic.
 Centralizes most business processing.
4. Integration Tier:
 Communicates with external resources and systems like data stores.
 Coupled with the business tier for accessing data or services in the resource tier.
5. Resource Tier:
 Contains business data and external resources like mainframes, legacy systems,
B2B integration systems, and services.
Benefits of Layered Architecture:
 Code Clarity:
 Easier for developers to understand and trace.
 Application Development:
 Simplifies application writing.
 Testing:
 Facilitates easier application testing.
 Business Rules Extension:
 Streamlines the extension of business rules on a specific domain object.

(Dotted)
2). What are Java EE containers? (NOV 18, APR 19, NOV 22, APR 23)
Ans: Java EE containers are the interface between the component and the lower-level
functionality of the application server provided by the platform to support that component and
API . The functionality of the container is defined by the platform to provide more productivity,
and is different for each component type.

Web Container/Browser:
 Mediates between web components/API and the web server.
 JSP pages, JavaServer Faces Facelets pages, servlets.
 Functions:
 Manages lifecycle of web components.
 Handles Request & Response processes.
 Dispatches requests to application components.
 Provides interfaces for context data (e.g., current request information).
Application Client Container:
 Serves as the interface between Java EE applications and clients/browsers.
 Operates on the client machine.
 Functions:
 Establishes a communication bridge between client applications and Java EE
server components.
 Facilitates the use of Java EE server components in special Java SE applications.
Key Container Points:
1. Security:
 Configures web components or EJB for authorized user access from client-
side/browsers.
 Ensures controlled access to system resources.
2. Transaction Model:
 Defines relationships among methods/functions within a single transaction.
 Treats all methods/functions in a transaction as a cohesive unit.
3. Remote Connectivity Model:
 Manages low-level communications between clients and EJB in Java EE.
 Facilitates remote connectivity, enabling efficient communication between clients
and server components.

(Critical)
3). What is Java Enterprise Edition (Java EE)? Explain. (NOV 19)
Ans: Java EE is a comprehensive and standardized platform for developing, deploying, and
managing enterprise-level applications. Its modular and layered architecture, along with
standardized APIs and security features, makes it well-suited for building robust, scalable, and
secure distributed systems.
1. Component-Based Architecture: Java EE promotes a component-based architecture,
where reusable components like Servlets, JSP, EJB, and JPA entities are assembled to
create enterprise applications.
2. Multi-Tiered Architecture: Java EE supports multi-tiered application development,
separating presentation, business logic, and data persistence layers to enhance
maintainability and scalability.
3. Standardized APIs: Java EE defines standardized APIs for various enterprise services,
including JDBC for database connectivity, JMS for messaging, and JNDI for naming and
directory services.
4. Security: Java EE incorporates comprehensive security mechanisms, including
authentication, authorization, and data encryption. It supports role-based access control
and integrates with various authentication mechanisms.
5. Transaction Management: It provides built-in support for managing distributed
transactions through the Java Transaction API (JTA), ensuring data consistency and
reliability across multiple data sources.
6. Concurrency and Resource Management: Java EE includes tools for managing
concurrency and resource pooling, optimizing performance and resource utilization.
Enterprise beans can leverage container-managed concurrency and resource
management.
7. Messaging: Java EE includes JMS for building messaging-based applications,
facilitating asynchronous communication between components for scalability and service
decoupling.
8. Enterprise Integration: Java EE supports integration with existing enterprise systems
and web services through standardized protocols and APIs, enabling seamless
connections to other platforms and services.
9. Persistence: Java EE provides JPA for object-relational mapping, allowing developers to
work with relational databases using Java objects. This simplifies database operations
and enhances portability across different database systems.

(Critical)
4). Explain the life cycle of a servlet. (NOV 18 , NOV 19, NOV 22, APR 23)
Ans: In Java Servlet, The web container maintains the life cycle of a servlet instance/Object.
Following are the Stages of life cycle of the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
1. Servlet Class Loading:
 The servlet class is loaded into RAM by the classloader when the first request for
the servlet is received from the web container.
2. Servlet Instance Creation:
 After loading the servlet class, the web container creates an instance (object) of
the servlet class.
 The servlet instance is created only once during the servlet's life cycle.
Subsequent requests reuse the existing instance.
3. Init Method Invocation:
 The init() method is invoked by the web container after creating the servlet
instance.
 The init() method is used to initialize the servlet and is part of the
javax.servlet.Servlet interface life cycle.
 Syntax: public void init(ServletConfig config)
4. Service Method Invocation:
 The web container calls the service() method each time a request for the servlet is
received.
 If the servlet class or object is not initialized (e.g., during the first request), it goes
through the class loading, instance creation, and init() method invocation steps
before calling the service() method.
 Syntax: public void service(ServletRequest request, ServletResponse
response)
5. Destroy Method Invocation:
 The web container calls the destroy() method before removing the servlet
instance from RAM.
 The destroy() method provides an opportunity for the servlet to clean up
resources (e.g., memory, threads) before it is taken out of service.
 Syntax: public void destroy()

(Critical)
5). Write a servlet code to display Square and Square root of numbers between 25 and
365 intabular form. (NOV 19)
Ans: import java.io.*;
import javax.servlet.*;
import javax.servelt.http.*;
public class Test extends HttpServlet{
public void doGet(HttpServletRequest hreq, HttpServletResponse hres) throws
ServletException, IOException{
PrintWriter pw = hres.getWriter();
out.println("<table border=1>");
for(int i=25; i<=365; i++){
out.println("<tr><td>"+(i*i)+"</td><td>"+Math.sqrt(i)+"</td></tr>");
}
out.println("</table>");
}
}

(Critical)
6). Write a short note on javax.servlet package. (NOV 18, NOV 22)
Ans: In Java Servlet Containing API i.e the javax.servlet and javax.servlet.http packages
represent interfaces and classes for servlet API where to design java web applications.
• The javax.servlet package contains so many interfaces and classes that are used by the
servlet or web container programming.
• In the Javax.servlet package, the ServletRequest Interface is used to handle client requests to
access a servlet. It provides the information of a servlet like, parameter names, content type,
content length and values.
There are many interfaces in the javax.servlet package. They are as follows:
1. Servlet Interface.
2. ServletRequest.
3. ServletResponse.
4. RequestDispatcher.
5. ServletConfig
6. ServletContext
7. ServletRequestListener
8. ServletRequestAttributeListener
9. ServletContextListener
10.ServletContextAttributeListener
Following are the List of Classes in javax.servlet package
1. GenericServlet.
2. ServletInputStream.
3. ServletOutputStream.
4. ServletRequestWrapper.
5. ServletResponseWrapper.
6. ServletRequestEvent.
7. ServletContextEvent.
8. ServletRequestAttributeEvent.
9. ServletContextAttributeEvent.
10. ServletException.
11. UnavailableException.
(Critical)
7). Explain the architecture of JDBC.
Ans: JDBC is a key component of Java Standard Edition, offering a standardized way for Java
applications to connect to and interact with relational databases, ensuring consistency and
database independence in SQL statement execution and result processing.

1. Definition:
 JDBC (Java Database Connectivity): A Java-based API (Application
Programming Interface) facilitating interaction between Java applications and
relational databases.
2. Purpose:
 Allows Java programs to:
 Connect to relational databases.
 Issue SQL statements.
 Process query results.
3. Standardization:
 Provides a standardized way for Java applications to interact with databases.
 Ensures consistency in connecting to, querying, and updating databases,
regardless of the underlying Database Management System (DBMS).
4. Integration:
 Part of the Java Standard Edition (Java SE):
 Included in the standard Java development toolkit.
5. Crucial Technology:
 A crucial technology for achieving database connectivity in Java applications.
6. Main Functionality:
 SQL Statement Execution:
 Allows developers to issue SQL statements.
 Result Processing:
 Provides mechanisms for processing the results of SQL queries.
 Database Independence:
 Offers a consistent approach to database interaction, promoting
independence from the specific DBMS in use.
Note:- All Questions Are Important (Only Dotted and Critical Ones are included)
Unit 2
1). Write a short note on RequestDispatcher Interface (NOV 18, APR 19 , NOV 19 , NOV
22)
Ans: The RequestDispatcher interface facilitates the inclusion of responses from multiple
servlets into a single response or forwarding client requests to another servlet for processing.
1. Purpose:
 Provides the facility for dispatching requests to another resource, such as HTML,
servlet, or JSP.
 Can be used for including the content of another resource in the response.
2. Obtaining RequestDispatcher Object:
 Two styles exist using:
 ServletRequest object.
 ServletContext object.
3. Method for Obtaining RequestDispatcher Object:
 Two similar methods exist in both ServletRequest and ServletContext interfaces:
 javax.servlet.ServletContext.getRequestDispatcher(String path)
 javax.servlet.ServletRequest.getRequestDispatcher(String path)
 Method:
 RequestDispatcher getRequestDispatcher(String path)
 Returns a RequestDispatcher object that acts as a wrapper for the
resource located at the given path.
 Can be used to forward a request to the resource or include the
resource in a response.
 The resource can be dynamic or static.
4. Additional Method:
 RequestDispatcher getNamedDispatcher(String name)
 Takes the name of the Servlet (or JSP page) declared via the Deployment
Descriptor.
 Expects the logical name of the destination servlet/JSP program as an
argument value.
5. Use Cases of RequestDispatcher:
 Used in two main cases:
 Include the Response of One Servlet into Another:
 Client gets the response of both Servlets.
 Forward Client Request to Another Servlet:
 Client calls a Servlet, but the response to the client is given by
another Servlet.

2). What is a Cookie? Explain its types. (APR 23)


Ans: Cookies in Java Servlets serve as a mechanism for tracking user information, enabling
personalized experiences, and facilitating user identification across sessions.
1. Definition:
 Cookies are text files stored on the customer's computer for tracking information.
 Java Servlets transparently support HTTP cookies.
2. Steps in Identifying Recurring Users:
 Server script sends cookies (e.g., name, age, ID) to the browser.
 Browser stores this information locally.
 On subsequent requests, the browser sends stored cookie information to identify
the user.
3. Accessing Cookies in Servlets:
 Servlets access cookies via request.getCookies() method, returning an array of
Cookie objects.
4. Common Uses of Cookies:
 Session authentication.
 Personalizing responses based on user preferences (e.g., setting background
color).
5. Types of Cookies:
a. Non-persistent Cookie (Session Cookie):
 Valid for one session, removed when the browser is closed.
 Temporarily stored in the browser's memory during active website usage.
 Exist only for the duration of a user's session.
b. Persistent Cookie:
 Valid for multiple sessions, not removed when the browser is closed.
 Stored on the user's device for an extended period, beyond the current session.
 Written to the user's hard drive, remaining until expiration or manual deletion.
6. Use Cases of Persistent Cookies:
 Store user data and preferences across different sessions.
 Enhance user experiences and provide long-term functionality.
7. Considerations:
 Persistent cookies are subject to privacy regulations and require user consent.

3). Write a servlet program to create a session and display the following:
i) Session ID
ii) New or Old
iii) Creation Time (NOV 19)
Ans: import java.io.*;
import javax.servlet.*;
import javax.servelt.http.*;
public class Test extends HttpServlet{
public void doGet(HttpServletRequest hreq, HttpServletResponse hres) throws
ServletException, IOException{
PrintWriter pw = hres.getWriter();
HttpSession hs = hreq.getSession(true);
out.println("<br>Session ID "+ hs.getId());
out.println("<br>Is New "+ hs.isNew());
out.println("<br>Creation Time "+ new java.util.Date(hs.getCreationTime()));
}
}
4). Write a short note on HttpSession.
OR
Explain How Java Handles Session Management through HttpSession
Ans: HttpSession is a fundamental component in Java web applications, allowing the
management of user sessions, user identification, and storage of user-specific data across
multiple requests and responses.
1. Stateless Nature of HTTP:
 HTTP is stateless, treating each request as independent.
 For user recognition and tracking across requests, session management
techniques are needed.
2. HttpSession Overview:
 HttpSession is a Java technology used in web applications for maintaining
session state.
 Part of the Java Servlet API, it facilitates server-side session management.
3. Key Points:
a. Session Management:
 Manages user sessions, logical associations between a user and the web
application.
 Spans multiple HTTP requests and responses.
b. User Identification:
 Assigns a unique session identifier (session ID) to users.
 Stored as a cookie or included in the URL.
c. Data Storage:
 Stores user-specific data as attributes within the session.
 Attributes can be accessed and modified throughout the user's session.
d. Attribute Storage:
 Attributes are key-value pairs, allowing storage of various data types.
 Enables storing information like login credentials, shopping cart contents, and
preferences.
e. Lifecycle:
 HttpSession has a defined lifecycle, created when a user accesses the application.
 Remains active during user interaction and expires after a configurable period of
inactivity or logout.
f. Scope:
 Attributes have session scope, accessible throughout the user's session.
 Not shared across different users or sessions.
g. Methods:
 Provides methods like setAttribute(), getAttribute(), removeAttribute(), and
invalidate() for attribute management.
 Supports creating, accessing, and ending user sessions.

5). Write a servlet code to download a file. (NOV 22)


Ans: import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet {
private static final String FILE_PATH = "path/to/your/file.txt"; // Replace with the actual file path
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get the file name from the path
String fileName = new File(FILE_PATH).getName();
// Set the content type and headers for the response
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
// Read the file and write its contents to the response output stream
try (FileInputStream fileInputStream = new FileInputStream(FILE_PATH)) {
int i;
while ((i = fileInputStream.read()) != -1) {
response.getWriter().write(i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}

6). Which things needs to be carefully checked and understood while writing file
uploading code in servlet? (NOV 22)
Ans: When writing file upload code in a servlet, there are several important considerations and
potential pitfalls that you should be aware of to ensure the security, reliability, and performance
of your application. Here are the key things to carefully check and understand:
1. Security Concerns:
 File Validation: Validate uploaded files for type, size, and content.
 File Type Checking: Check MIME type in addition to file extensions.
 File Size Limit: Set reasonable limits to prevent denial-of-service attacks.
 File Overwriting: Prevent unintentional overwriting of existing files.
 File Permissions: Ensure proper server-side file permissions.
2. Multipart Form Data Handling:
 Use libraries or built-in servlet container support for handling multipart form data.
3. Form Configuration:
 Set the HTML form's enctype attribute to "multipart/form-data".
4. File Storage:
 Decide where and how to store files (file system, database, cloud storage).
 Be mindful of file system location and directory structure.
5. File Name Sanitization:
 Sanitize file names to prevent harmful characters and directory traversal attacks.
6. Error Handling:
 Implement error handling for upload failures (e.g., disk space issues, file I/O
errors).
7. Performance Considerations:
 Handle large file uploads efficiently.
 Consider asynchronous processing for large uploads.
8. Network Considerations:
 Be aware of bandwidth consumption, especially for simultaneous large uploads.
9. Testing and Validation:
 Thoroughly test file upload functionality under various scenarios.
 Test for concurrent uploads and ensure multi-request handling.
10. Logging and Monitoring:
 Implement logging and monitoring for file upload activities, errors, and security
events.

7). What is Non-Blocking I/O? Explain WriteListener and ReadListener performing in


NonBlocking I/O? (NOV 18, APR 23
1. Ans: Introduction of Non-blocking I/O in Servlet 3.1:
 Non-blocking I/O was introduced to Servlet 3.1 to enhance the scalability of
applications.
 Asynchronous request processing was allowed in Servlet 3.0, but it relied on
traditional blocking I/O.
2. Problem with Traditional I/O:
 In Servlet 3.0, if incoming data is slow, the server thread must wait for the data
during read or write operations.
 This can lead to scalability issues as threads may be blocked, wasting resources
and memory.
3. Introduction of Event Listeners:
 Servlet 3.1 resolves the blocking issue by introducing event listeners:
ReadListener and WriteListener interfaces.
4. Implementation of ReadListenerImpl Class:
 ReadListenerImpl implements the ReadListener interface for asynchronous input
operations.
 The constructor initializes the ServletInputStream, HttpServletResponse, and
AsyncContext.
 The onDataAvailable method is invoked when data is available to be read without
blocking.
 The method reads the data in chunks and appends it to a StringBuilder.
 The onAllDataRead method is invoked when all data is read, setting up a
WriteListener for writing the response.
 The onError method handles any errors that may occur during asynchronous
processing.
5. Usage of WriteListenerImpl:
 The WriteListenerImpl class is expected to be another class that implements the
WriteListener interface.
 It would handle asynchronous output operations.
6. Queue for Storing Data:
 A Queue (in this case, a LinkedBlockingQueue) is used to store the read data.
 The data is processed asynchronously without blocking.
7. Considerations:
 The code focuses on efficient handling of non-blocking I/O during asynchronous
processing.
 It utilizes event listeners to manage data availability and response writing without
blocking threads.

8). Explain the working of Non-Blocking I/O. (NOV 18, APR 19, NOV 22)
Ans: The non-blocking I/O is implemented in a servlet, focusing on the use of AsyncContext
for asynchronous processing and the integration of an asynchronous HTTP client. This
approach allows the servlet to perform other tasks while waiting for I/O operations to complete,
enhancing the overall efficiency of the application.
1. Introduction to Non-blocking I/O:
 Non-blocking I/O allows applications to perform I/O operations without waiting for
the operation to complete.
 Traditional blocking I/O involves the program blocking until data is ready to be read
or written.
2. Basic Flow for Servlet with Async Support:
 The servlet where async support is desired should be annotated with
@WebServlet with asyncSupported set to true.
3. Thread Pool Implementation:
 A thread pool is created using the Executors framework. The servlet context
listener is used to initiate the thread pool.
4. Getting AsyncContext:
 The servlet gets an instance of AsyncContext through
ServletRequest.startAsync() method.
 AsyncContext provides references to ServletRequest and ServletResponse
objects.
 It also provides methods for forwarding the request to another resource using
dispatch() method.
5. Runnable Implementation for Heavy Processing:
 A Runnable implementation is created to handle the heavy processing.
 The AsyncContext object is used to either dispatch the request to another
resource or write a response using the ServletResponse object.
 After processing is finished, AsyncContext.complete() is called to signal that
async processing is complete.
6. AsyncListener Implementation:
 An AsyncListener implementation is added to the AsyncContext object to handle
callback methods.
 Callback methods can be used to provide error responses to clients in case of
errors or timeouts during async thread processing.
 Clean-up activities can also be performed in these callback methods.
9). Explain Cookie class with its constructor and any five methods. (NOV 19, APR 23)
Ans: 1) Cookies Overview:
 Cookies are small pieces of information sent by the web server in the response
header and stored in the browser's cookies.
 They are used for session management and can uniquely identify a client.
 Cookies are sent back to the server with additional requests, allowing the server to
track the session.
2. Cookie Constructor (Cookie()):
 The Cookie() constructor is used to create a cookie.
 Cookies typically have a name, a single value, and optional attributes such as a
comment, path, domain qualifiers, maximum age, and a version number.
 Some optional attributes should be used sparingly due to potential interoperability
issues with different web browsers.
3. Adding Cookies to Response:
 Cookies are sent to the browser using the
HttpServletResponse.addCookie(javax.servlet.http.Cookie) method.
 This method adds fields to the HTTP response headers to send cookies to the
browser, one at a time.
4. Cookie Syntax:
 The Cookie constructor syntax is public Cookie(java.lang.String name,
java.lang.String value).
 It constructs a cookie with a specified name and value.
5. Cookie Methods:
 setDomain(String domain): Sets the domain to which the cookie applies (e.g.,
google.com).
 getDomain(): Gets the domain to which the cookie applies.
 setMaxAge(int expiration): Sets the time (in seconds) before the cookie expires.
 getMaxAge(): Returns the maximum age of the cookie in seconds.
 getName(): Returns the name of the cookie. The name cannot be changed after
creation.
6. Additional Notes:
 Some web browsers have limitations on the number and size of cookies they
support. For example, a browser may support up to 20 cookies per web server and
300 cookies in total.
Note: All Questions are Important (Only Dotted and Critical Ones are included)
Unit 3
1). What are the benefits of using JSP? / Explain the reason why use JSP? (NOV 19)
Ans: JSP stands for Java Server Pages. It is a technology used in web development for building
dynamic web pages and web applications. JSP allows you to embed Java code within HTML
pages, enabling the execution of Java logic on the server-side to generate dynamic content that
is then sent to the client's web browser.
1. Code Security:
 JSP code runs on the server, and the logic remains on the server side.
 This prevents others from easily copying or accessing the underlying code,
enhancing code security.
2. Faster Page Loading:
 Customization of response pages occurs on the server side.
 Only the necessary content is sent to the client, resulting in faster loading times for
pages.
3. Browser Compatibility:
 JSP generates standard HTML that is sent to the user's browser.
 This approach minimizes cross-browser compatibility issues, as the server-side
processing ensures a consistent output.
4. JSP Support:
 JSP is supported by various web servers.
 Many web servers, including Java Web Server from Oracle, have built-in support
for JSP.
5. Compilation:
 Each JSP page is compiled into executable code on the first request.
 Subsequent requests invoke the compiled code directly, leading to faster
processing times, especially when coupled with a persistent JVM.
6. Similarity to HTML:
 JSP pages resemble HTML or XML pages, making them familiar to developers.
 Business logic can be written using scripting elements or JSP tags, ensuring
consistency in coding styles across the entire JSP page.
7. Separation of Logic and View:
 JSP enables the separation of the presentation layer from the business logic layer
in a web application.
 This separation enhances code organization and maintainability.

2). Write a short note on life cycle of JSP. (NOV 22, APR 23)
Ans: The JSP lifecycle provides a structured sequence of steps from the translation of JSP
source to the destruction of the associated servlet instance, allowing for proper initialization,
request handling, and cleanup.

1. Translation of JSP Page:


 A Java servlet file is generated from the JSP source file.
 The JSP container validates the syntactic correctness of the JSP page and tag
files.
 Standard directives, actions, and custom actions are interpreted.
2. Compilation of JSP Page:
 The generated Java servlet file is compiled into a Java servlet class.
 Translation of the Java source page to its implementation class can occur between
JSP deployment and processing.
3. Class Loading:
 The servlet class is loaded into the container.
4. Instantiation:
 An object (instance) of the class is created.
 The container manages one or more instances of this class in response to
requests and events.
 The init() method is invoked, and initialization occurs. The init() method is part of
the HttpJSPPage interface.
5. Initialization:
 The jspInit() method is invoked during the servlet instance initiation.
 It is called once during the JSP lifecycle.
 Custom initialization code can be placed in this method.
6. Request Processing:
 The _jspservice(HttpServletRequest request, HttpServletResponse response)
method is invoked by the container for handling all requests and responses.
 It cannot be overridden.
 This method is responsible for generating responses to HTTP methods (GET,
POST, etc.).
 It passes request and response objects.
7. Destroy:
 The _jspDestroy() method is invoked by the container when it decides it no longer
needs the servlet instance.
 This method is called when the servlet is ready for garbage collection.
 It is an opportunity for clean-up activities, such as releasing database connections
or closing open files.

3). Explain types of directives in JSP. (NOV 18, NOV 19, NOV 22, APR 23)
Ans: 1) JSP Directives
JSP directives provide special processing information about the page to the JSP server. They
influence the overall structure of the servlet class generated by the JSP container but do not
produce visible output for the client. The syntax for a JSP directive is typically:
<%@ directive attribute="value" %>
Here are the three types of directive tags:
1) Page Directive (<%@ page ... %>)
 Defines page-dependent attributes like scripting language, error page, and buffering
requirements.
 Examples of attributes include language, import, contentType, extends, isErrorPage,
session, and info.
 By convention, page directives are placed at the top of the JSP page.
<%@ page language="java" %>
<%@ page import="java.util.Date" %>
<%@ page contentType="application/msword" %>
<%@ page extends="somePackage.SomeClass" %>
<%@ page isErrorPage="true" %>
<%@ page session="true" %>
<%@ page info="This is a JSP Page" %>
2) Include Directive (<%@ include ... %>)
 Includes a file during the translation phase.
 Merges the content of other external files with the current JSP during translation.
 The file attribute specifies the page-relative or context-relative URI path to the file.
<%@ include file="relative-url" %>
3) Taglib Directive (<%@ taglib ... %>)
 Declares the use of a set of custom tags in the JSP page.
 Identifies the location of the tag library and provides a means to identify custom tags.
 The uri attribute is a URI that identifies the Tag Library Descriptor, and the prefix attribute
defines the prefix for custom tags.
<%@ taglib uri="uri" prefix="prefixOfTag" %>
 Custom tags hide complex server-side code from web designers. The URI points to the
Tag Library Descriptor, specifying the custom tags and their implementations.
4). What are the implicit objects in JSP? (NOV 19, APR 23)
Ans: Implicit Objects in JSP
JSP provides several implicit objects that are automatically created during the translation phase
and can be used directly in scriptlets without declaration or initialization. Here are the commonly
used implicit objects in JSP:
1. out (JspWriter):
 Used for writing data to the buffer and sending output as a response to the client's
browser.
 In servlets, an equivalent would be PrintWriter out = response.getWriter();.
 Example: <% out.print("JspWriter"); %>
2. request (HttpServletRequest):
 Represents the incoming HTTP request and is an instance of
HttpServletRequest.
 Used to retrieve request information, parameters, headers, etc.
 Example: <% String name = request.getParameter("uname"); %>
3. response (HttpServletResponse):
 Represents the HTTP response and is an instance of HttpServletResponse.
 Used to manipulate the response, such as redirecting to another resource.
 Example: <% response.sendRedirect("http://www.google.com"); %>
4. config (ServletConfig):
 Represents the servlet configuration and is an instance of ServletConfig.
 Used to retrieve initialization parameters for a particular JSP page.
 Example: <% String driver = config.getInitParameter("dname"); %>
5. application (ServletContext):
 Represents the servlet context and is an instance of ServletContext.
 Created once by the web container when the application or project is deployed.
 Used to retrieve initialization parameters and manage attributes in the application
scope.
 Example: <% String driver = application.getInitParameter("dname"); %>
6. session (HttpSession):
 Represents the HTTP session and is an instance of HttpSession.
 Used to set, get, or remove attributes and retrieve session information.
 Example: <% String name = (String) session.getAttribute("user"); %>
7. pageContext (PageContext):
 Represents the page context and is an instance of the PageContext class.
 Used to set, get, or remove attributes in various scopes (page, request, session,
application).
 Example: <% String name = (String) pageContext.getAttribute("user",
PageContext.SESSION_SCOPE); %>
8. page (Object):
 Represents the current JSP page and is an instance of the Object class.
 Can be cast to a servlet type for specific functionality.
 Example: <% ((HttpServlet) page).log("message"); %>
9. exception (Throwable):
 Represents an exception and is an instance of the java.lang.Throwable class.
 Used to print the exception, typically in error pages.
 Example: <%= exception %>

5). Explain the various scope of JSP application.


Ans: JSP Object Scope
In JSP, object scope refers to the availability or visibility of an object within different parts of the
application. JSP provides four different object scopes:
1. Page Scope:
 Objects with page scope are accessible only within the page in which they are
created.
 The data is valid only during the processing of the current response.
 Once the response is sent back to the browser, the data is no longer valid.
 Example:
<jsp:useBean id="employee" class="EmployeeBean" scope="page" />
2. Request Scope:
 Objects with request scope are accessible from pages processing the same request in
which they were created.
 The data is released once the container has processed the request.
 Data is available even if the request is forwarded to another page, but not if a redirect is
required.
 Example:
<jsp:useBean id="employee" class="EmployeeBean" scope="request" />
3. Session Scope:
 Objects with session scope are accessible from pages processing requests within the
same session.
 A session lasts as long as users interact with the application (until they close their
browser, go to another website, or log out).
 Data stored in session scope, such as user login information, is available throughout the
session.
 Example:
<jsp:useBean id="employee" class="EmployeeBean" scope="session" />
4. Application Scope:
 Objects with application scope are accessible from all JSP pages within the same
application.
 It creates a global object that is available to all pages.
 Application scope variables are typically created and populated when the application
starts and used as read-only for the rest of the application.
 Example:
<jsp:useBean id="employee" class="EmployeeBean" scope="application" />

6). Explain JSTL core Tag Library. (NOV 18)


Ans: JSTL Core Tag Library Overview
The JSTL (JavaServer Pages Standard Tag Library) Core Tag Library provides tags that are
essential for various functionalities in a web application. The Core Tag Library includes tags for
general-purpose actions, conditional actions, iteration, and URL-related actions.
Including JSTL Core Tag Library in JSP:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
Here, the uri attribute specifies the URI of the Core Tag Library, and the prefix attribute
provides a short name (c) that can be used as a prefix for the Core tags.
Core Tag Library Sections:
The Core Tag Library can be categorized into four functional sections:
A) General-Purpose Actions:
1. <c:out>:
 Displays the result of an expression.
 Example:
<c:out value="${'Hello World'}"/>
2. <c:set>:
 Sets the result of an expression evaluation in a 'scope'.
 Example:
<c:set var="salary" scope="session" value="${2000}"/>
3. <c:remove>:
 Removes a scoped variable.
 Example:
<c:remove var="salary"/>
4. <c:catch>:
 Catches any Throwable that occurs in its body and optionally exposes it.
 Example:
<c:catch var="catchException"> <% int x = 5/0; %> </c:catch>
B) Conditional Actions or Flow Control Statements:
1. <c:if>:
 Evaluates an expression and displays its body content only if the expression
evaluates to true.
 Example:
<c:if test="${salary > 20000}"> <p>My salary is: <c:out value="${salary}"/></p> </c:if>
2. <c:choose>, <c:when>, <c:otherwise>:
 Provides conditional processing similar to a switch statement.
 Example:
<c:set var="number1" value="${222}"/>
<c:set var="number2" value="${12}"/>
<c:set var="number3" value="${10}"/>
<c:choose>
<c:when test="${number1 < number2}">
${"number1 is less than number2"}
</c:when>
<c:when test="${number1 <= number3}">
${"number1 is less than or equal to number2"}
</c:when>
<c:otherwise>
<c:out value="${'number1 is the largest number!'}"/>
</c:otherwise>
</c:choose>
C) Iterator Actions:
1. <c:forEach>:
 Repeats the nested body content for a fixed number of times or over a collection.
 Example:
<c:forEach var="i" begin="1" end="5"> Item <c:out value="${i}"/><p> </c:forEach>
2. <c:forTokens>:
 Iterates over tokens separated by the supplied delimiters.
 Example:
<c:forTokens items="Chris-Steve-Liza" delims="-" var="name"> <c:out value="${name}"/><p>
</c:forTokens>
D) URL-Related Actions:
1. <c:redirect>:
 Redirects the browser to a new URL.
 Example:
<c:redirect url="http://abc.com"/>
2. <c:url>:
 Creates a URL with optional query parameters. Performs URL rewriting.
 Example:
<c:url value="/Register.jsp"/>
3. <c:param>:
 Adds a parameter to a containing 'import' tag's URL.
 Example:
<c:url value="/index.jsp" var="completeURL"/> <c:param name="user" value="Ann"/>

7). Explain the tag with its attribute. Support your answer with suitable code snippet.
(NOV 19)
Ans: The <jsp:useBean> action tag in JSP is used to locate or instantiate a bean class. If an
object of the bean class is already created, it doesn't create a new one depending on the
specified scope.
Here is the syntax for the <jsp:useBean> action tag:
<jsp:useBean
id="instanceName"
scope="page | request | session | application"
class="packageName.className"
type="packageName.className"
beanName="packageName.className | <%= expression %>"
/>
Attributes and Usage of <jsp:useBean> action tag:
 id: Used to identify the bean in the specified scope.
 scope: Represents the scope of the bean. It may be page, request, session, or
application. The default scope is page.
 page: Specifies that you can use this bean within the JSP page (default scope).
 request: Specifies that you can use this bean from any JSP page that processes
the same request. It has a wider scope than page.
 session: Specifies that you can use this bean from any JSP page in the same
session, whether processing the same request or not. It has a wider scope than
request.
 application: Specifies that you can use this bean from any JSP page in the same
application. It has a wider scope than session.
 class: Instantiates the specified bean class (creates an object of the bean class), but it
must have a no-arg or no constructor and must not be abstract.
 type: Provides the bean a data type if the bean already exists in the scope. It is mainly
used with the class or beanName attribute. If used without class or beanName, no bean
is instantiated.
 beanName: Instantiates the bean using the java.beans.Beans.instantiate() method.
Now, let's look at a simple example:
Java Code:
// Calculator.java (a simple Bean class)
package com.javatpoint;

public class Calculator {


public int cube(int n) {
return n * n * n;
}
}
JSP Code
<!-- index.jsp file -->
<jsp:useBean id="obj" class="com.javatpoint.Calculator"/>
<%
int m = obj.cube(5);
out.print("Cube of 5 is " + m);
%>
In this example, a bean of class Calculator is instantiated using <jsp:useBean>. The id is set
to "obj", and the class attribute specifies the fully qualified class name. The cube method of the
bean is then called, and the result is printed.
8). What is wrong in using JSP scriptlet tag? How JSTL fixes JSP scriptlet
shortcomings? (NOV 18, NOV 19)
Ans: JSTL offers a cleaner, more modular, and standardized approach to handling dynamic
content in JSP pages, addressing the limitations associated with scriptlet usage.
1. Code Reusability:
 JSP Scriptlets: Embedding business logic using scriptlet tags can result in
reduced code reusability, making it harder to separate concerns.
 JSTL: JSTL promotes a modular and reusable approach to coding by providing a
set of standard tags for common tasks, reducing the need for scriptlets.
2. Improved Structure:
 JSP Scriptlets: Using scriptlet tags can lead to poor code structure, making it
difficult to understand and maintain.
 JSTL: JSTL encourages a cleaner and more structured code organization, making
it easier to manage and maintain.
3. Enhanced Readability:
 JSP Scriptlets: Scriptlet tags in JSP can reduce the readability of HTML code due
to the mix of Java and HTML.
 JSTL: JSTL uses XML-like tags, improving the readability of the JSP code and
making it more understandable for HTML developers.
4. Simplified Understanding:
 JSP Scriptlets: Business logic embedded in scriptlets can make the JSP harder to
understand, especially for developers without strong Java knowledge.
 JSTL: JSTL tags are self-explanatory and easier to understand, making it more
accessible for both HTML and Java developers.
5. Error Handling:
 JSP Scriptlets: Scriptlets can lead to exceptions that may result in no view being
generated.
 JSTL: JSTL provides better error handling and separation of concerns, making it
easier to identify and handle exceptions.
6. Code Reduction:
 JSP Scriptlets: JSTL requires less code compared to scriptlets, leading to more
concise and maintainable JSP pages.
 JSTL: The standard tags provided by JSTL reduce the amount of boilerplate code,
resulting in faster development.
7. Standardization:
 JSP Scriptlets: Scriptlets may vary in coding style and conventions, leading to
inconsistencies.
 JSTL: JSTL provides a standard set of tags and conventions, promoting
consistency across JSP pages and making it easier for developers to collaborate.
8. Automatic Java Beans Introspection Support:
 JSP Scriptlets: Handling JavaBean code within scriptlets can be complex and
error-prone.
 JSTL: JSTL Expression Language (EL) simplifies the handling of JavaBeans,
providing automatic introspection support and reducing the complexity of code.
9. Human and Machine Readability:
 JSP Scriptlets: Mixing HTML and Java code in scriptlets can be challenging for
both developers and HTML generation tools.
 JSTL: JSTL, being expressed as XML-compliant tags, is easier for both
developers and HTML generation tools to understand, improving human and
machine readability.
10. Fast Development:
 JSTL: With its extensive set of tags, JSTL facilitates faster development by
simplifying common JSP tasks and reducing the need for custom scriptlets.

9). Explain XPATH in detail


Ans: XPath (XML Path Language) is a query language used for navigating XML documents and
selecting nodes based on various criteria. XPath provides a way to navigate through elements
and attributes in an XML document. Here are the key components and concepts of XPath:
1. Node:
 In XPath, everything in an XML document is considered a node. This includes
elements, attributes, text, and more.
 Nodes are categorized into different types, such as element nodes, attribute
nodes, text nodes, etc.
2. Location Path:
 XPath expressions use location paths to navigate through the hierarchical
structure of an XML document.
 A location path consists of a series of steps separated by slashes (/). Each step
represents a relationship between nodes.
3. Syntax:
 XPath expressions have a syntax similar to a directory/file path. For example,
/bookstore/book/title represents the path to select all <title> elements that are
children of <book> elements, which are in turn children of the root <bookstore>
element.
4. Axes:
 Axes define the relationship between the current node and the selected nodes in
the location path.
 Common axes include:
 child: Selects all children of the current node.
 parent: Selects the parent of the current node.
 ancestor: Selects all ancestors (parent, grandparent, etc.) of the current
node.
 descendant: Selects all descendants (children, grandchildren, etc.) of the
current node.
 following-sibling: Selects all siblings that follow the current node.
 preceding-sibling: Selects all siblings that precede the current node.
5. Node Tests:
 Node tests are used to filter nodes based on their node type or name.
 Examples of node tests include:
 *: Matches any element node.
 @attributeName: Matches any attribute node with the specified name.
Note: All Questions Are Important (Only Dotted and Critical Ones are included)
Unit 4
1). Write a short note on EJB architecture. (NOV 18, APR 23)
Ans: EJB Architecture Overview:

1. Enterprise Bean Server:


 Component transaction server supporting the EJB server-side model.
 Responsibilities:
 Management API
 Process and thread management
 Database connection pooling and caching
 System resources management
2. Enterprise Bean Container:
 Logical construct in the Full Java EE profile managing enterprise beans.
 Responsibilities:
 Provides runtime environment for EJBs
 Manages persistence
 Handles Lifecycle management of EJBs
 Ensures EJB security
3. Enterprise Bean:
 Reusable modules encapsulating related tasks with a defined interface.
 Functions:
 Contains methods executing business logic and accessing data sources.
 Server-side components for encapsulating application business logic.
 Offers specific enterprise services alone or with other EJBs.
4. Enterprise Bean Clients:
 Types of Client View:
 Remote Client View:
 Available from EJB onwards.
 Location-independent, accessible from the same or different JVM.
 Remote interface: Specifies remote business methods.
 Remote home interface: Methods for locating, creating, and removing
instances.
 Local Client View:
 Location-dependent, requires both local client and enterprise bean in the
same JVM.
 Interfaces:
 Local interface: Lightweight version for local clients.
 Local home interface: Specifies methods for local clients to locate,
create, and remove instances.

2). What are the various features provided by EJB? (NOV 19)
Ans: EJB (Enterprise JavaBeans): Server-side component architecture for building distributed
and scalable enterprise-level Java applications.
Key Features:
1. Standardized Component Model:
 Provides a standardized and reusable component model.
 Evolved components like session beans remain relevant for certain use cases.
2. Jakarta EE Platform:
 Integral part of the Jakarta EE (formerly Java EE) platform.
 Enables the development of robust, transactional, and scalable business
applications.
3. Alternative Approaches:
 Developers may use alternative approaches like Spring Framework and Java
Persistence API (JPA) for modern Java EE applications.
Features Provided by EJB:
1. Interoperability:
 Mapped to standard CORBA for compatibility with components developed in
different languages.
 EJB client view interface serves as a well-defined integration point.
2. Separation of Business and Presentation Logic:
 EJB performs a clear separation between business logic and presentation logic.
 Enables the development of multiple presentation logics for the same business
process.
3. Focus on Business Logic:
 Allows server vendors to focus on system-level functionalities.
 Developers concentrate solely on business logic for domain-specific applications.
4. Write Once, Run Anywhere:
 Uses Java language for portability across multiple platforms.
 Develop once and deploy on multiple platforms without recompilation.
5. Distributed Transaction Support:
 Provides transparency for distributed transactions.
 Clients can invoke methods on beans across different servers, machines,
platforms, or JVMs.
6. Vendor-Specific Enhancements:
 EJB specification offers flexibility for vendors to create their enhancements.
 EJB environment may become feature-rich due to vendor-specific enhancements.
3). What are types of enterprise bean?
Ans: 1. Session Bean:
 Java beans encapsulating business logic in a centralized and reusable manner.
 Lifespan: Short-lived, not persistent in a database.
 Types:
 Stateless: Pooled by the container for multiple clients.
 Stateful: Maintains client-specific session information across method calls.
 Singleton: Instantiated once per application, provides shared data.
 Responsibilities:
 Implements business logic, workflow, algorithms, and rules.
 Executes a specific business task during a single client session.
 Analogous to interactive sessions, not shared among clients.
 Removed when the EJB container is shut down or crashes.
2. Entity Bean:
 Persistent objects representing business entities (e.g., customers, products).
 Persistence:
 Typically corresponds to a table in a relational database.
 State is persistent, transactional, and shared among different clients.
 Types:
 Container-Managed Persistence (CMP): Container manages persistence based on
data-object mapping.
 Bean-Managed Persistence (BMP): Bean manages database connections and
state changes.
 Responsibilities:
 Contains data-related logic (e.g., inserting, updating, removing records in the
database).
3. Message-Driven Bean:
 Enterprise beans processing JMS messages asynchronously.
 Characteristics:
 No interfaces, accessed only through messaging.
 No conversational state maintenance.
 Short-lived, can be transaction-aware.
 Responsibilities:
 Receives and processes JMS messages, allowing asynchronous communication.
 Separates message processing from business logic.
 Features:
 No home and component interface.
 Defines message listener method invoked by the EJB container.
 Stateless, no state maintenance between message listener method calls.
 Performs logic based on message contents (e.g., client notification processing).

4). What are types of session beans? (APR 19, APR 23)
OR
Write a detailed note on the type of Session beans. (NOV 22)
Ans: Types of Session Beans:
1. Stateful Session Beans:
 State Representation:
 Instance variables represent the state of a unique client/bean session.
 Known as conversational state.
 Client Interaction:
 Similar to an interactive session.
 Not shared, one client per session.
 Session ends when the client terminates.
 State Duration:
 State retained for the duration of the client/bean session.
 Transient state, disappears when the client removes the bean.
 Advantages:
 Supports individual client-specific states.
 Suitable for scenarios requiring conversation-like interactions.
2. Stateless Session Beans:
 Conversational State:
 Does not maintain a conversational state with the client.
 Client-specific state, if any, lasts only for the duration of method invocation.
 State Equality:
 All instances are equivalent, allowing assignment to any client.
 State applies uniformly across all clients.
 Scalability:
 Supports multiple clients, offering better scalability.
 Requires fewer instances than stateful session beans for the same client load.
 Web Service Implementation:
 Can implement web services.
 Suitable for applications requiring large numbers of clients.
3. Singleton Session Beans:
 Instantiation and Lifecycle:
 Instantiated once per application, exists for the application's lifecycle.
 Concurrent Access:
 Shared across and concurrently accessed by clients.
 Functionality:
 Offers similar functionality to stateless session beans.
 Only one singleton session bean per application.
 State Maintenance:
 Maintains state between client invocations.
 Not required to maintain state across server crashes or shutdowns.
 Initialization and Cleanup:
 Can be instantiated upon application startup.
 Performs initialization and cleanup tasks for the application.
 Operates throughout the lifecycle of the application.
5). Explain life cycle of message driven beans. / Write short note on Lifecycle of a
Message Driven Bean with onMessage( ) Method. (April 19, Nov18, Nov19)
Ans: Message-Driven Beans (MDBs):

 Definition:
 Server-side components in the Java EE (Enterprise Edition) platform.
 Specifically designed to handle asynchronous messaging.
 Use Case:
 Process messages from message queues, topics, or other messaging systems.
 Enables scalable and loosely coupled message-driven processing.
 Characteristics:
 Client Interface:
 Unlike other EJB types, MDBs do not have a client interface.
 Activated and respond to incoming messages based on annotations and
configurations.
 Container Handling:
 Instance Pool:
 EJB container creates a pool of message-driven bean instances.
 Tasks Performed for Each Instance:
 If using dependency injection, container injects references before
instantiation.
 Calls the method annotated @PostConstruct, if present.
 Lifecycle:
 Similar to stateless session beans, MDBs have two states: nonexistent and
ready to receive messages.
 Calls the method annotated @PreDestroy at the end of the lifecycle.
 Instance is then ready for garbage collection.

6). What is Message Driven Bean? Explain its usage


Ans: Message-Driven Beans (MDBs) in Java EE:

 Definition:
 Type of server-side component in the Java EE (Enterprise Edition) platform.
 Specifically designed to handle asynchronous messaging.
 Use Case:
 Process messages from message queues, topics, or other messaging systems.
 Facilitates scalable and loosely coupled message-driven processing.
 Characteristics:
 Activation:
 Activated and respond to incoming messages based on message-driven
annotations and configurations.
 Client Interface:
 Unlike other EJB types, MDBs do not have a client interface.
 Functionality:
 Business Logic:
 Contains business logic invoked by passing messages.
 Acts as a JMS (Java Message Service) Receiver, asynchronously receiving
and processing messages.
 Interaction:
 Receives messages from queues or topics, requiring knowledge of the JMS
API.
 Acts as a JMS message listener, similar to an event listener but for JMS
messages.
 Asynchronous Processing:
 Allows Java EE applications to process messages asynchronously.
 Can process JMS messages sent by any Java EE component or non-Java
EE JMS applications/systems.
 Role in Java EE:
 JMS Message Listener:
 Serves as a JMS message listener for processing asynchronous messages.
 Versatility:
 Can handle messages from various sources within the Java EE ecosystem.
 Suitable for scenarios requiring decoupled and asynchronous
communication.

7). Explain about enterprise bean container. (NOV 22)


Ans: The Enterprise Bean Container, a crucial component of the Java EE (Enterprise Edition)
platform (now Jakarta EE), plays a pivotal role in managing Enterprise JavaBeans (EJBs) in
Java EE applications.
1. Runtime Environment:
 Provides a runtime environment for executing Enterprise Java Beans.
2. Persistence Management:
 Manages persistence for EJBs, ensuring data storage and retrieval.
3. Lifecycle Management:
 Handles the complete lifecycle of EJBs, covering creation, initialization, invocation, and
destruction.
4. Security Enforcement:
 Ensures security for EJBs by enforcing policies and access control, permitting only
authorized clients to invoke methods.
5. Concurrency Control:
 Manages concurrency for stateful and stateless session beans by offering pooled
instances.
 Controls client access to EJBs concurrently, ensuring the correct instance for each client.
6. Resource Pooling:
 Maintains pools of EJB instances, enhancing performance and resource utilization.
 Handles allocation and release of instances as requested by clients.
7. Transaction Management:
 Provides built-in support for transaction management.
 Coordinates commit or rollback of transactions, ensuring data consistency.
8. Resource Management:
 Manages access to external resources like databases and messaging systems.
 Coordinates resource connections and ensures proper resource release.
9. Naming and Directory Services:
 Offers access to Java Naming and Directory Interface (JNDI) for resource lookup.
10. Remote Method Invocation: - Handles network communication and remote method
invocation for distributed EJB access. - Ensures transparency to the client.
11. Interceptors and Aspects: - Enables developers to use interceptors and aspects for
concerns like logging and security without altering core business logic.
12. Error Handling: - Manages error handling and exception propagation within EJB methods. -
Ensures proper handling and logging of exceptions.
13. Component Pooling and Recycling: - Manages various resource pools, optimizing
resource utilization and recycling components.
14. Portability: - Ensures EJB components' portability across different Java EE-compliant
application servers. - Facilitates development once and deployment on various platforms.
8). Explain the life cycle of an interceptor. (NOV 18)
Ans:
 Association with Bean:
 Interceptor instances are created when the associated bean instance is created.
 For stateful session beans, interceptor instances are passivated during bean
instance passivation and activated during bean instance activation.
 Interceptor instances are destroyed when the associated bean instance is
removed.

 Callback Execution:
 PostConstruct and PostActivate callbacks are invoked after creating or activating
both the bean and interceptor instances.
 PreDestroy and PrePassivate callbacks are invoked before destroying or
passivating either the bean or interceptor instances.
 State and Dependency Injection:
 Interceptor instances may hold state and can be the target of dependency
injection.
 Dependency injection occurs during interceptor and bean instance creation,
utilizing the naming context of the associated enterprise bean.
 PostConstruct Callback:
 PostConstruct interceptor callback is invoked after dependency injection on both
interceptor and bean instances.
 Interceptors can perform actions like invoking JNDI, JDBC, JMS, other enterprise
beans, and accessing the EntityManager.
 Shared Naming Context:
 Interceptors share the enterprise naming context of the associated bean for
methods and lifecycle events.
 Annotations or XML deployment descriptor elements for dependency injection
refer to this shared naming context.
 EJBContext Injection:
 EJBContext object may be injected into an interceptor class.
 The interceptor can use the lookup method of the EJBContext interface to access
the bean's JNDI naming context.
 Extended Persistence Context:
 Use of an extended persistence context is supported only for interceptors
associated with stateful session beans.

9). How to define Interceptor? What is the role of AroundInvoke Method? (APR 19)
Ans: Interceptors are employed with Java EE managed classes to enable developers to invoke
methods in conjunction with method invocations or lifecycle events. They find common use in
tasks such as logging, auditing, and profiling. Interceptors can be specified within a target class
as interceptor methods or in an associated class known as an interceptor class.
 AroundInvoke:
In this interceptor example, an interceptor class named HelloInterceptor is used in conjunction
with a stateless session bean called HelloBean. The stateless session bean has two business
methods, getName and setName, for retrieving and modifying a string.
@Interceptors(HelloInterceptor.class)
public void setName(String name) {
this.name = name;
}
 The HelloInterceptor class defines an @AroundInvoke interceptor method named
modifyGreeting. This method converts the string passed to HelloBean.setName to
lowercase.
@AroundInvoke
public Object modifyGreeting(InvocationContext ctx) throws Exception {
Object[] parameters = ctx.getParameters();
String param = (String) parameters[0];
param = param.toLowerCase();
parameters[0] = param;
ctx.setParameters(parameters);

try {
return ctx.proceed();
} catch (Exception e) {
logger.warning("Error calling ctx.proceed in modifyGreeting()");
return null;
}
}

10). Define and explain Interceptors (APR 19, APR 23)


Ans: Defining an Interceptor:
 An interceptor method can be defined on either the enterprise bean class or an
associated interceptor class.
 Interceptor classes are separate from the bean class and have methods invoked in
response to business method invocations or lifecycle events.
 Multiple interceptor classes can be defined for a bean, allowing the carryover of state
across multiple method invocations.
 An interceptor class must have a public no-arg constructor and adheres to the
programming restrictions applied to enterprise bean components.
 Interceptor methods and classes are defined using metadata annotations or the
deployment descriptor.
 When annotations are used, the Interceptors annotation on the bean class or specific
methods denotes one or more interceptor classes. Invocation order is determined by their
sequence in the Interceptors annotation.
 Interceptors can be defined as either method interceptors or class interceptors in Java.
The preferred method is using metadata annotations, though they can be defined in the
application descriptor, potentially losing portability across different Java EE servers.
 Relevant annotations in the javax.interceptor package include @AroundInvoke,
@AroundTimeout, @PostConstruct, and @PreDestroy.
 For instance, an AroundInvoke method can be defined on either the enterprise bean
class or an interceptor class, providing flexibility based on application requirements.

11). What is Naming service? Explain with the help of a diagram. (NOV 22, APR 23)
Ans: Java Naming and Directory Interface (JNDI):
 JNDI is an application programming interface (API) designed for accessing various
naming and directory services.
 It is not tied to a specific naming or directory service and can be utilized to access
diverse systems such as file systems, distributed object systems (CORBA, Java
RMI, EJB), and directory services (LDAP, Novell NetWare, NIS+).
 Similar to JDBC, JNDI is an Object-Oriented Java API, providing a common
abstraction for accessing services from different vendors.
 While JDBC is used for accessing various relational databases, JNDI is employed
for interacting with different naming and directory services.
 Both JDBC and JNDI adhere to the architectural principle of defining a common
abstraction (API) that multiple vendors can implement.
 The API serves as a unified, objectified view of a service, abstracting away the
specifics of any particular vendor's implementation.
 JNDI Architecture:
 The JNDI architecture comprises an API and a service provider interface (SPI).
 Java applications utilize the JNDI API to access diverse naming and directory
services.
 The SPI facilitates the seamless integration of various naming and directory
services, allowing Java applications to access their services transparently.
 This architecture enables flexibility, as different services can be plugged into the
API, and the Java application using the JNDI API can access these services
without being concerned about the underlying implementation details specific to
each service provider.

12). Explain basic look up in JNDI. Also explain resource injection in JNDI. (NOV 18)
Ans:
 JNDI Hierarchy:
 JNDI organizes names into a hierarchy.
 Names can be represented as strings (e.g., "com.mypack.ejb.TBean") or objects
implementing the Name interface.
 A name is bound to an object in the directory service by storing the object or a
reference to it in the directory.
 Context Class:
 The Context class is at the core of the JNDI API.
 Used for performing lookups and establishing new name-value associations.
 To begin using JNDI, an InitialContext object is typically created:
Context ctx = new InitialContext();
 The InitialContext constructor looks for a system property called
java.naming.factory.initial, which contains the class name creating the
InitialContext.
 Some EJB containers, like Sun's J2EE SDK, may already have this property set.
 Lookup Operation:
 To look up an object, use Context.lookup() with the name of the object you want
to retrieve:
Object obj = ctx.lookup("cn=Yeshu Sambare, ou=People");
 The type of object returned by lookup() depends on the underlying naming system
and the associated object's data.
 Cast the result of lookup() to its target class.
 JNDI Lookups:
 Three JNDI lookups:
1. java:global
2. java:module
3. java:app
 Resource Injection:
 The javax.annotation.Resource annotation declares a reference to a resource,
applicable to a class, field, or method.
 The container injects the resource either at runtime or during component
initialization, depending on injection type.
 Elements of @Resource annotation:
 name: JNDI name of the resource.
 type: Java language type of the resource.
 authenticationType: Authentication type for the resource.
 shareable: Indicates whether the resource can be shared.
 mappedName: Nonportable, implementation-specific name to which the
resource should be mapped.
 description: Description of the resource.

13). What is EJB? Explain Advantages of EJB.


Ans: Enterprise JavaBeans (EJB) is a server-side component architecture used for building
distributed, scalable, and transactional enterprise-level Java applications. EJB is part of the
Java EE (Enterprise Edition) platform, which has been rebranded as Jakarta EE.
Advantages of EJB:
1. Component-Based Development:
 EJB promotes a component-based approach to application development. It allows
developers to build reusable and modular components that can be easily
integrated into different parts of an enterprise application.
2. Distributed Computing:
 EJB facilitates the development of distributed applications by providing a
framework for building components that can be deployed on multiple servers and
interact seamlessly. It supports remote method invocation (RMI) for
communication between distributed components.
3. Transaction Management:
 EJB provides built-in support for transaction management. This ensures that
business methods can participate in transactions, allowing for consistent and
reliable data updates across multiple operations.
4. Concurrency Control:
 For stateful and stateless session beans, EJB containers manage concurrency by
providing pooled instances. This controls how multiple clients can access EJBs
concurrently, ensuring the correct instance is used for each client.
5. Security Features:
 EJB offers robust security features, allowing developers to enforce access control
and implement security policies. It supports role-based access control, protecting
sensitive business logic and data.
6. Persistence Management:
 EJB provides a standardized approach to managing persistence. Entity beans, in
particular, are used to model and manage data entities, and the EJB container is
responsible for handling interactions with databases, making it easier to implement
data-related logic.
7. Scalability:
 EJB applications can be scaled horizontally by deploying components on multiple
servers. This allows the system to handle a growing number of users and
transactions effectively.
Unit 5
Q1: What is Persistence?Explain with an example?
Where does Java Peristence Api Fit In?
Explain persistent standards available in java?
Ans:
Definition:
 Persistence refers to the storage and retrieval of data in a way that allows it to outlast the
execution of a program.
 It involves saving data to a more permanent medium, like a database, so that it can be
reused across different program runs.

Example:
 Consider a task management application.
 When you add tasks, close the application, and later reopen it, the tasks persist—they
remain stored in the application.
 This enduring quality, achieved through mechanisms like databases, demonstrate the
concept of persistence.

Java Persistence API (JPA):


Fit In:
 Java Persistence API (JPA) is a Java specification for managing relational data in Java
applications.
 It fits into Java's ecosystem by providing a standardized way to interact with databases,
allowing developers to perform database operations using Java objects.

Persistent Standards in Java:

1) JPA (Java Persistence API):


Standardizes how Java objects are mapped to database tables, promoting consistency in
database interactions.
2) Hibernate:
An influential implementation of JPA, Hibernate simplifies database access in Java and aligns
with JPA specifications.

3) Java Serialization:
Enables the conversion of objects into a byte stream, facilitating storage or transmission. While
not specifically for databases, it's a way to make Java objects persist in various forms.

Q2: With the help of a diagram explain JPA architecture.


Ans:
Persistence Components in Java:

1. Persistence Class (javax.persistence.Persistence):


 Provides helper methods to obtain EntityManagerFactory instances, ensuring vendor-
neutral access.

2. EntityManagerFactory:
 Created during application startup using a Persistence Unit.
 Acts as a factory for creating EntityManager instances.
 Usually, a single instance per database, persisting throughout the application's lifespan.

3. EntityManager:
 Lightweight and cost-effective to create.
 Performs actual database operations, managing persistent objects (Entities).
 Serves as a factory for Query and CriteriaQuery instances.
4. Entity:
 Represents persistent objects mapped to datastore records.

5. Entity Transaction:
 Represents a unit of work with the database.
 Initiated via EntityManager for modifications.
 Short-lived, closed by committing or rejecting changes.

6. Query:
 Retrieves persistent objects using SQL or JPQL queries.
 Dynamically created using EntityManager.

7. Criteria:
 Non-string-based API for dynamic queries.
 Passed to EntityManager for creating Query objects.
 Represents semantic constructs of the query, including domain objects, predicates,
select clauses, etc.

Diagram:
Q3: What is Hibernate?Explain the need of using it along with its features?
What are the different components of hibernate?
Ans:
Definition:
 Hibernate is an Object-Relational Mapping (ORM) framework for Java, simplifying
database interactions by mapping Java objects to database tables.
 It simplifies the process of persisting Java objects (POJOs - Plain Old
Java Objects) into relational databases and retrieving them from the database.
 Hibernate is widely used in Java-based enterprise and web applications for database
interaction.

Here's an explanation of Hibernate and the need for using it and features:

1. Simplified Database Access:


 Need: Traditional JDBC involves complex SQL and manual mapping.
 Hibernate Feature: Provides a simple and intuitive way to interact with databases using
Java objects, reducing the need for intricate SQL queries.

2. Object-Relational Mapping (ORM):


 Need: Bridging the gap between object-oriented programming and relational databases.
 Hibernate Feature: Maps Java objects to database tables, allowing seamless integration
of object-oriented models with relational databases.

3. Automatic Table Creation:


 Need: Cumbersome manual creation of tables.
 Hibernate Feature: Automatically generates database tables based on Java objects,
reducing manual effort in table creation.

Components of Hibernate:

1. Application Layer:
 Represents the client application interacting with Hibernate.
 Java objects serve as entities to be persisted in the database.

2. Hibernate Configuration:
 Configuration settings in hibernate.cfg.xml or programmatically.
 Defines database connection details and properties.

3.SessionFactory:
 Thread-safe factory for creating Session instances.
 Created once during application initialization.

4.Session:
 Represents a unit of work, obtained from SessionFactory.
 Provides CRUD operations and transaction management.

5. Transaction:
 Manages data consistency and integrity.
 Supports features such as commit, rollback, and isolation levels.

Q4:Draw and explain the architecture of hibernate framework?


Ans:
The Hibernate framework follows a layered architecture that simplifies database interactions
and facilitates object-relational mapping (ORM). Here's an overview of the key components and
their roles in the Hibernate architecture:

1. Application Layer:
 Represents the client application interacting with Hibernate.
 Java objects serve as entities to be persisted in the database.

2. Hibernate Configuration:
 Configuration settings in hibernate.cfg.xml or programmatically.
 Defines database connection details and properties.

3.SessionFactory:
 Thread-safe factory for creating Session instances.
 Created once during application initialization.

4.Session:
 Represents a unit of work, obtained from SessionFactory.
 Provides CRUD operations and transaction management.

5. Transaction:
 Manages data consistency and integrity.
 Supports features such as commit, rollback, and isolation levels.

Q5:Explain Object Relational Mapping?Why is there a need for Object Relational


Mapping(ORM)?
Ans:
ORM is a technique that allows you to interact with a relational database using object-oriented
programming languages. It maps database tables to classes and rows to objects, enabling
developers to work with databases using the language's natural syntax rather than SQL.

In simpler terms, ORM lets you treat database interactions as if you're manipulating objects in
your code, abstracting away the complexities of SQL queries and making it more intuitive for
developers to work with databases in their preferred programming language.

Object-Relational Mapping (ORM):


 Need: Bridging the gap between object-oriented programming and relational databases.
 Hibernate Feature: Maps Java objects to database tables, allowing seamless integration
of object-oriented models with relational databases.

You might also like