Professional Documents
Culture Documents
(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.
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.
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.
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.
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 %>
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;
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.
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.
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;
}
}
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.
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.
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.
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:
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.
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.
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.